content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import Optional
def read(db,
query: Optional[dict] = None,
pql: any = None,
order_by: Optional[str] = None,
limit: Optional[int] = None,
offset: Optional[int] = None,
disable_count_total: bool = False,
**kwargs):
"""Read data from DB.
... | b2153ce1b83de7f3f7dd5311a619a0623aedc01b | 3,649,854 |
def check_horizontal(board: list) -> bool:
"""
Function check if in each line are unique elements.
It there are function return True. False otherwise.
>>> check_horizontal(["**** ****",\
"***1 ****",\
"** 3****",\
"* 4 1****"... | 0769f0821637c78c1a18e387eb64d6234a0ced5c | 3,649,855 |
import math
def update_events(dt: float, pos_x: float, pos_y: float, dir_x: float, dir_y: float, plane_x: float, plane_y: float):
""" Updates player position in response to user input.
"""
for e in pygame.event.get():
if e.type == pygame.KEYDOWN:
if e.key == pygame.K_ESCAPE:
... | e43cc7a2e6ab3f35637bf4ab37baefed96279656 | 3,649,857 |
def deg_to_xyz(lat_deg, lon_deg, altitude):
"""
http://www.oc.nps.edu/oc2902w/coord/geodesy.js
lat,lon,altitude to xyz vector
input:
lat_deg geodetic latitude in deg
lon_deg longitude in deg
altitude altitude in km
output:
returns vector x 3 long ECEF in... | 0493132eb0658026727d7a292862fcf2d5d6d48b | 3,649,858 |
def remove_unused_colours(ip, line_colours):
"""
>>> remove_unused_colours(np.array([[0,0,3], [1,5,1], [2,0,6], [2,2,2],[4,4,0]]), {2, 4})
array([[0, 0, 0],
[0, 0, 0],
[2, 0, 0],
[2, 2, 2],
[4, 4, 0]])
"""
#get a list of all unique colours
all_colours... | 7e80cbb2e3e9ac86da4cf7d6e99a6d9bf2edeead | 3,649,859 |
def extract_info(spec):
"""Extract information from the instance SPEC."""
info = {}
info['name'] = spec.get('InstanceTypeId')
info['cpu'] = spec.get('CpuCoreCount')
info['memory'] = spec.get('MemorySize')
info['nic_count'] = spec.get('EniQuantity')
info['disk_quantity'] = spec.get('DiskQuan... | 7f93dcad1a8d99743a30d441dad64c2b9af08037 | 3,649,860 |
def sum_values(**d):
# doc string 예제. git commit 메시지 쓰듯이 쓰면 된다
"""dict의 values를 더한 값을 리턴
key는 뭐가 들어오던지 말던지 신경 안 쓴다.
"""
return sum_func(*d.values()) | 29b90a04760376d2b8f6844994a7341fa742f05d | 3,649,861 |
def parse_title(title):
"""Parse strings from lineageos json
:param title: format should be `code - brand phone`
"""
split_datum = title.split(' - ')
split_name = split_datum[1].split(' ')
device = split_datum[0]
brand = split_name[0]
name = ' '.join(split_name[1:])
return [brand,... | c3783ab36f4f7e021bdd5f0f781bb289ab2d458f | 3,649,862 |
def addCountersTransactions(b):
"""Step 2 : The above list with count as the last element should be
[
[1, 1, 0, 1],
[0, 0, 0, 4],
[1, 1, 1, 3]
]
converted to the following way
[
[1, 1, 0, 1, 0],
[1, 1, 1, 3, 4]
]
with cnt 1 and cnt 2 for anti-mirroring tec... | 44fb81280fc7540c796e6f8308219147993c6b7a | 3,649,863 |
import typing
import torch
def aggregate_layers(
hidden_states: dict, mode: typing.Union[str, typing.Callable]
) -> np.ndarray:
"""Input a hidden states dictionary (key = layer, value = 2D array of n_tokens x emb_dim)
Args:
hidden_states (dict): key = layer (int), value = 2D PyTorch tensor of sha... | 21c91a4c031c561b6776a604aa653c3880d69b15 | 3,649,864 |
def get_bg_stat_info(int_faces, adj_list, face_inds, face_inds_new):
"""
Out put list of faces and list of verts for each stat.
"""
stat_faces = []
stat_verts = []
for k in range(len(int_faces)):
# Check if face already exists.
if int_faces[k] != 0:
continue
... | 262130ffcb4fe474ece01ed6a63705efdaac360c | 3,649,865 |
def config_data() -> dict:
"""Dummy config data."""
return {
"rabbit_connection": {
"user": "guest",
"passwd": "guest",
"host": "localhost",
"port": 5672,
"vhost": "/",
},
"queues": {"my_queue": {"settings": {"durable": True}, "... | cbbed3baf79b5928be47d3d00c747ac6be625ae5 | 3,649,867 |
def copy_linear(net, net_old_dict):
"""
Copy linear layers stored within net_old_dict to net.
"""
net.linear.weight.data = net_old_dict["linears.0.weight"].data
net.linear.bias.data = net_old_dict["linears.0.bias"].data
return net | 8ba7f40e72b65ebef9948025b3404cbc5a660960 | 3,649,868 |
async def read_book(request: Request) -> dict:
"""Read single book."""
data = await request.json()
query = readers_books.insert().values(**data)
last_record_id = await database.execute(query)
return {"id": last_record_id} | e2ec15df60e2e8a5974c16688a9e5caa8c4452d8 | 3,649,869 |
def setup_dev():
"""Runs the set-up needed for local development."""
return setup_general() | 889153114ffecd74c50530e867a03128279fc26f | 3,649,870 |
def countAllAnnotationLines(
mpqa_dir="mpqa_dataprocessing\\database.mpqa.cleaned", doclist_filename='doclist.2.0'
):
"""
It counts all annotation lines available in all documents of a corpus.
:return: an integer
"""
m2d = mpqa2_to_dict(mpqa_dir=mpqa_dir)
mpqadict = m2d.corpus_to_dict(doclis... | 2a1c981db125db163e072eb495144be2b004a096 | 3,649,871 |
def convergence(report: Report, **kwargs):
"""
Function that displays the convergence using a antco.report.Report object.
Parameters
----------
report: antco.report.Report
antco.report.Report instance returned by the antco.run() function.
**kwargs
figsize: tuple, default=(8, 5)... | 523e64b68d88d705f22a5c31faecee51e5e59b2d | 3,649,872 |
def ca_set_container_policies(h_session, h_container, policies):
"""
Set multiple container policies.
:param int h_session: Session handle
:param h_container: target container handle
:param policies: dict of policy ID ints and value ints
:return: result code
"""
h_sess = CK_SESSION_HAND... | b4c56108d137d8caa6fa65f6ffcfd8c649af1840 | 3,649,874 |
def extend(arr, num=1, log=True, append=False):
"""Extend the given array by extraplation.
Arguments
---------
arr <flt>[N] : array to extend
num <int> : number of points to add (on each side, if ``both``)
log <bool> : extrapolate in log-space
append <bool> :... | e5f8b7fea74b1a92dba19aed527be1c823c058f9 | 3,649,876 |
def do_associate_favorite(parser, token):
"""
@object - object to return the favorite count for
"""
try:
tag, node, user = token.split_contents()
except ValueError:
raise template.TemplateSyntaxError, "%r tag requires one argument" % token.contents.split()[0]
return AssociateFa... | 90ed604936a0b7639adf356911a803ae755a9653 | 3,649,878 |
from typing import Type
from pydantic import BaseModel # noqa: E0611
from typing import Tuple
from typing import List
def parse_cookie(cookie: Type[BaseModel]) -> Tuple[List[Parameter], dict]:
"""Parse cookie model"""
schema = get_schema(cookie)
parameters = []
components_schemas = dict()
propert... | 797c876676b1e002b4e54a7943f77301ed82efb1 | 3,649,879 |
def bdev_nvme_add_error_injection(client, name, opc, cmd_type, do_not_submit, timeout_in_us,
err_count, sct, sc):
"""Add error injection
Args:
name: Name of the operating NVMe controller
opc: Opcode of the NVMe command
cmd_type: Type of NVMe command. Va... | 3833256e71f47a49eef2643bf8c244308795a0b1 | 3,649,880 |
def tetheredYN(L0, KxStar, Rtot, Kav, fully=True):
""" Compare tethered (bispecific) vs monovalent """
if fully:
return polyc(L0, KxStar, Rtot, [[1, 1]], [1.0], Kav)[2][0] / \
polyfc(L0 * 2, KxStar, 1, Rtot, [0.5, 0.5], Kav)[0]
else:
return polyc(L0, KxStar, Rtot, [[1, 1]], [1.0... | a8a4be3c7b217164d690eed29eb8ab1acca45e05 | 3,649,881 |
def valid_payload(request):
"""
Fixture that yields valid data payload values.
"""
return request.param | 0c02e52a02b9089e4832ccf2e9c37fc2d355e893 | 3,649,882 |
def prune_deg_one_nodes(sampled_graph):
""" prune out degree one nodes from graph """
deg_one_nodes = []
for v in sampled_graph.nodes():
if sampled_graph.degree(v) == 1:
deg_one_nodes.append(v)
for v in deg_one_nodes:
sampled_graph.remove_node(v)
return sampled_graph | c4df72a66c6fb57d5d42a1b877a846338f32f42a | 3,649,885 |
def reduce_clauses(clauses):
"""
Reduce a clause set by eliminating redundant clauses
"""
used = []
unexplored = clauses
while unexplored:
cl, unexplored = unexplored[0], unexplored[1:]
if not subsume(used, cl) and not subsume(unexplored,cl):
used.append(cl)
return ... | d28fc08f214a04aac433827560251143204fa290 | 3,649,886 |
import numpy as np
def get_np_io(arr, **kwargs) -> BytesIO:
"""Get the numpy object as bytes.
:param arr: Array-like
:param kwargs: Additional kwargs to pass to :func:`numpy.save`.
:return: A bytes object that can be used as a file.
"""
bio = BytesIO()
np.save(bio, arr, **kwargs)
bio... | 278a452dc97d8ca74398771bd34545c7505c191f | 3,649,888 |
from typing import Mapping
def get_deep_attr(obj, keys):
""" Helper for DeepKey"""
cur = obj
for k in keys:
if isinstance(cur, Mapping) and k in cur:
cur = cur[k]
continue
else:
try:
cur = getattr(cur, k)
continue
... | f7e3af73c2e45a5448e882136811b6898cc45e29 | 3,649,889 |
def fork_node_item_inline_editor(item, view, pos=None) -> bool:
"""Text edit support for Named items."""
@transactional
def update_text(text):
item.subject.joinSpec = text
return True
def escape():
item.subject.joinSpec = join_spec
subject = item.subject
if not subject... | 7c4b0bdbe321bab427e22440e7225539262806f2 | 3,649,890 |
def get_selfies_alphabet(smiles_list):
"""Returns a sorted list of all SELFIES tokens required to build a
SELFIES string for each molecule."""
selfies_list = list(map(sf.encoder, smiles_list))
all_selfies_symbols = sf.get_alphabet_from_selfies(selfies_list)
all_selfies_symbols.add('[nop]')
self... | f18206e0c4c03ab75db3efd693655a1a1cacb9e2 | 3,649,891 |
import datasets
import random
def get_face_angular_dataloader(dataset_path, input_size, batch_size, num_workers, train_portion=1):
""" Prepare dataset for training and evaluating pipeline
Args:
dataset_path (str)
input_size (int)
batch_size (int)
num_workers (int)
trai... | 5aa6d62c98ca942e79bbfaca192b11353a0a2fe1 | 3,649,892 |
def compile_sql_numericize(element, compiler, **kw):
"""
Turn common number formatting into a number. use metric abbreviations, remove stuff like $, etc.
"""
arg, = list(element.clauses)
def sql_only_numeric(text):
# Returns substring of numeric values only (-, ., numbers, scientific notati... | ef8631e98cd74b276ad00731c75a5c1c907eb303 | 3,649,893 |
def run_sgd(model, epochs):
"""
Runs SGD for a predefined number of epochs and saves the resulting model.
"""
print("Training full network")
weights_rand_init = model.optimize(epochs=epochs)
# weights_rand_init = model.optimize(epochs=epochs, batch_size=55000, learning_rate=0.1)
print("M... | 14c6fd1ffa8aab3a783b5738093d69771d036411 | 3,649,894 |
def get_all_outcome_links_for_context_courses(request_ctx, course_id, outcome_style=None, outcome_group_style=None, per_page=None, **request_kwargs):
"""
:param request_ctx: The request context
:type request_ctx: :class:RequestContext
:param course_id: (required) ID
:type course_id:... | 78026eff6aef5a486d920a888d4dfdabc94bfc00 | 3,649,895 |
def GetContentResourceSpec():
"""Gets Content resource spec."""
return concepts.ResourceSpec(
'dataplex.projects.locations.lakes.content',
resource_name='content',
projectsId=concepts.DEFAULT_PROJECT_ATTRIBUTE_CONFIG,
locationsId=LocationAttributeConfig(),
lakesId=LakeAttributeConfig()... | 434cb149fdeff6154928a4514d1f6241d44c85a7 | 3,649,896 |
from typing import Optional
def softplus(
x: oneflow._oneflow_internal.BlobDesc, name: Optional[str] = None
) -> oneflow._oneflow_internal.BlobDesc:
"""This operator computes the softplus value of Blob.
The equation is:
.. math::
out = log(e^x+1)
Args:
x (oneflow._oneflow_inter... | 2bef1db640e0e5b3e9971b1d9b4fbe23e4eba808 | 3,649,897 |
from typing import Tuple
from typing import List
def diff_gcs_directories(
base_directory_url: str, target_directory_url: str
) -> Tuple[List[str], List[str], List[str]]:
"""
Compare objects under different GCS prefixes.
:param base_directory_url: URL for base directory
:param target_directory_ur... | 1e7727fb352d320c79de16d6efdd6f46120e89d7 | 3,649,898 |
from typing import List
def load_compatible_apps(file_name: str) -> List[Product]:
"""Loads from file and from github and merges results"""
local_list = load_installable_apps_from_file(file_name)
try:
github_list = load_compatible_apps_from_github()
except (URLError, IOError):
github_... | efbde4a2c2f4589bc73497017d89631e0333081c | 3,649,899 |
import gettext
def delete(page_id):
"""Delete a page."""
page = _get_page(page_id)
page_name = page.name
site_id = page.site_id
success, event = page_service.delete_page(page.id, initiator_id=g.user.id)
if not success:
flash_error(
gettext('Page "%(name)s" could not be d... | 9c858d19b27f42e71d6aa19ae636e282925f0492 | 3,649,900 |
def drift_var():
"""
Concept drift:
1. n_drifts
2. concept_sigmoid_spacing (None for sudden)
3. incremental [True] or gradual [False]
4. recurring [True] or non-recurring [False]
"""
return [(10, None, False, False), (10, 5, False, False), (10, 5, True, False)] | 34f2c55f928a16cca8c52307853ab32f56ecd954 | 3,649,901 |
def get_generators(matrix):
"""
Given a matrix in H-rep, gets the v-rep
Turns out, the code is the same as get_inequalities,
since lrs determines the directions based on the input.
Left like this for readability.
"""
return get_inequalities(matrix) | ab5c2059544842d5010cae1211acc7da9e021994 | 3,649,902 |
def num_instances(diff, flag=False):
"""returns the number of times the mother and daughter have
pallindromic ages in their lives, given the difference in age.
If flag==True, prints the details."""
daughter = 0
count = 0
while True:
mother = daughter + diff
if are_reversed(daught... | 84d39159c594b25aabfc9efceef0d13ebc15a817 | 3,649,903 |
import inspect
def get_dipy_workflows(module):
"""Search for DIPY workflow class.
Parameters
----------
module : object
module object
Returns
-------
l_wkflw : list of tuple
This a list of tuple containing 2 elements:
Worflow name, Workflow class obj
Examples... | a119d6defd6c741777c3fa2f1add6bc700357dbd | 3,649,904 |
def azel_fit(coo_ref, coo_meas, nsamp=2000, ntune=2000, target_accept=0.95, random_seed=8675309):
"""
Fit full az/el pointing model using PyMC3. The terms are analogous to those used by TPOINT(tm). This fit includes
the eight normal terms used in `~pytelpoint.transform.azel` with additional terms, az_sigma ... | 22c3989049933b55643d11bfb2aebeb4c629ed60 | 3,649,905 |
def geojson_to_labels(geojson_dict, crs_transformer, extent=None):
"""Convert GeoJSON to ObjectDetectionLabels object.
If extent is provided, filter out the boxes that lie "more than a little
bit" outside the extent.
Args:
geojson_dict: dict in GeoJSON format
crs_transformer: used to c... | d8e0ed7034796235c6311d47eb234bfd0f38e68a | 3,649,907 |
def processed_transcript(df):
"""
Cleans the Transcript table by splitting value fileds and replacing nan values, drop extra columns
PARAMETERS:
transcript dataframe
RETURNS:
Cleaned transcript dataframe
"""
#expand the dictionary to coulmns (reward, amount, offre... | 452668d6d9616ca382f7968e0ac4dd52658be9f6 | 3,649,908 |
import six
def _TestSuiteName(dash_json_dict):
"""Extracts a test suite name from Dashboard JSON.
The dashboard JSON may contain a field "test_suite_name". If this is not
present or it is None, the dashboard will fall back to using "benchmark_name"
in the "chart_data" dict.
"""
name = None
if dash_json... | 1b2e6cbd820bde3b24be5cca107e49ea2dabc732 | 3,649,909 |
def clean_data(list_in):
"""
Inputs:
list_in - filtered list of ticket orders
Outputs:
Return list of tuples, each tuple contains
(last name, first name, note,[tickets])
"""
notes_list = []
data_out = []
for row in list_in:
trimmed_row = row[row.index('Purcha... | f2cdf17895d1661e40b64f3fcc9ff92558f53bdd | 3,649,911 |
def adfuller(
vdf,
column: str,
ts: str,
by: list = [],
p: int = 1,
with_trend: bool = False,
regresults: bool = False,
):
"""
---------------------------------------------------------------------------
Augmented Dickey Fuller test (Time Series stationarity).
Parameters
----------
vdf: ... | 8f78b2128c981af15a84ac94f54435da4aee0c6c | 3,649,912 |
from typing import Union
from typing import List
from typing import Dict
from typing import Optional
def get_routes_bend180(
ports: Union[List[Port], Dict[str, Port]],
bend: ComponentOrFactory = bend_euler,
cross_section: CrossSectionFactory = strip,
bend_port1: Optional[str] = None,
bend_port2: O... | f5ec1539a04c0c9eee9184d190e265af4e187ef0 | 3,649,913 |
import json
def list_datasets(github_repo="Ouranosinc/xclim-testdata", branch="main"):
"""Return a DataFrame listing all xclim test datasets available on the GitHub repo for the given branch.
The result includes the filepath, as passed to `open_dataset`, the file size (in KB) and the html url to the file.
... | 199c56efcb105d9ff043f2a7c1ef51857a8b9b77 | 3,649,914 |
import json
def embed_terms(args, classes, dest, use_cache=True, path_to_json='ebd_cache.json'):
"""
Embeds class strings into word representations.
:param args
:param classes: (list of str) topic classes
:param dest: (str) path to destination file
:param path_to_json: (str) path to json file... | 8521b4828907c0083492b0d03848aeeb452d17e6 | 3,649,916 |
from pathlib import Path
def wf_paths(reachable):
"""
Construct all well-formed paths satisfying a given condition.
The condition is as follows: all the paths have height equal to
the ceiling of log_2(`reachable` + 1). `reachable` is interpreted
as a bitfield, with 1 meaning that the correspondin... | 86b0a2e6408a8257e201f21058459aea4aceac00 | 3,649,917 |
def get_imagemodel_in_rar(rar_path, mode):
""" 압축파일(rar_path)의 이미지파일의 name, width, height를 모아서 반환한다."""
image_models = []
with rarfile.RarFile(rar_path) as rf:
for name in rf.namelist():
if is_hidden_or_trash(name):
continue
if is_extensions_allow_image(name)... | ea94406e17b66bbbf0288b8f0cb03cdd723a2d63 | 3,649,918 |
from re import L
def run_single(i,threshold_area_fraction,death_to_birth_rate_ratio,domain_size_multiplier,return_history=False):
"""run a single voronoi tessellation model simulation"""
rates = (DEATH_RATE,DEATH_RATE/death_to_birth_rate_ratio)
rand = np.random.RandomState()
history = lib.run_simulati... | b4ef11ae873f69b472a2c41c2f5d33e88ed1169a | 3,649,919 |
def matrixmult (A, B):
"""Matrix multiplication function
This function returns the product of a matrix multiplication given two matrices.
Let the dimension of the matrix A be: m by n,
let the dimension of the matrix B be: p by q,
multiplication will only possible if n = p,
thus creating a matr... | 98065981c8047d927bacb07877dbf173ba379159 | 3,649,920 |
def TorsLattice(data = None, *args, **kwargs):
"""
Construct a lattice of torsion classes from various forms of input data
This raises an error if the constructed lattice is not semidistributive,
since the lattice of torsion classes is semidistributive.
INPUT:
- ``data``, ``*args``, ``**kwarg... | e07cfef58b2927b8e3c660ee20cc0c6bc365fa4b | 3,649,921 |
def get_accumulated_report(trigger_id, mission='fermi'):
"""
Return the last value for each keyword on the summary page for a given trigger_id
:param trigger_id:
:param mission: 'fermi' or 'swift'
:return:
"""
if 'fermi' in mission:
site = fermi_grb_site
elif 'swift' in mission:
... | de77dc845a48d6572b2ff9229eed57e7fd55b38c | 3,649,922 |
import torch
def sample(model, x, steps, temperature=1.0, sample=False, top_k=None):
"""
take a conditioning sequence of indices in x (of shape (b,t)) and predict the next token in
the sequence, feeding the predictions back into the model each time. Clearly the sampling
has quadratic complexity unlike... | c63ab2c001b7c88568d12d836da65abb368a8f31 | 3,649,923 |
def get_numbers(number, size, *, fg=DEFAULT_FGCHARACTER, bg=DEFAULT_BGCHARACTER):
"""Creates a shape of numbers.
Positional arguments:
number - number to print.
size - size of the shape.
Keyword arguments:
fg - foreground character.
bg - background character.
... | 1cc992796f7118cbc0b19938ece0f87ed146a0d2 | 3,649,924 |
def to_cmyk(r: int, g: int, b: int) -> _cmyk:
"""
Takes RGB values 0->255 and returns their values
in the CMYK namespace.
https://www.rapidtables.com/convert/color/rgb-to-cmyk.html
"""
r, g, b = to_float(r, g, b)
k = 1 - max(r, g, b)
c = (1 - r - k) / (1 - k)
m = (1 - g - k) / (1 -... | 804f12c944ba0c0a740ca94c3e622b061db57dc5 | 3,649,926 |
def GetHostsInClusters(datacenter, clusterNames=[], connectionState=None):
"""
Return list of host objects from given cluster names.
@param datacenter: datacenter object
@type datacenter: Vim.Datacenter
@param clusterNames: cluster name list
@type clusterNames: string[]
@param connectionSta... | c9722212e239eaec930da34dac2b5c82d45178fe | 3,649,927 |
def get_gfa_targets(tiles, gfafile, faintlim=99, gaiadr="dr2"):
"""Returns a list of tables of GFA targets on each tile
Args:
tiles: table with columns TILEID, RA, DEC; or Tiles object
targets: table of targets with columsn RA, DEC
gaiadr: string, must be either "dr2" or "edr3" (d... | aa8c5a42babca87d26ad93538035734db54574f8 | 3,649,928 |
from typing import Tuple
from typing import Union
def fit_size(
img: IMG,
size: Tuple[int, int],
mode: FitSizeMode = FitSizeMode.INCLUDE,
direction: FitSizeDir = FitSizeDir.CENTER,
bg_color: Union[str, float, Tuple[float, ...]] = (255, 255, 255, 0),
) -> IMG:
"""
调整图片到指定的大小,超出部分裁剪,不足部分设为指定... | 6cc33cb8c3fff4edec3bf15978f8cedc056a5e0c | 3,649,930 |
import winreg
def supports_colour():
"""
Return True if the running system's terminal supports colour,
and False otherwise.
Adapted from https://github.com/django/django/blob/master/django/core/management/color.py
"""
def vt_codes_enabled_in_windows_registry():
"""
Check the W... | d567b7818c314d345a30f10dffd99c7a3b411c3e | 3,649,932 |
def next_code(value: int, mul: int = 252533, div: int = 33554393) -> int:
"""
Returns the value of the next code given the value of the current code
The first code is `20151125`.
After that, each code is generated by taking the previous one, multiplying it by `252533`,
and then keeping the remainder... | a9e5183e405574cc56a138a244f14de08ea68d00 | 3,649,933 |
def read_csv_to_lol(full_path, sep=";"):
"""
Read csv file into lists of list.
Make sure to have a empty line at the bottom
"""
with open(full_path, 'r') as ff:
# read from CSV
data = ff.readlines()
# New line at the end of each line is removed
data = [i.replace("\n", "") for... | e53c46c6a8eabaece788111530fbf859dd23133f | 3,649,935 |
def read_experiment(path):
"""
Discovers CSV files an experiment produced and construct columns
for the experiment's conditions from the sub-directory structure.
Args:
path: path to the experiment's results.
Returns:
pd.DataFrame
"""
objects = list(path.rglob('*.csv'))
... | e9797fb71a0e9ba89e211fd0d079d5040e3a4639 | 3,649,936 |
from bs4 import BeautifulSoup
def single_keyword_search(keyword):
"""
구글에 keyword 검색결과를 html로 받아온뒤에 그 안에 일반 게시물 분류에 속하는
class='r' 부분만 모아서 return해주는 함수 입니다.
Args:
Keyword (String) : 구글에 검색할 Keyword
Returns:
title_list (bs4.element.ResultSet) : 구글 검색에서 확인된 일반게시물(class='r')들의 모... | 45909878da1c135c4dc6b1209c98ffc5e7e21b29 | 3,649,937 |
def partial_list(ys, xs, specified_shapes=None):
"""
Args:
ys: A list of tensors. Each tensor will be differentiated with the partial_nd
xs: A Tensor to be used for differentiation, or a list of tensors to be used for differentiation with the smae length as ys
specified_shapes: A list of... | 24b0d2583f21cd4497e1c38d79643e44eaab693e | 3,649,938 |
def _GuessBrowserName(bisect_bot):
"""Returns a browser name string for Telemetry to use."""
default = 'release'
browser_map = namespaced_stored_object.Get(_BOT_BROWSER_MAP_KEY)
if not browser_map:
return default
for bot_name_prefix, browser_name in browser_map:
if bisect_bot.startswith(bot_name_prefi... | b6b0fedd238aff07bfa46c61e9d792087b647a13 | 3,649,939 |
from re import T
import functools
import collections
def compile_train_function(network, batch_size, learning_rate):
"""Compiles the training function.
Args:
network: The network instance.
batch_size: The training batch size.
learning_rate: The learning rate.
Returns:
The upda... | 57778a2428d4348f6594d04ec35bc821a4fd8122 | 3,649,940 |
def filter_values(freq, values, nthOct: int = 3):
"""
Filters the given values into nthOct bands.
Parameters
----------
freq : ndarray
Array containing the frequency axis.
values : ndarray
Array containing the magnitude values to be filtered.
nthOct : int, optional
F... | 2a1b270049f1c2869fa03d7bc2a4f64658646b7a | 3,649,942 |
def create_project(request):
"""View to create new project"""
user = request.user
if user.is_annotator:
error = ErrorMessage(header="Access denied", message="Only admin and managers can create projects")
return render(request, 'error.html', {'error':error})
if request.method == "POST":
... | 34d6def496c9ddac99710425a9550be7fa8eba58 | 3,649,943 |
from typing import Optional
import pathlib
def limit(
observed_CLs: np.ndarray,
expected_CLs: np.ndarray,
poi_values: np.ndarray,
figure_path: Optional[pathlib.Path] = None,
close_figure: bool = False,
) -> mpl.figure.Figure:
"""Draws observed and expected CLs values as function of the paramet... | 85bf753844083dcfbea8273cabe6cf7c0513c6d9 | 3,649,944 |
def make_predictions(clf_object,predictors_str,data_source):
"""make_predictions comes up with predictions
from given input data
Input:
clf_object
object
constructed classification model
predictors_str
nd str array
stri... | ed5f29e65ddf3d7f7081b89e6f747925de944567 | 3,649,946 |
def get_token_annualized(address, days):
"""Return annualized returns for a specific token.
Args:
days [int]: Days ago for which to display annualized returns.
address [str]: Ethereum token address.
Return:
dict: Annualized returns for a specified token.
key [str]: Day... | 734b64fdce65d069eebd5fd62270b24fd2d27100 | 3,649,948 |
import random
import string
def generate_random_string(N):
"""
Generate a random string
Parameters
-------------
N
length of the string
Returns
-------------
random_string
Random string
"""
return ''.join(random.choice(string.ascii_uppercase + string.digits) f... | 3e2e672140e18546260a0882fa6cf06073bdf8e7 | 3,649,949 |
import re
def extract_charm_name_from_url(charm_url):
"""Extract the charm name from the charm url.
E.g. Extract 'heat' from local:bionic/heat-12
:param charm_url: Name of model to query.
:type charm_url: str
:returns: Charm name
:rtype: str
"""
charm_name = re.sub(r'-[0-9]+$', '', c... | 9905d6b5c7a2f5047bc939d1b6e23d128ee8984d | 3,649,950 |
def class_name(service_name: str) -> str:
"""Map service name to .pyi class name."""
return f"Service_{service_name}" | b4bed8a677f9eedfcd66d6d37078075b0967ea20 | 3,649,951 |
def interesting_columns(df):
"""Returns non-constant column names of a dataframe."""
return sorted(set(df.columns) - set(constant_columns(df))) | 84e548e806bcfd9031d620d3c02f942f60fa53cc | 3,649,952 |
def liberty_str(s):
"""
>>> liberty_str("hello")
'"hello"'
>>> liberty_str('he"llo')
Traceback (most recent call last):
...
ValueError: '"' is not allow in the string: 'he"llo'
>>> liberty_str(1.0)
'"1.0000000000"'
>>> liberty_str(1)
'"1.0000000000"'
>>> liberty_... | 2bc56be42a062668f94c9cc88baa94f5f73feaa3 | 3,649,953 |
import warnings
def is_valid_dm(D, tol=0.0, throw=False, name="D", warning=False):
"""
Return True if input array is a valid distance matrix.
Distance matrices must be 2-dimensional numpy arrays.
They must have a zero-diagonal, and they must be symmetric.
Parameters
----------
D : ndarra... | e21163a5d68fa5cf1c2e0bbed34276c7e5a6b851 | 3,649,954 |
from types import SimpleNamespace
import scipy
def solve_gradwavefront(data, excludeself=False, predict_at=None,
fix_covar=False, **kw):
"""Find turbulent contributions to measured fiber positions.
Assumes that the turbulent contributions can be modeled as the
gradient of a wavefr... | 94733f5cf073aa44752fa395fe24f66fc9524049 | 3,649,955 |
from typing import Any
def str_to_py(value: str):
"""Convert an string value to a native python type."""
rv: Any
if is_boolean_state(value):
rv = get_boolean(value)
elif is_integer(value):
rv = get_integer(value)
elif is_float(value):
rv = get_float(value)
else:
... | b0a5d0fbe573be6d9d961ac5c3c1895fd82539eb | 3,649,956 |
from typing import Dict
from typing import Any
from typing import Tuple
import json
import requests
def action(request: Dict[str, Any]) -> Tuple[str, int]:
"""Triggered from Slack action via an HTTPS endpoint.
Args:
request (dict): Request payload.
"""
if request.method != 'POST':
ret... | fdf24beee3e5dc929f575883114987419967b2e9 | 3,649,957 |
def inmemory():
"""Returns an xodb database backed by an in-memory xapian
database. Does not support spelling correction.
"""
return open(xapian.inmemory_open(), spelling=False, inmem=True) | ed67dd9bd7d70c5aab33c963dfed4e2103f5cfd1 | 3,649,958 |
def all(iterable: object) -> bool:
"""all."""
for element in iterable:
if not element:
return False
return True | 130a93230538122f35e29a6ec4ad5fca0efd835b | 3,649,959 |
def ind2slice(Is):
"""Convert boolean and integer index arrays to slices.
Integer and boolean arrays are converted to slices that span the selected elements, but may include additional
elements. If possible, the slices are stepped.
Arguments
---------
Is : tuple
tuple of indices (slice... | 6be6a82750f9f73b2008c528ff192b07b8e0a784 | 3,649,960 |
import re
def select_devices(devices):
""" 选择设备 """
device_count = len(devices)
print("Device list:")
print("0) All devices")
for i, d in enumerate(devices, start=1):
print("%d) %s\t%s" % (i, d['serial'], d['model']))
print("q) Exit this operation")
selected = input("\nselect: ")
... | 91c405c8a198deb01e8abecc592ac2286dc712fd | 3,649,962 |
def Fill( h ):
"""fill every empty value in histogram with
previous value.
"""
new_h = []
x,v = h[0]
if type(v) == ListType or type(v) == TupleType:
l = len(v)
previous_v = [0] * l
else:
previous_v = 0
for x, v in h:
if type(v) == ListType or t... | 429a4d723c38692e8ee0ebaea2fda1ec008cded6 | 3,649,963 |
from re import L
def pendulum(theta, S, mg, drag) -> ps.Composition:
"""Draw a free body animation of a pendulum.
params:
theta: the angle from the vertical at which the pendulum is.
S: the force exerted toward the pivot.
mg: the force owing to gravity.
drag: the force acting ... | 9dd7918b00bae82600d4bb064461f7b6e58e9fb2 | 3,649,964 |
def get_items():
"""Fetches items from `INITIAL_OFFSET` in batches of `PAGINATION_OFFSET` until there are no
more """
offset = INITIAL_OFFSET
items = []
while True:
batch = get_page_of_items(JSON_ENDPOINT.format(offset))
if not batch:
break
items.extend(batch)
... | b0950ee8eb291cceb1f0871e918b5aff26b6c2ab | 3,649,965 |
def tcombinations_with_replacement(iterable, r):
"""
>>> tcombinations_with_replacement('ABCD', 0)
((),)
>>> tcombinations_with_replacement('ABCD', 1)
(('A',), ('B',), ('C',), ('D',))
>>> tcombinations_with_replacement('ABCD', 2)
(('A', 'A'), ('A', 'B'), ('A', 'C'), ('A', 'D'), ('B', 'B'), (... | 432c826751bcfc1aa7bfef36cd25a198e6fe7b72 | 3,649,966 |
import random
def random_organism(invalid_data):
"""
Generate Random Organism
return: string containing "organism" name from CanCOGeN vocabulary.
"""
return random.choice(covid19_vocab_dict.get('organism')), global_valid_data | 9319d04ddf874c43d84489c2b20c52cee334a8c1 | 3,649,968 |
def comput_mean_ndcg(df, k):
"""
Input:rating_info
(usr_id, movie_id, rating)
output: 平均ndcg
对每一种人 得到他真实分数和预测分数的dataframe
然后得到values
"""
#df.insert(df.shape[1], 'pred', pred)
#print(df.groupby('user_id'))
piece = dict(list(df.groupby('user_id')))
ndcg_list = []
f... | 70bcb630b7df9940a76499f34a769bd2dca90283 | 3,649,970 |
from typing import List
def to_im_list(IMs: List[str]):
"""Converts a list of string to IM Objects"""
return [IM.from_str(im) for im in IMs] | 9694500ae2f5fa7c203100a5a1756fe71af862cc | 3,649,971 |
def ref_ellipsoid(refell, UNITS='MKS'):
"""
Computes parameters for a reference ellipsoid
Arguments
---------
refell: reference ellipsoid name
Keyword arguments
-----------------
UNITS: output units
MKS: meters, kilograms, seconds
CGS: centimeters, grams, seconds
""... | 8f5032af1375d758445ed139bc4a2d6989f15dc5 | 3,649,972 |
def is_number(s):
"""
Check if it is a number.
Args:
s: The variable that needs to be checked.
Returns:
bool: True if float, False otherwise.
"""
try:
float(s)
return True
except ValueError:
return False | 071aeac26a5a907caf1764dc20d7de1c6408714b | 3,649,973 |
import itertools
def combineSets(listOfSets):
"""
Combines sets of strings by taking the cross product of the sets and \
concatenating the elements in the resulting tuples
:param listOfSets: 2-D list of strings
:returns: a list of strings
"""
totalCrossProduct = ['']
for i in ... | 26a383d224716fd8f4cf8589607e2df1ccb82a7e | 3,649,975 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.