content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def buffer_shp_corners(gdf_list, bufferwidth = 0):
"""
Finds the lower left and upper right corners of a list of geopandas.GeoDataFrame objects. Optionally define a buffer (in degrees) around the list GeoDataFrames
:param gdf_list:
:param bufferwidth:
:return:
"""
lonmin = 181
lonmax = ... | feddebe25581590400f6845432e766e3453ebcee | 653,872 |
def write_halos(halos_dset, halos_dset_offset, halos, nhalos_to_write,
write_halo_props_cont):
"""
Writes halos into the relevant dataset(s) within a hdf5 file
Parameters
-----------
halos_dset: dictionary, required
Contains the halos dataset(s) within a hdf5 file where eit... | 408b275401b6f98a6cd6a888519d9681bdc84290 | 653,873 |
def transformPointsToImaris(points, scale = (4.0625, 4.0625, 3), offset = (0,0,0)):
"""Transform pixel coordinates of cell centers to work in Imaris
Arguments:
points (array): point coordinate array
scale (tuple): spatial scale of the image data
offset (tuple): spatial offset of the... | fcd9f6ace54c59c18f5df8816968ed6e99b0bc17 | 653,874 |
import base64
def file_to_base64(filepath):
"""
Returns the content of a file as a Base64 encoded string.
:param filepath: Path to the file.
:type filepath: str
:return: The file content, Base64 encoded.
:rtype: str
"""
with open(filepath, 'rb') as f:
encoded_str = base64.b64e... | 5baa42c50c91ef03c7bdbc12f79a652744975458 | 653,875 |
import shutil
def concatenate_job(job, input_ids):
"""This job just concatenates the input files together and returns them."""
out_path = job.fileStore.getLocalTempFile()
with open(out_path, 'w') as output:
for input_id in input_ids:
input_path = job.fileStore.readGlobalFile(input_id)
... | 63aa0cbab3009180f98aaf1400d4d64e3e57bd8d | 653,879 |
def is_bmp(codepoint):
"""Determine if a codepoint (interger) is in the BMP"""
return codepoint <= 0xffff | 186b1255f4c3e4ac5821e1d4f5c88e926ee8faae | 653,885 |
def str_concat(str1: str, str2: str) -> str:
"""Конкатенация двух строк
Args:
str1 (str): Строка 1
str2 (str): Строка 2
Returns:
str: Новая строка из двух строк
"""
return str1 + ' ' + str2 | c6171da71344adb3fb35bfde83cd64761365b1ec | 653,887 |
def _lines_to_list(path):
"""
Reads file from at the specified path and creates a list which contains
lines from the file, without a newline.
"""
with open(path, 'r') as f:
return f.read().splitlines() | f156c67fda91f08df7fe065ee10eb5c9d9428886 | 653,890 |
def convert(value):
"""Convert value in milliseconds to a string."""
milliseconds = value % 1000
value = value // 1000
seconds = value % 60
value = value // 60
minutes = value % 60
value = value // 60
hours = value % 24
value = value // 24
days = value
if days:
result... | a26921bf1db8655f363360d0215d2d4c12f2e406 | 653,891 |
def get_node_overview(data, requested_nodes):
"""
Creates a dictionary with all node keys as keys, and as value another dictionary which has
all attribute names as keys and the corresponding values as values.
:param data: The data objects corresponding to the nodes
:param requested_nodes: The nodes ... | 1a75d04c0ac0dc15a451137a435ed10cb2edab0f | 653,895 |
def reset_clickData(n):
"""
Resets the click data when new ticker is inserted
:param n: new ticker inserted
:return: None
"""
if n is None:
pass
else:
return None | 1aa808227a0d1b458f3d0df08fd99671d3675d17 | 653,897 |
from pydantic import types
from typing import List
from typing import Type
def get_int_like_types() -> List[Type]:
"""Returns many int-like types from stdlib and Pydantic."""
def _chk(x) -> bool:
try:
return issubclass(x, (int))
except Exception:
return False
can... | 37024a5e5f49442e9ac3dec8f48274f4bacfec25 | 653,901 |
def is_rule_exists_violation(rule, policies, exact_match=True):
"""Checks if the rule is the same as one of the policies.
Args:
rule (FirweallRule): A FirewallRule.
policies (list): A list of FirewallRule that must have the rule.
exact_match (bool): Whether to match the rule exactly.
Ret... | 3972036abb454281ba11288e741b4614f58a4822 | 653,903 |
def validate_higlass_file_sources(files_info, expected_genome_assembly):
"""
Args:
files_info(list) : A list of dicts. Each dict contains the
file's uuid and data.
expected_genome_assembly(str, optional, default=None): If provided,
each file should have this ge... | 42124e5a3132861dc3a81b8751859630761b80d2 | 653,908 |
from typing import Tuple
def get_channel_values(digitalOut, func) -> Tuple:
"""Get the result of applying 'func' to all DigitalOut channels."""
return tuple(func(channel_index) for channel_index in range(digitalOut.count())) | 0f8fffa2bae965e72fe386ae356c8f11b14db9fc | 653,910 |
def _filter_size_out(n_prev, filter_size, stride, padding):
"""Calculates the output size for a filter."""
return ((n_prev + 2 * padding - filter_size) // stride) + 1 | 286b970402e7b5a6d20f87dcaf6107f0eca459f0 | 653,911 |
def is_anyscale_connect(address: str) -> bool:
"""Returns whether or not the Ray Address points to an Anyscale cluster."""
is_anyscale_connect = address is not None and address.startswith(
"anyscale://")
return is_anyscale_connect | 80bf6688d3914f5ea06c3cd398c4b5c4b610997a | 653,912 |
def in_sector_bounding_box(polar_point, radius, start_theta, end_theta):
"""Check if a polar coordinate lies within the segment of a circle
:param polar_point: tuple representing the point to check (r,phi)
:param radius: radius of the segement
:param start_theta: start angle of the segement in rad
... | c6c9c2a53ab75970870adcdea6c2161015a7e8e4 | 653,926 |
import hashlib
def normalize_string(value):
"""
5.1.1.4 - c.3:
String values shall be rendered using the first eight characters of
their md5 (Message-Digest Algorithm) checksum.
"""
md5 = hashlib.md5(value.encode('utf-8')).hexdigest()
return md5[:8] | 0849ffd23fc2e0c82e0786e50adb9a8f22996e62 | 653,927 |
def get_rotation(row):
"""Generate a rotation matrix from elements in dictionary ``row``.
Examples
---------
>>> sdict = { \
'_pdbx_struct_oper_list.matrix[{}][{}]'.format(i // 3 + 1, i % 3 + 1): i \
for i in range(9) \
}
>>> get_rotation(sdict)
[[0.0, 1.0, 2.0], [3.0, 4.0, ... | 2afd9d01aa17b313b64d723c932fd4cd50f77d03 | 653,928 |
import re
import json
def fix_tokens_file(file_path):
"""
Replace each
# ::tok sentence
by json parsable version
# ::token json-parseable-sentence
so that
sentence == json.loads(json-parseable-sentence)
"""
token_line = re.compile('^# ::tok (.*)')
# read and modifiy toke... | 4ba6e2f7feabd1f970a5ccb7da437a765539323b | 653,931 |
def w(el1, el2):
"""
Returns weight based on residue pair
"""
pair = el1 + el2
return int(pair == 'AU' or
pair == 'UA' or
pair == 'GC' or
pair == 'CG') | b20ccb565dc4be5ea668b25314d4beb8f7ee3c0e | 653,933 |
def scan2colfil(x, y, x0, y0, scale, tipo=0):
"""
Transforma de x/y en proyeccion geoestacionaria a
En base a 5.2.8.2 de PUG3
Parameters
----------
x : float, float arr
coordenada vertical, en radianes
x : float
coordenada vertical del primer punto en radianes
x0 : float
... | d047c8ff939119aecec1dde9b9bf08e23e4acca8 | 653,937 |
from typing import Tuple
def create_columns(column_def: Tuple[str, str]) -> str:
"""
Prepare columns for table create as follows:
- types copied from target table
- no indexes or constraints (no serial, no unique, no primary key etc.)
"""
return (','.join(f'{k} {v}' for k, v in column_def)
... | 787ce1c3fc5e37c6055f48424e92eec84eb05448 | 653,938 |
def _tile_size(shape, out_shape, ndim):
"""Returns tile_size such that shape*tile_size = out_shape"""
size = [1] * ndim
for idx, (i, j) in enumerate(zip(shape, out_shape)):
if i != j:
size[idx] = j
return tuple(size) | 6f067243805b252cdabb3a9674d4d5d7fcea2703 | 653,942 |
def has_already_cover(cover_metadata={}):
"""Check if record has already valid cover in cover_metadata."""
return cover_metadata.get("ISBN") or cover_metadata.get("ISSN") | 7a1a09e4faa9d37f2d8b742fb91f8554bf83ff5a | 653,945 |
def append_concat_predictions(y_batch, predictions):
"""
Args:
y_batch (torch.Tensor or list):
predictions (list): accumulation list where all the batched predictions are added
Returns:
list: predictions list with the new tensor appended
"""
if isinstance(y_batch, list):
... | 5659b77899dd3a48f24de3bef05b0c7e73cf8cea | 653,949 |
def remove_comments(s):
"""remove comments (prefaced by #) from a single line"""
r = s.split("#")
return r[0] | 73724d2d1d39efb97c95607be8048d9300a174be | 653,950 |
def compact(objects):
"""
Filter out any falsey objects in a sequence.
"""
return tuple(filter(bool, objects or [])) | 60af7d26e786113d9af7a29f1e6a46ee2191453d | 653,954 |
def trim(text, max_length):
"""Trims text to be at most `max_length`, without splitting apart words."""
if len(text) <= max_length:
return text
text = text[:max_length + 1]
# Trim until the last two characters are the boundary between an
# alphanumeric character, and a non-alphanumeric cha... | 8d7bdebd4d09887d8a38f6181e68b4239e2b05a7 | 653,955 |
import time
def parse_date(value, dateformat='%Y-%m-%d'):
"""Parse a string into a date"""
return time.strptime(value.strip(), dateformat) | 87f382c74365e8a273355a6efe56ff94def5f9c0 | 653,956 |
def rayleigh_coefficients(zeta, omega_1, omega_2):
"""
Compute the coefficients for rayleigh damping such, that the modal damping
for the given two eigenfrequencies is zeta.
Parameters
----------
zeta : float
modal damping for modes 1 and 2
omega_1 : float
first eigenfrequen... | effb96fc4efed4ee57d31feb075099767cf5e03d | 653,957 |
def get_queue_arn(sqs_client, queue_url: str) -> str:
"""
Returns the given Queue's ARN. Expects the Queue to exist.
:param sqs_client: the boto3 client
:param queue_url: the queue URL
:return: the QueueARN
"""
response = sqs_client.get_queue_attributes(QueueUrl=queue_url, AttributeNames=["... | 58d980cce90861922c7f02d210ecca27dd8d82dc | 653,961 |
def compute_scaling_dnu(numax, numax_threshold=300, numax_coeff_low=0.267, numax_coeff_high=0.22, numax_exponent_low=0.76, numax_exponent_high=0.797):
"""
Compute the large frequency separation (`dnu`).
This function computes a value of `dnu` from an input `numax` as based on
literature scaling relati... | b8fb922c16c29750e04585dfdad7357773125843 | 653,962 |
def word_doc_freq_map(doc):
"""emit words
Args:
doc (list[string]): one document
Returns:
zip(string, int): emitted words
"""
words = set(doc)
return zip(words, [1] * len(words)) | ffae86353019cc269f3eae670037d88c8448bf51 | 653,963 |
def paraxial_focus(separation, z0, focal_length):
"""
Calculates the paraxial focus of a lens given its position, separation
between its two surfaces and the required focal length.
"""
focus = z0 + separation/2 + focal_length
return focus | 99f9367f2bdf388fe872d012df2f8d113d020602 | 653,966 |
def filter_by_length(genes, transcripts, min_length):
""" Given a minimum transcript length, this function
- Iterates over transcripts and keeps the ones with length >= min_length
- Removes genes not represented in the transcript set
"""
filtered_transcripts = {}
filtered_genes = {}
... | 534398a957a846adbe7ffde4d472881746b863eb | 653,971 |
def find_review_comment(user_gitee, group, repo_name, pull_id):
"""
Find the review comment for PR
"""
review_key = "以下为 openEuler-Advisor 的 review_tool 生成审视要求清单"
data = user_gitee.get_pr_comments_all(group, repo_name, pull_id)
for comment in data[::-1]:
if review_key in comment['body']:... | 2e351054350743ca00ec968ce6493dc6d620c79a | 653,972 |
def predict(model, data):
"""
Predicts and prepares the answer for the API-caller
:param model: Loaded object from load_model function
:param data: Data from process function
:return: Response to API-caller
:rtype: dict
"""
# return a dictionary that will be parsed to JSON and sent bac... | 2d45bdbecfcb17155cff2f31ff331cf0c1eacb85 | 653,974 |
import re
def get_fig_name(title, tag, legends=[]):
"""Get the name of the figure with the title and tag."""
fig_name = "_".join(re.split("/|-|_|,", title) + legends).replace(" ", "")
return f"{fig_name}_generalization_{tag}.pdf" | a1bb5c3d91eba412ffaca7354b5d663c37de0a46 | 653,975 |
import requests
def is_already_blocked(ip, firewall_ip_and_port):
""" This function checks if {ip} is already blocked in the firewall.
:param ip: IP to check.
:param firewall_ip_and_port: URL of firewall wrapper.
:return: True if IP if already blocked on the firewall, False otherwise.
"""
ret... | d698720a1287b27e87d3aacd9fb63defda09e4c3 | 653,977 |
def getFeatureId(feature):
"""
Return the ID of a feature
params:
feature -> a feature
"""
return feature["id"] | 8bdccc4166c67d9076f702d03414cb4f3e4e8a48 | 653,980 |
def field_name(field):
"""
Produce a clean version of a field's name.
The
:class:`zope.schema.fieldproperty.FieldPropertyStoredThroughField`
class mangles the field name, making it difficult to trace fields
back to their intended attribute name. This undoes that mangling
if possible.
T... | 2f93760c16a605502d0273c1462588b79252c96e | 653,984 |
def remap(degreeinput,degreemin,degreemax,dmxmin=0,dmxmax=65536):
"""
Convert the degree value to a 16 bit dmx number.
"""
DMXvalue = ((degreeinput - degreemin) * (dmxmax-dmxmin) / (degreemax - degreemin) + dmxmin)
return DMXvalue | 31f3d26342f7c5cc08964f2ff0430d51dd5c5672 | 653,985 |
def get_month_delta(date1, date2):
"""
Return the difference between to dates in months.
It does only work on calendars with 12 months per year, and where the months
are consecutive and non-negative numbers.
"""
return date2.month - date1.month + (date2.year - date1.year) * 12 | 0ec1216530dd8172174245156af72ecf620d12f0 | 653,995 |
def notas(*n, sit=False):
"""
-> Função para analisar notas e situações de vários alunos.
:param n: uma ou mais notas dos alunos.
:param sit: valor opcional, para mostrar a situação do aluno.
:return: dicionário com várias informações sobre a situação da turma.
"""
nota = dict()
nota['to... | e19c2ca417770e4ed72ffc087b39a625585a41b1 | 653,996 |
def months_between(date1, date2):
"""
Compare two dates and return the number of months beetween them.
**Parameters**
``date1``
First date for the comparison
``date2``
Second date for the comparison
"""
if date1 > date2:
date1, date2 = date2, date1
m1 = date1.ye... | acc7ad02f2f04dda451853a9dce6402408189e04 | 653,997 |
import re
def is_palindrome(usr_ip):
"""
Checks if string is a palindrome
ValueError: if string is invalid
Returns True if palindrome, False otherwise
"""
# remove punctuations & whitespace and change to all lowercase
ip_str = re.sub(r'[\s.;:,\'"!?-]', r'', usr_ip).lower()
if re.se... | 651330893b24e49f2a0409e7ab0984f7c3f1de7f | 653,998 |
import math
def perturb_coordinates(old_coords, negative_freq_vecs, molecule_perturb_scale, reversed_direction):
"""
Perturbs a structure along the imaginary mode vibrational frequency vectors
old_coords (np.ndarray): Initial molecule coordinates
negative_freq_vecs (list of np.ndarray): Vibrational f... | f7a084aa54f8ddc9ba8f71581f349065566ab702 | 654,002 |
def _get_deps(meta, section=None):
"""
meta : dict-like
Parsed meta.yaml file.
section : str, list, or None
If None, returns all dependencies. Otherwise can be a string or list of
options [build, host, run, test] to return section-specific dependencies.
"""
def get_name(dep)... | 4b34a88172e806a0682732843e8f14bbb8bf6889 | 654,005 |
def _kwargs_to_props(**kwargs):
"""
Receives `kwargs` and returns them as dict to give easier manipulation
for different methods.
:param kwargs: kwargs
:return: kwargs dict
"""
props = {k: v for k, v in kwargs.items() if v}
return props | 67372e0f96055aeeedebf62203a5be9636e9613c | 654,007 |
def chip_converter(chip):
"""Converts a chip name to usable string."""
chip_map = {
"3xc": "TC",
"wildcard": "WC",
"bboost": "BB",
"freehit": "FH"
}
return chip_map[chip] | 37ad159e2946546717ebce5c0878331a2bede55a | 654,008 |
def baseline_calc_hmean ( SSP1, SSP2, BSL_range, TAT):
""" Calculates measured baseline lengths (harmonic mean sound speed).
It needs:
SSP1 ... sound speed at beacon 1 in metres per second
SSP2 ... sound speed at beacon 2 in metres per second
BSL_range ... measured traveltime in milliseconds
TA... | 2de458102142307993546c4d19cea7520aed5632 | 654,009 |
def spectral_penalty_d_optimal(svs,
already_abs=False,
already_normalized=False,
eps=1e-7):
"""
D-Optimal Regularizer as described in https://openreview.net/pdf?id=rJNH6sAqY7
"""
svs = list(svs.values())
... | 875312ec63fb56b8c27a46da53b22fcd95dbfe15 | 654,010 |
def code_h_format(what):
"""
Converts content of code/pictures history to an html form
Minor Tweak: You can change the html tags however you like.
Another Tweak: Can change the length of displayed history (100 currently)
"""
if len(what) == 0:
return ''
res = '<ul>'
# pick t... | 233fd56003fe0b609afc99bf9062c43682a4c8fa | 654,012 |
def parse_values_in_lines(lines):
"""
Parses the lines for 'A = B' lines and returns a dictionary, as well as the
profile name
"""
values = {}
profile_name = None
for line in lines:
line = line.strip()
if len(line) > 2 and line[0] == '[':
profile_name = line[1:-1]... | 4e7ee62d226e1f052ebcab883b3bf44f98d6ae92 | 654,014 |
def remove_empty_items(v: list) -> list:
"""Remove Falsy values from list.
Sees dicts with all Falsy values as Falsy.
This is used to allow people to submit list fields which are "empty" but are not really empty like:
`[{}, None, {name:"", email:""}]`
Example:
>>> remove_empty_items([{}, N... | 9a3b38b6def088de531160710d58330b024c5b36 | 654,017 |
def Switch(node):
"""
Root of switch/case branch
Args:
node (Switch): Current position in node-tree
Return:
str : Translation of current node.
Children:
Expression Case+ Otherwise?
Expression:
Test-expression
Case:
Case-block
Otherwise:
Otherwise-block
Examples:
... | 538658b3ac8e913a897722f18c3fcfd45cb486b4 | 654,018 |
import re
def trim_id(id, prefix):
"""Remove insignificant characters from the feature ID
If we know the species in a downstream context, in an ID like
"ENSMUSG00000102628", we can infer everything except the "102628".
So we trim the ID to only those significant characters, which yields
a smalle... | 7f773dad15914fdada6b7210f004742e75960e4f | 654,019 |
def command_result_processor_command_uninitialized(command_line_command):
"""
Command result message processor if a command line command is not initialized (should not happen).
Parameters
----------
command_line_command : ``CommandLineCommand``
Respective command.
Returns
-... | dba198925f99cb986eada3cc74050a6f13bfc292 | 654,020 |
import colorsys
def generate_colour(num, count, rotate):
"""Create an RGB colour value from an HSV colour wheel.
num - index from the rainbow
count - number of items in the rainbow
rotate - number between 0 and 1 to rotate the rainbow from its
usual red first, violet last.
"""
h = num / count
h = h + rotate
... | 8709eed4ceb93671cceaf126908dbd2aaf01c374 | 654,021 |
def match_condition(exc_type):
"""Return a function that matches subclasses of ``exc_type``"""
return lambda _exc_type: issubclass(exc_type, _exc_type) | e6899d66fd81c484f9f073141d69fa3acce569c2 | 654,023 |
from typing import Any
def create_property(attr: str, default: Any, type_annotation: type) -> property:
"""Return a property descriptor given config attribute."""
def fget(self) -> Any:
if attr in self._env_overrides:
return self._env_overrides[attr]
if attr in self._config:
... | d7359b49a666e8826797d297e6642bd0736a0191 | 654,030 |
def wrapGrowthRatioDiv(value, MoM, YoY):
"""
Wrap the growth ratio into grids
MoM: month on month growth ratio
YoY: year on year growth ratio
"""
return "<div style='width:50%'>"+value+\
"</div><div style='width:50%'><table><tr><td>"+MoM+ \
"</td></tr><tr><td>"+YoY+"</td>... | 6977d42d1475ae0deeea8a2ce2a32bc0c9acc456 | 654,031 |
import re
def check_symbols(value):
"""
Checks if an string has symbols
:param value: String to be checked
:type value: String
:returns: True if there are symbols in the string
:rtype: Boolean
Examples:
>>> check_symbols('Lorem ipsum')
True
>>> check_... | 364cf64c135c80c7e6a5b70ab8dd07aa2e368c8c | 654,034 |
import re
def snake2camelback(snake_dict: dict):
"""Convert the passed dictionary's keys from snake_case to camelBack case."""
converted_obj = {}
for key in snake_dict.keys():
converted_key = re.sub(r'_([a-z])', lambda x: x.group(1).upper(), key)
converted_obj[converted_key] = snake_dict[k... | 6da0cdb40712a2ea0539fe520bb8164254dc04a8 | 654,035 |
def get_type(mal, kitsu_attr):
"""
Get the type of the weeb media.
:param mal: The MAL search result.
:param kitsu_attr: The attributes of kitsu search result.
:return: the type of the weeb media
"""
mal_type = mal.get('type')
if mal_type:
return mal_type
show_type = kitsu_a... | b98d026d0b2b6de6daa5fb9e713bd640c43c1fd4 | 654,037 |
def get_extension(filename: str, default_extension="py") -> str:
""" Get a file's extension (assumed to be after a period) """
if not filename:
return default_extension
return filename.lower().split(".")[-1] | 7336fac7c77cade12d79664b4088b4ecf0108e0a | 654,039 |
def fix_tuple_length(t, n):
"""Extend tuple t to length n by adding None items at the end of the tuple. Return the new tuple."""
return t + ((None,) * (n - len(t))) if len(t) < n else t | f21316b5c87052407a0b8cc240231c5b129aa51c | 654,042 |
def url(context, link_url):
"""
Get the path for a page in the Cactus build.
We'll need this because paths can be rewritten with prettifying.
"""
site = context['__CACTUS_SITE__']
url = site.get_url_for_page(link_url)
if site.prettify_urls:
return url.rsplit('index.html', 1)[0]
... | 977303df8a977a5257f4f4eaec63decd42612c7e | 654,043 |
def parse_coords(coord_str):
"""Parse a line like <x=1, y=2, z=-3> into [1, 2, -3]"""
coords = coord_str.strip('<>\n').split(',')
return [int(coords[x].split('=')[1]) for x in range(0, 3)] | c13c887fffa24deba81a176ee12532a05ad23e5f | 654,044 |
def wrap_check_stop(l, stop):
"""Check that stop index falls in (-l, l] and wrap negative values to l + stop.
For convenience, stop == 0 is assumed to be shorthand for stop == l.
"""
if (stop <= -l) or (stop > l):
raise IndexError('stop index out of range')
elif stop <= 0:
... | e1d6fd412240c98ede2b6c421c2154f91e7c5678 | 654,048 |
def snake_to_camel_case(s):
"""
Converts strings from 'snake_case' (Python code convention)
to CamelCase
"""
new_string = s
leading_count = 0
while new_string.find('_') == 0:
new_string = new_string[1:]
leading_count += 1
trailing_count = 0
while new_string.rfind('_... | f4d11323af7d34d600a45231cbe72c76a7c33115 | 654,049 |
def eulers_richardson_method(f, dx, y, yp, range, return_yp = False):
""" The Eulers Richardson method for solving a differential equation of second
order. Works by taking the Euler method, but uses the average values instead.
This produces a better approximation to the solution faster (in theory) than
... | 587106bc19b116b6bed6c32565e3f5a0e56dfdd6 | 654,055 |
def url_is_secure(data):
"""
=> Check if the passed in url is a secure
url
=> based on whether the url starts with https or https://
"""
return data.startswith("https://") | 69187e9ac7717cf78e09190c563e202073d14750 | 654,057 |
import json
def get_key(path=".keys/AES.key"):
"""
Load key from .keys/AES.key file
:param path: file path
:type path: String
:return: key
:rtype: bytearray
"""
with open(path, 'r') as f:
k = json.load(f)
return bytearray.fromhex(k["key"]) | fb653d3447629c3b50974f3aad2170ea4af50e79 | 654,058 |
def validateDir(value):
"""
Validate direction.
"""
msg = "Direction must be a 3 component vector (list)."
if not isinstance(value, list):
raise ValueError(msg)
if 3 != len(value):
raise ValueError(msg)
try:
nums = map(float, value)
except:
raise ValueError(msg)
return value | 214bc1f8c5833c8db8cb1a0cbe544b0d3330ccc5 | 654,064 |
def _get_pgsql_command(name, host="localhost", password=None, port=5432, user="postgres"):
"""Get a postgres-related command using commonly required parameters.
:param name: The name of the command.
:type name: str
:param host: The host name.
:type host: str
:param password: The password to u... | b7e44bd38cd153051ea2f9c6e04690a95f8f2c6d | 654,068 |
def snap_to_cube(q_start, q_stop, chunk_depth=16, q_index=1):
"""
For any q in {x, y, z, t}
Takes in a q-range and returns a 1D bound that starts at a cube
boundary and ends at another cube boundary and includes the volume
inside the bounds. For instance, snap_to_cube(2, 3) = (1, 17)
Arguments:... | ca4b1bc09d289ac3ecad4d8c0ceedb23ab121882 | 654,076 |
def main(*, a, b):
"""entrypoint function for this component
Usage example:
>>> main(
... a = pd.Series(
... {
... "2019-08-01T15:20:12": 1.2,
... "2019-08-01T15:44:12": None,
... "2019-08-03T16:20:15": 0.3,
... "2019-08-05T12:0... | 6ae580cb71b076ee542d145716a34134470c9cc3 | 654,078 |
def nrz_decision(x,t):
"""produces nrz symbol from analog voltage
Parameters
----------
x : float
the analog voltage
t: float
voltage threshold between 0 and 1 symbol
Returns
-------
int
the nrz symbol that represents x
"""
if x<t:
r... | 03b6d24c3fe5ea4ac043a7c10fce4a33c9038622 | 654,079 |
def serialize_quantity(quantity):
"""Serializes a propertyestimator.unit.Quantity into a dictionary of the form
`{'value': quantity.value_in_unit(quantity.unit), 'unit': quantity.unit}`
Parameters
----------
quantity : unit.Quantity
The quantity to serialize
Returns
-------
dic... | 8d25f1461615b042ed522938024265942ef6e691 | 654,082 |
def migrate(engine):
"""Replace 'backend' with 'store' in meta_data column of image_locations"""
sql_query = ("UPDATE image_locations SET meta_data = REPLACE(meta_data, "
"'\"backend\":', '\"store\":') where INSTR(meta_data, "
" '\"backend\":') > 0")
# NOTE(abhishekk): INS... | 6d7fa2beed8cf38cb7debe556663950a820af1c2 | 654,084 |
def get_all_collections(self):
"""Return all collections in the database"""
return self.app.db.table('collections').all() | 5cd86ad43992c6e6f07dee716408e7ea25692007 | 654,087 |
def read_input(path: str):
"""
Read game board file from path.
Return list of str.
"""
file = open(path, 'r')
return [line.strip() for line in file.readlines()] | 50d4ea64d816d486bd27e106d4977ae2c594e1f6 | 654,091 |
def make_ops_ast(expr, nfops, is_write=False):
"""
Transform a devito expression into an OPS expression.
Only the interested nodes are rebuilt.
Parameters
----------
expr : Node
Initial tree node.
nfops : OPSNodeFactory
Generate OPS specific nodes.
Returns
-------
... | 70068e5a48194467fff1f095460225e86dab5215 | 654,094 |
import torch
def resort_points(points, idx):
"""
Resort Set of points along G dim
:param points: [N, G, 3]
:param idx: [N, G]
:return: [N, G, 3]
"""
device = points.device
N, G, _ = points.shape
n_indices = torch.arange(N, dtype=torch.long).to(device).view([N, 1]).repeat([1, G])
... | a886b1c694a2c8c1ef5a3c2bdccf201aa7a53812 | 654,095 |
import re
def _include_local_or_system(x):
"""Wrap **x** in quotes if it is not wrapped in angle brackets."""
if re.fullmatch("<.*>", x):
return x
return '"' + x.strip('"') + '"' | 6175b8449f2ff76baf209a701939aac42763feb9 | 654,099 |
def is_ambiguous(num_sensed_blocked: int, num_confirmed_blocked: int, num_sensed_unblocked: int,
num_confirmed_unblocked: int):
"""
Check whether the conditions are ambiguous or not
:param num_sensed_blocked: number of sensed blocks
:param num_confirmed_blocked: number of confirmed bloc... | 26f03c0a82120f90f0e6d3b35205b8b6eea34636 | 654,104 |
import json
def enjson(obj, indent=4, encoding='UTF-8'):
"""
Dumps unicode json allowing non-ascii characters encoded as needed.
"""
return json.dumps(obj, indent=indent, ensure_ascii=False).encode(encoding) | 13f29ec422a026d076eef57a1f6f13db1305402c | 654,106 |
def nombre_sommets(G):
"""Renvoie le nombre de sommets d'un graphe"""
return len(G.keys()) | c322dfe32b0a351c1b4be1f62254621a7089125c | 654,111 |
def headingToYaw(heading):
""" Convert heading (degrees, NED) to yaw (degrees, ENU).
Args:
heading: float heading: degrees, NED
Returns:
Float, yaw: degrees, ENU
"""
return 90.0-heading | 120e7c80638d2fec5d507102cf8e30a7eb18d6da | 654,112 |
def opts_dd(lbl, value):
"""Format an individual item in a Dash dcc dropdown list.
Args:
lbl: Dropdown label
value: Dropdown value
Returns:
dict: keys `label` and `value` for dcc.dropdown()
"""
return {'label': str(lbl), 'value': value} | d9a9b97b9c586691d9de01c8b927e4924eba3a3e | 654,113 |
def rc_to_xy(row, col, rows):
"""
Convert from (row, col) coordinates (eg: numpy array) to (x, y) coordinates (bottom left = 0,0)
(x, y) convention
* (0,0) in bottom left
* x +ve to the right
* y +ve up
(row,col) convention:
* (0,0) in top left
* row +ve down
* col +ve to the... | 529f88a99ba5c3143c528df3eb844be834568c20 | 654,117 |
def has_relative_protocol(uri):
"""Return True if URI has relative protocol '//' """
start = uri[:2]
if start == '//':
return True
return False | 40c37b5f7ec6ea6de2ed02b742b2f2d0b149bc32 | 654,118 |
def wrap(value):
"""Return *value* as a list.
Reader._parse(elem, unwrap=True) returns single children of *elem* as bare
objects. wrap() ensures they are a list.
"""
return value if isinstance(value, list) else [value] | 13611946b2235eec9c55b038be287342a728568c | 654,122 |
def get_labelled_idxs(dataset):
"""
Get all indices with labels
"""
split_dict = dataset.get_idx_split()
train_idx = split_dict['train']
valid_idx = split_dict['valid']
test_idx = split_dict['test']
idxs_labelled = set(train_idx)
idxs_labelled = idxs_labelled.union(set(valid_idx))
... | 716a4d95aa33753ffa2bedbfecb44797cdc5763e | 654,125 |
from typing import Union
from typing import Tuple
from typing import Optional
def utm_region_code(
epsg: Union[int, Tuple[int, int, int]], tidx: Optional[Tuple[int, int]] = None
) -> str:
"""
Construct UTM gridspec identifier.
Examples:
- 32751 -> "51S"
- 32633, 10, 2 -> "33N_10_02... | 41fe8ffa6c195d70bd26bc6b71ab0c12b6929b2f | 654,127 |
def unique(a):
"""Find unique elements, retaining order."""
b = []
for x in a:
if x not in b:
b.append(x)
return b | 3455b9934842c426d450019721e6779dcf31f0e8 | 654,130 |
def upload_tenx_library_path(instance, filename):
"""Make a proper file path for uploading 10x library files."""
return "{0}/{1}/{2}".format(
'tenxlibrary',
instance.library.id,
filename
) | aabbb48a7aa082e466e8f623a15e49c52b77bea7 | 654,131 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.