content stringlengths 39 9.28k | sha1 stringlengths 40 40 | id int64 8 710k |
|---|---|---|
from typing import Tuple
import itertools
def get_img_windows_list(img_shape: Tuple[int, int], tile_size: int):
"""
return list of tiles coordinate inside an image
currently the tile are computed without overlaping and by rounding
so union of all tiles are smaller than image.
Tile are square.
... | ac245fb96587a3610b0950502276b5473b63db25 | 517,223 |
def groupwise_normalise(gs):
"""
Normalises each group of GeoSeries
:param gs: GeoSeries
:return: normalised GeoSeries
"""
return gs.groupby(level=0).apply(lambda x: x / x.sum()) | e0c87701658481ccea01828c75244b7a1043ee29 | 13,447 |
import tempfile
def create_named_text_file(dir: str, prefix: str, suffix: str) -> str:
"""
Create a named unique file.
"""
fd = tempfile.NamedTemporaryFile(
mode='w+', prefix=prefix, suffix=suffix, dir=dir, delete=False
)
path = fd.name
fd.close()
return path | 7876515d9243ca11d7954b0c259d1bd83c213dea | 402,248 |
def next_params(args, result):
"""Get the parameters for making a next link."""
next_offset = result['offset'] + result['limit']
if result['total'] > next_offset:
params = {'offset': next_offset}
for k, v in args.iterlists():
if k in ['offset']:
continue
... | 26475750fd50c08018ff88d89e2c473fe989a1ca | 398,777 |
def solution(array):
"""
ret = max{a[i] + a[j] + i - j} = max{a[i] + i} + max{a[j] - j}
"""
# 假设 第一个观光点是 0
ret, aii = 0, 0
for j, aj in enumerate(array):
# max{a[j] - j}
ret = max(ret, aj - j + aii)
# max{a[i] + i}
aii = max(aii, aj + j)
return ret | 5a1d764ee583a47ac9ab4020505c1fe37af5b8c5 | 581,761 |
import locale
import math
def parse_unit(s, unit, ceil=True):
"""Converts '123.1unit' string into ints
If ceil is True it will be rounded up (124)
and and down (123) if ceil is False.
"""
flt = locale.atof(s.split(unit)[0])
if ceil:
return int(math.ceil(flt))
return int(math.floo... | 8bd27dc8534d0bf7a5f03f41098b39bc7d5aa470 | 440,373 |
def get_lib_name(lib):
"""Returns the name of a library artifact, eg. libabc.a -> abc
Args:
lib (File): A library file
Returns:
str: The name of the library
"""
# On macos and windows, dynamic/static libraries always end with the
# extension and potential versions will be befor... | bafb2ef68cba448a2419c22977c40f103a426e9a | 517,017 |
def contains(a: str, b: str) -> bool:
"""Returns true if a contains all chars in b."""
return all([c in a for c in b]) | af90fae1f29af856e9aafbec6fd9f2a44d9331c1 | 137,042 |
def EnsureFull(path):
"""Prepends 'end_snippet', making it the full field path.
Args:
path: the path to ensure is full.
Returns:
The path made full.
"""
if not path.startswith("end_snippet."):
path = "end_snippet." + path
return path | 5de3d0a939c0c869eb9f52a9748597d574521fb3 | 510,588 |
from pathlib import Path
def file_exists(file_path):
"""Determines whether or not a file exists."""
path = Path(file_path)
exists = path.is_file()
return exists | ac6e573fe2152ec30e02e3301de948dc4a87e327 | 468,509 |
def _schultz_get_closest_extrema(contour):
"""
Part of Step 11.
Returns the closest repeating extrema to the start and end of the contour.
From Ex15B:
>>> contour = [
... [1, {1, -1}],
... [3, {1}],
... [0, {-1}],
... [3, {1}],
... [0, {-1}],
... [3, {1}],
... [0, {-1}],
... [3, {1}],
... [2, {1... | ae3374457f3d9d7cb34c14c47c0827e6001da350 | 413,436 |
def sanitise_db_creds(creds):
"""Clean up certain values in the credentials to make sure that the DB driver
doesn't get confused.
"""
tmp = {}
for name, value in creds.items():
if name == 'port':
tmp[name] = int(value)
elif name == 'password':
tmp['passwd'] = ... | a5f3e8d4aab2f5959a8a03833f7c3be653234126 | 18,547 |
def encode_classes(df):
"""Encodes the output classes as integers and returns a
dictionary of the encodings.
Parameters
----------
df : Pandas DataFrame
The dataframe containing the photometry of all events.
Returns
-------
Pandas DataFrame
The same dataframe with en... | fb1f6384e04e86b033e4b079676468a4e7e4ff60 | 64,317 |
def find_neighbors_hexagonal_grid(map_coordinates: list, current_position: tuple) -> list:
"""Finds the set of adjacent positions of coordinates 'current_position' in a hexagonal grid.
Args:
map_coordinates (list): List of map coordinates.
current_position (tuple): Current position of the hexag... | 2a6071d59a69b828eb252504508fa3f706969e1b | 698,662 |
import pprint
def dict_to_string(dict_):
"""Converts a dictionary into a pretty string
"""
return pprint.pformat(dict_) | d6dec89db37ae9e1c2f32d97595ff9e02146c326 | 622,167 |
def wrap(x):
""" Ensure x is a list of float """
if x is None:
return None
elif isinstance(x,(float,int)):
return [float(x)]
else:
return list(x) | e3031a96e08466487e6874e149989d55ecf21e2a | 191,611 |
def get_gpu_count () -> int:
"""
Special handling for detecting GPU availability: an approach
recommended by the NVidia RAPIDS engineering team, since `nvml`
bindings are difficult for Python libraries to keep updated.
returns:
count of available GPUs
"""
try:
import pynvml # type: ignore # p... | e51e9e803977fc5397ffa8b155a4b7b157b00d98 | 130,731 |
def list2str(l):
"""
Convert list to a string
:param l: list
:returns: list <string>
"""
s = ''
for i in range(len(l)):
s = s + str(l[i])
return s | 94e70d371f4c81c08dbdd7d2a583b9c2e68500a8 | 49,152 |
def _threshold_calc(random_edge, max_edge, vertex_degree):
"""
Calculate threshold for branch_gen function.
:param random_edge: number of vertex edges
:type random_edge: int
:param max_edge : maximum edge number
:type max_edge : int
:param vertex_degree: vertex degree
:type vertex_degre... | be50dd97241b2f5aa58c2c67bf9c52f3bde6b361 | 126,633 |
def args_to_list(items):
"""Convert an argument into a list of arguments (by splitting each element on comma)"""
result = []
if items is not None:
for item in items:
if item:
for val in item.split(','):
val = val.strip()
if val:
... | 1c73ec092160f311c0fa663d4dc4b6a4b717d5c0 | 118,872 |
def _get_sstable_proto_dict(*input_values):
"""Returns table key -> serialized proto map.
This function exists because the create_parse_tf_example_fn operates on
dequeued batches which could be 1-tuples or 2-tuples or dictionaries.
Args:
*input_values: A (string tensor,) tuple if mapping from a RecordIO... | c0d3b3aa9b423115a141b9fddfe6b1aca08912c2 | 426,445 |
def multiply_two_polynomials(polynomial_1: list, polynomial_2: list) -> list:
"""
This function expects two `polynomials` and returns a `polynomial` that contains
their `produce`.
:param polynomial_1: First polynomial
:param polynomial_2: Second polynomial
:return: A polynomial representing the... | 1e859089bb2d5178f745dcb0db13c39e9fcf7512 | 217,363 |
def _get_shlib_stem(target, source, env, for_signature: bool) -> str:
"""Get the base name of a shared library.
Args:
target: target node containing the lib name
source: source node, not used
env: environment context for running subst
for_signature: whether this is being done fo... | 196cb810731944270199e3a90548a3e6e8772a6e | 152,339 |
def bool_to_string(b):
"""Convert a boolean type to string.
Args:
b (bool): A Boolean.
Raises:
TypeError
Returns:
str: String representation of a bool type.
"""
s = str(b).lower()
if s in ["true", "false"]:
return s
raise TypeError("Value must be True o... | 586cd8312ba071982bf7db407d568181796e8e8e | 86,586 |
def place_rfs(length,count,width):
"""
place-rfs - returns a list of receptive field index lists
for use as rf-indices in an rf-array
params
length = the length of the input vector
count = the number of rfs
width = the width of each rf
The rfs will be placed such that the... | 94c13f594fcd9e8990792842b0020d00373c6415 | 278,454 |
def _process(json_data):
"""Return a list of filenames grouped by iteration."""
iterations = []
for iteration in json_data[u'iterations']:
filenames = [x[u'filename'] for x in iteration[u'spreadsheets']]
iterations.append(filenames)
return iterations | 98c89b637849c53d6cb2e67467f541bcb0e4099b | 341,209 |
def is_column_fully_sorted(column, max_column_length):
"""Check if a column is fully sorted, that is, if it's empty or full of the same colour
>>> is_column_fully_sorted(['b', 'b', 'b', 'b'], 4)
True
>>> is_column_fully_sorted([], 4)
True
>>> is_column_fully_sorted(['b', 'b', 'b', 'o'], 4)
... | cb3c7f06e3934b33d5657e8937ad276c1a751f61 | 276,916 |
def get_cutout(image, cutout_size):
"""Takes an image, and cuts it down to `cutout_size x cutout_size`
It only affects the final two dimensions of the array, so
you can easily deal with multiple images / multiple channels
simply by setting up the array with shape (n_channels, height, width)
Inp... | e6d70e395b3b5b032565fa39ee09d1b71bbfb4c8 | 601,690 |
def require_dict_kwargs(kwargs, msg=None):
""" Ensure arguments passed kwargs are either None or a dict.
If arguments are neither a dict nor None a RuntimeError
is thrown
Args:
kwargs (object): possible dict or None
msg (None, optional): Error msg
Returns:
dict: kwarg... | 12a66114dd24d316e0229225126f6d2af2d3f0e6 | 472,352 |
def simd_loop_filter(loops, tuning):
""" Filter out the SIMD candidate loops based on the tuning information.
We select the legal simd loop with the highest score.
If there is no such loop, we will set "loops" to all "1"s.
AutoSA will not tile loops with the tiling factor as one for latency hiding or
... | bf9c261aa6a3af7fd4cb30205f3745c7ed29a551 | 637,149 |
import configparser
def load_status(status_file):
"""
Load pipeline status
Args:
status_file (string): name of configparser file
Returns:
configparser.RawConfigParser
"""
config = configparser.RawConfigParser()
gl = config.read(status_file)
return config | bd118146e10f632c1edfed7c362eb5a39fa61069 | 578,072 |
def batch_by_property(items, property_func):
"""
Takes in a list, and returns a list of tuples, (batch, prop)
such that all items in a batch have the same output when
put into property_func, and such that chaining all these
batches together would give the original list (i.e. order is
preserved)
... | 8b01fa3f882bf3298e67432f67657476577831f8 | 549,663 |
def no_filter(img, m, *args):
"""filter that does nothing
Parameters
----------
img : 2D array (float)
image
m : scalar (float)
filter width
Returns
-------
output : 2D array (float)
same image as input
"""
return img | 88e42c8fd82aa27bb8a66eed59281be5fd809605 | 271,597 |
def get_I0_Phi0(self):
"""Return I0 and Phi0
Parameters
----------
self : OPslip
An OPslip object
Returns
-------
I_dict : dict
Dict with key "I0", "Phi0"
"""
return {"I0": self.I0_ref, "Phi0": self.IPhi0_ref} | ef7316f0fcbcf7b4bd5ed22e640eb8534bb1a963 | 132,087 |
def to_lower_case(given: str) -> str:
"""Returns 'given' in lower case
>>> to_lower_case("0D")
'0d'
"""
return given.lower() | 23e8298f7f4e33b827a76a7c17d1e5468f6d5fd1 | 19,278 |
def get_span_literal(span):
"""Get the literal value from an entity's TargetRule, which is set when an entity is extracted by TargetMatcher.
If the span does not have a TargetRule, it returns the lower-cased text.
"""
target_rule = span._.target_rule
if target_rule is None:
return span.text.... | ccd7bd17d4cd3da56b973b8667c67ebc67d6b219 | 406,161 |
def split_path(path):
"""
Normalise GCSFS path string into bucket and key.
"""
if path.startswith('gs://'):
path = path[5:]
path = path.rstrip('/').lstrip('/')
if '/' not in path:
return path, ""
else:
return path.split('/', 1) | d4f1881b9d280f9a5bca003e69b017bf2f408e54 | 101,477 |
def fix_line_breaks(text):
""" Convert Win line breaks to Unix
"""
return text.replace("\r\n", "\n") | c4c698fce80d7c3820f689a163d0df19ea682573 | 679,240 |
def despine(chart):
"""Despine altair chart.
"""
chart = chart.configure_axis(
ticks=False,
grid=False,
domain=False,
labels=False)
return chart | fe9c713f0320ecb58e1aea89799502be0073c6ec | 277,982 |
def projects_id_contacts_get(id):
"""
List all contacts associated with this project
:param id: Project id
:type id: int
:rtype: List[Contact]
"""
return 'do some magic!' | 0dec8c0bda6f8d5a6de0d028415c83c7c09624f5 | 344,897 |
def end_ignore_marker() -> str:
"""
Creates an end ignore marker.
:returns: The end ignore marker.
"""
return "# nb--ignore-end\n" | 18d08bf9844003d841dc89003e6a4b5457d18628 | 542,017 |
def _prefixscan_combine(func, binop, pre, x, axis, dtype):
"""Combine results of a parallel prefix scan such as cumsum
Parameters
----------
func : callable
Cumulative function (e.g. ``np.cumsum``)
binop : callable
Associative function (e.g. ``add``)
pre : np.array
The v... | 95eff470bc28cb55519608391686781edb2dce1c | 479,316 |
def bool_to_str(boolean: bool) -> str:
"""Bool to str."""
return str(boolean) | d67aaf110f850108b0503e8731aabb28a4fbc89c | 610,983 |
def crosscorr(data1, data2, lag=0, wrap=False):
""" Lag-N cross correlation.
Take two time series data1 and data2 then shift series 2 by a lag (+ve or -ve)
and then see what correlation between the two is.
Either wrap data around to fill gap or shifted data filled with NaNs
Parameters
-----... | 0f7f965d10b2ca8604b46f08f279eda479aafc81 | 143,136 |
def return_default_nb_of_cores(nb_of_cores, openmp_proportion=2):
"""Function that returns the number of cores used by OpenMP and Nipype by default.
Given ``openmp_proportion``, the proportion of cores dedicated to OpenMP threads,
``openmp_nb_of_cores`` and ``nipype_nb_of_cores`` are set by default to the ... | a1f0be9b795eb64eedec01ef58afe49c98fadc54 | 335,469 |
def dwid_exists(dwid, cursor):
"""See if a dwid exists in the database or not. If yes, return 1,
if not return 0."""
array = (dwid,)
cursor.execute('SELECT * from dwids where dwid=?', array)
if cursor.fetchone():
return 1
else:
return 0 | 08586088a14cdc11f8308da3d3038667c672fc13 | 644,637 |
import typing
import grp
def get_group_by_name(name: str) -> typing.Optional[typing.Mapping]:
"""
Get group info by group's name from group database.
"""
try:
group = grp.getgrnam(name)
return dict(gid=group.gr_gid, name=group.gr_name, members=group.gr_mem)
except KeyError:
... | 7d23c3d5e2ac58b679df4f499d5b764e2b9d0516 | 244,127 |
def _resolve(scope, key, context):
"""
Resolve scope and key to a context item
Provides very minimal validation of presence
Parameters
----------
scope: str
singular variant of scope in context
key: str
key to lookup context item in context within scope
context: dict
... | ac4bb1cc4ba485a34dc1c915949a4c838a64408a | 110,188 |
import random
def random_apply(img, transforms, prob):
"""
Apply a list of transformation, randomly with a given probability.
Args:
img: Image to be randomly applied a list transformations.
transforms (list): List of transformations to be applied.
prob (float): The probability to ... | 849c94fe6696bd724c02826e0677e3351537d257 | 393,072 |
def parse_size(s):
"""
Converts a string to an integer
Example input can either be: '(1234)' or '1234'
Example output: 1234
"""
s = s.replace('(', '').replace(')', '')
return int(s) | 510527930f5986e623d10a7834a452c2d4b61ebc | 298,574 |
def netperf_commands(target_ips):
"""Generate latency or throughput commands for netperf
Args:
target_ips (list(str)): List of ips to use netperf to
mode (str): Generate latency or throughput commands
Returns:
list(str): List of netperf commands
"""
lat_commands = []
tp... | 53879db0c29f2db3c259b774e997a39bcd41efd3 | 429,227 |
import base64
def get_image(image_uri):
"""
Loads a local png to be shown in dash
Args:
image_uri: uri of the image
Returns:
the string to be placed in a html.Img container
"""
with open(image_uri, "rb") as file:
encoded = base64.b64encode(file.re... | ccc360b0d37281c36ccfb2ffef4569d48ac201a9 | 211,800 |
def humanize_time(secs):
"""Convert seconds into time format.
:type secs: integer
:param secs: the time in seconds to represent in human readable format
(hh:mm:ss)"""
mins, secs = divmod(secs, 60)
hours, mins = divmod(mins, 60)
return '%02d:%02d:%02d,%s' % (hours, mins, int(secs),
... | c8771ab7c65372c67f72575a0a023864cda25802 | 78,494 |
import requests
def url_ok(url):
"""
Checks that a given URL is reachable.
:param url: A URL
:rtype: bool
"""
return requests.head(url).ok | f4aa22e55a6c05948488fcb16098c4ed76f9c0d6 | 31,649 |
def get_complete_phrases(ph2parse, tf_api):
"""Retrieve phrases completely covered by the parsings.
The phrase atom parser runs on phrase_atoms, which are
component parts of a complete phrase. In some cases the
parser was unable to parse a phrase_atom, meaning that
some phrases are left withou... | c08c3880fbcbd0f92591a2467c3fc2fb3fafc3ef | 398,236 |
import socket
def find_unused_port(base=1025, maxtries=10000):
"""Helper function. Finds an unused server port"""
if base > 65535:
base = 1025
for _ in range(maxtries):
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
serversocket.bind(("localhost",... | 1af439ac6882b760ce5a6b0abded895c8b0d1d12 | 645,203 |
def clean_string(string):
"""Removed unwanted characters from string."""
return string.replace(" ", "_").replace("'", "_").replace(".", "").replace(",", "_").encode('ascii', errors='ignore').decode() | 828dbfde7aa9300af99a722c4a31497b7c4e1958 | 233,993 |
def clean_state_labels(system_labels, system_charges):
"""Convert system labels and charges into clean labels like C$^{+}$.
Typically used for figure axes and labels.
Parameters
----------
system_labels : :obj:`list` [:obj:`str`]
Specifies the atoms in the system.
system_charges : :obj... | bca32ffd837eba3d188a8f5188beb60be99a3822 | 362,883 |
def strip_query(path):
"""Strips query from a path."""
query_start = path.find('?')
if query_start != -1:
return path[:query_start]
return path | 05245f7fead449431e5af0007ad61da42b3ac246 | 623,505 |
def get_parents(cur, term_id):
"""Return a set of parents for a given term ID."""
cur.execute(
f"""SELECT DISTINCT object FROM statements
WHERE stanza = '{term_id}' AND predicate IN ('rdfs:subClassOf', 'rdfs:subPropertyOf')
AND object NOT LIKE '_:%'"""
)
return set([x[0] ... | 31992acc6dfa72a60e4c9b522c665956e7c2c0c1 | 398,565 |
def euclid_dist(in_array1, in_array2):
"""
Computes the squared euclidean distance between two NumPy arrays
Parameters
----------
in_array1 : 1D ndarray of floats
NumPy array of real values.
in_array2 : 1D ndarray of floats
NumPy array of real values.
Returns
-------
... | 6e596d40b26d73f391f6a678af0403384b7f1d44 | 247,254 |
def xpath_class(name):
"""Returns an XPath expressions which finds a tag which has a specified
class."""
return 'contains(concat(" ", @class, " "), " %s ")' % name | c9ceb34fff0dbb251ff82ab9522018d1fe8095ad | 384,994 |
import re
def get_sub_formula(formula):
"""
"(SO3)2" -> ("(SO3)2", "(SO3)", "2")
"(SO3)" -> ("(SO3)", "(SO3)", "")
"""
match = re.search('(\([a-zA-Z\d]+\))(\d*)', formula)
if not match:
return
full_sub_formula = match.group(0)
sub_formula = match.group(1)
multiplier = ma... | b0f4570aff6e8678a3a4901968020d995ed81535 | 195,368 |
def clean_text(text):
"""
Given a block of text, clean it to remove unwanted characters other cruft.
This will:
1. Strip newlines - we don't care about them for word counts,
2. Cast to lowercase for consistency.
3. Replace / with a space, retaining the words on either side of the /
4. Repla... | 24879e8220637a4a5f97fa1dbdb81c1c83c07477 | 149,450 |
import torch
def redistribute_errors(power_deltaE_hyab, cmax, pc, pt):
"""
Redistributes exponentiated HyAB errors to the [0,1] range
:param power_deltaE_hyab: float tensor (with Nx1xHxW layout) containing the exponentiated HyAb distance
:param cmax: float containing the exponentiated, maximum HyAB difference be... | 3e5ce06b0e1ef68b3c04dbc4476ad7e890d91354 | 670,653 |
def make_words(text):
"""
make a list of words from a large bunch of text
Strips all the punctuation and other stuff from a
large string, and returns a list of words
"""
replace_punc = [('-', ' '),
(',', ''),
(',', ''),
('.', ''),
... | a45b2b0cf4c9fd83addc002426da3b5196da15e8 | 626,402 |
import re
def is_bvlapi_guid(guid):
""" Checks that a given string is potentially a GUID used by the API.
:param str guid: a string that might be a GUID
:rtype: bool
:return: is the given string a GUID?
"""
return re.match(r"^BVBL", guid) | ee2900effa8efa2b7bd3c4327f533d63a678d2ff | 360,801 |
def xyxy2xywh(box):
"""
Convert bounding box from xyxy to xywh format
:param box: array-like, contains (x1, y1, x2, y2)
"""
x1, y1, x2, y2 = box
w, h = x2 - x1, y2 - y1
x_c = x1 + w / 2
y_c = y1 + h / 2
return x_c, y_c, w, h | af8b5d4568dfc29a71164ccef58f15b9c06f695a | 34,874 |
def get_xy(artist):
"""Gets the xy coordinates of a given artist"""
if "Collection" in str(artist):
x, y = artist.get_offsets().T
elif "Line" in str(artist):
x, y = artist.get_xdata(), artist.get_ydata()
else:
raise ValueError("This type of object isn't implemented yet")
retu... | 535c0ee0307eac5645debc841dcdd89885c10600 | 128,213 |
def ordinal(string, d):
"""Return the ordinal of the character at dth position.
Specifically, the ordinal of end-of-string is defined to be -1.
"""
if d < len(string):
return ord(string[d])
elif d == len(string):
return -1
else:
raise IndexError | 64b96e6d1a489281ca068c59c89473a94bbc89f2 | 572,741 |
def starts_with(values, list):
"""Checks if a list starts with the provided values"""
return list[: len(values)] == values | 3b1da3a42f707b9d082b0f9734fbb5b0b763dcd1 | 242,115 |
def not_none(seq):
"""Returns True if no item in seq is None."""
for i in seq:
if i is None:
return False
return True | 0995fbce79593a7202574eee8c25b45e872ec61b | 134,211 |
def calculate(nth_number):
"""Returns the difference between the sum of the squares and the
square of the sum of the specified number of the first natural numbers"""
sums = sum(number for number in range(1, nth_number + 1))
sum_of_squares = 0
for number in range(1, nth_number + 1):
sum_of_sq... | ea5ca1233524e052536a74993718803c74f7c856 | 316,007 |
def bool_converter(value: str) -> bool:
"""
:param value: a string to convert to bool.
:return: False if lower case value in "0", "n", "no" and "false", otherwise, returns the value returned
by the bool builtin function.
"""
if value.lower() in ['n', '0', 'no', 'false']:
return False
... | 10251dfbb0200297d191dce1eb20237aed9e5ac9 | 11,550 |
from typing import List
def format_results(json_results: List) -> str:
"""
Purpose:
Format the json to a text response
Args:
json_results: crash data
Returns:
text_string: formatted text
"""
text = ""
if len(json_results) == 0:
text += "No 311 requests in t... | da8d1487bc9fcafd66bd1c13e2ee19876fd68f28 | 206,023 |
import torch
def is_sparse_tensor(tensor):
"""Check if a tensor is sparse tensor.
Parameters
----------
tensor : torch.Tensor
given tensor
Returns
-------
bool
whether a tensor is sparse tensor
"""
# if hasattr(tensor, 'nnz'):
if tensor.layout == torch.sparse_... | 8d7019b3bacab1e4139a00de9d69fef188477eb6 | 248,672 |
def get_block(cur, cp):
"""get block name of a codepoint"""
cur.execute("SELECT name FROM blocks WHERE first <= %s AND last >= %s", (cp,cp))
blk = cur.fetchone()
if blk:
blk = blk['name']
return blk | fbae26d4f262b6416a0d3b7abb2a1b83493ef8ca | 331,049 |
from typing import List
def group_consecutive_elements(l: list) -> List[tuple]:
"""Group consecutive elements of a list into a list of tuples
"""
return list(zip(l, l[1:])) | aea550fa3cf43bf4afd08d96c9d94803e88fb4a1 | 547,056 |
def katdal_ant_name(aips_ant_nr):
"""Return antenna name, given the AIPS antenna number"""
if aips_ant_nr < 65:
res = f'm{(aips_ant_nr-1):03d}'
else:
res = f's{(aips_ant_nr-65):04d}'
return res | 0c2bd8bfe1a9db42ce4853dd7125ba9fdc5e4534 | 312,511 |
def flip_y_perspective(row:int, current_player:int, is_vwall:bool=False)->int:
"""Flip row coordinates for player 1 so that -- no matter who the 'current player' is -- the enemy's gate is down.
Note that flip_y_perspective is its own inverse, so flip_y_perspective(flip_y_perspective(r, c, v), c, v) == r
""... | f649010a56676b22c4491bb9fb6624d10218acd7 | 217,836 |
def calculate_fg(row, fgsum, fgsub):
"""This function calculates a new functional group to be added to the
dataframe
fgsum : list of str (functional groups to add)
fgsub : list of str (functional groups to substract)
returns : count (int)"""
count = 0
for fg in fgsum:
count += row[fg... | 2178e0ea01ba0dfdf9f81cb0fef867007d4e74a5 | 261,981 |
def create_stream(client, name, description, member_emails, invite_only, mandatory_streams=None):
"""
Create a stream in Zulip and invite users to it.
:param client: A Zulip client object
:param name: Name of the stream
:param description: Description of the stream
:param member_emails: List of... | 394ec06e9cca378244ff57117a4c2be9c6a39523 | 178,059 |
def GetCorrespondingResidue(seqs, i):
"""Gets the corresponding residue number for two aligned sequences.
*seqs* is a set of two aligned sequences as *(head, sequence)* 2-tuples.
*i* is the number of a residue in sequential numbering of *seqs[0]*
without considering any of the gaps induced by alignmen... | 1f9e43b7e962bfab2d4db874d26728a9f6183750 | 522,751 |
def get_parametrize_markers_args(node):
"""In pytest 3.6 new API to access markers has been introduced and it deprecated
MarkInfo objects.
This function uses that API if it is available otherwise it uses MarkInfo objects.
"""
return tuple(arg for mark in node.iter_markers("parametrize") for arg in ... | b143d8be0d967bad6f6e7bee59828a45da9dea6a | 617,159 |
from typing import Dict
from typing import OrderedDict
def create_constraint_statements(schema_name: str,
table_name: str,
constraints: Dict,
**kwargs) -> Dict:
"""Function for generating primary key definitions def... | 1282eefa92682fb8214797e5b0fff4618565f3f8 | 385,272 |
def _to_iloc(data):
"""Get indexible attribute of array, so we can perform axis wise operations."""
return getattr(data, 'iloc', data) | 137dc760dc1e33e319017a0b8356a5e12add6b61 | 677,584 |
def is_harmony_cli(args):
"""
Returns True if the passed parsed CLI arguments constitute a Harmony CLI invocation, False otherwise
Parameters
----------
args : Namespace
Argument values parsed from the command line, presumably via ArgumentParser.parse_args
Returns
-------
is_ha... | f285bd9e904680266a93e65f82497abba7aef5f0 | 137,630 |
def fix_pyext(mod_path):
"""
Fix a module filename path extension to always end with the
modules source file (i.e. strip compiled/optimized .pyc, .pyo
extension and replace it with .py).
"""
if mod_path[-4:] in [".pyo", "pyc"]:
mod_path = mod_path[:-1]
return mod_path | 56adb08f200a7e63c30080472fb30c7a681eee64 | 560,203 |
import socket
def verify_inet_protocol(inet_protocol):
"""Verify the ``INET_PROTOCOL`` from a proxy protocol line.
Args:
inet_protocol (bytes): The segment from the proxy protocol line.
Returns:
socket.AddressFamily: The address family enum associated with the
protocol.
Rais... | d153127d0312732939141e8829c24712f76d6c2a | 532,360 |
def merge_outputs(*outputs):
"""
Merges model outputs for logging
Parameters
----------
outputs : tuple of dict
Outputs to be merged
Returns
-------
output : dict
Dictionary with a "metrics" key containing a dictionary with various metrics and
all other keys tha... | 6de690a5a8ec4f114d2fd3ab451879585b36376e | 520,849 |
def splitXY(dfXY):
"""
Takes a dataframe with all X (features) and Y (labels) information and
produces four different dataframes: nuclide concentrations only (with
input-related columns deleted) + 1 dataframe for each label column.
Parameters
----------
dfXY : dataframe with nuclide conce... | 8a2f0a331b8c8ece3f10c2e8e645f1c083125fb5 | 521,444 |
def _find_idx_without_numerical_difference(df, column1, column2, delta, idx=None, equal_nan=False):
"""
Returns indices which have bigger numerical difference than delta.
INPUT:
**df** (DataFrame)
**column1** (str) - name of first column within df to compare.
The values of df[c... | 9ed9f34b1b8718ee213fd7b8832e5efe7365f116 | 683,342 |
def get_all_items(list_widget, as_string=True):
"""
Gets all the items in a listWidget as a list
:param list_widget: your QListWidget
:param as_string: <bool> if set to true, will return the text of the item. If set to false will return the actual QListWidgetItem
:return: items of your QListWidget
... | 1b3fe7c8660075d65c28ef8e235359e56d3b5e7d | 85,386 |
from typing import Dict
def add_prefix_to_param(prefix:str, param_grid:dict) -> Dict[str,list]:
"""
Create a param_grid for Pipeline from an "ordinary" param_grid.
:param prefix: name of the step
:param param_grid: ordinary grid_param
:return: modified dict
"""
return { "%s__%s" % (prefix... | 542057cb3fea7da078070860793930cae55a8e3e | 282,723 |
def get_abos_options(clang_version_info):
""" Get options to enable aggressive-binary-operation-simplification.
Returns list of options which enables
aggressive-binary-operation-simplification option (which is needed for the
iterator checker) if the Clang version is greater then 8.
Otherwise return... | 3e7b78d1a085d8540accf96033e1039c9d329bea | 445,207 |
import requests
def get_remaining_rate_limit(api_key: str) -> int:
"""
Returns your remaining rate limit by
making a request to
:ref:`Apod <extensions/apod:Apod>` and
getting the header ``X-RateLimit-Remaining``,
that's returned on every API response.
For example, if you are using an
... | 39a1b49ca9148a655cc90e25f8a1b8027f4821b5 | 34,318 |
def is_upsidedown_wrong(name):
"""Tell if the string would get a different meaning if written upside down"""
chars = set(name)
mistakable = set("69NZMWpbqd")
rotatable = set("80oOxXIl").union(mistakable)
return chars.issubset(rotatable) and not chars.isdisjoint(mistakable) | bc281a66f004e29acb972007eb65d6e131eabb8e | 478,942 |
def get_related_field_model(field):
"""Returns a field's related field model's app and name or None"""
if field.rel:
model = field.rel.to
return {
'app': model._meta.app_label,
'model': model._meta.object_name
}
else:
return None | 23a872f83ec0be1778afae2fda6df5cabd2e0f24 | 448,545 |
def num2columnletters(num, power=0):
"""
Takes a column number and converts it to the equivalent excel column letters
:param int num: column number
:param int power: internal power multiplier for recursion
:return str: excel column letters
"""
if num <= 26:
return chr(num % 27 + 64)... | 39096fc9df99baba6ddbc1a7a48a7eb0068ddf44 | 632,398 |
def isin(elt, seq):
"""Like (elt in seq), but compares with is, not ==.
>>> e = []; isin(e, [1, e, 3])
True
>>> isin(e, [1, [], 3])
False
"""
for x in seq:
if elt is x: return True
return False | 19d451399bcaf38d1db5ac2e9440d678bae8255b | 230,791 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.