content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import decimal
def dround(decimal_number, decimal_places):
"""Round decimal_number up to decimal_places
:type decimal_number: decimal.Decimal
:param decimal_number: Decimal number.
:type decimal_places: integer
:param decimal_places: Number of decimal places to keep.
:rtype: decimal.Decimal... | be35ff43dbc051cf51a71849312ed80a3ece25a7 | 74,700 |
def owns_post(self, post):
"""
Whether the user owns a post
:param (User) self: The acting user
:param (Post) post: the post
:return (bool): whether the user owns the post
"""
return self.id == post.author.id | a411860cfa2b53026714584ee36d8aa671fdef31 | 74,701 |
def _convert_snake_to_kebab(snake_case_string: str) -> str:
"""
Convert a string provided in snake_case to kebab-case
"""
return snake_case_string.replace('_', '-') | 4539e049ead6a307bb4cea3cc5164b0925a4b600 | 74,706 |
def select_order(axtypes):
"""
Returns indices of the correct data order axis priority given a list of WCS CTYPEs.
For example, given ['HPLN-TAN', 'TIME', 'WAVE'] it will return
[1, 2, 0] because index 1 (time) has the lowest priority, followed by
wavelength and finally solar-x.
Parameters
... | dd5baf190a7fcf6c5b59e0b3a1877c3ac32d93eb | 74,707 |
def createFactorialTrialList(factors):
"""Create a trialList by entering a list of factors with names (keys)
and levels (values) it will return a trialList in which all factors
have been factorially combined (so for example if there are two factors
with 3 and 5 levels the trialList will be a list of 3*5... | e6019c97e6cf863df52575226b98d9324c31554b | 74,713 |
import json
def _from_json(filepath):
"""Load a json file to a dictionary."""
if not filepath:
return dict()
with open(str(filepath)) as lic_json_file:
return json.loads(lic_json_file.read()) | 3d1a28922116782b3867cab64c573111e5f39fa9 | 74,714 |
def comprobar_colision(p_activo, area, evento):
"""
Comprueba si hay colision y devuelve un booleano
:param p_activo: booleano que modificara
:param area: area en la que comprobara la colision
:param evento: evento que colisiono
:return: booleano con los datos de la colision
"""
if area.... | cc918eacf1d975bdd37d4f0535c46b361ff9da93 | 74,725 |
def group_member_ids(ppl_coll, grpname):
"""Get a list of all group member ids
Parameters
----------
ppl_coll: collection (list of dicts)
The people collection that should contain the group members
grp: string
The id of the group in groups.yml
Returns
-------
set:
... | 1ffc8c04ad05986bd681c7775b72a688ec8e984f | 74,726 |
from datetime import datetime
def age_check(agent_behavior, observation, scale):
"""
:param agent_behavior: Metrics to be used the agent.
:type agent_behavior: dict
:param observation: Content and metadata of message received and on which the trust is calculated.
:type observation: Observation
... | 86e15ac1d1e250a0fc9422887b04ce90148fea5c | 74,729 |
def flatten_filter(value):
"""Combine incoming sequences in one."""
seq = []
for s in value:
seq.extend(s)
return seq | 927a7f7e23154cd28f8b89e5867847abe17ef4c4 | 74,735 |
def EncodeFromLinkArray(m,N,L):
"""
EncodeFromLinkArray(m,N,L):
m: A list of 0s and 1s representing 'message bits'.
N: Length of the code.
L: A link array representing rows in a binary generator matrix.
Specifically, L[i] contains a list indicating the positions
in row ... | 74ff2dfd31596a7979cf48c5d491b049615a27b3 | 74,747 |
def get_answers(question):
"""extract unique answers from question parses."""
answers = set()
for parse in question["Parses"]:
for answer in parse["Answers"]:
answers.add((answer["AnswerArgument"],
answer["EntityName"]))
return answers | 29331ad07a37a1c4124e8769e7bcd9e09a1bed63 | 74,749 |
def classify_turn_direction(relative_azimuth, straight_angle=20):
"""Classify turn directions based on a relative azimuth
"""
if (relative_azimuth < straight_angle) or (relative_azimuth > (360 - straight_angle)):
return 'straight'
elif (relative_azimuth >= straight_angle) and (relative_azim... | 72150dffe470b2a70d4f0eff2875442506e6878a | 74,758 |
import torch
def TorchComplexExp(phase):
"""
e^(i*phase) =
cos phase + i sin phase
:param phase:
:return: Complex output
"""
real = torch.cos(phase)
imag = torch.sin(phase)
return torch.stack((real, imag), dim=-1) | c845260b00a1ad15a8d18a51ba8100190d0f7627 | 74,759 |
def munge_ram32m_init(init):
""" RAM32M INIT is interleaved, while the underlying data is not.
INIT[::2] = INIT[:32]
INIT[1::2] = INIT[32:]
"""
bits = init.replace("64'b", "")[::-1]
assert len(bits) == 64
out_init = ['0' for _ in range(64)]
out_init[::2] = bits[:32]
out_init[1::2... | 04a310c594fdbbe003da68244af26519941824e0 | 74,761 |
import random
def generate_n_ints(num: int = 6) -> list:
"""Generate a list of `num` pseudo-random integers
Args:
num (int, optional): N integers to generate. Defaults to 6.
Returns:
list: list of pseudo-random integers
"""
return [random.randrange(256) for _ in range(num)] | 162077cdcbc30465237379471f3797a2ed0c0ba9 | 74,762 |
def is_str(x):
"""judge x is a str type object
Args:
x : input x
Returns:
[bool]:
- True for x is str,
- False for x is not str
"""
return isinstance(x, str) | 24da09fa762e550d7f543845a475dfb990f8cfcc | 74,770 |
import re
def to_camel_case(s):
"""Converts a given string `s` to camel case."""
s = re.sub(r"(_|-)+", " ", s).title().replace(" ", "") # noqa
return ''.join(s) | fbc83a160239a79ca19a222728f0a25d56696ef7 | 74,772 |
import re
def extract_uuids_from_string(source_string):
"""
Extract uuids out of a given source string.
Args:
source_string (Source): string to locate UUIDs.
Returns:
([]) List of UUIDs found in the source string
"""
uuid_regex = "[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89... | 81b22220ae361360812a2e2ff98d82512c003e99 | 74,773 |
def my_languages(results: dict) -> list:
"""Returns all languages with score at least 60
Args:
results (dict): mapped languages with scores
Examples:
>>> assert my_languages({"Java": 10, "Ruby": 80, "Python": 65}) == ["Ruby", "Python"]
"""
return [
language
for lang... | 135d798d83099be71a0bc07b9cf3907cf76d5945 | 74,778 |
def cursor_query_response_to_dict(cursor):
"""
Turns cursor list-tuple response into a list-dict response;
Exhausts the cursor
"""
columns = cursor.column_names
results = [{col : item for col,item in zip(columns, res)} for res in cursor.fetchall()]
return(results) | d146835035724226cfbb76088e806bb814532408 | 74,782 |
def format32BitHexStr(hexStr):
"""
format the given string which represents a valid 32-bit hexadecimal number.
prefix "0x" will be added and will replace any valid prefix.
alphabetic letter will be formatted into upper case.
"0" will be used to fill the hexadecimal number if this number is represent... | 8005b20e34a29cd1a839c828dfcfa2c169ba0d66 | 74,790 |
def MODULE_PATH(analysis_module):
"""Returns the "module_path" used as a key to look up analysis in ACE."""
return '{}:{}'.format(analysis_module.__module__,
analysis_module.__name__ if isinstance(analysis_module, type) else type(analysis_module).__name__) | fe0efb189899364d4141fc0d13ae1669bf950394 | 74,797 |
def _get_scale(image, md_path_or_scale):
"""Get a valid scale from an image and a metadata path or scale.
Parameters
----------
image : np.ndarray
The input image.
md_path_or_scale : float or image filename
The path to the file containing the metadata, or the scale.
Returns
... | 6552040bac03649d2493b3bb1dc4b7980c3f1a5e | 74,801 |
from typing import Dict
from typing import Any
def purge_none(d: Dict[Any, Any]) -> Dict[Any, Any]:
"""Purge None entries from a dictionary."""
return {k: v for k, v in d.items() if v is not None} | 2f23c0b43863dae7f9fe5cc5c43650a6fc1b99e1 | 74,804 |
import math
def get_angle(point1, point2, point3):
"""
Calcula o ângulo interno de um triângulo passando três pontos, ou o ângulo entre uma
reta formada pelos pontos 1 e 2 e reta formada pelos pontos 1 e 3.
:param point1: tupla com as coordenadas x e y do primeiro ponto
:param point2: tupla com as... | 2d75c405ad786df711c6a509d575121b6e7563f7 | 74,810 |
def get_missing_coordinate(x1: float, y1: float, x2: float, angular_coefficient: float = -1.0) -> float:
"""Returns the y2 coordinate at the point (x2, y2) of a line which has an angular coefficient of
"angular_coefficient" and passes through the point (x1, y1)."""
linear_coefficient = y1 - (angular_coeffic... | 75c7bc35b76af10c7ca315f268bff13ead3361b4 | 74,812 |
def _point_mass(x, threshold=0.1):
"""
Find point masses in pandas.Series with frequency exceeding
specified value
Parameters
----------
x : pandas.Series
threshold : float
If value frequency exceeds threshold, consider value to have
point mass
Returns
-------
... | 82ee24d1aaf9a3eb6497d5ef09c84bb6ef4c5323 | 74,819 |
def _generateSpecial_MeshOpts_flatShading(
overlayList, displayCtx, source, longArg):
"""Returns no argument - the :attr:`.MeshOpts.flatShading` option is
deprecated.
"""
return [] | 7389e7a33e8b000750c14923a267e35006f45c98 | 74,823 |
def remove(i_list: list)-> list:
"""
Given an input list return a list without all the negative numbers
:param i_list: The source list
:return: A list with all positive member of i_list
"""
_shallow_list = []
for element in i_list:
if element >= 0: _shallow_list.append(element)
r... | 14d8cb43711ca724a8161f748d59f790303c8c91 | 74,825 |
def calc_centers(edges):
"""
Simple method for returning centers from an array of bin edges. Calculates center between each point as difference between containing edges.
Example, plt.plot(bicorr.centers(edges),counts,'.k')
Serves as a shortcode to first producing array of bin centers.
Paramete... | 6c25fa0c5b771dbf2e80675d7a01ba8c8dd8aa19 | 74,831 |
def FRZRAIN(conf, value):
"""Get Freezing Rain Color code from config"""
if value == 1:
return conf.get_color("colors", "color_frrain1")
else:
return conf.get_color("colors", "color_frrain2") | 71dcb4f5d0d8f03d5764c4e2ff8acdfdb57a66d4 | 74,833 |
def function_task_2(params):
""" Function given by task
:param params: [x, y]
:return: function value
"""
x, y = params
return (1.5 - x + x * y)**2 + (2.25 - x + x * y**2)**2 + (2.625 - x + x * y**3)**2 | d289296aab94116e552b85f6dfb42f5ecf9a9096 | 74,836 |
import re
def process_column_labels(list_of_labels):
"""Removes undesired spaces.
Parameters:
list_of_labels: list
list with column labels
Returns:
list_of_cleaned_labels: list
A list with cleaned lables
"""
list_of_cleaned_labels = [
re.sub(" +"... | 893cbce75c9212da747d640630fe9f025df3a19f | 74,838 |
from typing import Dict
def get_github_config(config: Dict[str, str]) -> Dict[str, str]:
"""
Get configuration keys for GitHub API.
:param config: app config
:type config: Config Class
:return: key-value dictionary of required GitHub keys
:rtype: dict
"""
return {
'deploy_key'... | a426aee55dec84c1e89b91738e3c67cf60a91288 | 74,840 |
import logging
async def _download_text(url, session):
"""Asynchronously request a URL and get the encoded text content of the
body.
Parameters
----------
url : `str`
URL to download.
session : `aiohttp.ClientSession`
An open aiohttp session.
Returns
-------
conte... | a198948876ddaa79a1e6bcdb0ce29471e55c02f2 | 74,842 |
def is_default(method):
"""Check if a method is decorated with the `default` wrapper."""
return getattr(method, "_is_default", False) | 933d9fd4a5b7eb3436e68b93f514cd4ce2acb5ca | 74,845 |
def clean_visits(data, test, n_visits=100):
"""
Drops rows of `data` with too few entries for given `test`
Parameters
----------
data : pandas.DataFrame
Must have at least columns 'visit' and `test`
test : str
Column of `data` used to determine which rows to drop
n_visits : ... | 021ed80298e9e5df7da79a169dac00a3d351656a | 74,854 |
def less(compare_item):
"""
Ensures the filtered item is less than the compare_item
result < compare_item
:return: Callback to be used by the query search.
"""
def callback(item):
return item < compare_item
return callback | 3b19cb2ae52845b6b5726b817e440e5a2dc2065b | 74,858 |
def method_cache_counter(space, name):
"""Return a tuple (method_cache_hits, method_cache_misses) for calls to
methods with the name."""
assert space.config.objspace.std.withmethodcachecounter
ec = space.getexecutioncontext()
return space.newtuple([space.newint(ec.method_cache_hits.get(name, 0)),
... | b2a43132521a1ca255387036d878ce6b7b13ac7c | 74,862 |
from typing import Union
from pathlib import Path
from typing import Any
import pickle
def load_pickle(filepath: Union[str, Path]) -> Any:
"""Load pickled data from disk
Args:
filepath: Path to pickle file
Returns:
Contents of pickle.
"""
with open(filepath, "rb") as f:
r... | 983b0879385685f942a89b61ea64c9a347f961c6 | 74,868 |
from typing import Union
def get_cell_sizes(cell_size: Union[int, list, tuple]):
"""Handle multiple type options of `cell_size`.
In order to keep the old API of following functions, as well as add
support for non-square grids we need to check cell_size type and
extend it appropriately.
Args:
... | b372c2a960f59d861f08eaecbbc2f7499226272e | 74,874 |
def get_severity(severity_int):
"""
helper meethod to swap severities
:param severity_int: integer value for severity
:return: collectd string for severity
"""
return {
1: "FAILURE",
2: "WARNING",
4: "OKAY"
}[severity_int] | 801479225422222e7339d54c2391893624fb58f4 | 74,875 |
def get_trf_command(command, transformation=""):
"""
Return the last command in the full payload command string.
Note: this function returns the last command in job.command which is only set for containers.
:param command: full payload command (string).
:param transformation: optional name of trans... | 8beedf188fcb3c24fd2bc855f0e2549484c18e3a | 74,881 |
def flip_edge(graph, edge):
"""
Flips an edge in a networkx graph.
:param graph: a target graph
:param edge: edge to flip
:return: None
"""
if graph.has_edge(*edge):
graph.remove_edge(*edge)
else:
graph.add_edge(*edge)
return None | 3f5bf91118137e12cc0367d9cc03b5befbf3e56a | 74,882 |
def props_boot(props):
"""Accesses boot properties."""
return props["boot"] | aed52522fac4349ec88414edda227e7743194143 | 74,884 |
def wp_sortkey(string):
"""Help function to sort WPs. Use as
wps = ['Medium','Tight','Loose','VTight','VLoose','VVTight']
sorted(wps,key=wp_sortkey)
"""
lowstr = string.lower()
if lowstr.startswith('medium'):
return 0
elif lowstr.lstrip('v').startswith('loose'):
return -1*(lowstr.count('v'... | 220117582b9992e9a4db5487bb320fcbf3b21cf6 | 74,885 |
def merge_dictionaries(dict1: dict, dict2: dict) -> dict:
"""
Returns a merged dictionary
Parameters:
dict1 (dict): A dictionary.
dict2 (dict): A dictionary.
Returns:
result (dict): The merged dictionary.
"""
result = {**dict1, **dict2}
return result | aca9c885ec6102a4913e13fd1528a25bdc036b33 | 74,886 |
def P_trans(N, M, DeltaJ, DeltaM):
"""
Calculates transition probability.
Parameters
----------
N : int
Total rotational angular momentum quantum number
M : int
Magnetic quantum number
DeltaJ : int
Change in rotational quantum number
DeltaM : int
Change i... | 9913ea43117a9bb322aec610c435501a2fe3d2b3 | 74,892 |
from typing import Optional
from typing import List
def parse_skip(line) -> Optional[List[int]]:
"""Returns None if the line is not a exdown-skip statement
Otherwise returns the lines to skip (numbering starts at 1).
The empty list indicates that the whole block must be skipped."""
line = line.lstrip(... | 41d3d7d8252fa263b6befd654ef92bf866dde7fa | 74,894 |
import requests
import json
def post(url, data = {}):
"""
Submit http post to a URL and parse the JSON that's returned
:param url: The URL to post to
:param data: Map defining the post params to submit. keys and values should be strings
:return: The JSON response
"""
r = requests.post(url,... | 28b744294f9a49bd74a7ffe87478cd7762dc10fd | 74,897 |
def _median(sorted_list):
"""Returns median value for specified sorted list.
Parameters
----------
arr: List[float]
Returns
-------
float
"""
assert sorted_list, "List is empty"
n_items = len(sorted_list)
return 0.5 * (sorted_list[(n_items - 1) // 2] + sorted_list[n_items ... | 5e31d6390a4f490e48e6d172fd5f2f3dcdbf5742 | 74,899 |
def data(prod, data):
"""Parse data using production and return the unboxed value from
the result of read()."""
(result, _) = prod.read(data)
return result | 870a28d5a09e92b9642ec16465be2f6441da69ca | 74,901 |
from datetime import datetime
def get_model_name(params):
"""
Return the model name according to the hyperparameters and creation time.
"""
creation_time = datetime.now().strftime('%Y%m%d_%H%M%S')
# Name to be used for the model
model_name = "{}_nc{}_bs{}_ep{}_lr{}_ld{}_df{}_uf{}_bt{}_cr{}_b... | 985aea874332ad43ca35ffc5b493ecaefe3e3291 | 74,905 |
def bezout(a, b):
"""Bézout coefficients for a and b
:param a,b: non-negative integers
:complexity: O(log a + log b)
"""
if b == 0:
return (1, 0)
u, v = bezout(b, a % b)
return (v, u - (a // b) * v) | bbfcd5e4f57d34291aced2356b021047f9bbd4c3 | 74,910 |
def isOnBoard(x, y):
"""Returns True if (x, y) is on the board, otherwise False."""
return x >= 0 and x <= 59 and y >= 0 and y <= 14 | f37d4b0c95403d4549946fe49543238209576db2 | 74,918 |
import re
def clean_text(text: str):
"""Returns string:
1. Stripped of all whitespaces at start and end
2. Any excess whitespace in between are replaced with an underscore "_"
3. All characters are lowercased
"""
clean_text = re.sub(' +', '_', text.strip()).lower()
return clean_text | f61c6c4ed16ba0efce441c4c6398b4414dfb68cf | 74,920 |
def _override_license_types_spec_to_json(override_license_types_spec):
"""
Given an override license types spec, returns the json serialization of the object.
"""
license_type_strings = []
for license_type in override_license_types_spec:
license_type_strings.append("\"" + license_type + "\""... | 57ab635a35c44e9deddeb015f197a1b071f8d4ff | 74,922 |
def channel_form(channels):
"""Construct HTML for the channel selection form."""
channel_checkbox_form_html = \
"<input type=\"checkbox\" name=\"channel\" value=\"{0}\">{0}"
channel_form_html = ""
for channel in channels:
channel_form_html = \
channel_form_html + \
... | 6632e24c23639e7f328c3260627591ae61e994fc | 74,925 |
def add_sample_dimension(F, array):
"""
Add an extra dimension with shape one in the front (axis 0) of an array representing samples.
:param F: the execution mode of MXNet.
:type F: mxnet.ndarray or mxnet.symbol
:param array: the array that the extra dimension is added to.
:type array: MXNet ND... | a4377bdf3295cd37cdcb21e1a54c23bb04799209 | 74,928 |
def _is_sorted(arr):
""" Returns `True` if the array is sorted ascendingly and `False if it isn't."""
i = 0
while (i+1 < arr.shape[0]):
if arr[i] > arr[i+1]:
return False
i += 1
return True | 20f6c3e29cffee88a88b95286f82f04053bd0eec | 74,939 |
def join_if_not_empty(items, sep=" "):
"""
Joins a list of items with a provided separator.
Skips an empty item.
"""
joined = ""
for item in items:
if item and len(item) > 0:
if joined != "":
joined += sep
joined += item
return joined | f67d6ba33714dae9dce0c3a85172e8ae83562e24 | 74,941 |
def load_data(file_name: str = 'sample1') -> list:
"""
Loads example
:param file_name: file name of example
:return: list loaded data
"""
date = ''
file = open(file_name)
try:
date = file.readlines()
except:
print("Zły format pliku !")
finally:
file.close(... | a4cce21023bc30a60fc47319d2d22919bf0facb8 | 74,945 |
def lorentzian(x,dc,a,gamma,centre):
"""Single Lorentzian function.
Parameters:
dc: float
baseline
gamma: float
linewidth
centre: float
peak centre
x: array
input parameter
returns a Lorentzian function
"""
lorentzian = dc + a*gamma**... | 371eb2a95a0381490099ff77d39560da093addf4 | 74,948 |
def _flatten(params):
"""Flatten the list objects in a list of DB-API parameters,
e.g. `[1, [2, 3]]` becomes `[1, 2, 3]`.
"""
params_flat = []
for param in params:
if isinstance(param, list):
for item in param:
params_flat.append(item)
else:
pa... | d9c87149e06c410014e70132c14b7143cbde8f67 | 74,951 |
import glob
import random
def get_images_paths(pattern='../data/*.jpg', size='full', test_percentage=0.2,
fast_set_size=300, verbose=False):
"""Return path of images that matches glob pattern.
Args:
pattern (str): glob pattern.
size (str): 'fast' for reduced dataset size,... | ddf50d311b1be8fc6f3ad443634a524286f8f949 | 74,952 |
def get_elements(tree, tag_name):
"""
returns a list of all elements of an XML tree that have a certain tag name,
e.g. layers, edges etc.
Parameters
----------
tree : lxml.etree._ElementTree
an ElementTree that represents a complete SaltXML document
tag_name : str
the name o... | b51ee50855d7eb0c05c6b2ef9b4a7ab36f356c27 | 74,953 |
def float_or_int(v):
""" cast to int if possible or to float """
vf = float(v)
try:
vi = int(vf)
if vi == vf:
return vi
except:
return vf | a85929972b5458bc83f67dbeebc998f8af1a2b5b | 74,956 |
def number_of_tokens(sentences, category=None):
"""
Count the number of words in sentences
If category is given, only count words of this category, otherwise count all
Args:
sentences (list) : the list of Sentence objects
category (str, default None) : the category to count
Return:
... | 4d3261355417d8c474f9861f1750a89092852e63 | 74,960 |
import re
def _filter_tre_measure_columns(df_experiments):
""" get columns related to TRE measures
:param DF df_experiments: experiment table
:return tuple(list(str),list(str)):
"""
# copy the initial to final for missing
cols_init = [col for col in df_experiments.columns if re.match(r'(r)?IR... | f215a3474362d97066770112c01ccc1e4f7e532c | 74,963 |
def get_accessor(identifier: str) -> str:
"""
Given a SeqRecord identifier string, return the access number as a string.
e.g. "ENSG00000004776|ENSG00000004776.13|ENST00000004982|ENST00000004982.6" -> "ENST00000004982.6"
"""
parts = identifier.split('|')
assert len(parts) == 4
return parts[3] | d0018b103145f805c52c13e5f1d95a0baa575c7f | 74,965 |
def rectifier(Iload, fswitch, dVout):
"""
rectifier Function
Returns the capacitance (in Farads) for a needed capacitor in
a rectifier configuration given the system frequency (in Hz),
the load (in amps) and the desired voltage ripple.
Parameters
----------
Iload: float
... | 2b0ec7973d6d9a80df4f79cd6139245eeb7ababe | 74,966 |
import csv
def read_csv(csv_path, id_column=0, delimiter=","):
"""
Reads tsv file content into a dict. Key is the id column value and the value is list of row values
Args:
csv_path: Path of the CSV file
id_column: Id column becomes the key of the dict. This column should be unique. Default... | cd0831e26082648e385fa9e345339d869daf9bec | 74,968 |
def tan2tantwo(tan: float) -> float:
"""returns Tan[2*ArcTan[x]] assuming -pi/2 < x < pi/2."""
return 2 * tan / (1 + tan) / (1 - tan) | 6f6317e0594c6965445d9e2588218af85671c198 | 74,972 |
def fao56_penman_monteith(net_radiation, temperature_mean, ws, latent_ht, sat_vp, avp,
delta_sat_vp, psy, sol_rad, shf=0.0, time_period="15min"):
"""
Estimate reference evapotranspiration (ETo) from a hypothetical
short grass reference surface using the FAO-56 Penman-Monteith equat... | 3f3501e3753b63f35237cf595ec026a51bb51640 | 74,975 |
def date_filter_okay(df, start, end):
"""
Boolean check of whether DataFrame has data between 2 dates
Parameters
----------
df : pandas.DataFrame
data to check
start : datetime-like
start time
end : datetime-like
end time
Returns
-------
bool
"""
... | 3abcea68df64f248b8eda1f7b491e98981835d6d | 74,977 |
def data_reader(file_path, col_sep='\t'):
"""
Load data
:param file_path:
:param col_sep:
:return: list, list: contents, labels
"""
contents = []
labels = []
with open(file_path, 'r', encoding='utf-8') as f:
for line in f:
line = line.rstrip()
parts = ... | 30f93637eb3047f6d146942787e9377c78598c9b | 74,978 |
import hashlib
def md5(filename):
"""
Creates the MD5 hash of a file.
:param filename: the name of the file, a string
"""
# Ensure that this script is not going to grab huge amounts of memory at once.
block_size = 65536 # 64 KB.
hash_function = hashlib.md5()
with open(filename, 'rb') ... | 22caf4a1c00a15adb4bf1bab9f44b93f5538dd68 | 74,979 |
from typing import List
def check_version(framework_version: str, supported_versions: List[str]) -> bool:
"""Check if framework version is in supported versions list."""
return any(framework_version.startswith(version) for version in supported_versions) | 34ed46c9d65cefac77ecdcd9daab9ac1ae0acf44 | 74,983 |
def median(numbers):
"""
Parameters
----------
numbers : list
a list of numbers
Returns
-------
median : double
the median of the list of numbers passed
"""
numbers.sort()
if len(numbers) % 2 == 1:
median = numbers[-round(-len(numbers) / 2)]
media... | 717256a6f7b959bf80262006e512fc40c0d89bd0 | 74,988 |
def cumulative_sum(points):
"""
Returns the cumulative sum.
"""
# logger.info('calculating cumulative sum')
csum = [0,]
prev = 0
# logger.info('start appending points')
for p in points:
csum.append(p+prev)
prev = p+prev
# logger.info('returning sum')
return csum | 18407079c0bcf2f4f5e2c0b2d3659afb3b537c08 | 74,989 |
def parse_int_value(value):
""" Parses string that is expected to be an integer.
"""
return int(value) | 9888e129031a83f269c067d2697606fd17a6eb17 | 74,991 |
from typing import Any
from typing import get_args
def get_inner(hint: Any, *indexes: int) -> Any:
"""Return an inner type hint by indexes."""
if not indexes:
return hint
index, indexes = indexes[0], indexes[1:]
return get_inner(get_args(hint)[index], *indexes) | b3fcd0d183cb231b13d27f2d4d1f8d53cd9b684e | 74,992 |
import math
def calculate_heat(score, seconds, score_base, decay_time):
"""
calculate_heat: The special sauce
This function will return the `seconds` + an adjustment such that things with more "heat" will have a higher
heat index than things that are either scored lower or are older. The algorithm is ... | c477c67994481c0076b4b675166bd5327d42fe03 | 75,000 |
import functools
def cached_property(fx):
"""Mimic the @property decorator but cache the result."""
@functools.wraps(fx)
def inner(self):
# Sanity check: If there is no cache at all, create an empty cache.
if not hasattr(self, '_cached_values'):
object.__setattr__(self, '_cache... | 619b08a6a8bbe0e01d08f550a25f021a7b8ad262 | 75,001 |
def generate_column_names_per_user(number_options=3):
"""
This function generates a list which will be used for columns,
Arguments:
number_options -- this determines the number of options a forecaster has to fultill (by default=3)
Returns:
column_names -- a list containing the column n... | 542dd5b9749b98785716fba5298fcd5dee47caa3 | 75,009 |
def _JoinChildNodes(tag):
"""Join child nodes into a single text.
Applicable to leafs like 'summary' and 'detail'.
Args:
tag: parent node
Returns:
a string with concatenated nodes' text representation.
"""
return ''.join(c.toxml() for c in tag.childNodes).strip() | 2572160e9addb9a92aa015621468ab3ff5ed1893 | 75,011 |
import binascii
def decode_base64(_base64):
"""Decode string from base64 to binary string format, then return it."""
return binascii.a2b_base64(_base64) | e2a395a44f98ac82a33374d86ce10a80bcbea1e1 | 75,013 |
import re
def abbreviate(words):
"""Returns an acronym for the words passed."""
words = words.upper()
# We split the string with delimiters of <space> or <hyphen>
sentence = re.split(' |-', words)
acronym = ''
for word in sentence:
acronym += word[0]
return acronym | 65ffb7a4a7874e5a4011634db6965e5da955ec5a | 75,014 |
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 _setup_animation_range_from_times(stage, times):
"""Set the start/end times for a USD stage using a provided start/end time.
Args:
stage (`pxr.Usd.Stage`):
The composed stage that will be modified by this function.
times (tuple[float or int, float or int]):
The start... | b7be16aebc26d66b4595cbec0e83d5292f229850 | 75,025 |
def file_metrics(file_path):
"""Retrieve the file stats."""
return file_path.stat() | 3a2765a2880659429a3eed9a714d57cc615835c6 | 75,026 |
import json
def get_prefix_counts(filename):
"""Builds a dictionary mapping key prefixes to their counts.
Args:
filename: The name of a JSON file.
Returns:
A dictionary mapping each key prefix to its count.
"""
prefixes = {}
f = open(filename)
keys = json.load(f)
total = 0
for key in k... | 6b50160cc6aca551ae9189d4a66978f0bb955a07 | 75,029 |
def get_pixel(image, i, j):
"""
This function is used to get the pixel from an image.
:param image: Image from which pixel is to be extracted.
:param i: x-coordinate of the pixel in the image.
:param j: y-coordinate of the pixel in the image.
:return: Returns the extracted pixel to the calling f... | 36fe35a8b3cf46b10d199c26f165885e37f9c0e4 | 75,031 |
from typing import Any
def to_int(element: Any) -> int:
"""Convert given element into `int` data type."""
return int(element) | 7420d22f5991cbedbcf15467b804bb6769af4f44 | 75,035 |
def CTL_CODE(DeviceType, Function, Method, Access):
"""Calculate a DeviceIoControl code just like in the driver's C code"""
return (((DeviceType) << 16) | ((Access) << 14) | ((Function) << 2) | (Method)) | e135c96b94ab1d9ed083f19702129855a56f60e0 | 75,036 |
def SegmentContains(main_l, main_r, l, r):
"""Returns true if [l, r) is contained inside [main_l, main_r).
Args:
main_l: int. Left border of the first segment.
main_r: int. Right border (exclusive) of the second segment.
l: int. Left border of the second segment.
r: int. Right border (exclusive) of... | 761b064131b7885327e59818f7838573ee292264 | 75,037 |
def transformToRGB(lst):
"""
Change representation from 0-255 to 0-1, for triples value corresponding to RGB.
"""
def normToOne(x): return float(x)/255.
return [(normToOne(x), normToOne(y), normToOne(z)) for x, y, z in lst] | ec83893155bfaca7cbbec8281bd84ccb8401a48f | 75,050 |
import zlib
def crc32(filename, chunk_size=1024):
"""Generates CRC32 of a file and outputs it's hexadecimal value
in a string. Because it does it by chunks, it can read large
files without running out of memory"""
crc = 0
with open(filename, "rb") as f:
while True:
data = f.read(chunk_size)
if not data:... | 239642f03f8315f07dcce6cb95f9410000d51b1a | 75,052 |
import six
def _bytes(*vals):
"""
This is a private utility function which takes a list of byte values
and creates a binary string appropriate for the current Python version.
It will return a `str` type in Python 2, but a `bytes` value in Python 3.
Values should be in byte range, (0x00-0xff)::
... | 49d3648ed733b1d80824d97695b32486d0e6d8b3 | 75,057 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.