content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def make_coro(func):
"""Wrap a normal function with a coroutine."""
async def wrapper(*args, **kwargs):
"""Run the normal function."""
return func(*args, **kwargs)
return wrapper | 080e543bc91daee13c012225ba47cd6d054c9ea5 | 3,637,600 |
def eliminate(values):
"""Apply the eliminate strategy to a Sudoku puzzle
The eliminate strategy says that if a box has a value assigned, then none
of the peers of that box can have the same value.
Parameters
----------
values(dict)
a dictionary of the form {'box_name': '123456789', ...}
Returns
-------
d... | a8f41f2cf789c1c14a4f70f760731864af65cc80 | 3,637,601 |
def sqlpool_blob_auditing_policy_update(
cmd,
instance,
workspace_name,
resource_group_name,
sql_pool_name,
state=None,
blob_storage_target_state=None,
storage_account=None,
storage_endpoint=None,
storage_account_access_key=None,
st... | 1248e12dae9f6299d86e26d069c22f560856a7e3 | 3,637,602 |
def find_unique_ID(list_of_input_smpls):
"""Attempt to determine a unique ID shared among all input
sample names/IDs, via a largest substring function performed
combinatorially exhaustively pairwise among the input list.
Parameters
----------
list_of_input_smpls : list
Returns
-------
... | c6ab308ac4e03d1ea6d855348a35eb3d58938439 | 3,637,603 |
import math
def cartesian_to_polar(xy):
"""Convert :class:`np.ndarray` `xy` to polar coordinates `r` and `theta`.
Args:
xy (:class:`np.ndarray`): x,y coordinates
Returns:
r, theta (tuple of float): step-length and angle
"""
assert xy.ndim == 2, f"Dimensions are {xy.ndim}, expectin... | c38c4abfbbe3acea6965530d58a1e6a9614a035b | 3,637,604 |
def return_manifold(name):
"""
Returns a list of possible manifolds with name 'name'.
Args:
name: manifold name, str.
Returns:
list of manifolds, name, metrics, retractions
"""
m_list = []
descr_list = []
if name == 'ChoiMatrix':
list_of_metrics = ['euclidean']
... | 5361a8c38069d01c5fc9383e4bc06407f485c0d2 | 3,637,605 |
def change_to_rgba_array(image, dtype="uint8"):
"""Converts an RGB array into RGBA with the alpha value opacity maxed."""
pa = image
if len(pa.shape) == 2:
pa = pa.reshape(list(pa.shape) + [1])
if pa.shape[2] == 1:
pa = pa.repeat(3, axis=2)
if pa.shape[2] == 3:
alphas = 255 *... | 3328ec90e114a7b2c0c2529d126494756f0ce608 | 3,637,606 |
def spacetime_lookup(ra,dec,time=None,buffer=0,print_table=True):
"""
Check for overlapping TESS ovservations for a transient. Uses the Open SNe Catalog for
discovery/max times and coordinates.
------
Inputs
------
ra : float or str
ra of object
dec : float or str
dec of object
time : float
reference t... | efdcfc315c82db808478c302163a146512659f0b | 3,637,607 |
from typing import Union
from datetime import datetime
import time
def utc2local(utc: Union[date, datetime]) -> Union[datetime, date]:
"""Returns the local datetime
Args:
utc: UTC type date or datetime.
Returns:
Local datetime.
"""
epoch = time.mktime(utc.timetuple())
offset ... | 34997f08a8ca7e2156849bb6be346964cc3fadcd | 3,637,608 |
import sys,time
from datetime import datetime
from datetime import timedelta
def getAsDateTimeStr(value, offset=0,fmt=_formatTimeStr()):
""" return time as 2004-01-10T00:13:50.000Z """
if (not isinstance(offset,str)):
if isinstance(value, (tuple, time.struct_time,)):
return time.strftime(... | 6de90e2d9ec39b843fbdef2721ad2495aa7faa46 | 3,637,609 |
import math
def gvisc(P, T, Z, grav):
"""Function to Calculate Gas Viscosity in cp"""
#P pressure, psia
#T temperature, °R
#Z gas compressibility factor
#grav gas specific gravity
M = 28.964 * grav
x = 3.448 + 986.4 / T + 0.01009 * M
Y = 2.447 - 0.2224... | 5ff1ad63ef581cea0147348104416913c7b77e37 | 3,637,610 |
def get_closest_mesh_normal_to_pt(mesh, pt):
"""
Finds the closest vertex normal to the point.
Parameters
----------
mesh: :class: 'compas.datastructures.Mesh'
pt: :class: 'compas.geometry.Point'
Returns
----------
:class: 'compas.geometry.Vector'
The closest normal of the ... | 95c9bf82c0c24da27ba8433feb9c5c02cf453713 | 3,637,611 |
from typing import Coroutine
import asyncio
import json
async def apiDiscordAssignrolesDelete(cls:"PhaazebotWeb", WebRequest:ExtendedRequest) -> Response:
"""
Default url: /api/discord/assignroles/delete
"""
Data:WebRequestContent = WebRequestContent(WebRequest)
await Data.load()
# get required vars
guild_id:... | 46c89f41c8b5bec43ad33b6bebecffd0d1b8623c | 3,637,612 |
def algo_reg_deco(func):
"""
Decorator for making registry of functions
"""
algorithms[str(func.__name__)] = func
return func | 56228dcf557e7de64c75b598fe8d283eb08050ba | 3,637,613 |
from typing import List
import operator
def find_top_slices(metrics: List[metrics_for_slice_pb2.MetricsForSlice],
metric_key: Text,
statistics: statistics_pb2.DatasetFeatureStatisticsList,
comparison_type: Text = 'HIGHER',
min_num_example... | 7d71a2a64001e792b4e7cc9467ae99bfe30ebf99 | 3,637,614 |
def parse_texts(texts):
"""
Create a set of parsed documents from a set of texts.
Parsed documents are sequences of tokens whose embedding vectors can be looked up.
:param texts: text documents to parse
:type texts: sequence of strings
:return: parsed documents
:rtype: sequence of spacy.Do... | 05f39ffa453ca448fe1d724d2a5fbb53c52c8ade | 3,637,615 |
import _json
def dict_to_string(d):
"""Return the passed dict of items converted to a json string.
All items should have the same type
Args:
d (dict): Dictionary to convert
Returns:
str: JSON version of dict
"""
j = {}
for key, value in d.items():
if value is Non... | 3a7b3e464fa68b262be7b08bdefa1c35f603b68f | 3,637,616 |
def domains(request):
"""
A page with number of services and layers faceted on domains.
"""
url = ''
query = '*:*&facet=true&facet.limit=-1&facet.pivot=domain_name,service_id&wt=json&indent=true&rows=0'
if settings.SEARCH_TYPE == 'elasticsearch':
url = '%s/select?q=%s' % (settings.SEARCH... | 98adcea3c7a2bd19a9253bc771cc286b6b998a97 | 3,637,617 |
def load_test_data(path, var, years=slice('2017', '2018')):
"""
Args:
path: Path to nc files
var: variable. Geopotential = 'z', Temperature = 't'
years: slice for time window
Returns:
dataset: Concatenated dataset for 2017 and 2018
"""
assert var in ['z', 't'], 'Test... | fa30a9514654bb3f99f74eaed7b87e3e2eb23430 | 3,637,618 |
def encode(state, b=None):
"""
Encode a base-*b* array of integers into a single integer.
This function uses a `big-endian`__ encoding scheme. That is, the most
significant bits of the encoded integer are determined by the left-most
end of the unencoded state.
>>> from pyinform.uti... | 09b5e96c3b9238d41f02cad938b6cb370a3a41da | 3,637,619 |
from typing import Optional
from typing import Set
def get_equivalent(curie: str, cutoff: Optional[int] = None) -> Set[str]:
"""Get equivalent CURIEs."""
canonicalizer = Canonicalizer.get_default()
r = canonicalizer.single_source_shortest_path(curie=curie, cutoff=cutoff)
return set(r or []) | af5cc4049af258b7724539e81218ef74dd8a3229 | 3,637,620 |
def _standardize_input(y_true, y_pred, multioutput):
"""
This function check the validation of the input
input should be one of list/tuple/ndarray with same shape and not be None
input will be changed to corresponding 2-dim ndarray
"""
if y_true is None or y_pred is None:
raise ValueErro... | c536e777c40a5ce7c886b20f61fac7f20341c20b | 3,637,621 |
import logging
def disk_detach(vmdk_path, vm):
"""detach disk (by full path) from a vm and return None or err(msg)"""
device = findDeviceByPath(vmdk_path, vm)
if not device:
# Could happen if the disk attached to a different VM - attach fails
# and docker will insist to sending "unmount/de... | b0f835c51eec4d97a8a925e12cbd3c7531b13fde | 3,637,622 |
def children_shape_ranks(rank, n):
"""
Return the partition of leaves associated
with the children of the tree of rank `rank`, and
the ranks of each child tree.
"""
part = []
for prev_part in partitions(n):
num_trees_with_part = num_tree_pairings(prev_part)
if rank < num_tree... | a07239b5f820578d0368f1b9ba7dbed50ac95cb1 | 3,637,623 |
def url_mapper(url, package):
"""
In a package.json, the "url" field is a redirection to a package download
URL published somewhere else than on the public npm registry.
We map it to a download url.
"""
if url:
package.download_urls.append(url)
return package | 95d6b67a42cac14110b457b96216a40a5d5430f9 | 3,637,624 |
import random
def electricPotential(n, V_SD_grid, V_G_grid):
"""
Function to compute the electric potential of the QDot.
:param n: the number of electrons in the dot
:param V_SD_grid: the 2d array of source-drain voltage values
:param V_G_grid: the 2d array of gate voltage values
:return: The... | fedc11b23d781d16c786dca213eaa578de8017f6 | 3,637,625 |
def mettre_a_jour_uids(nom_fichier, organisateurs, uids):
""" Met à jour le fichier CSV UID,EMAIL à partir du dictionnaire """
nouveaux_uids = False
for id_reunion in organisateurs:
if organisateurs[id_reunion]["id_organisateur"] not in uids:
uids[organisateurs[id_reunion]["id_organisate... | ac0f61b135c8a7bb9de9bb6b5b8e3f9fd7b176f0 | 3,637,626 |
import warnings
def _spectrogram(signal, dB=True, log_prefix=20, log_reference=1,
yscale='linear', unit=None,
window='hann', window_length=1024, window_overlap_fct=0.5,
cmap=mpl.cm.get_cmap(name='magma'), ax=None):
"""Plot the magnitude spectrum versus time.
... | 3648918524c73dff4427a49119a9926eea317f81 | 3,637,627 |
import pprint
def _merge_cwlinputs(items_by_key, input_order, parallel):
"""Merge multiple cwl records and inputs, handling multiple data items.
Special cases:
- Single record but multiple variables (merging arrayed jobs). Assign lists
of variables to the record.
"""
items_by_key = _maybe_n... | f78777f391747e964be6d02f77bb5c42db084546 | 3,637,628 |
def polar_distance(x1, x2):
"""
Given two arrays of numbers x1 and x2, pairs the cells that are the
closest and provides the pairing matrix index: x1(index(1,:)) should be as
close as possible to x2(index(2,:)). The function outputs the average of
the absolute value of the differences abs(x1(index(1... | f3f4f564a6645d183b5d7b1ce700e2ddf40241b7 | 3,637,629 |
def _calc_data_point_locations(num_points, x_values=None):
"""Returns the x-axis location for each of the data points to start at.
Note: A numpy array is returned so that the overloaded "+" operator can be
used on the array.
The x-axis locations are scaled by x_values if it is provided, or else the
... | 645af74a2547e25add5e7d7b0d8292568933c177 | 3,637,630 |
def is_base(base_pattern, str):
"""
base_pattern is a compiled python3 regex.
str is a string object.
return True if the string match the base_pattern or False if it is not.
"""
return base_pattern.match(str, 0, len(str)) | d0b0e3291fdbfad49698deffb9f57aefcabdce92 | 3,637,631 |
def stations_by_river(stations):
"""For a list of MonitoringStation objects (stations),
returns a dictionary that maps river names (key) to a list of MonitoringStation objects on a given river."""
# Dictionary containing river names and their corresponding stations
rivers = {}
for station in stati... | c7fc460aa3e387285abdddfcb216a8ec41d27e06 | 3,637,632 |
def dQ_dY(time):
"""Derivative of transformation matrix for nutation/presession with regards to the Y coordinate of CIP in GCRS
"""
# Rotation matrices
R3_E = R3(E(time))
R3_s = R3(s(time))
R2_md = R2(-d(time))
R3_mE = R3(-E(time))
dR3_s = dR3(s(time))
dR3_E = dR3(E(time))
dR3_mE... | 7341de34dccb4134bdc9b3d29e247dcc35b550bb | 3,637,633 |
def calculate(x: int, y: int = 1, operation: str = None) -> int:
"""Calculates the sum (or difference) of two numbers.
Parameters:
`x` : int
The first number
`y` : int, optional
The second number (default is `1`)
`operation`: str, optional
Pass "subtract" to perform subtract... | e2f79940c7329895bafe0c5ad2b17953f8276902 | 3,637,634 |
def get_power_state(instance):
"""Return the power state of the received instance.
:param instance: nova.objects.instance.Instance
:return: nova.compute.power_state
"""
instance_info = manage.VBoxManage.show_vm_info(instance)
return instance_info.get(constants.VM_POWER_STATE) | 407488593d5f29cb4d70387bdab18b5d13db5b23 | 3,637,635 |
def toBoolean(val, default=True):
"""convert strings from CSV to Python bool
if they have an empty string - default to true unless specified otherwise
"""
if default:
trueItems = ["true", "t", "yes", "y", "1", "on", ""]
falseItems = ["false", "f", "no", "n", "none", "0"]
else:
... | d3ca42f73674d0104c2c036462ae421b00501cd3 | 3,637,636 |
from typing import Union
def cache_put(
connection: 'Connection', cache: Union[str, int], key, value,
key_hint=None, value_hint=None, binary=False, query_id=None,
) -> 'APIResult':
"""
Puts a value with a given key to cache (overwriting existing value if any).
:param connection: connection to Ign... | 357141ac0cc128ee2cf9ff9db76bec10d947ede0 | 3,637,637 |
def _process_rows(app, sheet_name, rows, names_map, lang=None):
"""
Processes the rows of a worksheet of translations.
This is the complement of get_bulk_app_sheets_by_name() and
get_bulk_app_single_sheet_by_name(), from
corehq/apps/translations/app_translations/download.py, which creates
these... | 3cb43f813822b1d18ee6afa90412a7a4d6cec7e5 | 3,637,638 |
def parse_line(line, metric):
"""Parses statistics from a line an experiment log file"""
if "top-k" in line:
return f"top-k.{metric}", parse_csv(line)
elif "bottom-k" in line:
return f"bottom-k.{metric}", parse_csv(line)
else:
return f"ml.{metric}", parse_csv(line) | 9f9f263d3a27256ca98bfc42dbb7426044b8ba42 | 3,637,639 |
from typing import Tuple
def get_adjusted_pvalues(pvals: pd.Series, fdr_thresh: float = 0.05) \
-> Tuple[pd.Series, float]:
"""
Function that controls FDR rate.
Accepts an unsorted list of p-values and an FDR threshold (1).
Returns:
1) the FDR associated with each p-value,
2) the p-val... | d77bb4721eedd6af0797d2e4c7ea3fac8ddc0ab4 | 3,637,640 |
def solve_nonogram(constraints):
"""this function is solving all kinds of boards of the game and returning
the all possible solutions for it""" # BTM
return [solve_easy_nonogram(constraints)] | ec4f7a853af8d216ca800cc3aa2bde6a57c07a8b | 3,637,641 |
import os
import json
import importlib
def get_libs():
"""
Get all of the libraries defined in lib/definitions.
This is called automatically when the package is imported.
"""
print(">> Checking for libraries to download..")
definitions = os.listdir("lib/definitions")
tried = 0
down... | f4015db28081b20b91506a95b7567ee0a4d24e54 | 3,637,642 |
import scipy
def downsample_data(data, scale_factor, order):
"""
Downsample data
TODO: Scikit-image has a transform module that works better,
this function should have the option to use either
"""
return scipy.ndimage.interpolation.zoom(data, scale_factor, order=order, mode="constant") | 656c0e166e369cfec73cec5c7789e2f9f43875c7 | 3,637,643 |
def uwid(string):
"""Return the width of a string"""
if not PY3:
string = string.decode('utf-8', 'ignore')
return sum(utf_char_width(c) for c in string) | adae434637415293443570f11ba58035eecf7d98 | 3,637,644 |
def check_double_quote(inpstring):
"""
Check if some strings needs of a double quote (if some space are inside the string, it will need to be inside two double quote). E.g.: --sfmt="TIFF (unstitched, 3D)"
Input:
inpstring: input string or array of strings
Output:
newstring = new string (or... | 3da3941d9cd8c4c72643f87c533bcfbfbd9b9a79 | 3,637,645 |
import os
import requests
from bs4 import BeautifulSoup
import re
import urllib
def get_wheel_index_data(py_version, platform_version, url=torch_nightly_wheel_index, override_file=torch_nightly_wheel_index_override):
"""
"""
if os.path.isfile(override_file) and os.stat(override_file).st_size:
with... | 5ae87f003bb3077df8b4b5718e3f42ad108eb549 | 3,637,646 |
def get_linear_schedule_with_warmup(
num_warmup_steps, num_training_steps, last_epoch=-1
):
"""
Create a schedule with a learning rate that decreases linearly from the initial lr set in the optimizer to 0,
after a warmup period during which it increases linearly from 0 to the initial lr set in the optim... | 10ee7baafd4751c0d578207706653b5c63f192f3 | 3,637,647 |
import base64
def search_image_targets_for_tag(trust_data: dict, image: Image):
"""
Searches in the `trust_data` for a digest, given an `image` with tag.
"""
image_tag = image.tag
if image_tag not in trust_data:
return None
base64_digest = trust_data[image_tag]["hashes"]["sha256"]
... | 11cfb3e0fb985c8730f72f32466e77881a503b8b | 3,637,648 |
import os
import re
def convert_gene_ids(geneList,target):
"""
takes a list of gene ids (int) and returns the target field
Normally, the database can be used, however this script is
used for example if a species has not yet been entered in the db.
"""
if target not in ['taxid','symbol']:
... | ecd33d7a6aaad3ed0093da36b60e134e2aac8111 | 3,637,649 |
def calculate_intersection(a: BoundingBox, b: BoundingBox) -> int:
"""Calculate the intersection of two bounding boxes.
:param BoundingBox a: The first bounding box.
:param BoundingBox b: The second Bounding box.
:returns iou: The intersection of ``a`` and ``b``.
:rtype: int
"""
left = max(... | 74fd375f21a26af23208ba96bbd678ce30367b8f | 3,637,650 |
import fcntl
import os
import socket
import struct
def get_linux_ip(eth):
"""在Linux下获取IP"""
assert os.name == 'posix', NotLinuxSystemError('不是Linux系统')
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
ip = socket.inet_ntoa(fcntl.ioctl(s.fileno(), 0x8915, struct.pack('256s', eth[:15])))
return ... | 381d3681bee21de2f0fca489536e12f997eaaec8 | 3,637,651 |
def build_nn_model(input_shape):
"""Generate NN model
:param: input_shape (tuple): shape of the input
:return model: NN model
"""
model = keras.Sequential([
# input layer
# multi demensional array and flatten it out
# inputs.shape[1]: the intervals
# inpu... | c4f56369875bb5ae99b2f98ac25a91b9a985f5a8 | 3,637,652 |
def window_sumsquare(
window,
n_frames,
hop_length=512,
win_length=None,
n_fft=2048,
dtype=np.float32,
norm=None,
):
"""Compute the sum-square envelope of a window function at a given hop length.
This is used to estimate modulation effects induced by windowing observations
in sh... | 93d463933f126bc192bf5b3c872469c881096f2f | 3,637,653 |
from typing import Optional
def getLatestCode(appDbConnStr: str) -> Optional[ICode]:
"""get latest created code from db
Args:
appDbConnStr (str): app db connection string
Returns:
Optional[ICode]: code object
"""
latestIdFetchsql = """
select id
from code_... | aba4106f99e1e23cf0127ad45502bd17cde9c33e | 3,637,654 |
def start_initialization_pd(update: Update, context: CallbackContext) -> str:
"""When touch "Заполнить данные"."""
u = User.get_user(update, context)
current_text = update.effective_message.text
update.effective_message.edit_text(
text=current_text
)
context.bot.send_message(
c... | 8af74466b5dc84ef4ee0b5ff5a2d824a275ee5c9 | 3,637,655 |
def rpm_comments(table=RPMComment, prefix='comment_', relationships=False):
"""Get filters for rpm comments.
:param sqlalchemy.ext.declarative.api.declarativemeta table: database model
:param string prefix: prefix of the name of the filter
:return dict: dict of filters
"""
filters = dict(
... | b7e34abdc81e3afa2b19ffe118d129068526b315 | 3,637,656 |
def split_line(line) -> list:
"""Split a line from a dmp file"""
return [x.strip() for x in line.split(" |")] | e9c5fb93bab1007b3deb11b8d71fe0cffd3f5bab | 3,637,657 |
def translate(text):
"""."""
return text | a0732d6a802f9846de5b294863f2c096f72c6c70 | 3,637,658 |
def stream_bytes(data, chunk_size=default_chunk_size):
"""Gets a buffered generator for streaming binary data.
Returns a buffered generator which encodes binary data as
:mimetype:`multipart/form-data` with the corresponding headers.
Parameters
----------
data : bytes
The data bytes to stream
chunk_size : int... | b329f56cae62122dd4e341dfc80c9c6aaae7ba31 | 3,637,659 |
def helper(n, big):
"""
:param n: int, an integer number
:param big: the current largest digit
:return: int, the final largest digit
"""
n = abs(n)
if n == 0:
return big
else:
# check the last digit of a number
if big < int(n % 10):
big = int(n % 10)
# check the rest of the digits
return helper(n/1... | aa7fa862d326d9e3400b58c9c520a10672e7340c | 3,637,660 |
async def get_transfer_list(request: Request):
"""This function checks for transfer list for an authenticated user"""
transfer_status_list = []
# Code for globus
tokens = await globus.verify_globus_code(request)
if tokens:
globus_item_count = 10
if 'globus_item_count' in request... | b5fd46a1b249b01ee37414c7798518a976867a0c | 3,637,661 |
def conv_out_shp(IR, IC, KR, KC, border_mode, subsample):
"""
.. todo::
WRITEME
"""
ssR, ssC = subsample
def ceildiv(x, y):
r = x // y
if r * y < x:
return r + 1
return r
if border_mode == 'valid':
OR, OC = ceildiv(IR - KR + 1,ssR), ceildiv(IC... | 2d1664e54cf5362be6e6e89f482f27712ab0c380 | 3,637,662 |
def getPageNumber(ffile):
"""
Extract the page number from the file name
:param ffile:
:return: image URI as a string
"""
return str(ffile).split('_')[-1].split('.')[0] | f78166ae3da8ea234c98436144e6c815f341ff5e | 3,637,663 |
import colorsys
def colors_stepsort(r,g,b,repetitions=1):
"""
Sort colors in hue steps for more perceptually uniform colormaps
"""
lum = np.sqrt( .241 * r + .691 * g + .068 * b )
h, s, v = colorsys.rgb_to_hsv(r,g,b)
h2 = int(h * repetitions)
lum2 = int(lum * repetitions)
v2 = int(v * r... | c9ac5729c4208e681e3a91e09746b3bc8f0b3cc5 | 3,637,664 |
def get_string_hash(string: str, algorithm_name: str):
"""Calculates the hash digest of a string.
Args:
string: str: The string to digest.
algorithm_name: str: The name of the algorithm to hash the string with.
Returns:
A hash digest in string form.
"""
hash_algorithm = _get_alg... | 31eb5504703412ac775ae4344ef1ff2c4176104d | 3,637,665 |
import tqdm
def psd_error(times,rates,errors):
"""
obtain errors for the best frequency estimate of the signal
"""
"""
print(len(times),len(rates),len(errors))
newdatachoice = np.random.choice(len(times),size=int(0.1*len(times)))
newtimes = list(np.array([times[0]])) + list(np.array([times[-1]])) + list(time... | ecb8dcb297872dae1e9c9a0b491feaf2b2c74490 | 3,637,666 |
def solve(global_step):
"""add solver to losses"""
# learning reate
lr = _configure_learning_rate(82783, global_step)
optimizer = _configure_optimizer(lr)
tf.summary.scalar('learning_rate', lr)
# compute and apply gradient
losses = tf.get_collection(tf.GraphKeys.LOSSES)
regular_losses =... | 085317d679495ab1959106c64fdeb10aeeeeab02 | 3,637,667 |
def get_features_from_policy(env, policy):
"""Represent policies with average feature vector.
This only makes sense for linear reward functions, but it is only used for the
HighwayDriving environment.
"""
assert isinstance(env.unwrapped, HighwayDriving)
assert isinstance(policy, FixedPolicy)
... | 524256c80a8c4dec7b30378e5a377ac02456ffa7 | 3,637,668 |
import os
def get_files_from_folder(directory, extension=None):
"""Get all files within a folder that fit the extension """
# NOTE Can be replaced by glob for newer python versions
label_files = []
for root, _, files in os.walk(directory):
for some_file in files:
label_files.append... | e572333be8786a32aabf2e217411c9db11e65175 | 3,637,669 |
def predicate(line):
"""
Remove lines starting with ` # `
"""
if "#" in line:
return False
return True | ff7d67c1fd7273b149c5a2148963bf898d6a3591 | 3,637,670 |
def pad_slices(ctvol, max_slices): #Done testing
"""For <ctvol> of shape (slices, side, side) pad the slices to shape
max_slices for output of shape (max_slices, side, side)"""
padding_needed = max_slices - ctvol.shape[0]
assert (padding_needed >= 0), 'Image slices exceed max_slices by'+str(-1*padding_n... | 01b03094dd66a770cb40a136399486bbc018e969 | 3,637,671 |
import random
def average_img_from_dir(path_data_dir,filepat="*", \
parentaslabel=False,\
labels=[],\
sampling_rate=0.001,\
title="average image") :
"""
create and visualize average image of given dataset
dataset_path = path to dataset
sampling_r... | 98aaf33c35483a9100bb25d667970f9f177955f8 | 3,637,672 |
def get_size(positions):
"""Get the size of bounding rectangle that embodies positions.
Args:
positions (dict of Dendrogram: np.array): positions xy coordinates of dendrograms
Returns:
Tuple of width and height of bounding rectangle.
"""
max_y_list = [dendrogram.height + coords[1] ... | 2a212541746963d0aa83320d3aa08ddfb5d6f6e0 | 3,637,673 |
def getContactInfo(dic):
"""Returns the Contact info for Chapters.
dic -- Dictionary from the JSON with all values.
"""
return str(dic["content"]["$t"]).split(',')[1].split(':')[1].strip() | 27ed9bcb1e91db3cf58b82023505cfcffab00bcd | 3,637,674 |
import torch
import time
def draw_pointcloud(x: torch.Tensor, x_mask: torch.Tensor, grid_on=True):
""" Make point cloud image
:param x: Tensor([B, N, 3])
:param x_mask: Tensor([B, N])
:param grid_on
:return: Tensor([3 * B, W, H])
"""
tic = time.time()
figw, figh = 16., 12.
W, H = 2... | 8828088f8f319f0033c55a4fb5c63705a882f8cd | 3,637,675 |
def semantic_dsm(word_list, keyed_vectors):
"""Calculate a semantic dissimilarity matrix."""
vectors = np.array([keyed_vectors.word_vec(word) for word in word_list])
dsm = np.clip(pdist(vectors, metric="cosine"), 0, 1)
return dsm | 05a08b09af0cc95dc647c4a2388824a2f94ed7ec | 3,637,676 |
def prompt_id_num(message, length=ID_WIDTH):
""" Asks the user to enter a identifier which is a numeric string.
The length is the length of the identifier asked.
:param message: message to ask the input
:param length: the length of the identifier
:return: input
"""
response = input(message... | 5cf705e600891bf168ac77ecf3d57637144d7b97 | 3,637,677 |
def click_snr(wl, Spec):
"""Calculate snr in a specific range given by clicks on a plot """
plt.figure()
plt.plot(wl, Spec)
plt.show(block=True)
# points from click
# temp values untill implement above
point2 = np.max(wl)
point1 = np.min(wl)
map2 = wl < point2
map1 = wl > point1... | b61216780bce3e63687c4fc79b37de8e138fa756 | 3,637,678 |
def rnn_cell_forward(xt, a_prev, parameters):
"""
Implements a single forward step of the RNN-cell
Arguments:
xt -- your input data at timestep "t", numpy array of shape (n_x, m).
a_prev -- Hidden state at timestep "t-1", numpy array of shape (n_a, m)
parameters -- python dictionary containing:... | 891a5ec7a789dbd4e1ee67598c9e350d9eacffee | 3,637,679 |
import os
import random
def load_random_batch(cfg, data_paths):
"""
Loads a random batch (batch_size, image, masks, weights)
Parameters:
-----------
cfg: contains the cfg.BATCH_SIZE
data_paths: list containing strings
paths to the folder where the images, masks and weights are in
... | 9288e4b8b8a669cce1702639ba46d7458145151b | 3,637,680 |
def load_song(trainsize=5000, testsize=5000):
""" The million song dataset
Not a good dataset for feature selection or regression
Standard linear regression performs only a little bit better than a random vector.
Additional complex models, such as interesting kernels, are needed
To improve per... | ee428f7c34f256ab9eb3e271751932cc4abcdb4c | 3,637,681 |
def convert_node(node_data: NodeData):
"""
Convenience method for converting NodeData to a packed TLV message.
:param core.emulator.data.NodeData node_data: node data to convert
:return: packed node message
"""
node = node_data.node
services = None
if node.services is not None:
... | bef0f45295325e15c09249152d3252b7ed949b2e | 3,637,682 |
def parse_null_value(
null_value_node: "NullValueNode", schema: "GraphQLSchema"
) -> None:
"""
Returns the value of an AST null value node.
:param null_value_node: AST null value node to treat
:param schema: the GraphQLSchema instance linked to the engine
:type null_value_node: NullValueNode
... | ee4d3f544c83d58abaf40b5cc46aa8953a2745bc | 3,637,683 |
def SetDataTypesFromColInfo(df, tblCI):
"""
Use colinfo dictionaries to set newly-imported (CSV) DataFrame column types and Boolean Flag columns
"""
for col in df.columns:
#If col is a flag column (1/blank), convert to Boolean for memory and feather file size efficiency
if (col in tblCI... | 43b6ac47d760b613be7419a6d1e7910b04c792f8 | 3,637,684 |
def run_and_wait(request, _):
"""Implementation of RunAndWait."""
process_runner = new_process.ProcessRunner(request.executable_path,
request.default_args)
args = {}
protobuf_utils.get_protobuf_field(args, request.popen_args, 'bufsize')
protobuf_utils.get_protobuf_... | a7c505221c44fd40156fa2a17ee31307e82d0a2f | 3,637,685 |
import os
import numpy
def import_dicom_series(path, files_start_with=None, files_end_with=None,
exclude_files_end_with=('.dat', '.txt', '.py', '.pyc', '.nii', '.gz')):
"""Rudimentary file to load dicom serie from a directory. """
N = 0
paths = []
slices = []
files = os.lis... | c51a533e33fde6a8261c9514d8d4327eca69710e | 3,637,686 |
import random
def fight(player, enemy):
"""
This starts a round of combat between the user and their selected enemy.
It returns a list of information relating to combat, to be used in the
view function to display it, if required.
"""
# Random player damage based on 80-100% of player damage s... | bca739be92ccacb92c90d784cdbf5b4abb2e61c0 | 3,637,687 |
import time
async def POST_Dataset(request):
""" Handler for POST /datasets"""
log.request(request)
app = request.app
params = request.rel_url.query
if not request.has_body:
msg = "POST_Dataset with no body"
log.error(msg)
raise HTTPBadRequest(reason=msg)
body = await... | c88b960c51e1f215659eb01a8740d49b80c7d386 | 3,637,688 |
def sort_list_by_list(L1,L2):
"""Sort a list by another list"""
return [x for (y,x) in sorted(zip(L2,L1), key=lambda pair: pair[0])] | 04b7c02121620be6d9344af6f56f1b8bfe75e9f3 | 3,637,689 |
def _to_protobuf_value(value: type_utils.PARAMETER_TYPES) -> struct_pb2.Value:
"""Creates a google.protobuf.struct_pb2.Value message out of a provide
value.
Args:
value: The value to be converted to Value message.
Returns:
A google.protobuf.struct_pb2.Value message.
Raises:
... | 2714aa36c4b2ce98795c32993390853172863010 | 3,637,690 |
from typing import Union
from typing import List
def umap(adata, **kwargs) -> Union[Axes, List[Axes], None]:
"""\
Scatter plot in UMAP basis.
Parameters
----------
{adata_color_etc}
{edges_arrows}
{scatter_bulk}
{show_save_ax}
Returns
-------
If `show==False` a :class:`~m... | 454d606a62d783047ce5d09372ed0718cf3f4af4 | 3,637,691 |
def _prepare_grid(times, time_step):
"""Prepares grid of times for path generation.
Args:
times: Rank 1 `Tensor` of increasing positive real values. The times at
which the path points are to be evaluated.
time_step: Scalar real `Tensor`. Maximal distance between time grid points
Returns:
Tupl... | 7765a473ce6cf91281410006b07421daf6ed24a8 | 3,637,692 |
def unpack_singleton(x):
"""Gets the first element if the iterable has only one value.
Otherwise return the iterable.
# Argument:
x: A list or tuple.
# Returns:
The same iterable or the first element.
"""
if len(x) == 1:
return x[0]
return x | cf551f242c8ea585c1f91eadbd19b8e5f73f0096 | 3,637,693 |
from typing import Optional
from typing import Union
from typing import List
import sys
def main(argv: Optional[Union[str, List[str]]] = None) -> object:
"""
Apply R4 edits to FHIR JSON files
:param argv: Argument list. Can be an unparsed string, a list of strings or nothing. If nothing, we use sys.arg... | 2ef82dbb7d610935d676e8e36545fbf0e579e6f6 | 3,637,694 |
def distribution_filter_for(bijector):
"""Returns a function checking Distribution compatibility with this bijector.
That is, `distribution_filter_for(bijector)(dist) == True` implies
that `bijector` can act on `dist` (i.e., they are safe to compose with
`TransformedDistribution`).
TODO(bjp): Make this sens... | 5f139b7bc93257b8b58737fb1f70ce524d4d520b | 3,637,695 |
def create_markdown_table(table_info: dict, index_name: str='Id') -> str:
"""
Returns a string for a markdown table, formatted
according to the dictionary passed as `table_info`
Parameters:
table_info: Mapping from index to values
index_name: Name to use for the index column
R... | bcda7ddb9338c3f7e656a0ec74a495f0a677eaeb | 3,637,696 |
def _parse_sequence(sequence):
"""Get a string which should describe an event sequence. If it is
successfully parsed as one, return a tuple containing the state (as an int),
the event type (as an index of _types), and the detail - None if none, or a
string if there is one. If the parsing is unsuccessful... | 6ba7ed95bd6bf18e24ae6bce47fdc03868ac4a98 | 3,637,697 |
from typing import List
from typing import Dict
def make_car_dict(key: str, data: List[str]) -> Dict:
"""Organize car data for 106 A/B of the debtor
:param key: The section id
:param data: Content extract from car data section
:return: Organized data for automobile of debtor
"""
return {
... | 671cb2f82f15d14345e34e9823ea390d72cf040a | 3,637,698 |
import ast
def insert_code(src, dest, kind):
"""Insert code in source into destination file."""
source_text = open(src).read().strip()
destination_text = open(dest).read()
destination_lines = destination_text.split('\n')
destination_tree = ast.parse(destination_text)
if not destination_tree... | 7f07e8741f5354fc78b840c803424bfd70fe8997 | 3,637,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.