content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def adagrad(lr, epsilon, weight_decay):
"""\
Adagrad optimizer.
Adagrad is an optimizer with parameter-specific learning rates, which are
adapted relative to how frequently a parameter gets updated during
training. The more updates a parameter receives, the smaller the learning
rate. See: http:... | ba441ca1cf064d8d84c8d7a37223daeafc1de9c5 | 3,620,566 |
from typing import List
from typing import Dict
from typing import Counter
def layout_agnostic_vocabulary_vector(
results: List[Dict],
number_of_words: int
) -> List[str]:
"""Create a layout agnostic vocabulary vector
Finds the most popular words out of a bag comprised of all layouts
... | d5bd370293e34c8a792f7dff11a56f36675dceea | 3,620,567 |
def getTriangularVertices(n,
rotationAngles = [0, 0, 0],
phi_start = 0,
phi_end = np.pi,
plotIt = False):
""" Triangular approximation of a sphere
Two angular sweeps are necessary. One is theta that goes arou... | 8c8c25ef2aadec4dd33c39d6a438e066af2d33ec | 3,620,568 |
def _get_role_prefix(node):
"""Calculates the node role prefix used for grouping nodes in the graph"""
try:
role_prefix = node['role'][0].split("_")[0]
if role_prefix == REPO['EXCLUDE_ROLE_PREFIX']:
role_prefix = 'none'
role_prefix = node['role'][1].split("_")[0]
... | 0dafae13bd7c2530070809c16eb115556664dbee | 3,620,569 |
from typing import Optional
from typing import Union
from typing import Dict
from typing import List
def check_message(
message_id,
parameter: Optional[Union[str, Dict]],
level_type: Optional[Union[str, List[str]]],
level: Optional[Union[int, List[int], Dict]],
**kwargs,
) -> b... | 8d258e2bb8ac7874f113c6cac544370ab9f36fee | 3,620,570 |
from typing import TextIO
def process(fh: TextIO) -> FastaInfo:
""" Process a file """
if lengths := [len(rec.seq) for rec in SeqIO.parse(fh, 'fasta')]:
return FastaInfo(filename=fh.name,
min_len=min(lengths),
max_len=max(lengths),
... | 66cdd2766b9bf2c7a4e98c06f24db1bf6161c5ce | 3,620,571 |
import re
def cln_info(record):
"""Annotates pathogenicity using ClinVar
Args:
record (tuple): vcf line with fields separated in tuple
Returns:
significance + '|' + disease (str): pathogenicity and disease name implicated
"""
try:
significance = re.search(r"(CLNSIG=)([... | 8d201c77b00373d2e5ae7866d6c15b704105a344 | 3,620,572 |
from operator import inv
def n_clinic_to_unit_cube(x_array,box):
"""
---Inputs---
x_array : {2 mode numpy array}
array defining the "real" coordinate(s) at which to calculate values of
basis functions
shape (n_points, d)
dimension of first mode gives number of points
... | d55dd6f99047935df395dde174b4525a2f6b9bcd | 3,620,573 |
def permission_request_delete_link(context, perm):
"""
Renders a html link to the delete view of the given permission request.
Returns no content if the request-user has no permission to delete foreign
permissions.
"""
user = context['request'].user
if user.is_authenticated():
link_k... | 2212b61e2a5dafc9b486c8345e728c09461a4f29 | 3,620,574 |
def dummies(data):
"""
Manually creates labels for property type. sklearn label encoder was breaking the model shape.
"""
data['Property_Area'] = data['Property_Area'].replace('Rural', 0, regex=True)
data['Property_Area'] = data['Property_Area'].replace('Semiurban', 1, regex=True)
data['Property... | 607da5c4a023c789a3a6da27d0ddfe4bfafa7d3a | 3,620,575 |
from fsm.fsmspec import FSMSpecification
def get_specs():
"""
Get FSM specifications stored in this file.
"""
spec = FSMSpecification(
name='faq',
hideTabs=True,
title='Take the courselet core lessons',
pluginNodes=[
START,
SHOW_FAQS,
... | 2f4b522ad699a866d047acf09e21e68fe7b967b1 | 3,620,576 |
from typing import Union
from typing import Optional
from typing import List
from typing import Tuple
def render(
markup: str,
style: Union[str, Style] = "",
emoji: bool = True,
emoji_variant: Optional[EmojiVariant] = None,
) -> Text:
"""Render console markup in to a Text instance.
Args:
... | 06b0e6e135aa35661d089c86002d6e796dd92bd4 | 3,620,577 |
def info_colon_to_dict(value):
"""
Simple function to convert colon separated string to dict
"""
return info_to_dict(value, ":") | 264b05c130b41eca746c5fb30f6a591535151331 | 3,620,579 |
def parse_markdown(filename):
""" Takes a .md file and returns a parsed version in HTML.
Parses a markdown file using mistune, returns a string which
contains the parsed information in HTML.
Args:
filename: the file to be parse, must be a .md file.
Returns:
Variable which ... | 1d13da92f4c15a2cc7cad990b05b64bff4738f9b | 3,620,580 |
def create_full_example() -> model.DictObjectStore:
"""
Creates an :class:`~.aas.model.provider.DictObjectStore` which is filled with an example
:class:`~aas.model.aas.Asset`, :class:`~aas.model.submodel.Submodel`, :class:`~aas.model.concept.ConceptDescription`
and :class:`~aas.model.aas.AssetAdministra... | 935f1ed998d3f490e6ff46f550203faad3847f6d | 3,620,582 |
def filter_kmeans_segmentation(np_img, compactness=10, n_segments=800):
"""
Use K-means segmentation (color/space proximity) to segment RGB image where each segment is
colored based on the average color for that segment.
Args:
np_img: Binary image as a NumPy array.
compactness: Color proxim... | 6ebc0a18072646f8af87fae1f4d6e6679c7ad691 | 3,620,583 |
from typing import Optional
from typing import List
def _pytd_signature(
function: ast3.AST,
is_async: bool,
exceptions: Optional[List[pytd_node.Node]] = None
) -> pytd.Signature:
"""Construct a pytd signature from an ast.FunctionDef node."""
name = function.name
args = function.args
pos_params = ... | 46dc2a960e7f72636fdf5d2b6d45b2a8043e5a81 | 3,620,584 |
from unittest.mock import Mock
def dao_exchange_rate_mock():
"""
:return: Mock of gold_digger.database.DaoExchangeRate
"""
return Mock(DaoExchangeRate) | 22683a22e860a95199388f9d4d15539cc1f019a2 | 3,620,586 |
import six
def _repr_odict(dumper, data):
"""
Represent OrderedDict in yaml dump.
Source: https://gist.github.com/weaver/317164
License: Unspecified
>>> data = OrderedDict([('foo', 'bar'), ('mumble', 'quux'), ('baz', 'gorp')])
>>> yaml.dump(data, default_flow_style=False) # doctest: +SKIP
... | 6c141e7c2db180fc07041955ed7f4b49eadc56c6 | 3,620,588 |
def _update_inventory(context, rp, inventory):
"""Update an inventory already on the provider.
:raises `exception.ResourceClassNotFound` if inventory.resource_class
cannot be found in either the standard classes or the DB.
"""
_ensure_rc_cache(context)
rc_id = _RC_CACHE.id_from_string(i... | 02af39181ad73da7c21c1526308f571001860ae7 | 3,620,589 |
def assert_all_loaded(pairs, raise_=True):
"""
Returns True if all SleepStudy objects in 'pairs' have the 'loaded'
property set to True, otherwise returns False.
If raise_ is True, raises a NotImplementedError if one or more objects are
not loaded. Otherwise, returns the value of the assessment.
... | d211b77c2d16fafaff5555701af66d0144fb0b73 | 3,620,590 |
def max_pool(x, ksize, stride, name):
"""
Create a max pooling layer
:param x: input to max-pooling layer
:param ksize: size of the max-pooling filter
:param stride: stride of the max-pooling filter
:param name: layer name
:return: The output array
"""
return tf.nn.max_pool(x,
... | eed9b1a7334b4dbafa0f360aabaa0614b21f5596 | 3,620,591 |
def _check_robot_postproc_compatibility(robot, processor):
"""
Verify the compatibility of the selected robot and the processor.
:return:
"""
warning = ''
robot_type = mimic_utils.get_robot_type(robot)
processor_type = processor.type_robot
# Always return without a warning if the p... | 186b6953aed40c01b879717966cb39e82ead8c8c | 3,620,592 |
def flush(hand):
"""Return True if there is a flush"""
suits = [s for r,s in hand]
return len(set(suits)) == 1 | 75f5542b5a187e6bf3e3b59f961357d0921c6a76 | 3,620,593 |
from typing import List
def filter_by_name(candidates: List[Element], query: EdifactStackQuery) -> List[Element]:
"""
returns those elements that have the given name (in the query)
"""
filtered_by_names = [
x
for x in candidates
if are_similar_names(x.attrib["name"], query.name... | 4c6e405b932e4c53e60d474352a14723200aa7e1 | 3,620,594 |
def remote_shortname(socket):
"""
Obtains remote hostname of the socket and cuts off the domain part
of its FQDN.
"""
return socket.gethostname().split('.', 1)[0] | e52ec17a36800029a9889dc1b5e567567b9c9340 | 3,620,596 |
def MakePlot(specWithCuts, specWithoutCuts, options):
"""
Creating the final plot. The plot will be a two panel plot:
1st panel shows the comparison of the spectra.
2nd panel shows the ratio of the normalised spectra with and
without pileup rejection (as without/with)
... | 27a206b538347b4657aa924f93e8f1d428da1dae | 3,620,597 |
def network_instance_list(network=None, host=None):
"""
Retrieves information about all resources.
Parameter *kind*:
If *kind* is set, only resources with a matching kind will be returned.
Return value:
A list with information entries of all matching network_instances. Each list
entry contains exactly th... | 7eab3046a89662ce1b0f13fa6ee93481bbf7f51c | 3,620,598 |
def formatParagraphLine(text, width):
"""
:return: array of rows
"""
words = text.split()
tail = words
result = []
buf = ''
while len(tail):
curWord, tail = tail[0], tail[1:]
if len(buf) + len(curWord) + 1 > width:
if buf == '':
row = curWord
... | 14672342e24706df117425d5e59f9d2c762faab2 | 3,620,599 |
import io
def process_image(base_image, mask_array, output_format="jpeg"):
"""
Create the final image including the aerial imagery background with the
outside of the featured boundaries masked.
:param base_image: A file-like object with the image
:type base_image: File-like object
:param mask... | 73e45f5b2bd006e40be09696c5b8674d70d5a6ba | 3,620,600 |
def get_scene(scene_id, client=default):
"""
Return scene corresponding to given scene ID.
"""
return raw.fetch_one("scenes", scene_id, client=client) | d1ae7409b3eec57a8b24d0522cae89ee45e9a87b | 3,620,601 |
def build_uwp(
package_family_name, target, location=None,logo44x44=None, lnk_name=None,
) -> Lnk:
"""
:param lnk_name: ex.: crafted_uwp.lnk
:param package_family_name: ex.: Microsoft.WindowsCalculator_10.1910.0.0_x64__8wekyb3d8bbwe
:param target: ex.: Microsoft.WindowsCalcul... | 092a518e682b870353431efbdbdd3a341f360ca7 | 3,620,602 |
def elevation_nl(xarray=False):
"""
Fetch surface elevation dataset for the Netherlands.
"""
fname = REGISTRY.fetch("elevation_nl.nc")
ds = xr.open_dataset(fname)
if xarray:
return ds
else:
grid = xugrid.Ugrid2d.from_dataset(ds)
return xugrid.UgridDataArray(ds["elevat... | 48d85e99911f3a6a5d9ec31a3f3d231b25129ac4 | 3,620,603 |
def parse_single_event(when, local_tz=None, now=None):
"""
This function parses a text string describing a single time range on a
specified date, returning a tuple of start and end times
(datetime.datetime). The year will be set to the current year, unless the
optional argument now is provided, in w... | 36f1e4eddfe37cea2ae28e942cbc1f0d54cffe37 | 3,620,604 |
def encode(state: "knx_stack.State", msg: "knx_stack.Msg") -> "knx_stack.Msg":
"""
>>> import knx_stack
>>> address_table = knx_stack.AddressTable(0x1001, [], 255)
>>> association_table = knx_stack.AssociationTable(address_table, [])
>>> state = knx_stack.State(knx_stack.state.Medium.usb_hid,associa... | a44730583b3c9692a08be0ac084bd947b6d75cd1 | 3,620,605 |
def _antialias_filter_image(data, oldstep, newstep, oldfmax=None,
window="blackman"):
"""Apply an anti-aliasing prefilter to an image to prepare
it for subsampling.
Parameters
----------
data : np.ndimage
The 2D image to be filtered.
oldstep: float or (float,... | f54a56ffd487bc1efa9e33d3de329c2c17d173cb | 3,620,606 |
def post(name):
"""Prints a post."""
global config
global dbh
if name == "all":
return index()
elif name == "":
return index(config.getint("blog", "default"))
elif "\t" in name:
(selector, term) = name.split("\t", 1)
return search(term)
c = dbh.cursor()
c.execute("SELECT post_title, post_content FROM... | e97651ccda47ca638ee428553c6010f684d93c54 | 3,620,607 |
import pandas
def read_csv(csv_path: PathLike) -> pandas.DataFrame:
"""
Read a csv file. Returns a DataFrame.
"""
csv_info = pandas.read_table(
csv_path,
sep=",",
index_col=False,
header=None,
).T
csv_info.columns += 1 # Make the channel numbers correspond ... | 0ca2d856efae3026998b461b0f7a0d6442bd3680 | 3,620,608 |
def c2t00a(tta, ttb, uta, utb, xp, yp):
""" Form the celestial-to-terrestrial matrix given the date, the UT1 and
the polar motion, using IAU 2000A nutation model.
:param tta, ttb: TT as a two-part Julian date.
:type tta, ttb: float
:param uta, utb: UT1 as a two-part Julian date.
:type uta, utb... | e174e6623eadb97d841d941b6efa97bd5ddc9f66 | 3,620,609 |
def center_of_mass(input, labels=None, index=None):
"""
Calculate the center of mass of the values of an array at labels.
Args:
input (cupy.ndarray): Data from which to calculate center-of-mass. The
masses can either be positive or negative.
labels (cupy.ndarray, optional): Labe... | 2af2c745accf40e1c65909bdd88f983e4f8dd448 | 3,620,610 |
def encodewrap(s):
"""改行コードを\nに置換する。"""
r = []
if not s:
return u""
for c in s:
if c == '\\':
r.append("\\\\")
elif c == '\n':
r.append("\\n")
elif c == '\r':
pass
else:
r.append(c)
return "".join(r) | a3486f3340d898751371fb4d4e29876120ec280b | 3,620,611 |
def initialize_new_task_list(user_info, all_tasks):
"""
initializes new task and user from POST request
"""
new_user = User(**user_info)
new_user.save()
user_id = new_user.id
for task in all_tasks.values():
task['user_id'] = user_id
new_task = Task(**task)
new_task.sa... | 850c2c0fd0a540249566b554d262ac377d548341 | 3,620,612 |
def load_labels(label_path, label_interest):
"""
Loads the label table.
Parameters
----------
label_path: string,
path to label csv table
label_interest: string,
name of variable to predict. Has to be in the table loaded by
the parameter label_path.
Returns
----... | d70e024bd1671330944ddab982facc02fa0d7be6 | 3,620,613 |
from typing import Tuple
from typing import Optional
from typing import Sequence
from typing import Union
def clonotype_modularity(
adata,
ax=None,
target_col="clonotype_modularity",
jitter: float = 0.01,
panel_size: Tuple[float, float] = (6, 4),
base_size: float = 2,
size_power: Optional[... | 83ea2453bb0b773129858bbb48fc8a6545f4a09e | 3,620,614 |
def gen_plot_4(fig, x_recon_l,x_recon_r,inputs_l,inputs_r ):
"""Create a pyplot plot and save to buffer."""
ax1 = get_ax(x_recon_l, fig, subplot='141', az=0)
plot_skeleton_and_scatter(x_recon_l, ax1)
ax2 = get_ax(inputs_l, fig, subplot='142', az=0)
plot_skeleton_and_scatter(inputs_l, ax2)
ax3 = ... | 02ee41334db4142ed0144fa28dd711246234d289 | 3,620,615 |
def is_lone_coo(where):
"""Check if ``where`` has been specified as a single coordinate triplet.
"""
return (len(where) == 3) and (isinstance(where[0], Integral)) | 83e258e21fbac34010699f18ee2f510ba31e1f99 | 3,620,616 |
import time
def get_tzoffset():
""" 取得時區差異秒數 (在臺灣會取得負值: -28800)
"""
global _tzoffset, _tzoffset_last_update
current_time = time.time()
if (current_time - _tzoffset_last_update) > 3600:
_tzoffset_last_update = current_time
_tzoffset = time.altzone
if _tzoffset is None:
_tzoffset = time.timezone
if _t... | a8ed92007c400c6599ef863ad95594c0b7bd6247 | 3,620,617 |
def build_metrics(config):
"""pytorch_lightning metrics"""
metrics = {}
if config.trainer.metrics is not None:
for name, cfg in config.trainer.metrics.items():
metrics[name] = build_from_config(cfg, METRICS)
return edict(metrics) | 1fef4f90a49194ad632607782aec68a59ab59dca | 3,620,618 |
def kde_scipy(x, x_grid, bandwidth=0.2, **kwargs):
#x_grid = np.linspace(-4.5, 3.5, 1000)
"""Kernel Density Estimation with Scipy"""
# Note that scipy weights its bandwidth by the covariance of the
# input data. To make the results comparable to the other methods,
# we divide the bandwidth by the s... | aa8a1a5fc538f09668b69d35ebcde4d756bf79b6 | 3,620,619 |
def gini(x):
"""Calculate the Gini coefficient for series of observed values (x).
where:
* x is the array of observed values (and all x are positive, non-zero values)
Note: x must be a numpy array or a pandas series
See: https://www.statsdirect.com/help/default.htm#nonparametric_methods/gini.htm
... | 352c4fa44529a43bdd9862e7949b1103e7969f42 | 3,620,620 |
import requests
def try_request(url, params=None, data=None, timeout=5, num_retries=1, method='post'):
"""
@params dict: 请求查询参数
@data dict: 提交表单数据
@timeout int: 超时时间,单位秒
@num_retries int: 超时重试次数
"""
headers = {"User-Agent": "Mozilla/5.0 (X11; CentOS; Linux i686; rv:7.0.1406) Gecko/20100101... | 508a9959cb05b50dd395f0a3d1050691b5479621 | 3,620,621 |
def qv_to_char(qv):
"""Convert a qv to a phred-encoded char."""
return chr(qv + CHAR_OFFSET) | 83cc3c421ef3194b483e233b79e13607d622cf83 | 3,620,622 |
import urllib3
import json
def get_public_urls():
"""Get a list of available external tunnel URLs"""
urls = []
try:
http = urllib3.PoolManager()
req = http.request('GET', 'http://localhost:4040/api/tunnels')
data = str(req.data, 'utf-8')
obj = json.loads(data)
tunn... | d17e57cafe0833f35b4c5742a96901869dd8b7b1 | 3,620,623 |
def is_fragment(href):
"""Return True if href is a fragment else False"""
is_fragment = False
try:
if href[0] == '#':
is_fragment = True
except IndexError:
is_fragment = False
return is_fragment | da1899ac1b59b8a6a42034a46194ff0d09a8799d | 3,620,624 |
def adjacency_matrix(graph):
"""
:param graph:
:return: dictionary
Converts directed graph to an adjacency matrix.
Note: The distance from a node to itself is 0 and distance from a node to
an unconnected node is defined to be infinite. This does not mean that there
is no path from a node to... | 4e14880bdcec130a3cf4357f54609422142efa39 | 3,620,625 |
def get_item_by_id(item_id):
"""
Return item by id
:param item_id:
:return object:
"""
return session.query(Catalog).filter_by(id=item_id).first() | ebdf9569414619d49d624652763df6d20a616dac | 3,620,629 |
from typing import Callable
def data_generator(X: np.ndarray,
encoder_preprocessor: Callable,
predictor: Callable,
conditional_func: Callable,
batch_size: int,
shuffle: bool = True,
**kwargs):
"""
... | caf40a9358dc6dbb67389429081789a0aae1e06d | 3,620,630 |
import re
def generate_room_times(course_data: CourseData) -> dict:
"""
Generates data structure for getting the room availability.
"""
room_time = {}
# iterate through all the courses
for course in course_data.courses:
# checks if room does not already have an entry
if course.... | ede287525b40dfc828494cb2375465177843f80d | 3,620,631 |
def make_mlph_data(modified, h):
"""Creates features and target labels data with MLPH histogram computations.
:param modified: Boolean value to indicate if modified MLPH is used
:param h: Integer with window size for MLPH histogram computations
:return: Training set features and target labels numpy mat... | 69e76ca70f9fb4a044ff3ee3a1ea332acf6879be | 3,620,632 |
from framework.auth import signals as auth_signals
def add_poster_by_email(conference, message):
"""
:param Conference conference:
:param ConferenceMessage message:
"""
# Fail if no attachments
if not message.attachments:
return send_mail(
message.sender_email,
... | 39f88e0126d174f237cb8620d86ea291113e2e14 | 3,620,633 |
def _remove_scheme(bucket_path):
"""Remove scheme from the bucket path."""
if '://' not in bucket_path:
raise BuildManagerException('Invalid bucket path: ' + bucket_path)
return bucket_path.split('://')[1] | 7bc507acd8d0deccb95a705dc4863bb8bdedebae | 3,620,634 |
import multiprocessing
def run_sources_on_mesh(mesh, sources_list, processes=1):
"""
Run multiple sets of sources on the mesh, supports multiprocessing.
:param mesh: Mesh to be used in calculations.
:param sources_list: a LIST of LISTS of sources, like:
[[mag1_1, mag1_2, mag1_3],
[mag2_2, mag... | 4a8cd6c4d776f611e4f84280dc00d35035d6ae11 | 3,620,637 |
def parse_xml_io(xml_io):
"""
Parses xml and get data for mapped_name key
"""
assert xml_io is not None
port_names = []
for xml_cell in xml_io.findall("CELL"):
mapped_name = xml_cell.get("mapped_name")
# define properties for scalar pins
scalar_mapped_pins = vec_to_scalar... | 471aa357d8a9b791c0d053739df19c9b781a1f0f | 3,620,638 |
def isposdef(A):
""" Check if a matrix positive definite."""
if np.array_equal(A, A.T):
try:
np.linalg.cholesky(A)
return True
except np.linalg.LinAlgError:
return False
else:
return False | 270806133e06fbee16af3fdc689bedaf7f5e1af7 | 3,620,639 |
def read(stream):
"""Read a Scheme expression from a stream"""
def read_ahead(token):
if token == '(':
expr = []
while True:
token = stream.next_token()
if token == ')':
return expr
else:
expr... | ae1029023070f8e0b7d254b3b328cba4e54ecc74 | 3,620,640 |
def reset_initial_conditions(ClockStruct, InitCond, ParamStruct, weather):
"""
Function to reset initial model conditions for start of growing
season (when running model over multiple seasons)
*Arguments:*\n
`ClockStruct` : `ClockStructClass` : model time paramaters
`InitCond` : `InitCondCl... | 3435c62de186f3c3564047089ffb5af942a976a0 | 3,620,641 |
def myocardialmass(myocardvol):
"""
Specific gravity of heart muscle (1.05 g/ml)
"""
return myocardvol*1.05 | ca12a23a27a3dc2cb3df96abe4bfe94424125b14 | 3,620,643 |
def lineEdit(*args, editable:bool=True, transparentBackground:bool=True, borders=False, **kwargs):
""" Generate a pre-customized QLineEdit Widget
:param parent: Parent Index
:param editable: Defines whether the line edit should be editable or not
:param transparentBackground: Sets the style sheet to a ... | 6332f303f57597c3124fc17c3549b9a7d9e90859 | 3,620,644 |
from re import T
def sheva_nah_ending_tsere_hiriq_male(neg_idx, guess, guesses):
"""`sheva` before `tsere`, `hiriq-male` is `sheva-nah`
This rule was emperically checked for the Pentateuch.
"""
pattern = [
{"vowel": T.NAME_SHEVA},
{"vowel": T.NAME_TSERE},
{"vowel": T.NAME_HIRI... | dd4c0a0b92da0afe0d9abb0d591409c715beb505 | 3,620,645 |
import time
def train(gan, train_dataset, n_epochs, epochs_so_far=0, checkpoint_path=None):
"""Train the GAN model
Args:
gan (GAN): GAN model to train
train_dataset (tf.data.Dataset): training dataset
n_epochs (int): number of epochs to train
epochs_so_far (int, optional): sta... | 04c34d4d2b0a5c8473e680e03f1f1ba7101a20c0 | 3,620,646 |
def curvature(dem, res, kind, L=None):
"""
Calculate curvature for a digital terrain model.
Parameters
----------
dem : ndarray
Terrain elevation (m).
res : float
DEM resolution (m).
kind : str
Curvature calculation method. Allowed values are:
- 'liston... | 37e61a21831bc24dead3a16c50e1a56e3706523a | 3,620,647 |
def parse_datasets(xml_str, tds_type):
"""
"""
results = []
root = etree.fromstring(xml_str)
ns_map = root.nsmap
# check a ns_map for a key of None, i.e.default namespace and set to arbitray prefix so we can use xpath
# Search for k of None, delete and set a random prefix to the original ns value
for k... | 4841393dce5e938e0f4a38723f7f385d7cc25966 | 3,620,648 |
async def challenge(websocket, user):
"""Challenges a user.
"""
return await websocket.send(f'|/challenge {user}, gen8metronomebattle') | bee53e79d085ebc7f8a48e0091adb2e6605a2ac6 | 3,620,649 |
def onset_to_hosp_or_asymp(clip_low=2, clip_high=21.1, mean=6.2, std=4.3):
"""
Returns the time for someone to either get removed or hospitalized
in days within range(clip_low, clip_high),
of a truncated_norm(mean, std).
"""
return sample_truncated_norm(clip_low, clip_high, mean, std) | 7646651026363239a258c5ca88b5d261af1127a1 | 3,620,650 |
def create_character_ngrams(text_list, length):
""" Create character ngrams of the specified length from a string of text
Args:
text_list (list): Pre-tokenized text token to process.
length (int): Length of ngrams to create.
http://stackoverflow.com/questions/18658106/quick-implement... | 5df4dda2fe83a921c3b949fa3e9e7e843c333530 | 3,620,652 |
def unscramble_wavefunction(wavefunction):
""" the state ordering within the wavefunctions (complex numpy array)
returned by cirq's simulate() function are not in standard sequential counting order
(0, 1, 2), but are scrambled
this function takes a wavefunction of arbitrary qubit legnth, an... | df797aa25ed1bb353cdf45627905b9b232870591 | 3,620,653 |
def fit_bonus_points(
gameweek=NEXT_GAMEWEEK, season=CURRENT_SEASON, min_matches=10, dbsession=session
):
"""Calculate the average bonus points scored by each player for matches they play
between 60 and 90 minutes, and matches they play between 30 and 59 minutes.
Mean is calculated as sum of all bonus p... | a48cecb8eb0f77b474ac83523bb47d0921ab5e0b | 3,620,654 |
import io
def get_gt_SHT(gt_path, img_w, img_h, scaling=1., sigma=4):
""" Retrieves and generates the GT density for the ShanghaiTech A/B dataset."""
mat = io.loadmat(gt_path)
points = mat["image_info"][0, 0][0, 0][0]
den = gen_scaled_den_from_points(img_w, img_h, points, scaling, sigma)
return ... | 7e0cf51572e3578520b7f1c5fac784bc751b11cb | 3,620,655 |
def air2vacMortonIAU(wl_air):
"""Take an input air wavelength in Angstroms and return the vacuum
wavelength.
Formula taken from
https://www.astro.uu.se/valdwiki/Air-to-vacuum%20conversion
"""
s = 1e4 / wl_air
n = 1 + 0.00008336624212083 + (0.02408926869968 / (130.1065924522 - s**2))\
... | 66823170493c3b7d8f63bd7d2e32364aa5efa78e | 3,620,657 |
def get_vocabs(datasets):
"""Build vocabulary from an iterable of datasets objects
Args:
datasets: a list of dataset objects
Returns:
a set of all the words in the dataset
"""
print("Building vocab...")
vocab_words = set()
vocab_tags = set()
for dataset in datasets:
... | 05a11e1ed47887c05bdbbd1845074a5765d67701 | 3,620,659 |
def get_max_node(candidates, gr_values, column_prefix=""):
"""Given a set of candidate nodes, and return the one with the
highest Gain Ratio.
Args:
candidates (list): List of candidate nodes.
gr_values (dict): Dictionary with column names as keys and
the corresponding Gain Rat... | 5d64dad256784a932bcdc85265713d2b32c19c47 | 3,620,660 |
def tablefy(data, column=None, gutter=1, width=79):
"""
Convert a list of strings into being a table, displaying in a left-to-right
and top-to-bottom pattern. This does not sort the values.
:param data: list of strings
:param column: width of column, if None, detected
:param gutter: width of g... | d8aa63421578b9a0c4cb9c3fa106e7336de946d9 | 3,620,661 |
def stations_by_distance(stations, p):
"""This function uses haversine to calculate the distance between all the UK river monitoring stations
and a given co-ordinate named in this function as p. We then return a list of the stations as instances
of MonitoringStations and sort the list by the distances to th... | c6484e199333e1636f7ea4952d19a015e9e174d5 | 3,620,662 |
import functools
def once(func):
"""
Decorate func so it's only ever called the first time.
This decorator can ensure that an expensive or non-idempotent function
will not be expensive on subsequent calls and is idempotent.
>>> func = once(lambda a: a+3)
>>> func(3)
6
>>> func(9)
... | 60e6c4a9e26b322c27da74ca98e119056247b900 | 3,620,663 |
import asyncio
def pytest_pyfunc_call(pyfuncitem):
"""
Run asyncio marked test functions in an event loop instead of a normal
function call.
"""
for marker_name, fixture_name in _markers_2_fixtures.items():
if marker_name in pyfuncitem.keywords:
event_loop = pyfuncitem.funcargs... | b3d98cdd09abcd8e2325f972aa6e41d3279c942a | 3,620,664 |
def contourAverage(inputC):
"""Function that approximate a contour by a line inside the contour.
It realizes the mean of the lines of two points on a same column.
If there is one point or strictly more than 2 points in a same
column, the column is not considered and no mean is realized.
... | c6a27c39792bea00ae05978769f87d0d768421a2 | 3,620,665 |
def repeat(x, repeats, axis=None):
"""Repeat elements of an array.
It returns an array which has the same shape as `x`, except
along the given axis. The axis is used to speficy along which
axis to repeat values. By default, use the flattened input
array, and return a flat output array.
The num... | 094574bd3c01479cd2535e8d5990c9f2a7233287 | 3,620,666 |
def format_search_filter(model_fields):
"""
Creates an LDAP search filter for the given set of model
fields.
"""
ldap_fields = convert_model_fields_to_ldap_fields(model_fields)
ldap_fields["objectClass"] = config.LDAP_AUTH_OBJECT_CLASS
search_filters = import_func(config.LDAP_AUTH_FORMAT_SEA... | bceeefcd4dd00de5fcbd31b3bc72e7404f1b4ef9 | 3,620,668 |
def explore_match(win, img1, img2, kp_pairs, status = None, H = None, show=True):
"""
This function draws a set of keypoint pairs obtained on a match method of a descriptor
on two images imgf and imgb
:param win: window's name (str)
:param img1: image1 (numpy array)
:param img2: image2 (numpy ar... | 85b77ec3aa325e1cb28cb6c33ec0ebb2457c99c7 | 3,620,669 |
def get_sorted_list_of_expr_not_in_use(path_to_db: str) -> list:
"""
Only expressions that are not in use can be deleted
This list is used in the dropdown menu of expressions to be deleted
Args:
path_to_db: filename of the SQL database containing
a JSON entry that returns a... | fb71b2fb69229f989e828e4cd8ed867ffaf81a38 | 3,620,670 |
def missing_query(*args, **kwags):
"""
A query returning something not in the local DB
"""
response = {
'responseHeader': {'params': {'rows': 1}},
'response': {
'numFound': 1,
'docs': [{
'id': 'abcde',
'chec... | c40ad0a6044bcaceee1b7431508a770f8fe21f61 | 3,620,671 |
def _element_basis(string: str):
"""
Parse element and basis from string
Args: str
Returns: element, basis
"""
cut_list = string.split(".")
element = cut_list[0]
basis = " ".join(cut_list[1:])
return element, basis | c6be1c2a05832bb3bbc4577015b541136c724a08 | 3,620,672 |
def calc_hist(img):
"""
To calculate histogram of an RGB image
Parameters
----------
img : Array of uint8
Image whose histogram is to be calculated
Returns
-------
histogram : np.array
The required histogram
"""
histogram = [0] * 3
for j in range(3):
... | 084b3b7dc43caa06f400043d0116884abc6ad46c | 3,620,674 |
def upper_bound(x):
"""Return the upper bound of interval x."""
"*** YOUR CODE HERE ***"
return x[1] | e1e797d929c55ba18b098a22d242eb79a2db263f | 3,620,675 |
def proportion_linear(time_right: float,
time_between: float,
time_step: float) -> tuple:
"""
:param time_right: right border in time
:param time_between: time between borders
:param time_step: step in time between borders
:return: _Iterable_(alpha, beta)
... | a2841baf2b3022e2be7f47111e63f1f6eb9e76e2 | 3,620,676 |
import requests
def getusercid(username):
"""
getusercid(string) -> string
tries to retrieve the CID of an avatar for a name to cid lookup
"""
getuser = 'http://www.imvu.com/catalog/web_av_pic.php?av=%s' % (username)
r = requests.get(getuser)
link = r.url
cid = link[link... | 3f296e82191290646bef5e0c6e209f5d47b273f7 | 3,620,677 |
def channels(sound_object):
"""
DETERMINE IF A SOUND OBJECT IS MONO OR STEREO
RETURN AN INTEGER REPRESENTING THE NUMBER OF CHANNELS (1, 2, 4, 6)
CHANNEL 4 and 6 ARE NOT IMPLEMENTED YET (NEW FEATURE IN SDL 2.0)
:param sound_object: numpy.ndarray; Sound samples into an array
:return: int; return t... | b6b1635794fc9531e28c378cfdbb00b2c12d1561 | 3,620,678 |
def validate_request():
""" This method validates the Request payload.
Args
expected_args(tuple): where i = 0 is type and i > 0 is argument to be
validated
Returns
f(*args, **kwargs)
"""
def real_validate_request(f):
@wraps(f)
def decorated(... | 179c0c544982f899629c0cb46ff67f8ec7136086 | 3,620,679 |
def mr2rho(w,t,p):
"""rho = mr2rho(w,t,p)
w in g/kg
t in K
p in mb
This was provide by Holger Linne' from Max Planck Institute.
Dave Turner
Pacific Northwest National Laboratory
Currently at the University of Wisconsin-Madison
dave.turner@pnl.gov
"""
rho = w * (p * 0.3477) / t
return rho | 595cbb884a6824c7ec5fd28a1110a4dff1016417 | 3,620,680 |
def dir_to_cart(v, lattice):
"""
Convert direct coordinates to cartesian.
Parameters
----------
v : ndarray
| Dimension: (3)
The direct vector to be converted.
lattice : ndarray
| Dimension: (3,3)
The crystal lattice, where the first lattice vector is
[... | c18094ff761fbdf3936fa4b1310aabfde19e579f | 3,620,681 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.