content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
from pathlib import Path
def get_cache_dir() -> Path:
"""
Returns a cache dir that can be used as a local buffer.
Example use cases are intermediate results and downloaded files.
At the moment this will be a folder that lies in the root of this package.
Reason for this location and against `~/.ca... | 6f8655b9d8a145e7c018293456ac88546c78a34d | 41,747 |
def represents_int(string: str):
"""Checks if a `string can be turned into an integer
Args:
string (str): String to test
Returns:
bool
"""
try:
int(string)
return True
except ValueError:
return False | bc5cfb39e3b89309a7d29608d9bafb28ae67cd18 | 41,754 |
def parse_brackets(line: str) -> tuple[int, str]:
"""
Returns the index at which closing brackets don't align anymore,
or if all closing ones do match, the string needed to complete it.
"""
stack: list[str] = []
opening_map = {
")": "(",
"]": "[",
"}": "{",
">": "... | 3df3bc7bf6d1513b3d387023485949645b19e81c | 41,755 |
def client_error(message, http_status_code=400):
"""
Simple util function to return an error in a consistent format to the calling
system (API Gateway in this case.
:param message:
:param http_status_code:
:return:
"""
return "ERROR::CLIENT::{}::{}".format(http_status_code, message) | ea6f1a3073b856eb2f08b84b62cf9c95d9a62de4 | 41,759 |
def get_zamid_s(zamid):
"""Gets the state of a nuclide from a its z-a-m id. 1 = first excited state, 0 = ground state.
Parameters
----------
zamid: str
z-a-m id of a nuclide
"""
s = int(zamid[-1])
return s | 750108113619f5176bf75e479b52989f9546f876 | 41,763 |
def ceil(a, b):
"""
Returns the ceiling of a on b
"""
c = float(a) / float(b)
if c == int(c):
return int(c)
return int(c) + 1 | f6c7d46f05512d0766d4f9b39cdff224ed7d9bb7 | 41,777 |
def market_cap(df, min_cap=200):
"""filters out stocks that don't meet the min_cap minimum capitalization
criteria.
:df: dataframe
:min_cap: minimum market_cap number (*1 million) for stocks to include in
stock universe (default = 200)
:returns: Dataframe with stocks that have market capita... | 01f716510f3d172e262fcd220ce6affab1e22e19 | 41,778 |
def attach(item, action):
"""Attaches a parse action to an item."""
return item.copy().addParseAction(action) | 7cbfbcee8316a009168ce577a6a178aa9d8384f1 | 41,780 |
from typing import List
def arraysum(array: List[int]) -> int:
""" Get the sum of all the elements in the array.
arraysum
========
The `arraysum` function takes an array and returns the sum of all of its
elements using divide and concuer method.
Parameters
----------
array: List[int]
... | 8a2ea3bd6391f7ed402f07b381d561c816a7c68d | 41,783 |
import torch
def save_model(network, path):
"""
Save (trained) neural network to a file.
Intended to save trained models, but can save untrained ones as well.
Parameters
----------
network: pytorch object
Pytorch object or custom pytorch object containing model information.
path:... | 173c123b00f18635d3aa271f4b5d1789ee9a81f8 | 41,784 |
def ReadPairs(filename):
"""Read pairs and match labels from the given file.
"""
pairs = []
labels = []
with open(filename) as f:
for line in f:
parts = [p.strip() for p in line.split()]
pairs.append((parts[0], parts[3]))
labels.append(1 if parts[1] == par... | ab1c0a34f94c61b2d999a10a2fabab57790280b7 | 41,786 |
from typing import List
from typing import Tuple
from typing import Dict
def edf_annotations(triggers: List[Tuple[str, str, float]],
durations: Dict[str, float] = {}
) -> List[Tuple[float, float, str]]:
"""Convert bcipy triggers to the format expected by pyedflib for writin... | 8c26f7e7bd874bc2a996e251f02513135e8e9e49 | 41,788 |
def get_N(longN):
"""
Extract coefficients fro the 32bits integer,
Extract Ncoef and Nbase from 32 bit integer
return (longN >> 16), longN & 0xffff
:param int longN: input 32 bits integer
:return: Ncoef, Nbase both 16 bits integer
"""
return (longN >> 16), (longN & (2 ** 16 - 1)) | bb8a0c041d8821958901681d925d278fb7083ba5 | 41,792 |
def join_list_mixed(x, sep=', '):
"""
Given a mixed list with str and list element join into a single str
:param x: list to be joined
:param sep: str to be used as separator between elements
:return: str
"""
return sep.join([sep.join(y) if isinstance(y, list) else y for y in x]) | 5faa80d7a451ceeff658938976f291337a6ee8d0 | 41,797 |
import re
def trim(string: str) -> str:
"""Takes in a string argument and trims every extra whitespace from in between as well as the ends."""
return re.sub(" +", " ", string.strip()) | 5c7b428d742a7255b0036d4eeb75a5fab2817e36 | 41,800 |
def _proc_lines(in_str):
""" Decode `in_string` to str, split lines, strip whitespace
Remove any empty lines.
Parameters
----------
in_str : bytes
Input bytes for splitting, stripping
Returns
-------
out_lines : list
List of line ``str`` where each line has been stripp... | 66cd12550503ffd421bab32084a0c23897f90588 | 41,801 |
import itertools
def decode_years_to_min_max(summarized_year_string):
"""
decode a summarized string of years into minimum & max. year values
>>> decode_years_to_min_max('2000-2002, 2004')
(2000, 2004)
>>> decode_years_to_min_max('1992, 1994-1995')
(1992, 1995)
>>> decode_years_to_min_max... | 078b74432fc762c4ba39accec90a72a6cec00dc9 | 41,802 |
def font_style(
custom_font, font):
"""
Changes font family
:param custom_font: font used by Message in Tkinter GUI
:param font: font the user selects
:return: font used by GUI
"""
custom_font.config(family=font)
return custom_font | d2bf35924abd32b6232039c6284dbb35891a4df8 | 41,803 |
def y_in_process(coord2d: list, y_coord: int, ly: int, processes_in_y: int) -> bool:
"""
Checks whether a global y coordinate is in a given process or not.
Args:
coord2d: process coordinates given the cartesian topology
x_coord: global y coordinate
lx: size of the lattice grid in y ... | 0d67c92426f44fff405e7f50f4219ad2d2c76361 | 41,804 |
import requests
def fetch_coordinates(apikey, address):
"""
Get the coordinates of address.
Returns:
return: longitude and latitude of address.
Args:
apikey: token for Yandex service.
address: name of specific place.
"""
base_url = "https://geocode-maps.yandex.ru/1.x"... | 027a73130526522019cadf1982c22039873c732b | 41,809 |
import torch
def compute_iou(pred_mask, gt_mask):
"""
Computes IoU between predicted instance mask and
ground-truth instance mask
"""
pred_mask = pred_mask.byte().squeeze()
gt_mask = gt_mask.byte().squeeze()
# print('pred_masks', pred_mask.shape, 'gt_masks', gt_mask.shape)
intersecti... | fbfbfaa92954d950dd18e5bf9e21bf303676a28d | 41,812 |
def document_path(doc_id, options):
"""Return relative path to document from base output directory."""
if options.dir_prefix is None:
return ''
else:
return doc_id[:options.dir_prefix] | 91ef1244839580d9d218639676d0f6979008cf67 | 41,813 |
import re
def pip_to_requirements(s):
"""
Change a PIP-style requirements.txt string into one suitable for setup.py
"""
if s.startswith('#'):
return ''
m = re.match('(.*)([>=]=[.0-9]*).*', s)
if m:
return '%s (%s)' % (m.group(1), m.group(2))
return s.strip() | dcfceacfab4c47429bd7aff7bc6795ab7f3f7b5f | 41,816 |
def range_check(value, min_value, max_value, inc_value=0):
"""
:brief Determine if the input parameter is within range
:param value: input value
:param min_value: max value
:param max_value: min value
:param inc_value: step size, default=0
:return: Tru... | bf21759371706144e9d25f0692c60d3246e66159 | 41,819 |
import json
def destructure(env):
"""Decodes Nix 2.0 __structuredAttrs."""
return json.loads(env['__json']) | 93b7fbee7262358c75d8f7d9343e51fef2662f6a | 41,820 |
def passAuth(password):
""" Returns true if the password matches with the user's password, else returns false."""
if password == 9241:
return True
else:
return False | 63f60643f999de198b237d3b4f0d2e4c9046157e | 41,825 |
def _dict_printable_fields(dict_object, skip_fields):
"""Returns a list of strings for the interesting fields of a dict."""
return ['%s=%r' % (name, value)
for name, value in dict_object.items()
# want to output value 0 but not None nor []
if (value or value == 0)
and name no... | 776663a70a7f76879722e9ae55feef7ab50d5880 | 41,827 |
def _get_host(self, request, prefix_path = None):
"""
Retrieves the host for the current request prepended
with the given prefix path.
:type request: Request
:param request: The request to be used.
:type prefix_path: String
:param prefix_path: The prefix path to be prepended to the
host... | 9b3c205734820ac03ba8e1e3441e7ea6540fc6c3 | 41,829 |
def create_labels_lookup(labels):
"""
Create a dictionary where the key is the row number and the value is the
actual label.
In this case, labels is an array where the position corresponds to the row
number and the value is an integer indicating the label.
"""
labels_lookup = {}
for idx,... | b80bab4792d4bd403a903c18907d16b2bcb79418 | 41,834 |
from typing import Optional
from typing import List
def str2list(x: str) -> Optional[List]:
"""Convert string to list base on , delimiter."""
if x:
return x.split(",") | 62cd7f087f72981e22f2f8fdc1871a394e00501b | 41,836 |
def mag2Jy(info_dict, Mag):
"""Converts a magnitude into flux density in Jy
Parameters
-----------
info_dict: dictionary
Mag: array or float
AB or vega magnitude
Returns
-------
fluxJy: array or float
flux density in Jy
"""
fluxJy = info_dict["Flux_zero_Jy"] ... | b81d3b8abd10e30e12c33d2a91b42981d2c0d522 | 41,837 |
def buildProcessArgs(*args, **kwargs):
"""Build |CLI| arguments from Python-like arguments.
:param prefix: Prefix for named options.
:type prefix: :class:`basestring`
:param args: Positional arguments.
:type args: :class:`~collections.Sequence`
:param kwargs: Named options.
:type kwargs: :class:`dict`
... | e802e8b35a7b0e6f9bd06e62f29e4dce49580dea | 41,838 |
def strip_suffix(string, suffix):
"""Remove a suffix from a string if it exists."""
if string.endswith(suffix):
return string[:-(len(suffix))]
return string | 0ca354328ce8579fcce4f16f4f0dfdeac4708391 | 41,843 |
def create_url(config):
"""Create github api url."""
return '{base_url}/repos/{repo_owner}/{repo_name}/issues'.format(**config) | 3e3068f7a02ca65d8f2d5a1b987378e3b50d8dba | 41,846 |
def minmax_scale(array, ranges=(0., 1.)):
"""
normalize to [min, max], default is [0., 1.]
:param array: ndarray
:param ranges: tuple, (min, max)
:return:
"""
_min = ranges[0]
_max = ranges[1]
return (_max - _min) * (array - array.min()) / (array.max() - array.min()) + _min | 105dcecb40ac982dcf0973e15b9f2cc80e9a8469 | 41,850 |
def update_zones(
self,
zones: dict,
delete_dependencies: bool,
) -> bool:
"""Configure zones on Orchestrator.
.. list-table::
:header-rows: 1
* - Swagger Section
- Method
- Endpoint
* - zones
- POST
- /zones
.. warning::
... | e4c1470411b75e23df02c3b14398b311d0ca59e1 | 41,855 |
def IsVector(paramType):
""" Check if a param type translates to a vector of values """
pType = paramType.lower()
if pType == 'integer' or pType == 'float':
return False
elif pType == 'color' or pType.startswith('float'):
return True
return False | 58a14693ffabc2230eea0b3f6702aa56ffc514ca | 41,857 |
def secondsToMinutes(times):
"""
Converts splits in seconds to minutes.
"""
return times / 60.0 | 04a97bbadce9ef982fab72fc7dced25aea16c3de | 41,860 |
def calc_frequencies(rolls):
"""
1) Create a list of length 11 named totals with all zeros in it
2) Go through the rolls[][] list with a nested loop;
add the number in rolls[row][col] to the appropriate entry in the
totals list.
"""
# Initialize a list of length 11 na... | 6735e0ab5111fcf51f86f7f9b1d1dcba569652ed | 41,862 |
def getRelativeFreePlaceIndexForCoordinate(freePlaceMap, x, y):
"""
Returns the Index in the FreePlaceValueArray in witch the given Coordinate is in
:param freePlaceMap: The FreePlaceMap to check on
:param x: The X Coordinate to Check for
:param y: The Y Coordinate to Check for
:return: The foun... | 855b5c6e4e225bb5f25b941d84d71756822ec152 | 41,868 |
def rating_class(rating):
"""
Outputs the Bootstrap CSS class for the review rating based on the range.
"""
try:
rating = float(rating)
except ValueError:
return ""
if rating >= 80:
return "success"
if rating >= 50:
return "info"
if rating >= 20:
... | 46bb43032a7193ffe63e91bc261a36eca84da0a6 | 41,870 |
def create_info(type, client_public_key, server_public_key):
"""
Create info structure for use in encryption.
The start index for each element within the buffer is:
value | length | start |
-----------------------------------------
'Content-Encoding: '| 18 | 0 |
... | 0e2dae46522d89c8b099721d05bac6ae0058e64a | 41,879 |
def get_total(alist, digits=1):
"""
get total sum
param alist: list
param digits: integer [how many digits to round off result)
return: float
"""
return round(sum(alist), digits) | 27a26f21e74036a56796f1cc05fcfb88efa41a45 | 41,883 |
import json
def to_json(obj):
"""Object to JSON."""
return json.dumps(obj) | 2029d7507b029ea1d9c11c99a3a9735d0094a3c6 | 41,886 |
import re
def replaceall(replace_dict, string):
"""
replaceall will take the keys in replace_dict and replace string with their corresponding values. Keys can be regular expressions.
"""
replace_dict = dict((re.escape(k), v) for k, v in list(replace_dict.items()))
pattern = re.compile("|".join(lis... | 66c6ec299476986011de21a5f28a613c44435d33 | 41,894 |
def roll_rating(flight_phase, aircraft_class, roll_timecst):
""" Give a rating of the Roll mode : Level1 Level2 or Level 3 according to MILF-8785C
Args:
flight_phase : string : 'A', 'B' or 'C'
aircraft_class : int : 1, 2, 3 or 4
roll_timecst (float): Roll Mode time constante [s]
R... | 7e24ad1cf3c2433ed7b3e5fe7dab8a53b35a6d8d | 41,898 |
def correct_invalid_value(value, args):
"""This cleanup function replaces null indicators with None."""
try:
if value in [item for item in args["nulls"]]:
return None
if float(value) in [float(item) for item in args["nulls"]]:
return None
return value
... | e7c575d45237dce82491e53afeccb953b21e1b33 | 41,906 |
from typing import Dict
def generate_wiki_template_text(name: str, parameters: Dict[str, str]) -> str:
"""
Generate wikitext for template call with name and parameters.
Parameters should not contain unescaped '{', '}' or '|' characters,
otherwsie generated text can be incorrect.
"""
result = ... | 2c785431fed529cafa45a22a824033d284dffd44 | 41,907 |
import importlib
def my_model(opts):
"""Creates model object according to settings in parsed options.
Calls function with name opts.opts2model in module opts.model_module to
create model instance.
Args:
opts (obj): Namespace object with options. Required attributes are
opts.model... | 9c31d2ba15c157cf5f7b15a7cf6fba88ce16a981 | 41,908 |
def group_cpu_metrics(metrics):
"""Group together each instances metrics per app/space"""
grouped_metrics = {}
for metric in metrics:
grouped_metrics.setdefault(metric['space'], {}).setdefault(metric['app'], []).append(metric['value'])
return [(app, space, metric_values,)
for space,... | 91b91601c359e2b80c31b80fcb80bd5915d5972d | 41,915 |
def time2secs(timestr):
"""Converts time in format hh:mm:ss to number of seconds."""
h, m, s = timestr.split(':')
return int(h) * 3600 + int(m) * 60 + int(s) | e06432cd56db691574e8400a23a57982e9177531 | 41,916 |
def convert_arabic_to_roman(arabic):
"""
Convert an arabic literal to a roman one. Limits to 39, which is a rough
estimate for a maximum for using roman notations in daily life.
..note::
Based on https://gist.github.com/riverrun/ac91218bb1678b857c12.
:param arabic: An arabic number, as str... | 6f786c75250fe4da7e7c540acc82a8fc100254a7 | 41,917 |
def compare(a, b):
"""Sort an array of persons with comparator.
Comparator:
- If scores are equal, compare names.
- If a.score is higher than b.score, a should appear first.
- Vice versa.
"""
if a.score == b.score:
return a.name < b.name
return b.score - a.score < 0 | 5f58377a5d783c88cb214230d2823ce319860652 | 41,921 |
def delete_com_line(line : str) -> str:
"""Deletes comments from line"""
comm_start = line.find("//")
if comm_start != -1:
line = line[:comm_start]
return line | e75d74f68222d35e1231a3725d4a34c1d3e768ad | 41,924 |
def flatten_image(img):
"""
takes in an (m, n) numpy array and flattens it
into an array of shape (1, m * n)
"""
s = img.shape[0] * img.shape[1]
img_wide = img.reshape(1, s)
return img_wide[0] | d97d070d9f827f57c79a6714e10d7b4cb8e06a46 | 41,929 |
def non_step(func):
"""A decorator which prevents a method from automatically being wrapped as
a infer_composite_step by RecipeApiMeta.
This is needed for utility methods which don't run any steps, but which are
invoked within the context of a defer_results().
@see infer_composite_step, defer_results, Recip... | f257a882fd5cf9b92e786153ba2a524ead75745e | 41,933 |
def count_calls(results):
"""count number of "call" nodeid's in results"""
return len(list(r for r in results.keys() if r[1]=='call')) | e3ad7fa2fb8577fff615e55514afbcbe1af0ac9d | 41,937 |
import typing
def exclude_header(
headers: typing.Sequence[str], exclude: typing.Set[str]
) -> typing.Sequence[typing.Optional[str]]:
"""
Exclude header.
Exclude columns from header by changing the entry to None.
:param headers: headers
:param exclude: columns to be excluded
:returns: he... | 29d432abcae17848c42b6d238b744157a51ba133 | 41,940 |
def get_locus_blocks(glstring):
"""
Take a GL String, and return a list of locus blocks
"""
# return re.split(r'[\^]', glstring)
return glstring.split('^') | 8981ca07549544f26139c11c21394979658abe2a | 41,944 |
import re
def is_instance_type_format(candidate):
"""Return a boolean describing whether or not candidate is of the format of an instance type."""
return re.search(r"^([a-z0-9\-]+)\.", candidate) is not None | 53568168301800776b5c7f1b39bbeddc8dc0ca0f | 41,946 |
def enforce_file_extension(file, extension):
"""
Returns the given string (file name or full path) with the given extension.
string had no file extension .extension will be appended. If it had another
extension it is changed to the given extension. If it had the given
extension already the unchanged... | 021d69bcc1d4cf3f3fc500e9c8418c60b8c99d9f | 41,947 |
def merge(list1, list2):
"""
Merge two sorted lists.
Returns a new sorted list containing all of the elements that
are in either list1 and list2.
This function can be iterative.
"""
merged = []
idx1 = 0
idx2 = 0
while idx1 < len(list1) and idx2 < len(list2):
... | 57d2bf358d6d0d3353e4b3953e2ddce3c2d28050 | 41,953 |
def read_key_words(file):
"""Reads list of words in file, one keyword per line"""
return [line.rstrip('\n') for line in open(file)] | 337bac4b6c2eac8a36ec372ea90c8bcab8218ed9 | 41,956 |
def bk_nearest_neighbor_search(search_string, tree):
"""
Search tree for nearest matches to supplied string.
Parameters
----------
search_string : str
search string
tree : BKTree
tree to search
Return values
-------------
matches : list
list of strings conta... | b86f0663f711aea29abbb79e203ee74452d34207 | 41,959 |
def month_id(dte):
"""
Return an integer in the format YYYYMM.
Argument:
dte - the dte to use in making the month id.
"""
result = dte.year * 100 + dte.month
return result | ab5fcab351e7884b05803d0077d0eec473d08fa5 | 41,961 |
def delete_snapshot(connection, snapshot_id=None):
"""Deletes a snapshot.
* connection: An ec2 connection instance.
* volume_id: ID of snapshot to delete.
Returns True if deletion is successful.
"""
return connection.delete_snapshot(snapshot_id) | 702bfffaa7d69453613e42aefcb019963191b152 | 41,964 |
import threading
def _get_internal_name(name):
"""Returns the internal thread-local name of an attribute based on its id.
For each specified attribute, we create an attribute whose name depends on
the current thread's id to store thread-local value for that attribute. This
method provides the name of this th... | 522a686ab7aaca18dfa8e2ac667881b15a75fd32 | 41,967 |
def gcd_step(a, b):
"""
Performs a single step of the gcd algorithm.
Example: gcd_step(1071, 462) == (2, 147) because 1071 == 2 * 462 + 147.
"""
if a < b:
return (0, b)
res = 0
while a >= b:
a -= b
res += 1
return (res, a) | 02eedde8652a285c1b7af999d439c9fe77349d3f | 41,970 |
def generate_Q_data(Q):
"""
問題のテキストデータを生成する。改行コードはCR+LFとする。
Parameters
==========
Q : tuple
read_Q()の返り値
Returns
=======
txt : str
問題のテキストデータ
"""
crlf = '\r\n' # DOSの改行コード
size, block_num, block_size, block_data, block_type, num_lines = Q
txt = 'SIZE %d... | 70c3c1c0b2550a6805b1b2abedf0e5b115377e05 | 41,977 |
def get_feature_names(factors_path):
"""
Get feature names by reading header of factors csv
Args:
factors_path: path to factors csv with names of features as header
Returns:
list(str): list of column names read from file
"""
with open(factors_path) as f:
col_names = f.... | 0e224a610d9b4f072d76562b6efb0fb675eab5e0 | 41,978 |
def _transitive_parenthood(key,
term_dict):
"""Finds all parents, transitively, of `key` in `term_dict`.
Does not include itself in the set of parents, regardless of the type of
relation. This is left to the caller to decide.
Args:
key: Go Term, e.g. GO:0000001
term_dict: Go... | 9c3aa32ad90d02965aad67ffa436b0d02af65ba4 | 41,984 |
def organize(iterable, key):
"""Put all of the elements in `iterable` into
a dictionary which maps possible return values
of key onto lists of items of iterable
iterable - any iterable object (e.g. a list, or tuple)
key - a function that takes items in interable as inputs
... | 19edcc50738a0247e57c0b7c4d1812e63000b7ef | 41,985 |
def __getWindow(window_config:str): #Called in genImgPatches()
"""Parses window_config to get height and width as integers
Args:
window_config (str): string of window height and width. Example: '5000,5000'
Outputs:
window (dict): diction... | 8f9a9858f9f96c5f2698f922b63f2e7d328138a9 | 41,986 |
def get_slot(datetime_sec, band):
"""
Return IBP schedule time slot (0 ... 17) from given datetime_sec (second
from UNIX time epoch) and band (14, 18, ..., 28) MHz value
"""
time_xmit = 10 # sec (transmitting time length)
n_slots = 18 # number of slots
period_sched = n_slots * time_xmit
... | 0566887707e280b5c31f1ae87a3b443757421ce7 | 41,990 |
from unittest.mock import call
def fsl_cluster(finput, findex, thresh=0.9, fosize=None, fothresh=None, **kwargs):
"""
Run FSL Cluster command (https://fsl.fmrib.ox.ac.uk/fsl/fslwiki/Cluster)
:param str finput: Input filename, image to be thresholded
:param float thresh: Chosen threshold; default = 0.9... | cf314748daaeb9880ebc9c914f880eaa091fa0f9 | 41,993 |
def form_for_field(config, field):
"""
Gets the form name which contains the field that is passed in
"""
for form in config['forms']:
if field in form['csv_fields'].values():
return form['form_name'] | d960154bbf473a2e8a730fd74fd70c3896620df0 | 41,994 |
def evaluate_chi2(chi2: float, gt_chi2: float, tol: float = 1e-3):
"""Evaluate whether chi square values match."""
if chi2 is None:
return False
return abs(chi2 - gt_chi2) < tol | 2277365b1eb87d6591634ee92abe7380eec4e77f | 41,995 |
import ast
def copy_location(new_node, old_node):
"""An ast.copy_location extension.
This function behaves identically to the standard ast.copy_location except
that it also copies parent and sibling references.
"""
new_node = ast.copy_location(new_node, old_node)
new_node.parent = old_node.pa... | ac827c9edf2a8de6c7abb1f6fd23eca8480c8cc4 | 41,996 |
def get_latitude(dataset):
"""Get latitude dimension from XArray dataset object."""
for dim_name in ['lat', 'latitude']:
if dim_name in dataset.coords:
return dataset[dim_name]
raise RuntimeError('Could not find latitude dimension in dataset.') | 6a0eb8cbe27c0a802133ec80f7feb7f11afe8b15 | 42,000 |
async def get_indexed_tags(redis):
"""Get all tags monitored for indexing.
Args:
redis (aioredis.Redis): a Redis interface.
Returns:
A list of monitored tags as `str` objects.
"""
return await redis.lrange('indexed_tags', 0, -1, encoding='utf-8') | 5f9c7cd1c2eb89e04013ddfd6fdb81d24b4d5685 | 42,003 |
def linear_search(l, item):
"""
Liner Search Implementation.
Time O(n) run.
O(1) space complexity, finds in place.
:param l: A List
:param item: Item from the List or N/a (-1).
:return:the founded index of the wanted item.
"""
for i in range(len(l)):
if item == l[i]:
... | 18369cdf07bd4784e21bb01b8a3545c5d742e5cf | 42,004 |
import functools
def dec_check_lines(func):
"""
Decorator to check the currently displayed lines on the LCD to prevent rewriting on the screen.
"""
@functools.wraps(func)
def wrapper(self, *args, **kwargs):
str_args = str(args) + str(kwargs)
if self.lines != str_args:
... | 104be359535ed3ac11b40dc2a578eea73915ad15 | 42,008 |
def circumcircle(u, v, w):
"""find the center/radius of circumcircle of triangle uvw"""
vu, wv, uw = (u - v), (v - w), (w - u)
d = 2 * ((u - v).crs(v - w)).dot((u - v).crs(v - w))
a = (v - w).dot(v - w) * (u - v).dot(u - w) / d
b = (u - w).dot(u - w) * (v - u).dot(v - w) / d
c = (u - v).dot(u - ... | ee824a1ccc96663d1e347057938b1a6fc4da80ac | 42,010 |
def convert_ms(ms):
"""
Converts milliseconds into h:m:s
:param ms: int
:return: str
"""
seconds = (ms / 1000) % 60
seconds = int(seconds)
if seconds < 10:
seconds = "0" + str(seconds)
else:
seconds = str(seconds)
minutes = (ms / (1000 * 60)) % 60
minutes = ... | 1b39e0ac151fbdf6a3e7a6a15e83c36ff40e0810 | 42,011 |
def GetASTSummary(ast):
""" Summarizes an AST field
Flags:
P - AST_PREEMPT
Q - AST_QUANTUM
U - AST_URGENT
H - AST_HANDOFF
Y - AST_YIELD
A - AST_APC
L - AST_LEDGER
B - AST_BSD
K - AST_KPERF
M - AST_MACF
C - AST_CHUD
... | af6bd56509666162501dee0e3077a6470b9a6c0a | 42,016 |
def is_number_tryexcept(s):
"""
Returns True if string `s` is a number.
Taken from: https://stackoverflow.com/questions/354038/how-do-i-check-if-a-string-is-a-number-float
"""
try:
float(s)
return True
except ValueError:
return False | 569f73b4be50e1ddb4157ec98e59c2310d874412 | 42,019 |
import six
def split_ver(v):
"""Split v into a list of integers.
Args:
v (:obj:`str` or :obj:`list` of :obj:`int` or :obj:`int`):
Version string to split using periods.
Returns:
:obj:`list` of :obj:`int` or :obj:`str`
"""
v = v.split(".") if isinstance(v, six.string_... | c3bebb064c229c65c306f0cf40697337e2884a3b | 42,031 |
def overlap(x):
"""Function to define the overlap between two lists contained in a pandas dataframe
1) return the length of the drug shared list
Parameters
----------
x : Dataframe
Dataframe containing the drug list related to the side effect and the drug list related to the target
"""
... | fb3fe3a74583b5c719d8a32d0c93d56d5d70dc9b | 42,035 |
def distance2(x1, y1, z1, x2, y2, z2):
"""Calculates the distance^2 between point 1 and point 2."""
return (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2) + (z1 - z2) * (z1 - z2) | ff2740fe1ce3e52e336a18dca9c4f7bb504cacf4 | 42,038 |
from textwrap import dedent
def dedent_nodetext_formatter(nodetext, has_options, caller=None):
"""
Just dedent text.
"""
return dedent(nodetext) | 7a4a06a68470f75eba26aa311b99f85a2859367a | 42,039 |
def get_grid(size):
"""Create grid with size."""
return [[[] for _ in range(size)]
for _ in range(size)] | 53db2ac06d8ada944575d022685bbf2f21929b09 | 42,040 |
def format_datetime(value, format="%B %d, %Y"):
"""Format a date time to (Default): Month Day, LongYear"""
if value is None:
return ""
return value.strftime(format).lstrip("0").replace(" 0", " ") | 747a31ff83a2497d7d3257d7311e7e18071b5848 | 42,041 |
def noop_walk(_data, _arg):
"""
No-op walker.
"""
return 0 | 4f60f855d7d3671ca61bd64b19f47524dc560ebe | 42,043 |
def work_dir(tmpdir):
"""Return temporary directory for output/input files."""
return tmpdir.mkdir('work_dir') | 952bf3fbe1a81a43a37d35e255a6ddc97a1a18ee | 42,044 |
import six
def _IsUrl(resource_handle):
"""Returns true if the passed resource_handle is a url."""
parsed = six.moves.urllib.parse.urlparse(resource_handle)
return parsed.scheme and parsed.netloc | 8ebd20a55c168cbefd243cbc01c87ea051a35c52 | 42,046 |
def run(state, initial):
"""
Run the stateful action ``state`` given initial state ``initial``.
Equivalent to ``state.run(initial)``.
:return: A tuple of ``(a, s)``, where ``a`` is the value of the action,
and ``s`` is the new state.
"""
return state.run(initial) | 6204133fe147ff3ab6fd68cb69e697391ffa65f6 | 42,054 |
def author() -> str:
"""
It gets the authors string.
:return: See description.
:rtype str.
"""
return '(c) 2020 Giovanni Lombardo mailto://g.lombardo@protonmail.com' | 8275d724299012f8bac866db512e695b97a87b2a | 42,056 |
def _matches_to_sets(matches):
"""
Helper function to facilitate comparing collections of dictionaries in
which order does not matter.
"""
return set(map(lambda m: frozenset(m.items()), matches)) | 4e8b38131130275c1ced0c960c0f6ef6d59c4790 | 42,057 |
def eval_precisions(scores, targets, topk=(1,)):
"""Computes the precision@k for the specified values of k
Args:
scores: FloatTensor, (num_examples, num_classes)
targets: LongTensor, (num_examples, )
"""
maxk = max(topk)
num_examples = targets.size(0)
_, preds = scores.topk(maxk, 1, largest=True, s... | 42e76d0b036b39a7531cdcbde6c7ebc3fa6ff13f | 42,058 |
def escape(query):
"""Escape a value to be used in a query"""
query = query.replace("\\", "\\\\")
query = query.replace("|", "\\|")
query = query.replace("*", "\\*")
return query | 8eb162fc3eae6bc9c54257f33273ac8fee19637c | 42,060 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.