content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import Tuple
def should_commit(kwargs: Kwargs) -> Tuple[bool, Kwargs]:
"""Function for if a schema class should create a document on instance."""
return kwargs.pop('create') if 'create' in kwargs else True, kwargs | 3e554d661b069e71da86dc8f3d43e754236a9037 | 24,200 |
from typing import Dict
import os
import collections
def create_view_files_widget(ws_names2id: Dict[str, str], ws_paths: Dict[str, WorkspacePaths], output):
"""Create an ipywidget UI to view HTML snapshots and their associated comment files."""
workspace_chooser = widgets.Dropdown(
options=ws_names2id,
... | 115eba9c894010b461e0a654ba239bc7c8157bb1 | 24,201 |
def _get_frame_time(time_steps):
""" Compute average frame time.
:param time_steps: 1D array with cumulative frame times.
:type time_steps: numpy.ndarray
:return: The average length of each frame in seconds.
:rtype: float
"""
if len(time_steps.shape) != 1:
raise ValueError("ERRO... | e849e5d6bcbc14af357365b3e7f98f1c50d93ee4 | 24,202 |
import random
def next_symbol_to_learn(ls):
"""Returns the next symbol to learn. This always returns characters from the
training set, within those, gives higher probability to symbols the user
doesn't know very well yet. `ls` is the learn state. Returns a tuple like
("V", "...-")
"""
total = ... | d4b574a6f841ee3f2e1ce4be9f67a508ed6fb2de | 24,203 |
def query_table3(song):
"""
This function returns the SQL neccessary to get all users who listened to the song name passed as an argument to this function.
"""
return "select user_name from WHERE_SONG where song_name = '{}';".format(song) | ed9a3fb7eb369c17027871e28b02600b78d483a9 | 24,204 |
import sys
import os
def create_background(
bg_type,
fafile,
outfile,
genome="hg18",
size=200,
nr_times=10,
custom_background=None,
):
"""Create background of a specific type.
Parameters
----------
bg_type : str
Name of background type.
fafile : str
Na... | 4babaf0eb6ed2f7e600fc7db7a8f8a4ee3b59d3b | 24,205 |
def train_test_data(x_,y_,z_,i):
"""
Takes in x,y and z arrays, and a array with random indesies iself.
returns learning arrays for x, y and z with (N-len(i)) dimetions
and test data with length (len(i))
"""
x_learn=np.delete(x_,i)
y_learn=np.delete(y_,i)
z_learn=np.delete(z_,i)
x_test=np.take(x_,i)
y_test=np... | 7430e9ea2c96356e9144d1689af03f50b36895c6 | 24,206 |
def construct_Tba(leads, tleads, Tba_=None):
"""
Constructs many-body tunneling amplitude matrix Tba from single particle
tunneling amplitudes.
Parameters
----------
leads : LeadsTunneling
LeadsTunneling object.
tleads : dict
Dictionary containing single particle tunneling a... | 83c582535435564b8132d3bd9216690c127ccb79 | 24,207 |
def inplace_update_i(tensor_BxL, updates_B, i):
"""Inplace update a tensor. B: batch_size, L: tensor length."""
batch_size = tensor_BxL.shape[0]
indices_Bx2 = tf.stack([
tf.range(batch_size, dtype=tf.int64),
tf.fill([batch_size], tf.cast(i, tf.int64))
],
axis=-1)
return tf... | 61cb7e8a030debf6ff26154d153de674645c23fe | 24,208 |
from zipfile import ZipFile
from bert import tokenization
import tarfile
import sentencepiece as spm
from .texts._text_functions import SentencePieceTokenizer
import os
def bert(model = 'base', validate = True):
"""
Load bert model.
Parameters
----------
model : str, optional (default='base')
... | c35de9c8d65c356dc00029ba527aacf0c844218e | 24,209 |
import matplotlib.pyplot as plt
def surface(
x_grid, y_grid, z_grid,
cmap="Blues", angle=(25, 300), alpha=1.,
fontsize=14, labelpad=10,
title="", x_label="", y_label="", z_label="log-likelihood"):
"""
Creates 3d contour plot given a grid for each axis.
Arguments:
``x_gr... | 5c7b1933e451978e9dab5006126663e7f44ef6dc | 24,210 |
async def record_trade_volume() -> RecordTradeVolumeResponse:
"""
This api exists for demonstration purposes so you don't have to wait until the job runs again to pick up new data
"""
await deps.currency_trade_service.update_trade_volumes()
return RecordTradeVolumeResponse(success=True) | 2921353360c71e85d7d5d64f6aed505e5f9a66b9 | 24,211 |
import os
def dataload_preprocessing(data_path, dataset, long_sent=800):
"""
:param data_path: base directory
:param dataset: select dataset {'20news', 'mr', 'trec', 'mpqa'}
:param long_sent: if dataset has long sentences, set to be constant length value
:return: seq_length, num_classes, vocab_si... | cb3462f5ec731a631de2a6f1a70aa6d7e32f79c9 | 24,212 |
def logged_in():
"""
Method called by Strava (redirect) that includes parameters.
- state
- code
- error
"""
error = request.args.get('error')
state = request.args.get('state')
if error:
return render_template('login_error.html',
error=error,
... | 71a2590f2f2fbcc67e73a2afb9180a5974d98252 | 24,213 |
def unit_string_to_cgs(string: str) -> float:
"""
Convert a unit string to cgs.
Parameters
----------
string
The string to convert.
Returns
-------
float
The value in cgs.
"""
# distance
if string.lower() == 'au':
return constants.au
# mass
... | 32b16bf6a9c08ee09a57670c82da05655cb3fd16 | 24,214 |
import os
import stat
def _make_passphrase(length=None, save=False, file=None):
"""Create a passphrase and write it to a file that only the user can read.
This is not very secure, and should not be relied upon for actual key
passphrases.
:param int length: The length in bytes of the string to genera... | c802e74d367a9aa09bac6776637fe846e6d8b3b6 | 24,215 |
from operator import mul
def Mul(x, x_shape, y, y_shape, data_format=None):
"""mul"""
if data_format:
x_new = broadcast_by_format(x, x_shape, data_format[0], y_shape)
y_new = broadcast_by_format(y, y_shape, data_format[1], x_shape)
else:
x_new = x
y_new = y
return mul.... | b6bf343e8a3ceb5fe5a0dc8c7bd96b34ecb7ab2f | 24,216 |
import logging
def new_authentication_challenge(usr: User) -> str:
"""
Initiates an authentication challenge. The challenge proceeds as follows:
1. A user (:class:`sni.user`) asks to start a challenge by calling
this method.
2. This methods returns a UUID, and the user has 60 seconds to chang... | d0c27b211aadc94556dc285a1588ff908338b950 | 24,217 |
def create_channel(application_key):
"""Create a channel.
Args:
application_key: A key to identify this channel on the server side.
Returns:
A string id that the client can use to connect to the channel.
Raises:
InvalidChannelTimeoutError: if the specified timeout is invalid.
Other errors ret... | 8b54ac3204af4dbeaf603e788aa0b41829f4807b | 24,218 |
def generate_new_admin_class():
"""
we need to generate a new dashboard view for each `setup_admin` call.
"""
class MockDashboard(DashboardView):
pass
class MockAdmin(Admin):
dashboard_class = MockDashboard
return MockAdmin | 7f691e8f294bf6d678cb8f1ce59b4f12ca77c866 | 24,219 |
def for_default_graph(*args, **kwargs):
"""Creates a bookkeeper for the default graph.
Args:
*args: Arguments to pass into Bookkeeper's constructor.
**kwargs: Arguments to pass into Bookkeeper's constructor.
Returns:
A new Bookkeeper.
Raises:
ValueError: If args or kwargs are provided and the B... | 649f2c33c5cdedf4d08c2ac991c0d1a044c50fe4 | 24,220 |
def check_paragraph(index: int, line: str, lines: list) -> bool:
"""Return True if line specified is a paragraph
"""
if index == 0:
return bool(line != "")
elif line != "" and lines[index - 1] == "":
return True
return False | b5737a905b32b07c0a53263255d3c581a8593dfa | 24,221 |
import tqdm
import os
def most_similar(train_path, test_path, images_path, results_path, cuda=False):
"""
Nearest Neighbor Baseline: Img2Vec library (https://github.com/christiansafka/img2vec/) is used to obtain
image embeddings, extracted from ResNet-18. For each test image the cosine similarity with all... | 348064308bb942d9c762b2ebd4a29f8b22e5fe8a | 24,222 |
from fnmatch import fnmatchcase
import os
def find_packages(where='.', exclude=()):
"""Return a list all Python packages found within directory 'where'
'where' should be supplied as a "cross-platform" (i.e. URL-style) path; it
will be converted to the appropriate local path syntax. 'exclude' is a
se... | f8c7ea3641506fb013bcb90fe8ffd186f737dc89 | 24,223 |
import logging
def mask(node2sequence, edge2overlap, masking: str = "none"):
"""If any of the soft mask or hard mask are activated, mask
:param dict exon_dict: Dict of the shape exon_id: sequence.
:param dict overlap_dict: Dict of the shape (exon1, exon2): overlap between them.
:param str masking: Ty... | 5f10491773b4b60a844813c06a6ac9e810162daa | 24,224 |
import os
def load_patch_for_test_one_subj(file_path, sub_i, patch_shape, over_lap=10,
modalities=['MR_DWI', 'MR_Flair', 'MR_T1', 'MR_T2'],
mask_sym='MR_MASK',
suffix='.nii.gz',
use_norm... | 901e449da0d3defa13c5b5d401775d7d217d78e7 | 24,225 |
def extract_el_from_group(group, el):
"""Extract an element group from a group.
:param group: list
:param el: element to be extracted
:return: group without the extracted element, the extracted element
"""
extracted_group = [x for x in group if x != el]
return [extracted_group] + [[el]] | ed6598fd0d7dcb01b35a5c2d58c78d8c2a2397f5 | 24,226 |
def example_function_with_shape(a, b):
"""
Example function for unit checks
"""
result = a * b
return result | 33403e6f67d4d6b18c92b56996e5e6ed21f6b3ad | 24,227 |
from typing import Mapping
from typing import Any
def fields(
builder: DataclassBuilder, *, required: bool = True, optional: bool = True
) -> "Mapping[str, Field[Any]]":
"""Get a dictionary of the given :class:`DataclassBuilder`'s fields.
.. note::
This is not a method of :class:`DataclassBuilde... | 47b3bd86076ac14f9cca2f24fedf665370c5668f | 24,228 |
from typing import Dict
from typing import List
def gemm(node: NodeWrapper,
params: Dict[str, np.ndarray],
xmap: Dict[str, XLayer]) -> List[XLayer]:
"""
ONNX Gemm to XLayer Dense (+ Scale) (+ BiasAdd) conversion function
Compute Y = alpha * A' * B' + beta * C
See https://github.com/... | dbc257c98fa4e4a9fdb14f27e97132d77978f0c2 | 24,229 |
from datetime import datetime
def check_response(game_id, response):
"""Check for correct response"""
if response["result"]["@c"] == "ultshared.rpc.UltSwitchServerException":
game = Game.query.filter(Game.game_id == game_id).first()
if "newHostName" in response["result"]:
print("n... | a5de41170d13022393c15d30816cc3c51f813f36 | 24,230 |
from sys import path
import zipfile
def extract_to_dst(src, dst):
"""extract addon src zip file to destination."""
copied_items = []
zip_file = path.basename(src)
zip_name, _ = path.splitext(zip_file)
cache_path = path.join(root_path, 'cache', zip_name)
with zipfile.ZipFile(src, 'r') as z:
... | 1ddaa1fd2c1697f166dfdceb58490c9ceb963b73 | 24,231 |
def get_signal_handler():
"""Get the singleton signal handler"""
if not len(_signal_handler_):
construct_signal_handler()
return _signal_handler_[-1] | bd74ddb1df0c316d4e62e21259e80c0213177aeb | 24,232 |
def post_rule(team_id):
"""Add a new rule.
.. :quickref: POST; Add a new rule.
**Example request**:
.. sourcecode:: http
POST /v1/teams/66859c4a-3e0a-4968-a5a4-4c3b8662acb7/rules HTTP/1.1
Host: example.com
Accept: application/json
{
"name": "Servers",
"descri... | 687873cb4398877afb6ed444263f4990039a9f6d | 24,233 |
def intents(interface):
"""
Method to get an object that implements interface by just returning intents
for each method call.
:param interface: The interface for which to create a provider.
:returns: A class with method names equal to the method names of the
interface. Each method on this ... | 4e514424721ba2fc2cf4261cc856f6984d3781de | 24,234 |
def model(X, Y, learning_rate=0.3, num_iterations=30000, print_cost=True, is_plot=True, lambd=0, keep_prob=1):
"""
实现一个三层的神经网络:LINEAR ->RELU -> LINEAR -> RELU -> LINEAR -> SIGMOID
参数:
X - 输入的数据,维度为(2, 要训练/测试的数量)
Y - 标签,【0(蓝色) | 1(红色)】,维度为(1,对应的是输入的数据的标签)
learning_rate - 学习速率
... | 39130fffd282a8f23f29a8967fe0e15386817ed1 | 24,235 |
from collections import OrderedDict
from urllib.request import urlretrieve
from urllib import urlretrieve
import scipy.ndimage as nd
def load_phoenix_stars(logg_list=PHOENIX_LOGG, teff_list=PHOENIX_TEFF, zmet_list=PHOENIX_ZMET, add_carbon_star=True, file='bt-settl_t400-7000_g4.5.fits'):
"""
Load Phoenix stell... | 39807e591acf1a7338a7e36f5cd50ffffa1ff66b | 24,236 |
def write_ini(locStr_ini_file_path, locStr_ini):
"""
.. _write_ini :
Write the given string into the given INI file path.
Parameters
----------
locStr_ini_file_path : str
The file full path of the INI file. If the extension ".ini" is not included,
it would be adde... | 1376f50fa9d91c797cbaccc4066c379e0c085aea | 24,237 |
def create_form(data, form_idx=0):
""" Creates PDB structure forms.
form_idx = 0 is apo; 1 - holo1; and 2 - holo2
Note: Only works for homodimers.
"""
# Make a deep copy of BioPandas object to make changes
data_out = deepcopy(data)
# If form_idx == 2 that's holo2 already
if ... | 45058e1770519a51677c47a7b78d1b1c2ca2c554 | 24,238 |
from typing import Dict
import logging
def get_verbosity(parsed_arguments: Dict) -> int:
"""
Gets the verbosity level from parsed arguments.
Assumes parameter is being parsed similarly to:
```
parser.add_argument(f"-{verbosity_parser_configuration[VERBOSE_PARAMETER_KEY]}", action="count", def... | b0bf38c8883335f76000a29dcdefe46eccc5040a | 24,239 |
def update_versions_in_library_versions_kt(group_id, artifact_id, old_version):
"""Updates the versions in the LibrarVersions.kt file.
This will take the old_version and increment it to find the appropriate
new version.
Args:
group_id: group_id of the existing library
artifact_id: arti... | 0f579f10c6e675330f332b1fe0d790e25448d23f | 24,240 |
def GetIdpCertificateAuthorityDataFlag():
"""Anthos auth token idp-certificate-authority-data flag, specifies the PEM-encoded certificate authority certificate for OIDC provider."""
return base.Argument(
'--idp-certificate-authority-data',
required=False,
help='PEM-encoded certificate authority ce... | 99fa02a0998a1c5e58baa8b334561d715ca4421a | 24,241 |
def MapBasinKeysToJunctions(DataDirectory,FilenamePrefix):
"""
Function to write a dict of basin keys vs junctions
Args:
DataDirectory (str): the data directory
fname_prefix (str): the name of the DEM
Returns:
A dictionary with the basin key as the key and the junction as the v... | adb206e711373c07ac28e477cf8dbf842af33d91 | 24,242 |
def password_renew(_name: str, old_password: str, new_password: str):
"""パスワード変更"""
old_dat = old_password
new_dat = new_password
new_hs = sha256(new_dat.encode()).hexdigest() # sha256で暗号化
old_hs = sha256(old_dat.encode()).hexdigest() # sha256で暗号化
if User.select().where(User.name != _name):
... | c8ecc0d905b190535e3770838eeec37159dea95b | 24,243 |
from typing import Callable
from typing import List
from typing import Tuple
from typing import Dict
import requests
def fetch_abs(compare_res_fn: Callable[[res_arg_dict], List[BadResult]], paper_id: str) -> Tuple[Dict, List[BadResult]]:
"""Fetch an abs page."""
ng_url = ng_abs_base_url + paper_id
legacy_... | a7e239b06213684cda34935956bf1ad1ec29ea6e | 24,244 |
def is_happy(number:int) -> bool:
"""Returns a bool that states wether a number is happy or not"""
results = []
result = thing(number)
results.append(result)
while results.count(result) < 2: # Checking if a number has shown up in the list of previous results again as that is
result = ... | 80a96325c28c346b2b23b5c6fb67c9cc62d0477c | 24,245 |
def self_play(n_iterations=10, ben_steps=1000, training_steps=int(1e4),
n_eval_episodes=100, **kwargs):
"""
Returns an agent that learns from playing against himself from random to
optimal play.
"""
agents = [RLAgent(**kwargs), RandomAgent()]
for _ in range(n_iterations):
benchmark(agents[... | b38d593c53ecc528a3932fe8eba2091fdcd68067 | 24,246 |
import json
import base64
import time
def auth(event, context):
"""
Return the plain text session key used to encrypt the CAN Data File
event dictionary input elements:
- CAN Conditioner Serial Number
- Encrypted data
Prerequisites:
The CAN Conditioner must be provisioned with a se... | a040fa68b0c1a65c5f0ca25ac4a58326796598ce | 24,247 |
def xpro_aws_settings(aws_settings):
"""Default xPRO test settings"""
aws_settings.XPRO_LEARNING_COURSE_BUCKET_NAME = (
"test-xpro-bucket"
) # impossible bucket name
return aws_settings | 72a7bd4a6ba40b19a6fda530db2bf67b0e4e5fc2 | 24,248 |
def function_check(arg, result):
"""arg ↝ result : return"""
if result == TypeBuiltin():
return TypeBuiltin()
if arg == KindBuiltin() and result == KindBuiltin():
return KindBuiltin()
if arg == SortBuiltin() and result in (KindBuiltin(), SortBuiltin()):
return SortBuiltin()
r... | 23840d8c2fba48803d7acc9b32b68ab0903d1d57 | 24,249 |
def test_parameter_1_1():
"""
Feature: Check the names of parameters and the names of inputs of construct.
Description: If the name of the input of construct is same as the parameters, add suffix to the name of the input.
Expectation: No exception.
"""
class ParamNet(Cell):
def __init__(... | f5d5be6f1403884192c303f2a8060b95fd3e9fca | 24,250 |
def frule_edit(request, frule_id):
""" FM模块编辑应用包下载规则 """
try:
frule = FRule.objects.filter(id=frule_id).first()
if not frule:
response = '<script>alert("Rule id not exist!");'
response += 'location.href=document.referrer;</script>'
return HttpResponse(response... | 1d5d83aaeff5483905e28f428719a6ce0b7833bc | 24,251 |
from typing import Tuple
def load_preprocess_data(days_for_validation: int,
lag_variables: list,
random_validation: bool = False,
seed: int = None,
lag: int = 8,
reload: bool = True,
... | 7238841e8f5e32be5ecb15ab5811720b41e8ad63 | 24,252 |
def extract_sha256_hash(hash):
"""Extrach SHA256 hash or return None
"""
prefix = 'sha256:'
if hash and hash.startswith(prefix):
return hash.replace(prefix, '')
return None | 11e9f352f3783657d52772c4b69387151d13f3d2 | 24,253 |
def logout():
"""User logout"""
global bandwidth_object, qos_object
bandwidth_object = {}
qos_object = {}
success_login_form = None
return redirect(url_for('base_blueprint.login')) | d3ec08fe6e8e0ca70f2f81b11878750efa101781 | 24,254 |
from typing import OrderedDict
def draft_intro():
"""
Controller for presenting draft versions of document introductions.
"""
response.files.append(URL('static/js/codemirror/lib', 'codemirror.js'))
response.files.append(URL('static/js/codemirror/lib', 'codemirror.css'))
response.files.append(U... | 1ae932af2a9b89a35efbe0b1da91e26fe66f6403 | 24,255 |
import pathlib
def collect_shape_data(gtfs_dir):
"""Calculate the number of times a shape (line on a map) is travelled.
Appends some additional information about the route that the shape belongs to.
Args:
gtfs_dir: the directory where the GTFS file is extracted
Returns:
pandas.DataFr... | 0fa16cc889696f01b25b4eb60ded423968b6aa20 | 24,256 |
def lick():
"""
Returns a string when a user says 'lick' (This is a joke command)
:return: A string
"""
return "*licks ice cream cone*" | a4e92d7371abe078c48196b0f7d7e899b1b0e19e | 24,257 |
def from_dict(obj, node_name='root'):
"""Converts a simple dictionary into an XML document.
Example:
.. code-block:: python
data = {
'test': {
'nodes': {
'node': [
'Testing',
'Another node'
... | 3308fb85baea5c145f4acd22fb49a70458f4cc51 | 24,258 |
def parse_ascii(state: str, size: int) -> str:
"""
Args:
state: an ascii picture of a cube
size: the size of the cube
Returns:
a string of the cube state in ULFRBD order
"""
U = []
L = []
F = []
R = []
B = []
D = []
lines = []
for line in state.s... | 7ec24a22c3052a76c820dcca54c913c2d5229e5d | 24,259 |
def _get_build_failure_reasons(build):
# type: (Build) -> List[str]
"""Return the names of all the FailureReasons associated with a build.
Args:
build (Build): The build to return reasons for.
Returns:
list: A sorted list of the distinct FailureReason.reason values associated with
... | 7f446ff96f93443a59293e36f4d071d79218f24d | 24,260 |
import re
def parse_line(line: str):
"""
Parses single record from a log according to log_pattern.
If error occurs in parsing request_time, the log line is considered broken and function returns None.
If error occurs in parsing URL, while request_time is present,
the URL is marked as 'parse_fa... | 1d747d22b28019f030c982455bfc89ea03e8631f | 24,261 |
def for_all_arglocs(*args):
"""
for_all_arglocs(vv, vloc, size, off=0) -> int
Compress larger argloc types and initiate the aloc visitor.
@param vv (C++: aloc_visitor_t &)
@param vloc (C++: argloc_t &)
@param size (C++: int)
@param off (C++: int)
"""
return _ida_typeinf.for_all_arglocs(*args... | 9cc568f16d64f8a1bb206a08a73cdb4c3b6adcc4 | 24,262 |
def fetch_project_check_perm(id, user, perm):
"""Fetches a project by id and check the permission.
Fetches a project by id and check whether the user has certain permission.
Args:
project_id:
The id of the project.
user:
A User instance.
perm:
... | dcf7271ebe171f77748eebdc61b2c74039da0690 | 24,263 |
def toRoman(n):
""" Convert an integer to Roman numeral."""
if not (0 < n < 5000):
raise OutOfRangeError("number out of range (must be 1..4999)")
if int(n) != n:
raise NotIntegerError("decimals can not be converted")
result = ""
for numeral, integer in romanNumeralMap:
while... | 275cd966e6dda8adfbde16ffc9ba0f6a4928ad3e | 24,264 |
import matplotlib.pyplot as plt
def imsave(addr,im):
"""
input a string of save address, an im array\n
save the image to the address
"""
return plt.imsave(addr,im) | 0931ec70c1258827a9d65f4c5b7d2ba9aa2e6a99 | 24,265 |
import multiprocessing
def simulate_one(ticket: Ticket, strategy: Strategy, trials: int) -> float:
"""
:param ticket:
:return:
"""
diagnostics = False
workers = multiprocessing.cpu_count()
things = [(strategy, ticket) for x in range(0, trials)]
chunksize = int(len(things) / workers)
... | cba86eaabc1b25681cf8b4e9d4c3134c186d5d43 | 24,266 |
def download_prostate():
"""Download prostate dataset."""
return _download_and_read('prostate.img') | a65174dd85491d259c94b9df31c739b62a9e50be | 24,267 |
import json
import random
import hashlib
def decBIPKey(encrypted_privK, passphrase, currency):
"""
Decrypt an encrypted Private key
Show the corresponding public address
"""
#using the currencies.json file, get the currency data
with open('currencies.json', 'r') as dataFile:
currencies = json.load(dataFile)
... | 743a87753463ca269ff6a120024813a5e61445ac | 24,268 |
def plot_data(coordinate, box=[], plt_inst=None, **kwargs):
"""
Plot the coordinate with the "std box" around the curve
Args:
coordinate (float[]): 1D array of the coordinate to plot
box (float[]): 1D array of the box around the curve
plt_inst (pyplot): pyplot in... | 4c549425f076217cb8b0302a49137bc8e85b661a | 24,269 |
import os
import yaml
import json
def read_config_file(config_file):
"""Read an YAML config file
:param config_file: [description]
:type config_file: [type]
"""
if os.path.isfile(config_file):
extension = os.path.splitext(config_file)[1]
try:
with open(config_file) as ... | e8c7d09d0d303be100d67adfe36f39766eb325af | 24,270 |
def param_curve(t, R, r, d):
"""Coordinates of a hypotrochoid for parameters t, R, r and d"""
x = (R - r)*cos(t) + d*cos((R - r)/r*t)
y = (R - r)*sin(t) - d*sin((R - r)/r*t)
z = 3*sin(t)
return x, y, z | dd60c3aada02e589d50566910bbc63b6b67c40d8 | 24,271 |
from core.models import Snapshot, ArchiveResult
from typing import Optional
from typing import Iterable
from pathlib import Path
import os
from datetime import datetime
def archive_link(link: Link, overwrite: bool=False, methods: Optional[Iterable[str]]=None, out_dir: Optional[Path]=None) -> Link:
"""download the... | c45216d61b4a4fae8dec6a7829959211cb829813 | 24,272 |
import inspect
import os
def get_tests_dir(append_path=None):
"""
Args:
append_path: optional path to append to the tests dir path
Return:
The full path to the `tests` dir, so that the tests can be invoked from anywhere.
Optionally `append_path` is joined after the `tests` dir the... | b7af8440b1835e862550b88ea781093b6cea54a6 | 24,273 |
def create_collection(metadata_url: str = METADATA_URL,
thumbnail_url: str = THUMBNAIL_URL) -> pystac.Collection:
"""Create a STAC Collection using AAFC Land Use metadata
Args:
metadata_url (str, optional): Metadata json provided by AAFC
Returns:
pystac.Collection: py... | 97fa19b32b6b9556ad1a117a248721027cac1db0 | 24,274 |
def calculate_average_crossing_per_month_and_measure(num_of_months, list_with_agg_values):
"""Calculates the average crossings per month and per measure.
Args:
num_of_months: the number of months based on the
frequency of each measure, saved as
a dict or a ... | 750d1b944a4f8723a4f39fc2f92b42f1011ea9c7 | 24,275 |
import re
import os
def scan_album_folder(folder, file_list):
"""
Renames all files in a folder. If all the files in the folder have the same Year and Album
metadata, the folder itself will be renamed to the format "[YEAR] ALBUM"
"""
folder_data = []
folder_counts = {'found': 0, 'renamed': 0,
... | a679a1de082a994c75b8afea925851e537426a12 | 24,276 |
from typing import List
from typing import Optional
from typing import Dict
def predict_with_inferer(
images: Tensor, network, keys: List[str], inferer: Optional[SlidingWindowInferer] = None
) -> Dict[str, List[Tensor]]:
"""
Predict network dict output with an inferer. Compared with directly output networ... | 2184c5f681bcf13787b59a036d0f4572a391a852 | 24,277 |
import re
def split_data(line):
"""
method splits varibles on line
"""
data = list()
arr = np.array([string for string in line.split(", ")], dtype=str)
for _, item in enumerate(arr):
word_parse = re.compile(r''' ((?<=:.)-*[0-9]+\.*[0-9]*)''', re.X)
parts = word_parse.findall(... | 8fcab989a6220ddccf653552b5e9eaf98bd83277 | 24,278 |
def show_outcome_group_global(request_ctx, id, **request_kwargs):
"""
:param request_ctx: The request context
:type request_ctx: :class:RequestContext
:param id: (required) ID
:type id: string
:return: Show an outcome group
:rtype: requests.Response (with OutcomeGrou... | 0e8d8c9411e3bc6d7cdbdede38cca65878dccb65 | 24,279 |
import hashlib
def md5sum(file: str) -> str:
"""
Create a strings with the md5 of a given file
:param file: filename of the file whose md5 is computed for
:return: md5 string
"""
md5_hash = hashlib.md5()
with open(file, "rb") as file:
content = file.read()
md5_hash.update(con... | 0ec81688aa298e73a064034760cdd1687b2561a4 | 24,280 |
def read_data(filetype, filename, prn):
"""Calls the appropriate position reader function based on the filetype."""
func_name = filetype + '_data'
possibles = globals().copy()
possibles.update(locals())
func = possibles.get(func_name)
if func is None:
raise NotImplementedError(func + ' i... | 91949a7cc1573a44ebb504b3a5542ff289b2100a | 24,281 |
from typing import List
from typing import Tuple
def processContours(contours: List[float], contourpoints: List[List[float]], frame: pims.frame.Frame, debug=False) -> Tuple[List[List[float]], pims.frame.Frame]:
"""Get bounding boxes for each contour.
Parameters
----------
contours : List[float]
... | 95bf52e0377b6df8b1d80cc0bc0a1bb8979c359b | 24,282 |
def simulate_games(num_games, switch, num_doors=3):
"""
Simulate a multiple game of the Monty Hall problem.
Parameters:
- num_games: Integer, the number of games you want to simulate.
- switch: Boolean, whether or not your strategy is to switch doors
after the reveal.
... | 0296375eb5f57f1b5e9580086f08150774a30956 | 24,283 |
from typing import Iterable
import functools
import operator
def prod(iterable:Iterable) -> Iterable:
"""math.prod support for Python versions < v3.8"""
return functools.reduce(operator.mul, iterable, 1) | be811e39b7dd70669fbfc84db5492b4c7383d68f | 24,284 |
import subprocess
def compress_video(video_path):
"""
Compress video.
:param video_path: Path to the video.
:return: None.
"""
return subprocess.call(["gzip", video_path]) == 0 | 9159076bae502da7c863dc6ef16372a6e2da4161 | 24,285 |
def trim_resource(resource):
"""
trim_resource
"""
return resource.strip(" \t\n\r/") | 5a9d9bbf6da72cf967eee1e9198d109f096e3e41 | 24,286 |
import requests
def wikipedia_request_page_from_geocoding(flatitude, flongitude):
""" Get list of wikipedia page identifiers related to the specified geocode """
places_list = []
loc = "{}|{}".format(flatitude, flongitude)
print(loc)
parameters = {
"action": "query",
"list": "ge... | b61ea747c40f132d312e03c6d3b649e35f53430c | 24,287 |
def globalBinarise(logger, img, thresh, maxval):
"""
This function takes in a numpy array image and
returns a corresponding mask that is a global
binarisation on it based on a given threshold
and maxval. Any elements in the array that is
greater than or equals to the given threshold
will be... | d16bcc8a78a62b5ec945c6e0ff245a10402d22f1 | 24,288 |
import os
import logging
def connect_to_db(schema='sys', database='', return_df=True):
"""Query database and fetch table data.
Args:
schema (str): MySQL table schema. Default to 'sys'.
database (str): MySQL table name. Deafult to ''.
return_df (bool): Condition to return the dataframe... | cb0f6ab06a9fcd05bfb2ca8b19859ca72a6072c2 | 24,289 |
def times_by_stencil(results):
"""Collects times of multiple results by stencils.
Args:
results: List of `Result` objects.
Returns:
A tuple of lists (stencils, times).
"""
stencils = results[0].stencils
if any(stencils != r.stencils for r in results):
raise ValueError('... | a304924f6f82e6611c9469a21f92592f67d7c84d | 24,290 |
def get_bulk_and_slab(bulk, miller=[1,1,1], layers=4, vacuum=16):
"""Create a slab and conventional bulk cell from a bulk cell input
Parameters
----------
bulk : pymatgen structure
pymatgen structure of the bulk material
miller : list
list of miller indices
layers : int
... | 4a914dfba1ee4efea747464036b868a07311cb9d | 24,291 |
def gogogo_figure(ipympl, figsize, ax=None):
"""
gogogo the greatest function name of all
"""
if ax is None:
if ipympl:
with ioff:
fig = figure(figsize=figsize)
ax = fig.gca()
else:
fig = figure(figsize=figsize)
ax = fig... | 750b75b669f233b833cd575cbf450de44b0ad910 | 24,292 |
from re import L
def unzip6(xs):
"""
unzip6 :: [(a, b, c, d, e, f)] -> ([a], [b], [c], [d], [e], [f])
The unzip6 function takes a list of six-tuples and returns six lists,
analogous to unzip.
"""
a = L[(i[0] for i in xs)]
b = L[(i[1] for i in xs)]
c = L[(i[2] for i in xs)]
d = L[(... | 04ac4aae355b82f1709479296239e4d197224975 | 24,293 |
import re
def grep(lines=None,expr=None,index=False):
"""
Similar to the standard unit "grep" but run on a list of strings.
Returns a list of the matching lines unless index=True is set,
then it returns the indices.
Parameters
----------
lines : list
The list of string lines to ... | aefbf15ba94e8ac2ceced3ed3958abb7e4a70163 | 24,294 |
from bs4 import BeautifulSoup
from typing import Dict
def get_table_map_from_text(sp: BeautifulSoup, keep_table_contents=True) -> Dict:
"""
Generate table dict only
:param sp:
:param keep_table_contents:
:return:
"""
table_map = dict()
for flt in sp.find_all('float'):
try:
... | 686cad1a219e53a4d5548bf55e5696da94bd7170 | 24,295 |
import os
def tag_copier(path, cliargs):
"""This is the tag copier worker function.
It gets a path from the Queue and searches index for the
same path and copies any existing tags (from index2)
Updates index's doc's tag and tag_custom fields.
"""
doclist = []
# doc search (matching path)... | 832a2acbb260835d278940efadd8b1f778baf821 | 24,296 |
def grainfromVertices(R=None,fname='shape.txt',mixed=False,eqv_rad=10.,rot=0.,radians=True,min_res=4):
"""
This function generates a mesh0 from a text file containing a list of its vertices
in normalised coordinates over a square grid of dimensions 1 x 1. Centre = (0,0)
coordinates must be of the form:
... | 12333a4be631dc8fe8646677d8830646b8563624 | 24,297 |
def get_block(blockidx, blocksz, obj):
"""
Given obj, a list, return the intersection of
obj[blockidx*blocksz:(blockidx+1)*blocksz] and obj
Ex: get_block(2, 100, range(250) returns [200, 201, ..., 249]
"""
if blockidx*blocksz > len(obj):
return []
elif (blockidx+1)*blocksz > len(obj... | 8666cc30be23619a49f899beec17d3ba1f0fb357 | 24,298 |
import warnings
def RDS(net,waves,coupons,p,size,seeds,posseed,poswave):
"""Conducts respondent-driven sampling
Input:
net: network, networkx graph
waves: maximum number of waves, integer (use 0 with poswave=True for contract tracing)
coupons: number of coupons per respon... | 5480a85e9f160f988cff384306a90913a6eac905 | 24,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.