content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import re
def check_file(file_contents: str) -> bool:
"""Check file for the snippet"""
return bool(re.search(r"^if __name__ == \"__main__\":", file_contents, re.M)) | 974f4e29a92dc3c9f9c4b12c79af2940758cd8d6 | 626,415 |
def getInnerText(node):
"""
Get all the inner text of a DOM node (recursively).
"""
# inspired by http://mail.python.org/pipermail/xml-sig/2005-March/011022.html
inner_text = []
for child in node.childNodes:
if child.nodeType == child.TEXT_NODE or child.nodeType == child.CDATA_SECTION_NO... | c6a7dc3a9e49168cf0c971cac465312921c748f5 | 626,417 |
import yaml
def load_yaml(path):
"""Load YAML file into Python object."""
with open(path, "r") as file_data:
data = yaml.safe_load(file_data)
return data | 4c2029673d42f85b11cd482b0a17d13097afbfb2 | 626,420 |
def dot(a, b, out=None):
"""
Dot product of two arrays. Specifically,
- If both `a` and `b` are 1-D arrays, it is inner product of vectors
(without complex conjugation).
- If both `a` and `b` are 2-D arrays, it is matrix multiplication,
but using ``a @ b`` is preferred.
- If either `a... | 266ea378f94e668355e3a58d1beb9ab6c7d65210 | 626,421 |
def labeller(n, symbol="q"):
"""Autogenerate labels for wires of quantum circuits.
Parameters
==========
n : int
number of qubits in the circuit
symbol : string
A character string to precede all gate labels. E.g. 'q_0', 'q_1', etc.
>>> from sympy.physics.quantum.circuitplot import ... | bd464c8ec7cc9e7ca32010184c983c46c16ffb2c | 626,425 |
def _get_api_name(func):
"""e.g. Convert 'do_work' to 'Do Work'"""
words = func.__name__.split('_')
words = [w.capitalize() for w in words]
return ' '.join(words) | 39eb8b01fa9a3e257f25d8870038543c3eb8d823 | 626,427 |
def _fix_uppercase(kwargs):
"""
Properly handle uppercase arguments which are normalized by click.
"""
if 'c' in kwargs:
kwargs['C'] = kwargs.pop('c')
return kwargs | 560f894b5c5324e284111f1235041924f3a54ac5 | 626,428 |
import math
def inverse_kinematic(x, y, a1, a2):
"""
:param x: x position of end effector
:param y: y position of end effector
:param a1: length of member 1
:param a2: length of member 2
:return: angles of a 2 joint same plane robot arm
"""
# find q2 angle of the second joint
num ... | a5a9d16cbab28b50bbbe98425c9e384fe1b68eb6 | 626,430 |
import requests
def get_current_microsoft_public_keys(ms_signing_key_url='https://login.microsoftonline.com/common/discovery/keys'):
"""Returns the list of currently in use public keys.
Args:
ms_signing_key_url: The known url for the public keys
.. note::
These guys are updated approxim... | 8a107c00f17c3cfca1ffa353d5334737977deb8a | 626,432 |
from typing import Optional
def get_season_url(
base_url: str, year: Optional[int] = None, season: Optional[str] = None
) -> str:
"""Creates the URL for the season endpoint."""
if year is None or season is None:
return f"{base_url}/season"
return f"{base_url}/season/{year}/{season.lower()}" | 3d8520f65a65c2c4d8c4749a22acc269e076543a | 626,433 |
def intersection(lista, listb):
"""Return the intersection between two lists. Note,
for duplicate values, each duplicate will be returned as
we merely check if item in lista, is in listb."""
return [item for item in lista if item in listb] | bd97d4a1869d87701cd1b14dfaccf139b1a30e23 | 626,434 |
def bed4_to_node2coordinates(bed4):
"""Compute the node2coordinates DataFrame: exon name, chrom, start, end"""
node2coordinates = bed4\
[["name", "chrom", "chrom_start", "chrom_end"]]\
.set_index("name")
return node2coordinates | 2425dcc4d5ebbc2e0312d06cc85c69f27bbe076d | 626,439 |
from typing import Counter
def count_layer_types(model):
"""Count layers by layer type.
Parameters
----------
model : keras.engine.training.Model
A Keras model.
Returns
-------
collections.Counter
Counter object containing number of layers in the model by layer type.
... | d34df3bb908244a0469ac7d998b9410381ed79c7 | 626,442 |
async def prefix_getter_static(prefix, message):
"""
Returns a prefix for the message.
This function is a coroutine.
Parameters
----------
prefix : `str`
The prefix to return.
message : ``Message``
The received message to parse the prefix from.
Returns
... | c7726ae81e6db546d49f364fc35f132bb9224730 | 626,443 |
import torch
def silu(x):
"""
Smoothed ReLU (Sigmoid-ReLU)
"""
return x*torch.sigmoid(x) | 3ef82437e95585e41a0c73deaea03b08c228e0aa | 626,447 |
def use_kd_tree(request):
"""Whether to use the KD Tree in CVTArchive."""
return request.param | 12989d688dc68bc00572a07a99aa099313f766f9 | 626,449 |
def _zero_based_index(i, l, start=True):
"""Compute the 0-based index from the slice index i in a list of length l
Assuming step is 1.
Examples
--------
>>> _concrete_index(2, 100)
2
>>> _concrete_index(2, 100, start=False)
2
>>> _concrete_index(-1, 100, start=False)
99
>>> ... | bbafa7a0ffbcf87ea2ff52b55b48b506aaef2367 | 626,450 |
def checksum(spreadsheet):
"""
Calculate the checksum of a spreadsheet by summing up the ranges of all
lines.
>>> checksum([
... [5, 1, 9, 5],
... [7, 5, 3],
... [2, 4, 6, 8]
... ])
18
"""
return sum(
max(line) - min(line)
for line in spreadsheet
... | aff44ebd654bd4e59d49df9d0963a1f969d5b5b4 | 626,453 |
def lsymm(self, ncomp="", nl1="", nl2="", ninc="", kinc="", noelem="",
imove="", **kwargs):
"""Generates lines from a line pattern by symmetry reflection.
APDL Command: LSYMM
Parameters
----------
ncomp
Symmetry key:
X - X symmetry (default).
Y - Y symmetry.
... | 4a4e356bf6694f8e55c77d54615cbc55dbcdd8a7 | 626,456 |
def comp_masses(self):
"""Compute the masses of the Lamination
Parameters
----------
self : Lamination
A Lamination object
Returns
-------
M_dict: dict
Lamination mass dictionary (Mtot, Mlam, Mteeth, Myoke) [kg]
"""
rho = self.mat_type.struct.rho
V_dict = self.... | 4ef2b61a382f0a1822eae86a8f138ecf85490de1 | 626,457 |
def get_xpath_parent(xpath, level=1):
""" Get the parent xpath at any level, 1 is parent just above the input xpath.
Args:
xpath (str): Input xpath
level (int, optional): Parent level. Defaults to 1.
Returns:
str: Parent xpath
"""
if not xpath.startswith("/"):
rais... | 55f9cea636908a668c8ea49757df6ec4c043b6dc | 626,458 |
def pad_list(xs, pad_value=0., pad_left=False):
"""Convert list of Tensors to a single Tensor with padding.
Args:
xs (list): A list of length `[B]`, which contains Tensors of size `[T, input_size]`
pad_value (float):
pad_left (bool):
Returns:
xs_pad (FloatTensor): `[B, T, inp... | 18b1f649fb10b54607d1dd8b2106172ac9af743e | 626,463 |
def get_cube_diff(cube_1, cube_2):
"""
Take the difference of two Iris data cubes.
Computed as cube_1 - cube_2.
Parameters
----------
cube_1 : Iris cube.
cube_2 : Iris cube.
Return
------
Iris cube containing the difference of cube_1 - cube_2
"""
diff_cube = cu... | 9d059f043f4ebecbb746babcfe472325837376d4 | 626,464 |
def and_from_dict(kwargs):
"""
Generate a SQL And statement from a dict of keyword args
:param kwargs: Keyword arguments dict
:return: String AND statement
"""
return " AND ".join(f"{x} = %({x})s" if kwargs[x] is not None else f"{x} is %({x})s" for x in kwargs) | 2f10769dda29aefaf3963ef8a1cc89bef2213bf1 | 626,466 |
def PNewOTFTable (inOTF, access, tabType, tabVer, err,
numDet=1, numPoly=0, numParm=0):
""" Return the specified associated table
inOTF = Python OTF object
access = access code 1=READONLY, 2=WRITEONLY, 3=READWRITE
tabType = Table type, e.g. "OTFSoln"
tabVer = table... | edea1d30b0b8c519f7245de16764b46ff419ee24 | 626,467 |
import re
def uncamel(val):
"""Return the snake case version of :attr:`str`
>>> uncamel('deviceId')
'device_id'
>>> uncamel('dataCenterName')
'data_center_name'
"""
s = lambda val: re.sub('(((?<=[a-z])[A-Z])|([A-Z](?![A-Z]|$)))', '_\\1', val).lower().strip('_')
return s(val) | 27c6b5338d8da39a6b45d420749457147738e416 | 626,468 |
def GetGroup(node,groupName,verbose=False):
"""
**GetGroup** - Gets the requested group node within the
netCDF Loop Project File
Parameters
----------
rootGroup: netCDF4.Group
A group node of a Loop Project File
Returns
-------
dict {"errorFlag","errorString"/"value"}
... | 1ea13ce6723d87f2f654099ce4a9030945a51b90 | 626,469 |
def remove_blank_wrap(value, context):
"""
Remove blank and text wrap in the value.
"""
return "".join(value.split()) | f364d0013f103c8ce2ef27c67f1857e5e8d61217 | 626,470 |
import torch
def _onenorm_matrix_power_nnm(A, p):
"""
Compute the 1-norm of a non-negative integer power of a non-negative matrix.
Parameters
----------
A : a square ndarray or matrix or sparse matrix
Input matrix with non-negative entries.
p : non-negative integer
The power t... | 539488739aaf79f9caabcc5412b72ea7040318fd | 626,478 |
import torch
def log_int_prod_gaussians(N1: dict, N2: dict) -> torch.Tensor:
"""Calculate log integral N(x; m1, cov1) * N(x; m2, cov2) dx
Args:
N = {'mean': torch.Tensor(k, d), 'cov': torch.Tensor(k, d, d)}
Returns: k1-by-k2 matrix
"""
# get number of components
k1, d = N1['mean'].sh... | eb0910bc1f7bee2c47e8d2dacdc48772c54f97d6 | 626,481 |
def as_macro_define(m, v):
"""Return as a C preprocessor command line macro definition"""
if v:
return '-D%s=%s' % (m, v)
return '-D%s' % (m,) | 3301c7083ec5d16aa87f03d86ca38536e3a45c9a | 626,482 |
def get_ants_transforms(in_affine_transformation, in_bspline_transformation):
"""Combine transformations for antsApplyTransforms interface."""
return [in_bspline_transformation, in_affine_transformation] | 49c2c9c272bfe9ceb16568b1173eee4bf4a2df0c | 626,485 |
def prandtl(viscosity: float, Cp: float, KAPPA=0.026) -> float:
"""Calculatres the Prandtl number.
Args:
viscosity (float): Air dynamic vicosity [Ns/(m^2)].
Cp (float): Spectfic Heat Constant Pressure [J/kg*K].
KAPPA (float, optional): W/(mK) air. Defaults to 0.026.
Returns:
... | 67221c6bb1e6393bff688f1ef2a96d3a6ad25536 | 626,487 |
def connection_requires_http_tunnel(
proxy_url=None, proxy_config=None, destination_scheme=None
):
"""
Returns True if the connection requires an HTTP CONNECT through the proxy.
:param URL proxy_url:
URL of the proxy.
:param ProxyConfig proxy_config:
Proxy configuration from poolman... | 8ae18bea3530d1497d34c8dc25e0a0d9a5def017 | 626,488 |
def tmp_working_directory_path(tmp_path) -> str:
"""
Return a path to a temporary working directory (different path for each test).
"""
destination = tmp_path.joinpath("obfuscation_working_dir")
destination.mkdir()
return str(destination) | 44a155ebc3b0c3bfe36b951dcdfb84180f108b79 | 626,492 |
from typing import MutableMapping
def _toc_enabled(env: MutableMapping) -> bool:
"""Is there a valid ToC definition in the Markdown?"""
opts = env["mdformat-toc"]["opts"]
return bool(opts) | 552fcd42907ac0af5d338d05d42c861db5118865 | 626,495 |
def harmonic_oscillator(grids, k=1.):
"""Potential of quantum harmonic oscillator.
Args:
grids: numpy array of grid points for evaluating 1d potential.
(num_grids,)
k: strength constant for potential vp = 0.5 * k * grids ** 2
Returns:
vp: Potential on grid.
(num_grid,)
"""
vp = 0.5 *... | 52ebb4e89b18668f48e5ee20875499347a5e95cf | 626,496 |
def insertion_sort(list):
"""
Takes in a list and sorts the list using an insertion sort method.
Modifies the list in place, but returns it for convenience.
"""
round_number = 1
curr = round_number
while round_number < len(list):
while curr > 0:
if list[curr] < list[curr ... | fb330af713546daa020deba7ed07937f2be6db11 | 626,497 |
def get_users_without_name(conn):
"""Get users with empty name column"""
res = conn.execute("""
SELECT id FROM people
WHERE name=''
""")
ids = [person[0] for person in res.fetchall()]
return ids | e89af83b97391a62c9e048d72b2da2e1247f8ec4 | 626,501 |
def build_annual_urls(first_url,year):
"""
This method takes the first SD url and creates a list of
urls which lead to the following pages on SD which will be
scraped. The page list is for a given year.
"""
page_urls = []
for i in range(20):
url_100 = first_url.replace('&show=25','&... | 1104ea6c9f7cfe61bb61c25ddd7e314b1c6a1903 | 626,502 |
def unit_vector(v):
"""Return the unit vector of the points
v = (a,b)"""
h = ((v[0]**2)+(v[1]**2))**0.5
if h == 0:
h = 0.000000000000001
ua = v[0] / h
ub = v[1] / h
return (ua, ub) | dc7a886856978809b76d3897d56291d1721651aa | 626,507 |
import unittest
import torch
def require_cpu(test_case):
"""
Decorator marking a test that must be only ran on the CPU. These tests are skipped when a GPU is available.
"""
return unittest.skipUnless(not torch.cuda.is_available(), "test requires only a CPU")(test_case) | 6bd547d091ffa2214bfacf516c084954503523c5 | 626,510 |
def escape(s):
"""
Replace potential special characters with escaped version.
For example, newline => \\n and tab => \\t
"""
return s.replace('\n', '\\n').replace('\t', '\\t').replace('\r', '\\r') | b6324b8c2e21a166712a56e9a969600567a9b3f8 | 626,512 |
def bresenham(x1, y1, x2, y2):
"""
Return a list of points in a bresenham line.
Implementation hastily copied from RogueBasin.
Returns:
List[Tuple[int, int]]: A list of (x, y) points,
including both the start and end-points.
"""
points = []
issteep = abs(y2-y1) > abs(x2... | d115b822feeb0e5c8de7db01b2eb7f04d41047ef | 626,514 |
def Affine(x, w, b):
"""Computes the affine transformation.
Args:
x: Inputs
w: Weights
b: Bias
Returns:
y: Outputs
"""
# y = np.dot(w.T, x) + b
y = x.dot(w) + b
return y | 52dd0490cbd2c83112097300cc959c40fb9b7dbb | 626,516 |
def lines_from_geometry(geo):
"""Convert an iterable of geometry to lines. Suitable for passing
directly to `matplotlib.collections.LineCollection`.
:param geo: An iterable of geometry items. If cannot be coverted to a
line, then ignored.
:return: A list of coordinates.
"""
... | 4da48a6a0c43ea06331a19b704aff1f7362da1e2 | 626,518 |
def enumerate_dataset(start=0):
"""A transformation that enumerates the elements of a dataset.
It is similar to python's `enumerate`.
For example:
```python
# NOTE: The following examples use `{ ... }` to represent the
# contents of a dataset.
a = { 1, 2, 3 }
b = { (7, 8), (9, 10) }
# The nested st... | 5e35a9551627bf32d80f0fb1ea8bd0a514ac9796 | 626,519 |
from typing import Optional
from datetime import datetime
def get_timestamp(tstamp: Optional[datetime] = None) -> object:
"""Get a string representing the a time stamp.
Args:
tstamp: datetime.datetime object representing date and time. If set to None,
the current time is taken.
Retur... | de49fa79b804b1630d871a36781d86c32aaa7e5d | 626,521 |
def determine_wgtflag(vwgt, adjwgt):
"""Determine the wgtflag used in many parallel partitioning routines
"""
if vwgt is None and adjwgt is None:
return 0
if vwgt is None:
return 1
return 2 if adjwgt is None else 3 | cb7941989549625ac389c73016528c9484653a52 | 626,523 |
import inspect
def get_method_arguments(method, exclude=None):
"""
Return the method's argument, associated with a boolean describing whether
or not the given argument is required.
"""
signature = inspect.getfullargspec(method)
args_count = len(signature.args) if signature.args else 0
... | c44a82e173e32145dac91e7b6262b62553d55269 | 626,524 |
def load(attr, element, default=None):
"""
Helper function for loading XML attributes with defaults.
"""
if not element in attr.__dict__:
return default
return attr[element] | 922d51a6c1bb3848878adf33764ead89a4c34a8f | 626,526 |
def to_int(s, fallback=0):
"""Try to cast an int to a string. If you can't, return the fallback value"""
try:
result = int(s)
except ValueError:
# logging.warning("Couldn't cast %s to int" % s)
result = fallback
except TypeError:
# logging.warning("Couldn't cast %s to int... | c1fcdf6b8a9140139e9e28336a827d736a561d88 | 626,527 |
def get_list(node, tag):
"""
Get sub-nodes of this node by their tag, and make sure to return a list.
The problem here is that xmltodict returns a nested dictionary structure,
whose substructures have different *types* if there's repeated nodes
with the same tag. So a list of one thing ends up bein... | 1eebf70507960f4f97bb25ec5f4b728e80cd2b2a | 626,529 |
def get_center(centers, vector, distance_function):
"""
Determines which center is closest to the given vector.
The given distance function will be used to calculate the distance between
the vector and possible centers.
The centers should be a list of numpy vectors, and vector should be a numpy
... | 05e4bc3cf1ef653cfc4d9a1835d3fa17610a8787 | 626,532 |
def import_optional(mod, import_from=None):
"""
import module or object 'mod', possibly from module 'import_from', and
return the module object or object. If the import raises
ModuleNotFoundError, returns None.
This method was written to support importing "optional" dependencies so
code can be... | 0ed88c26c7b2ca12d281f1244f59bd1f76df9364 | 626,534 |
def fixedPoint(f, epsilon):
"""
f: a function of one argument that returns a float
epsilon: a small float
returns the best guess when that guess is less than epsilon
away from f(guess) or after 100 trials, whichever comes first.
"""
guess = 1.0
for i in range(100):
if abs(f(gues... | 550c019b7f64748a9f34ce197046eb707ce68d1e | 626,537 |
def mdhtmlEsc(val):
"""Escape certain Markdown characters by HTML entities or span elements.
To prevent them to be interpreted as Markdown
in cases where you need them literally.
"""
return (
""
if val is None
else (
str(val)
.replace("&", "&")
... | 46b4437904b37d67926c54a6dff013ae6fa95b73 | 626,540 |
import inspect
def isbuiltin(object):
""" Convinience method to check if object is builtin. """
if inspect.isbuiltin(object):
return True
return getattr(object, '__module__', None) == 'builtins' | a3c249a6d49f3b865b8b99b749f7db0a21e6f374 | 626,541 |
def linkable_longitude(value):
"""
Append proper direction to a float represented longitude.
Example:
In: -83.472899
Out: 83.472899W
"""
value = float(value)
direction = 'E' if value > 0 else 'W'
value = abs(value)
return '{0}{1}'.format(value, direction) | 0686577bb4b6583c3b81cc5c46270676c0c1c2df | 626,545 |
def _merge_set_groups(group_1, group_2):
"""
Mergers the two set groups.
Merging groups is a pre-operation of difference calculation, so copying is not required.
Parameters
----------
group_1 : `None`, `set` of `Any`
The first group to merge.
group_2 : `None`, `set` of `Any... | f82a7cabf39daf4e67b3a3a997d8049b039fc64b | 626,546 |
def is_formatted_text(value: object) -> bool:
"""
Check whether the input is valid formatted text (for use in assert
statements).
In case of a callable, it doesn't check the return type.
"""
if callable(value):
return True
if isinstance(value, (str, list)):
return True
if... | 556e78f42c3d5de96dba3385c6823f20e16ff74d | 626,547 |
def lerp(channel1, channel2, current_step, total_steps):
"""
:lerp: linear interpolation function for traversing a gradient
:param channel1: int | the rgb channel for the starting color in the gradient.
:param channel2: int | the rgb channel for the ending color in the gradient.
:param curr... | e51baf41855c94a4ffacadef89f1733729cf9e85 | 626,548 |
def getQLColliderNode(target):
"""
get the Qualoth qlColliderShape node related to the target.
:param target: `PyNode` node from where to get the related qlColliderShape node.
:return: `PyNode`
"""
if target.nodeType() == "transform":
target = target.getShape()
if not target: ret... | 96b4d578b25e7c63466c7ab761d47c877a063f99 | 626,552 |
import requests
def get_models_json(service):
"""Get the models/versions from the service along with service version."""
r = requests.get(service + 'models?format=json')
service_version = r.headers['User-Agent'].split(' ')[0].split('/')[1]
return r.json(), service_version | a4a97b7608e51af3d58af4cbf06d6db4ae087b04 | 626,559 |
def norm255_tensor(arr):
"""Given a color image/where max pixel value in each channel is 255
returns normalized tensor or array with all values between 0 and 1"""
return arr / 255. | a0f1c02b3e735f214ae9c3c0055db5b52bead62e | 626,562 |
from typing import Tuple
from typing import Dict
from typing import Union
def _read_dat_single_line(
package: str,
) -> Tuple[
int, Dict[str, Dict[str, Tuple[float, float, float]]], Dict[str, Union[str, tuple]]
]:
"""Extracts all relevant information from a single line of TRACAB's .dat file
(i.e. one ... | fecd768c7c74d063329771915731e4aa4a8bd4d5 | 626,563 |
from typing import Any
from typing import get_origin
from typing import Union
from typing import get_args
def is_Optional_type(t: type):
""" Check if the given type is Optional[] """
# https://stackoverflow.com/questions/56832881/check-if-a-field-is-typing-optional
# An Optional[] type is actually an alia... | 408cf470cfa91f3ef5bbc0928144bb0511187d40 | 626,564 |
import shutil
def hfill(s, sequence):
"""Pad a string s with a sequence to fill the terminal horizontally."""
width = shutil.get_terminal_size().columns
return (s + sequence * ((width - len(s)) // len(sequence))) | 2b7cbb5efe5b1a429ee74d82bdb3df2dde327d1e | 626,571 |
def path_exists(source, path, separator='/'):
"""Check a dict for the existence of a value given a path to it.
:param source: a dict to read data from
:param path: a key or path to a key (path is delimited by `separator`)
:keyword separator: the separator used in the path (ex. Could be "." for a
... | defc53d492b9e805a916476ea5dc700024e52e44 | 626,573 |
def collision_check(tile_rects, bus_rect):
"""
Function to check for bus collisions
:param tile_rects: The nested list of all tile rects on the map
:param bus_rect: The rect of the shuttle bus
:return: Whether there is a collision or not as a boolean value
"""
for rects in tile_rects:
... | 9fc2576a63cabae6af27e57d965d368a3a5b629a | 626,576 |
def cbrt(x):
"""Cube root."""
if 0 <= x:
return x ** (1.0 / 3.0)
return -(-x) ** (1.0 / 3.0) | 28c66d52eae60999cee627042c0ae653977e4f65 | 626,578 |
def fit_line(x1,x2,y1,y2):
"""Return the coefficients a,b in y(x)=a*x+b, given two points"""
a = (y2-y1)/(x2-x1)
b = (x2*y1 - x1*y2)/(x2-x1)
return a,b | 73afee310a1e94e93294e7fc598d26880c540668 | 626,582 |
def hex_nring(npix):
"""
For a hexagonal layout with a given number of pixels, return the
number of rings.
"""
test = npix - 1
nrings = 1
while (test - 6 * nrings) >= 0:
test -= 6 * nrings
nrings += 1
if test != 0:
raise RuntimeError(
"{} is not a vali... | 36b0c0f302f3ed5fd7355c90b581b6c0e6ff8feb | 626,583 |
def restexpose(func):
"""
Decorate a function to clearly mark it as an exposed REST method
"""
setattr(func, 'restexposed', True)
setattr(func, 'exposed', False)
return func | 9e4e00b5b8ea8b468cd9126f72786237c0917fe7 | 626,584 |
def read_True_steps_suffix_map(txtfile_name_with_path):
"""
This function reads the text file that contains all the steps in the configuration file, the
corresponding suffix, and whether they were completed or not.
Args:
txtfile_name_with_path: string, full name and path of the text file
R... | 363676d44f1cd410394a68e267d92a34f2cc6f27 | 626,585 |
def distance_between(origin_x, origin_y, destination_x, destination_y):
"""Calculate the distance between two points. """
return ((origin_x - destination_x)**2 + (origin_y - destination_y)**2)**.5 | fd71bb437e55d3a811c7153e03ea0525f3cd6536 | 626,586 |
def isPrime(n):
"""Return True if n is a prime."""
if n > 2 and n % 2 == 0:
return False
for x in range(3, int(n**0.5 + 1), 2):
if n % x == 0:
return False
return True | c9cd5d2346c4548860bda2cf7a5f1f9ced4d1e68 | 626,592 |
def partition_hostname(hostname):
"""Return a hostname separated into host and domain parts."""
parts = hostname.partition('.')
return dict(hostname=parts[0],
domainname=parts[2] if parts[1] == '.' else None) | fd56a97ed369e33252dc44e474c10bd1fe7daba0 | 626,604 |
def solve(tokens):
"""
Given a list of tokens where
each token is subdivided into
a frequency range, a character,
and a string, count the total
number of tokens that are valid
where a token is valid if and only
if the frequency of the character
appearing in the given string lies
... | 3ac31bebe80ac2a75eadc955f79f6a6c971d2b54 | 626,605 |
def remove_multiple_blank_lines(instring):
"""
Takes a string and removes multiple blank lines
"""
while '\n\n' in instring:
instring = instring.replace('\n\n', '\n')
return instring.strip() | b28f64a20301def88f098018d9992b8a8889cc04 | 626,612 |
def parse_custom_command(command: str) -> list:
"""
Convert custom medusa command from string to list to be usable in subprocess.
:param command: Custom medusa command
:return: Parameters for medusa command
"""
command_split = command.split(" ")
command_list = []
for parameter in comma... | 40d4d62b0ec2f5ee950587cdf5cc92e04d580af8 | 626,615 |
import random
def random_element_from_list(element_list):
"""Returns a random element from list."""
return element_list[random.SystemRandom().randint(0, len(element_list) - 1)] | 4ee390d22fa3cfdd32a031fc3b6ec4714b027a9a | 626,621 |
import math
def sqrt(x):
"""Return sqare root of input"""
square = math.sqrt(x)
return square | 75a6626518af1aab06ad68d82cd415aa105737e5 | 626,622 |
def get_or_create_metrics(run):
"""Returns the "subfolder" of the HDF5 file "run/metric" where metrics may be stored."""
if "metrics" not in run:
run.create_group("metrics")
return run["metrics"] | 928e7098252df2b8e562b24024137d5270da9f4b | 626,624 |
import random
def flip_coin(bias=0.5):
"""Flip a biased coin."""
return random.random() <= bias | 09d968888740fff767dbd35cce2d21e602f672a1 | 626,625 |
def rev_c(seq):
"""
simple function that reverse complements a given sequence
"""
tab = str.maketrans("ACTGN", "TGACN")
# first reverse the sequence
seq = seq[::-1]
# and then complement
seq = seq.translate(tab)
return seq | f6951fb2088effeb8326ae415dc664cf8e9a08d2 | 626,626 |
def refresh(session, *entities):
"""Refresh entities from the current session."""
if not entities:
return []
return [session.query(entity.__class__).get(entity.id) for entity in entities] | 771bbf6d2b3671ed70e714a8eaf40b9ca2e3cf9b | 626,627 |
import re
def remove_spaces(text):
"""
Remove all the tabs, spaces, and line breaks from the raw text
Args:
text(str) -- raw text
Returns:
text(str) -- text clean from tabs, and spaces
"""
# remove \t, \n, \r
text = text.replace("\t", "").replace("\r", "").replace("\n", "")... | 64e0da2b0a6c274476ed1a560fd814479608908b | 626,628 |
from io import StringIO
from typing import Tuple
import re
import json
def parse_timewarrior_data(input_stream: StringIO) -> Tuple[dict, list]:
"""
Parse data passed to report from timewarrior.
"""
header = 1
config = dict()
body = ""
for line in input_stream.readlines():
# Extract... | 942a12348f41b35dc10c8780bafa647c6460c05a | 626,629 |
def mint(string):
"""
Convert a numeric field into an int or None
"""
if string == "-":
return None
if string == "":
return None
return int(string) | 1820bce7bf94c7735204336f98a0a6ad53cdee6f | 626,633 |
import string
def remove_punctuation_and_lower(s):
"""
This will return a string without puntuation and all words are in lower-case.
The punctuation symbols are get from the module 'string'.
The set of punctuation symbols are '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
"""
return s.translate(str.make... | 056f3d49626080ca0e3d64794980ea039e073f8e | 626,636 |
def to_bool(bool_str):
"""Convert a string to bool.
"""
return True if bool_str.lower() == 'true' else False | a581f9a4970b9d363326bdd2780e23897bc9791a | 626,642 |
def hs_library_pattern(name, mode = "static", profiling = False):
"""Convert hs-libraries entry to glob patterns.
Args:
name: The library name. E.g. HSrts or Cffi.
mode: The linking mode. Either "static" or "dynamic".
profiling: Look for profiling mode libraries.
Returns:
L... | c432eda9162d7bc7be4e7c84cae446b6583839c4 | 626,644 |
import struct
import fcntl
import termios
def terminal_size() -> tuple:
"""
Get terminal width and height
"""
packed_struct = struct.pack('HHHH', 0, 0, 0, 0)
h, w, hp, wp = struct.unpack('HHHH', fcntl.ioctl(0, termios.TIOCGWINSZ,
packed_struct)... | e7cb16ef46c57fcc57d45cc3fbac302eff869249 | 626,645 |
def split_by_lines(text, remove_empty=False):
"""
Split text into lines. Set <code>remove_empty</code> to true to filter out
empty lines
@param text: str
@param remove_empty: bool
@return list
"""
lines = text.splitlines()
return remove_empty and [line for line in lines if line.strip()] or lines | 875405e0c3ef981ed4c2cee367577d233558955d | 626,646 |
import re
def expand_distances(d_expression):
"""
Check if a distance expression contains at least one term d[x]. If yes, then
the distances are expanded and we assume the user has specified an
expression such as d[0] + d[2].
"""
regexpr = re.compile(r'.*d\[\d*\].*')
if regexpr.match(d_exp... | 1b0d4d2eac123615a16ee6d92009a6c079d21447 | 626,656 |
def eliminate_from_neighbors(csp, var) :
"""
Eliminates incompatible values from var's neighbors' domains, modifying
the original csp. Returns an alphabetically sorted list of the neighboring
variables whose domains were reduced, with each variable appearing at most
once. If no domains were reduce... | 2a37e8dc89650f5b1bac80f0f7f2ba1746e15f54 | 626,657 |
def generate_triangular_board(edge=7, mirrored=False):
"""
Creates a board with a shape of equilateral triangle.
The size of the triangle's side (in fields) is specified by the edge argument.
By default the resulting board will be a triangle pointing down (pointy top)
of right (flat top). Setting m... | 61b19fa464444952a04c17d3d060e7e1b70f187b | 626,660 |
def compose(func_1, func_2, unpack=False):
"""
compose(func_1, func_2, unpack=False) -> function
The function returned by compose is a composition of func_1 and func_2.
That is, compose(func_1, func_2)(5) == func_1(func_2(5))
"""
if not callable(func_1):
raise TypeError("First argum... | 2b1cd3acc28533a766adeb935f57a31563f92f60 | 626,662 |
import logging
import json
def loadjson(jsonfile):
"""Load content from json file as dictionary.
Parameters
----------
jsonfile : str
Path to json file to be read.
Returns
-------
d : dict
Dictionary of the content stored in the json file.
"""
logging.info("... | 920787e4cd7c314ed836a7afe2768f12a29342b0 | 626,666 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.