content stringlengths 39 9.28k | sha1 stringlengths 40 40 | id int64 8 710k |
|---|---|---|
def not_at_goal_set(trees):
"""convenience / readability function which returns the not terminated trees from a list
:param trees: list of input trees
:type trees: list
:return: trees from the input list which are not terminated
:rtype: list
"""
not_at_goal = []
for tree in trees:
... | 0f5e911573a86deb16f842c8a2d57da06dc7db3f | 563,773 |
def permalink_to_full_link(link: str) -> str:
"""Turns permalinks returned by Praw 4.0+ into full links"""
return "https://www.reddit.com" + link | 13a2eb003d4268eaffd4e1d0a51064a7e1b5e009 | 567,912 |
def extract_helm_from_json(input_json):
"""Extracts the HELM strings out of a JSON array.
:param input_json: JSON array of Peptide objects
:return: output_helm: string (extracted HELM strings separated by a newline)
"""
output_helm = ""
for peptide in input_json:
if len(output_helm) > 0... | 8bad6bbc46f0c535f76cfb144d0d929a4d4b37c5 | 561,806 |
def category_name(value):
"""Maps category value to names"""
return {
0: "idle",
1: "unassigned",
2: "work",
3: "private",
4: "break",
}.get(value, "?") | 5db040c808182b71fb3328fffefd82df02c9da73 | 442,761 |
import inspect
def private_method(func):
"""Decorator for making an instance method private."""
def func_wrapper(*args, **kwargs):
"""Decorator wrapper function."""
outer_frame = inspect.stack()[1][0]
if 'self' not in outer_frame.f_locals or outer_frame.f_locals['self'] is not args[0]... | 7dcab3cc628d8fa8e9eca357f026c6a7c598ed20 | 147,019 |
def unify_pos(pos, size):
"""
Convert position into standard one.
Example: Given size = 5, Point(-2, -7) -> Point(3, 3)
"""
return pos % size | b7298aaa0c0055b038dead8e2a3a8424ca145b72 | 464,813 |
def exclude(func):
"""Return the opposite of ``func`` (i.e. ``False`` instead of ``True``)"""
return lambda x: not func(x) | 8052e10311a5d0be206da9d3a82a36564e69b7f8 | 607,558 |
import random
def randInt32(rng=random.random):
"""returns a random integer in [-2147483648..2147483647].
rng must return float in [0..1]
"""
i = int(rng() * 0x7FFFFFFF)
if rng() < .5:
i *= -1
return i | fd51eeabf32ececcf19acaca425cbcf5844cf00f | 514,585 |
import typing
def split_name(name: str) -> typing.Tuple[str, str]:
"""
Returns a likely `(first, last)` split given a full name. This uses
very simple heuristics, and assumes Western usage.
:param name: A full name (first and last name).
:return: A split pair with the first names, and the last na... | 54fe7579d382674b35b6e177e2c6feb6beeef6f8 | 380,417 |
def create_grid_string(grid):
"""Return a crossword grid as a string."""
size = len(grid)
separator = ' +' + ('-----+')*size
column_number_line = ' '
column_number_line += ''.join(f' {j:2} ' for j in range(size))
result = f'{column_number_line}\n{separator}\n'
for (i, row) in enumerate(... | 2a820971f941e30de4d47482b65bbe5c1ebd34cf | 540,076 |
def superset_data_db_name() -> str:
"""The name (in Superset) of the database that Superset reads from"""
return 'MyCompany DWH' | e03a9e07268402badf35d649ef2bf3689e672dc1 | 466,996 |
def get_subsequences_matching_query(hit_obj):
"""Takes a SearchIO hit object, and returns a list with the first element
being a string representing the coordinates of the query to which the
subject sequence aligns, and the second being the corresponding subject
subsequence(s).
"""
# ***Eventuall... | f2382cb92d7b95289b2f4fc35bb08f25a5b830e0 | 611,463 |
def buoy_distance(pixel_width, focal_length, ACTUAL_WIDTH=0.4):
""" Calculates the distance of the buoy from the boat.
The algorithm uses the similar triangles in the following equation:
(focal_len / pixel_width) = (actual_distance / actual_width)
Keyword arguments:
pixel_width -- The width of... | 492c4bb532cfed8aec0619b003711157051331ee | 491,931 |
def init_jsobject(cls, bridge, name, value, description=None):
"""Initialize a JS object that is a subclassed base type.
Arguments:
cls -- Class the object has to be created from
bridge -- JSBridge instance to use
name -- Name of the JS object
value -- Value of the object wrapped as JS object
... | 18d5a49b23e996c84aee725e29ffed2bee183f96 | 249,401 |
def default_order(json_page_obj):
"""Return ordering based on metadata."""
return json_page_obj["meta_order"], json_page_obj["title"] | 04afeeaa9fd24b25638dc64cd1d97c4b64e01096 | 155,314 |
def centered_average(nums):
"""
take out 1 value of the smallest and largst
compute and return the mean of the rest
int div --> truncate the floating part?
ASSUME:
+3 ints
pos/neg
unsorted
dupes possible
Intutition:
- computing an average (sum / # of points)
Approac... | f6a664dd501b5ac36709d1ea482a5b274174d381 | 562,574 |
def x12_271_member_not_found_message() -> str:
"""A X12 271 message where the member is not found in the payer system and does not have insurance coverage"""
return 'ISA*00* *00* *ZZ*890069730 *ZZ*154663145 *200929*1705*|*00501*000000001*0*T*:~GS*HS*890069730*154663145*20200929*1705*... | c98abb2ad2214c56c8a64d0f777f2a4354c7f885 | 550,105 |
def is_file_supported(suffix: str) -> bool:
"""
Check a path to be supported by safitty (only YAML or JSON)
Args:
suffix (str): path extension
Returns:
bool: File is YAML or JSON
"""
return suffix in [".json", ".yml", ".yaml"] | d89f10f563f1a415fd108b1a05b989ab20e0b191 | 448,641 |
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 ``(nx, ny)``.
Returns:
* ``[dx, dy]``
Spacing the y and x directions
Examples:
>>> pri... | 456a895baf875fb32dc9319602620848176b3ba1 | 62,546 |
def look_through_rows(board, column, player):
""" Given a matrix, a column of the matrix, and a key,
This function will look through the column bottom to top,
and find the first empty slot indicated by a 0 and place
a piece there (1 or 2)
>>> look_through_rows(numpy.matrix('0,0,0,0,0; 0,0,0,0,0; 0,0... | 9849a0543d7430ac215b1debb6af820b573bde50 | 342,234 |
def get_available_resources(threshold, usage, total):
"""Get a map of the available resource capacity.
:param threshold: A threshold on the maximum allowed resource usage.
:param usage: A map of hosts to the resource usage.
:param total: A map of hosts to the total resource capacity.
:return: A map... | e5eca0a5eb6977d580f74ae6592b13211ac04f37 | 75,792 |
from typing import List
from typing import Dict
def find_it(seq: List[int]) -> int:
"""
Given an array, find the int that
appears an odd number of times.
:param seq:
:return:
"""
pares: Dict[int, int] = dict()
result: int = 0
for n in seq:
if n not in pares:
pa... | 224b01d5c09c4c97927760624931549c94972b41 | 301,458 |
def AND(*args) -> str:
"""
Creates an AND Statement
>>> AND(1, 2, 3)
'AND(1, 2, 3)'
"""
return "AND({})".format(",".join(args)) | c36b5fc6cfeeedfc0cc47c389a97aa1b63e77377 | 488,738 |
def scaled_grad(g, inv_d):
"""Computes the scaled gradient."""
return inv_d * g | c6b812a723d7c92dd66e63925368b7a542a2a50a | 541,690 |
def invariants(tensor):
"""
Calculates the first, second, and dimensionless invariants of the gradient
tensor.
.. note:: The coordinate system used is x->North, y->East, z->Down
Parameters:
* tensor : list
A list of arrays with the 6 components of the gradient tensor measured
... | 31a7bbe891be97b1e945fde85c956a36f1b28be3 | 262,322 |
def first_of(iterable, function):
"""
Return the first matching element of an iterable
This function is useful if you already know there is at most one matching
element.
"""
for item in iterable:
if function(item):
return item
return None | d7a083575859bcdf92df697d4cb8a0bb22dbb19f | 107,868 |
def find_features(extent, df):
"""
given an extent and a dataframe, return a new dataframe
containing only features that fall within the extent
Parameters
----------
extent: list -- geographic extent in lon (deg E)/lat (deg N)
df: the geopandas dataframe to slice
"""
xleft, xrigh... | 90d7e0811dbb6340d89387dc5331c4039cc9f6bf | 617,010 |
def sum_even_integers(sequence):
"""
What comes in:
-- A sequence
What goes out:
Returns the sum of the items in the sequence that:
-- are integers AND
-- are even.
Side effects: None.
Examples:
sum_even_integers([3, 10, 6, 5, 5, 10])
returns 10 + 6 + 10, ... | ef7b1b1785d4d5ec0948f1b29b6e06bcb2e1ebda | 448,790 |
import random
def balance_dataset(data, ratio):
"""
Subsamples dataset according to ratio.
@param data: List of samples.
@param ratio: Ratio of samples to be returned.
@return: Subsampled dataset.
"""
sampled_data = random.sample(data, int(ratio * len(data)))
return sampled_data | a2471e909d0b8622bfb806912d54915254c4c198 | 222,533 |
def linear(y_0, y_1, x_0, x_1, k):
"""Returns the particular integral and its derivative for linear load.
y_0, y_1 the ordinates @ the extremes of the loading,
x_0, x_1 the abscissae @ the extremes of the loading,
k the stiffness of the oscillator.
The returned functions are defined in te... | 9c1f9b1c0e5a7af70ca3dae48a6df103846534d2 | 277,449 |
from datetime import datetime
def _datetime_now() -> datetime:
"""Wrap ``datetime.now`` to easily mock it for testing.
Returns
-------
datetime
Current datetime.
"""
return datetime.now() | 3373dbbcc6181c4a25e3b79f85f432876b56294a | 438,057 |
def _get_available_memory(mem_feat, constraints=None):
"""Get available memory
If constraints are given, parse constraint string into array of
constraints and compare them to active features. Currently only
handles comma-separated strings and not the more advanced
constructs described in the slurm ... | 9783084657979b46bd5a2a1c81abed09f5969fcd | 605,963 |
def split(attr):
""" Split <key>=<val> into tuple (<key>,<val>),
if only string is passed, return ('id', <val>)"""
if '=' in attr:
ret = attr.split('=')
return ret[0], ret[1]
else:
return 'id', attr | a975e8a0b44c73e52566144a80f886e88de61b04 | 377,303 |
def zero_diag(Q):
"""
Copy of Q altered such that diagonal entries are all 0.
"""
Q_nodiag = Q.copy()
for ii in range(Q.shape[0]):
Q_nodiag[ii, ii] = 0
return Q_nodiag | 8c40fc58ee8e7af7a905de1d17b39c7d074cda17 | 73,034 |
def get_extremas_from_positions(positions):
"""
returns the minimum and maximum value for each dimension in the positions given
"""
return zip(*[(min(values), max(values)) for values in zip(*positions)]) | 9b30e2fde7f1ce5cf54b849793b67a5c02897c60 | 456,666 |
def degree(G,nbunch=None,weight=None):
"""Return degree of single node or of nbunch of nodes.
If nbunch is ommitted, then return degrees of *all* nodes.
"""
return G.degree(nbunch,weight) | 9a1fcc95960d6f318054fbc0a5a69add8ed78a46 | 511,466 |
def calc_angle(per, line):
"""
Calculate angle between two vector.
Take into consideration a quarter circle
:param per: first vector
:type per: DB.XYZ
:param line: second vector
:type line: DB.XYZ
:return: Angle between [-pi, pi]
:rtype: float
"""
return (1 if per.Y >= 0 els... | 81290fd40dfd4d714f56478a2c41b33156ca8157 | 20,665 |
def generate_target_states_list(sweep, initial_state_labels):
"""Based on a bare state label (i1, i2, ...) with i1 being the excitation level of subsystem 1, i2 the
excitation level of subsystem 2 etc., generate a list of new bare state labels. These bare state labels
correspond to target states reached fr... | cbd7dc76790b48614fe81ec08c29453947c6984e | 556,989 |
def linked_embeddings_name(channel_id):
"""Returns the name of the linked embedding matrix for some channel ID."""
return 'linked_embedding_matrix_%d' % channel_id | da3a095d86add49741fcb15f28059c124e6e7916 | 635,838 |
from typing import Callable
from typing import List
from typing import OrderedDict
def order_json(data, sort_fn: Callable[[List[str]], List[str]] = sorted):
"""Sort json to a consistent order.
When you hash json that has the some content but is different orders you get
different fingerprints.
.. cod... | 657f932d54111405ee9ac606346d2b7cc02391eb | 640,090 |
import torch
def compute_argmax(ten):
"""Compute argmax for 2D grid for tensors of shape (batch_size, size_y, size_x)
Args:
ten (torch.[cuda].FloatTensor): (batch_size, size_y, size_x)
Returns:
indices (torch.[cuda].LongTensor): (batch_size, 2) index order: (y, x)
"""
batch_size ... | d69c6ae13dfa2aef27a7e6ed621e928c146c0554 | 651,526 |
def get_util_shape(row):
"""Get utility term shape based on ROI.
Parameters
----------
row : pandas.core.series.Series
Row of func_df DataFrame.
Returns
-------
str
If 'chest' or 'rib in row['Roi'], then return 'linear'.
Otherwise, return 'linear_quadratic'.
""... | 4ebb50dd0991f3edda7f33ad17fb3a3dfaf39de3 | 48,897 |
def isprefix(path1, path2):
"""Return true is path1 is a prefix of path2.
:param path1: An FS path
:param path2: An FS path
>>> isprefix("foo/bar", "foo/bar/spam.txt")
True
>>> isprefix("foo/bar/", "foo/bar")
True
>>> isprefix("foo/barry", "foo/baz/bar")
False
>>> ispre... | fad5eed531ed7fb3ed4e982d3fd7649dbf08ecac | 622,237 |
from typing import Tuple
def sat_idx_to_in_orbit_idx(sat_idx: int, num_sat_per_orbit: int) -> Tuple[int, int]:
"""
Compute the satellite index in orbit and orbit index.
Starting from the satellite index in the constellation.
Args:
sat_idx: Index of the satellite in the constellation.
n... | 2985747f75887217bc4f1761d2407fce00db37d1 | 275,340 |
def non_gaussian(onset, frame):
"""
Calculate the Non-Gaussian parameter :
..math:
\alpha_2 (t) = \frac{3}{5}\frac{\langle r_i^4(t)\rangle}{\langle r_i^2(t)\rangle^2} - 1
"""
r_2 = ((frame - onset)**2).sum(axis=-1)
return 3 / 5 * (r_2**2).mean() / r_2.mean()**2 - 1 | 961388fa6d7d362683ee830d3834afcf2b5c0740 | 410,720 |
def get_rain_svg(risk_of_rain: float) -> str:
"""
Get SVG path to risk of rain icon
:param risk_of_rain: Risk of rain between 0 and 1
:return: path to SVG resource
"""
if risk_of_rain < 0.33:
return 'Icons/Shades.svg'
return 'Icons/Umbrella.svg' | fb5d28d9d0105d333366d8ced97cc04693cd9a37 | 278,973 |
import importlib
def get_extractor_implementation(cls, pkg=None):
"""
Get the implementation of an Extractor.
:param cls: class name (str)
:param pkg: package where implementation is found (str)
:return: class implementation
"""
# known extractors
# others must be fully specified throu... | 33bfa823e4b5dd44a0a02483f2a51965855c1bf2 | 592,210 |
import torch
def disagreement(logits_1, logits_2):
"""Disagreement between the predictions of two classifiers."""
preds_1 = torch.argmax(logits_1, dim=-1).type(torch.int32)
preds_2 = torch.argmax(logits_2, dim=-1).type(torch.int32)
return torch.mean((preds_1 != preds_2).type(torch.float32)) | 82d12bb657018c4b446fd05c94c8f5834ce4fd59 | 636,464 |
def getPropertyAsSingleValue( data, name, default ):
"""
Read a property from an LDAP data structure.
Multi-valued properties are read as single-valued,
with only the first value being used.
"""
try:
return data[name][0]
except (IndexError, KeyError):
return default | 18d806b11d155a3c7dfbdf1d0aa2606a037e1bda | 398,468 |
from typing import Tuple
from typing import List
from typing import Dict
def selection(triple: Tuple[str, str, str], variables: List[str]) -> Dict[str, str]:
"""Apply a selection on a RDF triple, producing a set of solution mappings.
Args:
* triple: RDF triple on which the selection is applied.
*... | fee52583e62d589863214e74e99fc427a0b6577d | 35,175 |
import json
def dump_json(file, array):
"""Dumps a dict to a JSON file"""
with open(file, 'w') as f:
return json.dump(array, f) | 605a7bfcaeb7502749999b7a0b8353c724b66242 | 102,631 |
def models_of_same_type(*models):
"""
Checks whether all the provided `models` are of the same type.
"""
return len(set(m._meta.concrete_model for m in models)) == 1 | c66abb7f115aee7f25fad474f560f1ea5d244d6b | 316,064 |
def get_layout_locations(version, base_path, dsid):
"""Return dataset-related path in a RIA store
Parameters
----------
version : int
Layout version of the store.
base_path : Path
Base path of the store.
dsid : str
Dataset ID
Returns
-------
Path, Path, Path
... | 1e147b1b056a63747b9445468cb043358cb64b44 | 295,940 |
def calCentroid(xmn, ymn, xmx, ymx):
"""
Function to calculate the centroid of a given image
"""
xmid = (xmx + xmn) / 2
ymid = (ymx + ymn) / 2
return xmid, ymid | 98212262d8eff2b55f14a1feabfa49b00c33912a | 182,385 |
def eqrr(registers, opcodes):
"""eqrr (equal register/register) sets register C to 1 if register A is
equal to register B. Otherwise, register C is set to 0.
"""
return int(registers[opcodes[1]] == registers[opcodes[2]]) | 08b7e01e940fb6313fdcdc80df9fde604f951c5d | 245,485 |
def get_normalisation_coefficient(sample_size):
"""
Returns a multiplicator for normalising entropy
estimated on the sample based on the size of the sample.
The coefficients were estimated empirically based
on bootstrap resampling.
"""
if sample_size < 55:
raise ValueError('No coeffi... | add5b906f1f0fe3ad65647ec448896634008e5a3 | 267,817 |
import torch
def focal_loss(bce_loss, targets, gamma, alpha):
"""Binary focal loss, mean.
Per https://discuss.pytorch.org/t/is-this-a-correct-implementation-for-focal-loss-in-pytorch/43327/5 with
improvements for alpha.
:param bce_loss: Binary Cross Entropy loss, a torch tensor.
:param targets: a... | b0f6cf127be66f178a2b509675bfab7007288e99 | 509,870 |
def response_id(req_data):
"""
Get the ID for the response from a JSON-RPC request
Return None if ID is missing or invalid
"""
_id = None
if isinstance(req_data, dict):
_id = req_data.get('id')
if type(_id) in (str, int):
return _id
else:
return None | 7c34d733aff93e213754833a2aadb19e0edfc0b5 | 160,374 |
import requests
from bs4 import BeautifulSoup
def get_data(url):
"""
Return BeautifulSoup html object.
"""
r = requests.get(url)
data = BeautifulSoup(r.text, 'lxml')
return data | 2f21b5e7be7e86f4d04c361369332109cd852632 | 493,177 |
from typing import List
import re
def _find_matching_tags(tag: 'str', lst: 'List[str]'):
"""
Extract the full list of matches to the regex stored in tag.
:param tag: A regex to search for
:type tag: str
:param lst: A set of tags to search
:type lst: List[str]
:return: The matching tags f... | 0976aba29fcefffff57428714882e6421de83846 | 557,412 |
def serialize_tree(root):
""" Given a tree root node (some object with a 'data' attribute and a 'children'
attribute which is a list of child nodes), serialize it to a list, each element of
which is either a pair (data, has_children_flag), or None (which signals an end of a
sibling chain).
"""
l... | 830a0dcaad9921b7eae1714bd2c7758aa11c4ad0 | 679,991 |
from typing import List
from typing import Dict
def species_by_charge(state_ids: List[str], charges: List[int]) -> Dict[int, List[str]]:
"""Make a dict with charge as key, and lists of species as values.
Parameters
----------
state_ids - identifiers for states
charges - charges for states
Re... | 2b6736b4773f5d11a949c422de760a989ea9f252 | 391,158 |
def admin_pc_client(admin_pc):
"""Returns the client from the default admin's ProjectContext """
return admin_pc.client | e870e216b7a21c9e879d1bd12a5255f224c62310 | 73,811 |
from pathlib import Path
def filesize(fname):
"""
Simply returns the size of the file fname in bytes
"""
return (Path(fname).stat().st_size) | 1cf2cb0fbab2533e69c5200b25a134ee6dd61424 | 39,588 |
def _format_optname(value):
"""Format the name of an option in the configuration file to a more
readable option in the command-line."""
return value.replace('_', '-').replace(' ', '-') | e12d0d27ed744d45d789f3e9e0207f04be9f5024 | 638,190 |
import zlib
import pickle
def blobdumps(py_obj, cPickle_protocol=2, compression_level=7):
"""
Pickle any Python object, and compress the pickled object.
Returns a binary string.
`compression_level`: Between 1 and 9
The higher the level is, the more compressed the object will be.
"""
... | d84096ec369cff633f13f13754adf75565394d3e | 462,649 |
def format_imports(import_statements):
"""
-----
examples:
@need
from fastest.constants import TestBodies
@end
@let
import_input = TestBodies.TEST_STACK_IMPORTS_INPUT
output = TestBodies.TEST_STACK_IMPORTS_OUTPUT
@end
1) format_imports(import_input) -> output
-----
:... | 91514d19da4a4dab8c832e6fc2d3c6cbe7cca04a | 705,430 |
def CleanStrForFilenames(filename):
"""Sanitize a string to be used as a filename"""
keepcharacters = (' ', '.', '_')
FILEOUT = "".join(c for c in filename if c.isalnum() or c in keepcharacters).rstrip()
return FILEOUT | f121fc167fcb80b00bf1f6aa5ecbff9b36acc54a | 282,200 |
def lerp(a, b, x):
"""Linear interpolation between a and b using weight x."""
return a + x * (b - a) | b6790c221e797bfa0fe063a22ebced60eab877db | 681,170 |
def make_key(x,y):
"""
function to combine two coordinates into a valid dict key
"""
return f'{x}, {y}' | 14e414dd448eba8e3a7adfb5d5bbfc7f4fd22165 | 426,959 |
import re
def extract_swagger_path(path):
"""
Extracts a swagger type path from the given flask style path.
This /path/<parameter> turns into this /path/{parameter}
And this /<string(length=2):lang_code>/<string:id>/<float:probability>
to this: /{lang_code}/{id}/{probability}
"""
return re.sub('<(?:[^:]... | 8563f028d4736d4032492a6d7a166aa5c3d97e36 | 607,791 |
def find_number_3_multiples(x):
"""Calculate the number of times that 3 goes into x."""
mult3=x//3
return mult3 | 64d429b520688afabad656b9d975daf8d9846ff1 | 122,881 |
def is_triangle_possible(triangle):
"""Check if triangle is possible."""
return sum(sorted(triangle)[:2]) > max(triangle) | 6ce637fb523547b6aa11cd30e7497706ac97b88e | 186,894 |
def create_content_item_id_set(id_set_list: list) -> dict:
""" Given an id_set.json content item list, creates a dictionary representation"""
res = dict()
for item in id_set_list:
for key, val in item.items():
res[key] = val
return res | 455f131fcf781fabf2573a226023f2cd8d4be5ae | 526,139 |
import ast
def parse_imports(filepath):
"""Formulate a dictionary of imports within a python file for usage by ``apipkg``.
Parameters
----------
filepath
The python file containing the imports to be parsed.
Returns
-------
imports_for_apipkg
A dictionary of imports in the... | 9229c83812038d6a4370857fb933e0de69d87fd7 | 217,835 |
def aic_hmm(log_likelihood, dof):
"""
Function to compute the Aikaike's information criterion for an HMM given
the log-likelihood of observations.
:param log_likelihood: logarithmised likelihood of the model
dof (int) - single numeric value representing the number of trainable
parameter... | 86fdea3262697eb5dd168f4f0927befa285c0e1a | 544,464 |
def searchList(listOfTerms, query: str, filter='in'):
"""Search within a list"""
matches = []
for item in listOfTerms:
if filter == 'in' and query in item:
matches.append(item)
elif filter == 'start' and item.startswith(query):
matches.append(item)
elif filter... | 1a8b0fa6e870b2b3f088b634e3be1cc94a44e95b | 143,573 |
def get_extrap_col_and_ht(height, num, primary_height, sensor='Ane', var='WS'):
"""
Determine name of column and height to use for extrapolation purposes
:param height: comparison height
:param num: number/label of comparison height
:param primary_height: Primary comparison height
:param sensor:... | 286fd76046ee1bb9a128d1334b3475b5f15bafa3 | 273,460 |
def add_plugin_to_endpoints(endpoints, plugin):
"""
Add the endpoint key to each endpoint dictionary in the list
:param endpoints: List of endpoint dictionaries
:param plugin: String of the plugin name
"""
for endpoint in endpoints:
endpoint.update({
'plugin': plugin,
... | 2784278479c74a5b265dd8dedb0e7dd72ab3cd57 | 441,528 |
def compose(*functions):
"""
Compose functions
This is useful for combining decorators.
"""
def _composed(*args):
for fn in functions:
try:
args = fn(*args)
except TypeError:
# args must be scalar so we don't try to expand it
... | 50089b9343e6c7a91e88f679d8d02d7533083596 | 139,650 |
def getArrayDimensions(shape):
"""
Get the dimensions of the grid where the cell will be zoomed.
The zoomed cell contains a `numpy` array and will be displayed
in a table with the same shape than it.
:Parameter shape: the cell shape
:Returns: a tuple (rows, columns)
"""
# Numpy scala... | b79ae249763328196a3ab48306738287c063f600 | 361,080 |
def get_item_properties(item, columns):
"""Get specified in columns properties, with preserved order.
Required for correct cli table generation
:param item: dict
:param columns: list with arbitrary keys
"""
properties = []
for key in columns:
properties.append(item.get(key, ''))
... | 7e2a9bd3d337b2fc5fd83e10243ff7e96783f79a | 553,576 |
def get_original_keys(keys, keymap, strict=False):
"""
Get original keys from normalized keys.
Args:
keys:
The collection of keys that identify a value in the dataset.
keymap:
The keymap returned from :meth:`load` or :meth:`loads`.
strict:
If true... | 876d2ba8a7be2b8652958c27b0841242c5ed279e | 289,939 |
from pathlib import Path
def enterprise_1_12_artifact() -> Path:
"""
Return the path to a build artifact for DC/OS Enterprise 1.12.
"""
return Path('/tmp/dcos_generate_config_1_12.ee.sh') | 33273d2a4e220c6b28b69310c69452172e4cad29 | 289,310 |
import json
def create_label(name, color, repos, session, origin):
"""
Creates label
:param name: name of the label
:param color: color of the label
:param repos: repository where label is created
:param session: session for communication
:param origin: repository where the label came fro... | c5f157673967c8f1b8928c3831abf4558ef5dc92 | 674,625 |
def indent(block):
"""Indent each row of the given string block with ``n*2`` spaces."""
indentation = " " * 2
return "\n".join([indentation + s for s in block.split('\n')]) | c694c3eca23fbc5d2d8b4df2d321f55db559799e | 342,904 |
def version_greater_or_equal_to(version, min_version):
"""Compares two version strings and returns True if version > min_version
>>> version_greater_or_equal_to('1.0', '0')
True
>>> version_greater_or_equal_to('1.0', '0.9.9.9')
True
>>> version_greater_or_equal_to('1.0', '2.0')
False
>>> version_greate... | b3050bd321374abb0d2e82b3080a4174644d20e9 | 605,226 |
def to_red(string):
""" Converts a string to bright red color (16bit)
Returns:
str: the string in bright red color
"""
return f"\u001b[31;1m{string}\u001b[0m" | c4c7ee43c872b1ea9ad37c1d72540a1227b58926 | 98,298 |
import re
def get_function_name(line):
"""Get name of a function."""
func_name = re.split(r"\(", line)[0]
func_name = re.split(r" ", func_name)[-1]
func_name = re.sub(r"(\*|\+|\-)", r"", func_name)
return func_name | f5b7048755000929822a6d97577dc872a4d4e966 | 656,369 |
def linearize_dict(indict, sep='_', lower=False):
"""Linearize levels of an input dict, using separator
Args:
indict(`dict`): input dict with nested levels
sep(str): separator
lower(bool): lower all itens
Returns:
`dict`: output dict with just one level
"""
def li... | 7e236f607cb4c583c9818dd3c51b3184f9e26252 | 523,895 |
def check_resource_existence(client, resource_group):
"""Create if resource group exists in Azure or not
:param client: Azure object using ResourceManagementClient
:param resource_group: string, name of Azure resource group
:return: True if exists, otherwise False
:rtype: boolean
"""
respon... | b6f66d10593ce8208167bb965bbdc7c5252296ee | 145,487 |
import re
def diff_replace_old_new(diff):
"""Return the (old, new) filenames from difference tuple `diff`."""
match = re.search(r"replaced '(.+)' with '(.+)'", diff[-1])
if match:
return match.group(1), match.group(2)
else:
return None, None | ef8365320bc9a01d5de9aec8265b7f572eb15011 | 142,693 |
import hashlib
def checksum_file(f, blocksize: int = 2 << 15) -> str:
"""
Checksum a file-like object.
"""
hasher = hashlib.sha256()
for block in iter(lambda: f.read(blocksize), b""):
hasher.update(block)
f.seek(0)
return hasher.hexdigest() | c40f53bf03612564f5817c1a732e246dce330ed3 | 605,351 |
def get_node_set_map(tuple_list):
"""
Function to get a mapping of random node names to values between 0
and number of nodes - 1, with a modified adjacency list.
Args:
tuple_list : adjacency list with weights and arbitrary node names
Returns:
tuples : canonicalized adjacency list
... | e30113775a4783d38da6b994fc49b83154db10ae | 317,655 |
import json
def is_new_version_model_file(model_file_path: str) -> bool:
"""Check whether the model file belongs to the new version of HuggingFace Tokenizers,
i.e., >= 0.8
Parameters
----------
model_file_path
Path to the model file
Returns
-------
is_new_version
Whet... | 5cea582ca6fd4a86bcb71832fe8866f86a319b0e | 408,754 |
import json
def configure_connection (instance, name = 'database', credentials = None):
"""Configures IBM Streams for a certain connection.
Creates or updates an application configuration object containing the required properties with connection information.
Example for creating a configuration for a ... | 4d55b1ff45c59831b8d398a0420df9a7048bab6a | 233,314 |
def has_tag(method, tag: str) -> bool:
"""
Checks if the given method has the given tag.
:param method: The method to check.
:param tag: The tag to check for.
:return: True if the tag exists on the method,
False if not.
"""
return hasattr(method, '__tags') an... | efa797eee30cff4614db899a968b1122c5882de2 | 515,964 |
def make_plant_indices(plant_ids, storage_candidates=None):
"""Make the indices for existing and hypothetical generators for input to Switch.
:param iterable plant_ids: plant IDs.
:param set storage_candidates: buses at which to enable storage expansion.
:return: (*dict*) -- keys are {'existing', 'expa... | 526ceb12896ddc9f4e7abae977b733896f277ebc | 488,244 |
def get_blurb(in_file):
"""Get the first paragraph of a Markdown file"""
with open(in_file, "r") as f:
f.readline() # Title
f.readline() # Title underline
f.readline() # Blank
out = ""
line = f.readline()
while len(line) > 0 and line != "\n":
out +... | 8701ad31e5e99dd42b6cfab222b1c33aab255a5a | 535,189 |
def pointInRect(p, rect):
"""Return True when point (x, y) is inside rect."""
(x, y) = p
xMin, yMin, xMax, yMax = rect
return (xMin <= x <= xMax) and (yMin <= y <= yMax) | 1754deaf63b1b78f2ed5c67cc8a7824e4c8f1a35 | 152,278 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.