content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import os
def read_plumed_output(plumed_output):
"""
This function modifies the given plumed output file if it is corrupted, meaning that
there might be some duplicates in the time series having the same time frames. If the
file is not corrupted, this fucntion does nothing but only read in the data.
... | d9ede4c28ec277f8020063e82aed93cd8caf7f0a | 39,800 |
from typing import Dict
from typing import List
def negative_binomial_graph(state: str, data: Dict[str, Dict[int, List[float]]]) -> str:
"""A function to display a negative binomial regression model graphically"""
pd.options.mode.chained_assignment = None
# First, creating a pandas dataframe for our dat... | b56a62f254304bae8adc1fa3b9c8ee41b567ec58 | 39,801 |
def get_user_name():
"""Return eser name from console.
Returns:
user_name (string): name of user from console
"""
return prompt.string('May I have your name? ') | 24693959973e03827c5a705b14afcbb181dbe81e | 39,802 |
def RMSEerror(bpmES, bpmGT, timesES=None, timesGT=None):
""" RMSE: """
diff = bpm_diff(bpmES, bpmGT, timesES, timesGT)
n,m = diff.shape # n = num channels, m = bpm length
df = np.zeros(n)
for j in range(m):
for c in range(n):
df[c] += np.power(diff[c,j],2)
# -- final RMSE
... | 246108c13efedc6508cc5722a668879e6708482b | 39,803 |
def decompress_word(word):
"""
Returns the delta values stored on a word.
Outliers are retrieved as -((1<<mode)-1)
"""
GRABS_PER_MODE = (0,28,14,10,7,6,5,4)
FULLMASK = (0,0b1,0b11,0b111,0b1111,0b11111,0b111111,0b1111111)
if (word>>30)==0b00:
mode = 3
elif (word>>30)==0b01:
... | 5fb92bacccd31aaadd7f60947607bb7e59b261c7 | 39,804 |
def _add_metadata_as_attrs_da(data, units, description, dtype_out_vert):
"""Add metadata attributes to DataArray"""
if dtype_out_vert == 'vert_int':
if units != '':
units = '(vertical integral of {0}): {0} kg m^-2)'.format(units)
else:
units = '(vertical integral of quant... | 3bdead2b0b341a065ef1e147660605c9c591c0df | 39,805 |
import os
import io
def txtlist(imdir):
"""Return a list of absolute paths of *.txt files in current directory"""
return [os.path.join(imdir, item) for item in os.listdir(imdir) if io.is_text_file(item) and not io.is_hidden_file(item)] | 27b4ddedfc8ed85a55d28b0d1a78f0a603e0af9f | 39,806 |
def concat(inputs, axis=0, **kwargs):
"""Concatenate the inputs along the given axis.
All dimensions except the :attr:`axis` should be same:
```python
x1 = dragon.ones(shape=(2, 3))
x2 = dragon.zeros(shape=(2, 4))
y = dragon.concat([x1, x2], axis=1) # Ok
z = dragon.concat([x1, x2], axis=0... | 454a097fdd767f7d55b5458b8e102ddd99b58612 | 39,807 |
def plot_umatrix(
u_matrix: np.ndarray,
n_rows: int,
n_colums: int,
cmap: str = "Greys",
fontsize: int = 18,
) -> plt.Axes:
"""Plot u-matrix.
Parameters
----------
u_matrix : np.ndarray
U-matrix containing the distances between all nodes of the
unsupervised SOM. Shap... | fce91af934f57807215dcb2dc54161ca5c2af0ee | 39,808 |
def some_version_installed(item_pl):
"""Checks to see if some version of an item is installed.
Args:
item_pl: item plist for the item to check for version of.
Returns a boolean.
"""
if item_pl.get('OnDemand'):
# These should never be counted as installed
display.display_debug... | e675e7613e3050560b1e173290454a13f2b461da | 39,809 |
def download(
asset,
name,
temporal_resolution,
year_initial,
year_final,
logger
):
"""
Download dataset from GEE assets.
"""
logger.debug("Entering download function.")
in_img = ee.Image(asset)
# if temporal_resolution != "one time":
# assert (year_initial and ... | f12fc7bcedc08b6a54dfd407a30deaedc080a2ac | 39,810 |
def _search_in_render_layer_all():
""" 全てのViewLayerのレンダリングプロパティを取得
Returns:
[type]: [description]
"""
render_layer_settings = {}
render_layer_settings["scene_use_freestyle"] = bpy.context.scene.render.use_freestyle
render_layer_settings["linestyle_names"] = _get_linestyle_names()
... | c3bc2104769e2a4357ab1155258bf9b4565e796e | 39,811 |
def load_uvarint_b(buffer):
"""
Variable int deserialization, synchronous from buffer.
:param buffer:
:return:
"""
result = 0
idx = 0
byte = 0x80
while byte & 0x80:
byte = buffer[idx]
result += (byte & 0x7F) << (7 * idx)
idx += 1
return result | f45534114fa310c027e9ff7627a41bfd51950b48 | 39,812 |
def read_frame_file(file_name, start_time, end_time, channel=None, buffer_time=1, **kwargs):
""" A function which accesses the open strain data
This uses `gwpy` to download the open data and then saves a cached copy for
later use
Parameters
----------
file_name: str
The name of the fra... | f0bd4aefe86cacaedb32ef04161f5dd037f896af | 39,813 |
def parse_print_dur(print_dur):
"""
Parse formatted string containing print duration to total seconds.
>>> parse_print_dur(" 56m 47s")
3407
"""
h_index = print_dur.find("h")
hours = int(print_dur[h_index - 2 : h_index]) if h_index != -1 else 0
m_index = print_dur.find("m")
min... | 7b1a29f31ba38e7d25b4dca9600d4be96a1da3ac | 39,814 |
def skin(image_path, thres=500):
""" Extract the skin and create a mesh.
Parameters
----------
image_path: str
the MRI image we want to extract the skin.
thres: int
the skin threshold.
Returns
-------
actor: vtkActor
one actor handling the surface.
"""
#... | 1e514ec97e903332dcb7b076a131ef0d52b6719c | 39,815 |
def Contract_CloneComboLegs(dst, src):
"""Contract_CloneComboLegs(Contract::ComboLegListSPtr & dst, Contract::ComboLegListSPtr const & src)"""
return _swigibpy.Contract_CloneComboLegs(dst, src) | ba19c03fd0892d9e19bbf5bbb021b191915203be | 39,816 |
from datetime import datetime
def read_datetext(sPathTxt_):
""" Return date array from text file sPathTxt. """
lstD = [datetime.date(*[int(s) for s in l.strip().split('.')]) for l in open(sPathTxt_, 'r').readlines()]
return np.array(lstD) | ef8ff8e940b9dc73d2ff322ff2fb2ccf845292aa | 39,817 |
def welcoming():
"""
Welcoming for user
"""
return("""
*************************************************
** **
** Welcome to speech emotion recognition! **
** **
********... | b3bcd19adda9cc8aa9678e823d1e524ba36f80af | 39,818 |
def report_threadpool_stats(threadpool, prefix="threadpool"):
"""Report stats about a given threadpool."""
def report():
return {prefix + ".working": len(threadpool.working),
prefix + ".queue": threadpool.q.qsize(),
prefix + ".waiters": len(threadpool.waiters),
... | 6a3e66c813b7754f02416e91b68a27084b8b1504 | 39,819 |
def Calc_Hot_Pixels(ts_dem,QC_Map, water_mask, NDVI,NDVIhot_low,NDVIhot_high,Hot_Pixel_Constant):
"""
Function to calculates the hot pixels based on the surface temperature and NDVI
"""
for_hot = np.copy(ts_dem)
for_hot[NDVI <= NDVIhot_low] = np.nan
for_hot[NDVI >= NDVIhot_high] = np.nan
fo... | fd25495001d24aef4a6a134245986901c16049f6 | 39,820 |
def _find_vlan(mac, domain_interfaces):
"""
Given a mac address and a collection of domains and their network
interfaces, find the domain that is assigned the interface with the
desired mac address.
Parameters
----------
mac : str
The MAC address.
domain_interfaces : dict
... | c4f667dd80146de83157e8966cb34e5867457397 | 39,821 |
def welcome():
"""List all available api routes."""
return (
f"Available Routes:<br/>"
f"/api/v1.0/precipitation<br/>"
f"/api/v1.0/stations<br/>"
f"/api/v1.0/tobs<br/>"
f"/api/v1.0/start<br/>"
f"/api/v1.0/start/end"
) | 1ef135fbebbf8ad7f64b6096635550304b819e87 | 39,822 |
import os
def archive_url(file_path, app="processed", is_latest=False):
"""
Accepts the relative path to a CAL-ACCESS file in our achive.
Returns a fully-qualified absolute URL where it can be downloaded.
"""
# If this is the 'latest' version of the file the path will need to be hacked
if is_... | b3a53a59eda131d02a784c7b77cfadf29f69884d | 39,823 |
from typing import Dict
def split_dae_alg(eqs: SYM, dx: SYM) -> Dict[str, SYM]:
"""Split equations into differential algebraic and algebraic only"""
dae = []
alg = []
for eq in ca.vertsplit(eqs):
if ca.depends_on(eq, dx):
dae.append(eq)
else:
alg.append(eq)
... | a1b7d72eeae6597047c641f036857a162d162bc9 | 39,824 |
def CalScore(names_d, daily_d,
once_intime=2, once_late=1.5, twice_intime=1, twice_late=0.5):
"""
Calculate daily score.
"""
due = daily_d["due"]
due = parse(due, settings={'TIMEZONE': 'US/Eastern'})
actions = daily_d["actions"]
for act in actions:
if act["type"]=="ad... | 4c044c10cd086b49716f1e618ddb1070944384cd | 39,825 |
def test_average_pool_4(op_tester):
"""
The Identity case
"""
d1 = np.random.rand(4, 256, 6, 6).astype(np.float16)
def init_builder(builder):
i1 = builder.addInputTensor(d1)
o = builder.aiOnnx.averagepool([i1],
kernel_shape=[1, 1],
... | 4b6a4da15830adef1fd23536e721fe115843d4e3 | 39,826 |
import os
import re
def canonicalize_path(path, prefix=None):
"""Canonicalize a given path.
Remove the prefix from the path. Otherwise, if the path starts with
/build/XXX/package-version then remove this prefix.
Args:
path
Returns:
Canonicalized path.
"""
dummy_prefix = ... | 47bd737502466f15679047ec77b9d4f5a3cbea33 | 39,827 |
import numpy
def insert_dummies_on_linear_atoms(geo, lin_idxs=None, gra=None, dist=1.,
tol=5.):
""" Insert dummy atoms over linear atoms in the geometry.
:param geo: the geometry
:type geo: automol molecular geometry data structure
:param lin_idxs: the i... | 06219b3b070a58e01ea6cfe881d7b6fa8b32748b | 39,828 |
import time
def get_times(T, dt, ex_in_rate, ns, input_intensity, stop_between=0):
"""Return computation times for numpy and tensorflow models for
networks with n neuron for n in ns"""
# Storage vectors for computation times
tf_build_times = np.empty((len(ns), 1), dtype=np.float32)
np_build_ti... | 5eeea894c1bdbc4ecc594e4b598ad1163ddf8c8b | 39,829 |
def SO(
directed = False, preprocess = "auto", load_nodes = True, load_node_types = True,
load_edge_weights = True, auto_enable_tradeoffs = True,
sort_tmp_dir = None, verbose = 2, cache = True, cache_path = None,
cache_sys_var = "GRAPH_CACHE_DIR", version = "2021-07-12", **kwargs
) -> Graph:
"""Retu... | 2a597f4311796b97257b7715f65ce0f63d24f595 | 39,830 |
import collections
import json
def parse_peptides(tumfile, normfile, prefix, suffix):
"""
This module takes in a peptides file and squashes it into the minimum number of peptides
required to describe the potential neo-immunopeptidome. It's main function is to take
transcript-level mutation calls and ... | e708c5fc63078f3913472740933feb792ea8701d | 39,831 |
import cPickle
import os
import sys
def unpackData( filename, options, data ):
""" unpackData unpacks a pickle object
"""
if not os.path.exists( filename ):
sys.stderr.write( 'Error, %s does not exist.\n' % filename )
sys.exit(1)
f = open( filename, 'rb' )
d = cPickle.load( f )
f.close()... | aafe37038fe4300580e52fed6feb47d64856888f | 39,832 |
import sys
def _getvars(expression, user_dict, depth, vm):
"""Get the variables in `expression`.
`depth` specifies the depth of the frame in order to reach local
or global variables.
"""
cexpr = compile(expression, '<string>', 'eval')
if vm == "python":
exprvars = [ var for var in ce... | 09f63e554ac976c4896a167f185d1cf577febcca | 39,833 |
def get_prefixer(prefix: str, resolver: UrlResolver = lambda x: x) -> UrlResolver:
"""Returns a `UrlResolver` that prefixes otherwise invalid URLs with
`prefix`.
"""
def prefixer(url: str) -> str:
url = resolver(url)
if url.startswith("http"):
return url
return prefi... | 53334bbcfbcc5e5ca479c5f84ff6f5adb0d5f5b7 | 39,834 |
def NASNetLarge(
input_shape=None,
include_top=True,
weights="imagenet",
input_tensor=None,
pooling=None,
classes=1000,
):
"""
ImageNet 모드에서, NASNet 모델을 인스턴스화합니다.
선택적으로 ImageNet에서 사전 트레이닝된 가중치를 로드합니다.
모델에서 사용하는 데이터 형식 규칙은 Keras 구성 `~/.keras/keras.json`에 지정된 규칙입니다.
참고 : 각 Ke... | fcb8ac7e9156c685ac5149e3ed97fcdc3484bcf3 | 39,835 |
def entityAttrsGet(_id):
""" Responds to GET requests sent to the /v1/entities/<_id>/attrs API endpoint. """
accepted, content_type = hiascdi.process_headers(request)
if accepted is False:
return hiascdi.respond(
406, hiascdi.confs["errorMessages"][str(406)],
"application/js... | b140b6bf921c7a4f74df2f9cef973bd769e00867 | 39,836 |
from typing import Union
def r_to_oxd(
r: Union[np.ndarray, xr.DataArray, float],
r_min: float = 0.852,
r_max: float = 6.65,
instrument_factor: float = 0.171,
):
"""
Convert ratios to OxD
Parameters
----------
r
r_min
r_max
instrument_factor
Returns
-------
... | ac4699c02927addbc7955608fffa12df7c10a63a | 39,837 |
def box_utils_expand_boxes(boxes, scale):
"""Expand an array of boxes by a given scale."""
w_half = (boxes[:, 2] - boxes[:, 0]) * .5
h_half = (boxes[:, 3] - boxes[:, 1]) * .5
x_c = (boxes[:, 2] + boxes[:, 0]) * .5
y_c = (boxes[:, 3] + boxes[:, 1]) * .5
w_half *= scale
h_half *= scale
b... | 3ef6be9d33c255bf1f2202540d95e3f7f81faf66 | 39,838 |
def merge_mmio_overhead_elimination_maps(elim_maps):
""" Merge different MMIO overhead elimination maps.
This adds values together and re-calculates percentages.
"""
if not elim_maps:
return {}
result = {}
# 1. Totals
total_bytes_raw = sum(m['overall']['bytes_raw'] for m in elim_ma... | ce696de00f6c8c60ecb006aeaf8f430c4a67e908 | 39,839 |
from functools import reduce
def union_by_category(category, filter_ids, user=None):
"""TODO (ASUC) Write docstring."""
playlists = Playlist.objects.filter(id__in=filter_ids, category=category)
if category == "custom":
playlists = playlists.filter(user=user)
intersected = [playlist.courses.all... | 1994a6a913a8f63994184bae150b69d236265762 | 39,840 |
def get_regions():
"""Get list of all AWS regions"""
client = boto3.client("ec2")
response = client.describe_regions()
regions = [region["RegionName"] for region in response["Regions"]]
return regions | e8052e59262a2af091f2587e9c58fdd92c4826e7 | 39,841 |
import os
def GetBuildDir():
"""Returns the absolute path of the directory where the test binaries are."""
return os.path.abspath(GetFlag('build_dir')) | bb66117f956f0d93fa1a2ac088ef642a84e4e3a9 | 39,842 |
def prepare_labels(cells: list, root_labels: str, root_images: str) -> np.ndarray:
"""
Convinience for label load. Takes a list of cells (the naming is used to
refer to the fact that we often use minipics of cells from tables - they
need not be cells. Just any list of strings such that the strings are
... | f5a8f1dc65c05b9803104bc99c4fcfbdc6974e0e | 39,843 |
import functools
def which(exe):
"""
Decorator wrapper for salt.utils.path.which
"""
def wrapper(function):
@functools.wraps(function)
def wrapped(*args, **kwargs):
if salt.utils.path.which(exe) is None:
raise CommandNotFoundError(
"The ... | a21b2e91ba44a9ded71cac439f25e00af65bef25 | 39,844 |
def st_grep_on_off(what, to_find_on=None, to_find_off=None, n=1, rev=False, verbose=False):
"""
filter a list of strings for groups delimited by "on" /"off"
input: list of strings
output: list of strings
use n to select how many groups to return
warning: does not accept word_only yet!
"""
line... | 90f1e190114e750c1317f72e9e8fc5218b4c8853 | 39,845 |
def tests():
""" Make these Unittests for each function. """
tests_list = [
'assertNotEqual',
'assertEqual'
]
return tests_list | cdba4e6293df2231640d6896a5104791cdf073be | 39,846 |
def view(request):
"""
A minimal view for use in testing.
"""
return HttpResponse("Content.") | 2cb59d2cc4e136f1760186bd41aa1852a0d1fdc0 | 39,847 |
def prodtab_321():
"""
produces angular distance from [3,2,2] plane with other planes up to (321) type
"""
listangles_321 = [anglebetween([3, 2, 1], elemref) for elemref in LISTNEIGHBORS_321]
return np.array(listangles_321) | f1c6c4e62ec3a274561966042a7f3f2331ea39f6 | 39,848 |
from operator import add
def gradient_step(v: Vector, gradient: Vector, step_size: float) -> Vector:
"""Moves `step_size` in the `gradient` direction from `v`"""
assert len(v) == len(gradient)
step = scalar_multiply(step_size, gradient)
return add(v, step) | 9894976ccb06423dcfcfc491314dee1c97a33c00 | 39,849 |
def _inactiveplayers():
"""
Scrape DB to find players who are not on active rosters.
"""
rosters = _activerosters()
dbrosters = _eidset() # players not in rosters scrape but in db.
notactive = dbrosters.difference(rosters)
return notactive | 12bd8c7ba27992a856b9e02eefc51395662f0e21 | 39,850 |
def logoutHttpMethods(request,*args,**kwargs):
"""
注销
:param request:
:param args:
:param kwargs:
:return:
"""
logout(request)
return response_success() | 14480c529bb13a6ed85af9ae0b600f9720231027 | 39,851 |
def isPostCSP(t, switch=961986575.):
"""
Given a GALEX time stamp, return TRUE if it corresponds to a "post-CSP"
eclipse. The actual CSP was on eclipse 37423, but the clock change
(which matters more for calibration purposes) occured on 38268
(t~=961986575.)
:param t: The time stamp... | 2b731ec0bb06ce08d2a36137e3d48563e5cb0c11 | 39,852 |
def build_wheels(dist_dir, pip_wheel_args):
"""build wheels using pip wheel command line tool"""
args = ["pip", "wheel", "--wheel-dir", dist_dir] + pip_wheel_args
spawn(args)
return dist_dir | 5b7cd19cc4cf6bf400d54f0dd01b65b88f64c0c7 | 39,853 |
def taoyuan_water_supply_network_1():
"""
Real Name: TaoYuan Water Supply Network 1
Original Eqn: 0
Units: m3
Limits: (None, None)
Type: constant
primary design assumes zero in this model, which means does not consider
the impact of this pipeline.
"""
return 0 | ee1d3c739d55fce93edfce77890d9abc6a96ed92 | 39,854 |
from typing import OrderedDict
def convert_trsp_index(geneDictNonCoding, df, TR_index_dict):
"""
take input geneDict and output a single transcript for each gene
use transcript slices defined in TR_index_dict
for noncoding genes, take the longest transcripts
There are ~7 snoRNAs that have multiple noncoding ... | 8c9af2e10e3e25305e660c23d2b9c7d738283eb1 | 39,855 |
def menunode_fieldfill(caller, raw_string, **kwargs):
"""
This is an EvMenu node, which calls itself over and over in order to
allow a player to enter values into a fillable form. When the form is
submitted, the form data is passed to a callback as a dictionary.
"""
# Retrieve menu info - taken... | f08fdbfdd57a4383b51b23a60c1c59df1638df50 | 39,856 |
def scaleBenchmarks(runLength, benchmark='design'):
"""
Set the design and stretch values of the number of visits, area of the footprint,
seeing values, FWHMeff values, skybrightness, and single visit depth (based on SRD values).
Scales number of visits for the length of the run, relative to 10 years.
... | b31a6719bb788fed8f6c1da768eee0cbf925c8d3 | 39,857 |
def serialize_for_api(data):
"""Transform complex types that we use into simple ones recursively.
Note: recursion isn't followed when we know that transformed types aren't
supposed to contain any more complex types.
TODO: this is rather ugly, would look better if views/models defined
transformation... | 54c3f98f2816ddf3cd73b45657490bb6b5c11fa1 | 39,858 |
from unittest.mock import patch
def patch_validate_gpg_sig(return_value):
"""
Mocks the InsightsUploadConf.validate_gpg_sig method so it returns the given validation result.
"""
def decorator(old_function):
patcher = patch("insights.client.collection_rules.InsightsUploadConf.validate_gpg_sig",... | f1cdf8605718c197fad7dec53113ef0d7ba17c39 | 39,859 |
def _ncac_to_stubs(ncac):
"""
Vector const & center,
Vector const & a,
Vector const & b,
Vector const & c
)
{
Vector e1( a - b);
e1.normalize();
Vector e3( cross( e1, c - b ) );
e3.normalize();
Vector e2( cross( e3,e1) );
M.col... | 67dc2475d04ddb660949aebbb5273f48fd6f8761 | 39,860 |
def constructBayesNet(gameState):
"""
Question 1: Bayes net structure
Construct an empty Bayes net according to the structure given in the project
description.
There are 5 kinds of variables in this Bayes net:
- a single "x position" variable (controlling the x pos of the houses)
- a singl... | 1fff7cc9c1cdef09242372be6d9fc5908ee70642 | 39,861 |
import os
def motioncheck(ref_file, end_file, out_path=None, thres=5.0):
"""
Checks motion between structural scans of the same modality.
Ideally obtained at the beginning and end of a scanning session.
Parameters
----------
ref_file: nifti file
Nifti file of first localizer acquire... | 450e925b2c7e65bacb4ebefcb7cdcfa1b9bd141b | 39,862 |
def __cocoseg_to_binary(seg, height, width):
"""
COCO style segmentation to binary mask
:param seg: coco-style segmentation
:param height: image height
:param width: image width
:return: binary mask
"""
if type(seg) == list:
rle = cocomask.frPyObjects(seg, height, width)
... | 3735eb59838b3bb8816d306a4be273442f425b50 | 39,863 |
import uuid
def get_a_uuid() -> str:
"""Gets a base 64 uuid
Returns:
The id that was generated
"""
r_uuid = str(uuid.uuid4())
return r_uuid | 20e87638c3718b4b75ffc48cf980216120edaea8 | 39,864 |
from pathlib import Path
def cookiecutter_cache_path(template):
"""
Determine the cookiecutter template cache directory given a template URL.
This will return a valid path, regardless of whether `template`
:param template: The template to use. This can be a filesystem path or
a URL.
:ret... | cbdc72195bf47fb1bb91368ac2bbca3890775a60 | 39,865 |
def libtree(lib):
"""Generates a filesystem-like directory tree for the files
contained in `lib`. Filesystem nodes are (files, dirs) named
tuples in which both components are dictionaries. The first
maps filenames to Item ids. The second maps directory names to
child node tuples.
"""
root = ... | 9d76fa201036ba5a8c05605b914ddbf83c4b2e83 | 39,866 |
def generate_comic_html(comic={}):
"""Generates part HTML for the qotd supplied"""
return """
<h3>Dilbert by Scott Adams -</h3>
<a href="{0}"><img alt="{1} - Dilbert by Scott Adams" src="{2}"></a>
""".format(comic['url'], comic['title'], comic['image']) | 6003abddbe7b8f3ca281787b09d92b42907669fb | 39,867 |
def get_cloudify_endpoint(_ctx):
"""
ctx.endpoint collapses the functionality for local and manager
rest clients.
:param _ctx: the NodeInstanceContext
:return: endpoint object
"""
if hasattr(_ctx._endpoint, 'storage'):
return _ctx._endpoint.storage
return _ctx._endpoint | 37ac79f564626399bd940d4c9d9fd9fb8417c424 | 39,868 |
from typing import Dict
from typing import Any
def some_invoice(full_invoice_data: Dict[str, Any]) -> Invoice:
"""Returns some `Invoice`."""
return Invoice(**full_invoice_data) | 4cf1a8ce0c32d217392cc4a621bda5f1956656c3 | 39,869 |
def order_by(field, desc=False):
"""
Allows ordering of results. You may only ever order a collection's results
once in a given request. For example::
# sort results by Instances group
client.linode.instances(order_by(Instance.group))
:param field: The field to order results by. Must ... | 9b4c000a261d315da132b1d721242bd646eabc95 | 39,870 |
def new_post():
"""NEW-POST page which allows users to create new blog posts."""
form = PostForm()
if form.validate_on_submit():
post = Post(
user=current_user, title=form.data.get("title"), body=form.data.get("body")
)
db.session.add(post)
db.session.commit()
... | beb75ff7349b7a3bfbaa73c9e22506055d20689f | 39,871 |
def qsin(dataset, ssb=1, **kwargs):
"""
Equivalent to :meth:`sp`, with pow = 2 (squared sine bell apodization window).
See Also
--------
em, gm, sp, sine, sinm, hamming, triang, bartlett, blackmanharris
"""
return sp(dataset, ssb=ssb, pow=2, **kwargs) | 6a58c48e7f8afe49f5a0a48e0169aae2217ff970 | 39,872 |
def standardize_smiles(smiles):
"""Return a standardized canonical SMILES string given a SMILES string.
Note: This is a convenience function for quickly standardizing a single SMILES string. It is more efficient to use
the :class:`~molvs.standardize.Standardizer` class directly when working with many molec... | dd05ce98f2deb9a24dfe93a37c2b556ba9dfdb8e | 39,873 |
import random
def geraPalavraAleatória():
"""
Função que retorna uma string a partir da
lista de palavras global
"""
global palavras
return random.choice(palavras) | a6482c865a3ebd8229e85826359186b63e348af0 | 39,874 |
def get_iphot_line(iphot, linenum, lcobject, iphotlinechars=338):
"""
This gets a random iphot line out of the file iphot.
"""
iphotf = open(iphot, 'rb')
filelinenum = iphotlinechars*linenum
if filelinenum > 0:
iphotf.seek(filelinenum - 100)
else:
iphotf.seek(filelinenum)
... | 4ca9aa58f915bef8264316614ab9b73e733bbdb3 | 39,875 |
import logging
import platform
def get_sys_cards():
"""This function retrieves the system cards using nvsmi for linux and windows;
macOS support is in the works.
:return: returns a tuple containing the in `gpu_ratios_min` and actual `gpu_ratios`; the
difference being that the latter is sorted in asce... | 14ba62996e7833dd85d573392db64de75f110cc6 | 39,876 |
def get_initial_density(xgrid, ygrid):
"""
Initialize a "relatively" random density profile. Please see notebook for visualization
:param xgrid:
:param ygrid:
:return:
"""
xm, ym = np.meshgrid(xgrid, ygrid, indexing="ij")
x0 = np.random.uniform(0.5 * xgrid.min(), 0.0)
y0 = np.random... | cac62af297acf4903e4a5a9e7d505431015070dc | 39,877 |
def get_vendors(ven):
"""
Input arguments for function = tuple
Coverts tuple into a list. I know, it is silly.
Input example:
get_vendors(("Neste", "Circle K"))
Output example:
['Neste', 'Circle K']
"""
vendors_list = list(ven)
return vendors_list | 7703a1efc2f6cb329f8c15dc4df19a966d3c4197 | 39,878 |
def delete_all_closed(bot, update, session, user):
"""Delete all closed polls of the user."""
for poll in user.polls:
if poll.closed:
session.delete(poll)
return i18n.t('deleted.closed_polls', locale=user.locale) | eca0cf8726cdde29eb999053e4e3b2564e6e0e3f | 39,879 |
def BS_call(S, K, r, sigma, T):
"""Define a function of Black_Scholes for call option(without dividend)
"""
d1 = (np.log(S / K) + (r + 0.5 * np.power(sigma, 2))* T) / sigma / np.sqrt(T)
d2 = d1 - sigma*np.sqrt(T)
C = S * norm.cdf(d1) - K * np.exp(-r * T) * norm.cdf(d2)
return C | 10c14dab21d33fed801654194ef1d209027d2c67 | 39,880 |
def publish_checklist(request, checklist_id):
# for "messages", refer https://stackoverflow.com/a/61603003/6543250
"""if user cannot retract upvote, then this code be uncommented
if Upvote.objects.filter(user=User.objects.filter(username=username).first(), checklist=Checklist.objects.get(id=checklist_id)):... | ec215711b1219174e7a6117f84a947ac69d4c707 | 39,881 |
def get_menu_items(soup):
"""Return a dictionary of key menu-items and value prices"""
items = clean(soup.find_all(class_="menu-item__name")) # has tags
prices = clean(soup.find_all(class_="menu-item__price")) # has tags
menu_items = dict(zip(items, prices)) # zip into dict with item:price
retu... | 7d73fb3210ae67ce9a7055be3fc8fc7bd318addc | 39,882 |
def only_max(sim, rtrv, y, y_hat, y_lrn, y_ex, ex_counts, n_ex, n_y, sim_pars):
"""
Only the most similar exemplar has a non-zero learning rate, which is constant.
Notes
-----
This is the form of learning assumed by Ghirlanda (2015) when showing the equivalence
between exemplar and RW famil... | 2790d3af3cd6a786776af44a2a33bdf1c00492a3 | 39,883 |
def analyse_book(gutenberg_file):
"""Takes a text file from the Gutenberg Project, returns a list of words
in book that are not in word_list"""
result = []
word_usage.clear()
fin = open(gutenberg_file)
remove_header(fin)
for line in fin:
if '*** END OF' in line:
break
... | efabc433e749a525b141614d1c0045f0997cc04c | 39,884 |
def is_format(fid):
"""
Check the raw file for frequency base
"""
first = fid.readline()
first = first.strip().split('/')
first = first[0].split(',')
if float(first[5]) == 50.0 or float(first[5]) == 60.0:
return True
else:
return False | 7eeefbacad859afb6e179c530aec41d90f6c5bb1 | 39,885 |
def get_success_rate(episodes_infos, task_names, per_task=False):
"""
:param episodes_infos: nested lists (n_tasks, n_episodes, n_timestemps) of dicts
i.e. (meta_batch_size, fast_batch_size, n_timestemps)
"""
# info keys: reachDist, pickRew, epRew, goalDist, success, goal, ta... | 5c4ed56d09bc474fd4025667160c5dd5886fed09 | 39,886 |
def load_raw_ens_data(data_dir):
"""
Loads raw ensemble [time, ens, station]
"""
rg = Dataset(data_dir + 'data_interpolated_00UTC.nc')
ens = rg.variables['t2m_fc'][:]
return ens | 6a8ab674b942f501cfce9b33189af13f2d3692c2 | 39,887 |
from typing import Any
from datetime import datetime
def stringify_mongovalues(v: Any):
"""
Mostly the values are fine, but at least datetime needs handled.
Also need to handle datetimes embedded in dicts, so use recursion to get them.
"""
if type(v) == datetime:
return v.isoformat()
e... | 27349086a58681f0d06ce795b3792cc4e25e97fc | 39,888 |
from typing import List
import tqdm
import time
import os
def pvrpm_sim(
case: SamCase,
save_results: bool = False,
save_graphs: bool = False,
progress_bar: bool = False,
debug: int = 0,
threads: int = 1,
) -> List[Components]:
"""
Run the PVRPM simulation on a specific case. Results w... | cd490ad067292fda9ba7683726fd3730ff11e761 | 39,889 |
def ftp_quit():
""" Quit session """
f_quit = FTP.quit()
return f_quit | 83987196f3ad9b8d11d11ab2ea8088291b0e048f | 39,890 |
def multi_pred(exe, gw, gf, program, y_pred, seq, batch_size, \
n_his, n_pred, step_idx, dynamic_batch=True):
"""multi step prediction"""
pred_list = []
for i in gen_batch(
seq, min(batch_size, len(seq)), dynamic_batch=dynamic_batch):
# Note: use np.copy() to avoid the modificat... | de41c95b0667aa8ce1dc411ae2c09c73711f2e3d | 39,891 |
def max_gram_basis(op_labels, dataset, max_length=0):
"""
Compute a maximal set of basis circuits for a Gram matrix.
That is, a maximal set of strings {S_i} such that the gate
strings { S_i S_j } are all present in dataset. If max_length > 0, then
restrict len(S_i) <= max_length.
Parameters
... | 8d104f91ee70b6a9db74f80edfbc9d5de8e3a3f3 | 39,892 |
import click
def create_cli() -> click.Command:
"""Build and return an instance of `queso`.
# Returns
cli (click.Command): contains both built-in and custom commands.
"""
@click.group(name="queso", cls=CustomCommandsGroup)
@version_option("-v", "-V", "--version")
def cli():
pass
... | 8046490563aa137af74825890c9228f489ee179f | 39,893 |
def nodeSetAdd(nset, newNSet, op):
"""
Adds newNSet to the nset using operation op.
nset : the currrent nodes set (or None).
newNSet : the new nodes set.
op : the operation type.
Returns : the combined nodes set or None if an error occurs.
"""
return xmlsecmod.nodeSetAdd(nset, ne... | 438d72ec7e89c252c4eb9d14a9d03fb7ac35d341 | 39,894 |
def to_web_mercator(x_lon, y_lat):
""" Converts lat, long into web mercator. Needed for tiletanic. """
if abs(x_lon) >= 180 and abs(y_lat) > 90:
print 'Invalid coordinate values for conversion'
return None
num = x_lon * 0.017453292519943295
x = 6378137.0 * num
a = y_lat * 0.01745329... | 1268844a8d4eacb95e6608309e1a97c140a7b6eb | 39,895 |
def down_sample(df, target):
"""
Fixes imbalanced dataset by down-sampling
Parameters
----------
df : pandas.DataFrame
target : name of the target column in df
Returns
-------
downsampled_df : pandas.DataFrame
"""
dfs = []
target_value_counts = df[target].value_counts()... | dbf3288f838fe46c308279f9aef0f6db7422632e | 39,896 |
import os
import filter_dataset
import tqdm
def load_data(data_path=config.DATA_PATH, vector_length=187):
"""A function to load gender recognition dataset from `dataset` folder
After the second run, this will load from results/features.npy and results/labels.npy files
as it is much faster!"""
# make s... | bfa69c3462e0417ea328ef5542c1808478d82bda | 39,897 |
from operator import add
def mean1(m):
"""mean(m) returns the mean along the first dimension of m. Note: if m is
an integer array, integer division will occur.
"""
return add.reduce(m)/len(m) | 79acbc4cdf1750a82d9d223207de47d5ddcb1302 | 39,898 |
import math
def H_cond(X, Y, bins):
"""
Calculates the conditional entropy of X depending on Y.
If X and Y are already discretised, set \ref bins to the amount of bins, aka states of X and Y.
If X and Y are not discretised, \ref bins will be used, to diskretise X and Y into \ref bins states
@para... | a67f639f319aa0fad3fe3a1aeef824c3b81ffe91 | 39,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.