content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import itertools
def euler38():
"""Solution for problem 38."""
# '123456789' will be decomposed in at least two elements,
# the smallest being 4 at most characters long
sol = 0
digits = {str(d) for d in range(1, 10)}
for n in range(10000):
s = ""
for i in itertools.count(1):
... | c757460b10b07379dd372a6a7b40b1536e16d407 | 49,400 |
def builtin_swap(a, b):
"""Modify the stack: ( a b -- b a )."""
return (b, a) | a288f5484d45edb64513ffd0afcab6d03609faf6 | 49,401 |
from typing import Union
from typing import Tuple
import re
def package_version(split: bool = False) -> Union[str, Tuple[str, str]]: # pragma: no cover
"""Get current package version.
Args:
split: Flag indicating whether to return the package version as a
single string or split into a tup... | 2d9e9a719c9a25053f78aa35b362875aaa166a60 | 49,402 |
import codecs
def _add_method(class_re, method_name, file_name=None):
"""
Loads a file ./ocrd_page_user_methods/{{ method_name }}.py and defines a MethodSpec applying to class_re
"""
source = []
if not file_name:
file_name = method_name
with codecs.open(join(dirname(__file__), 'ocrd_pa... | e66b07b98e32fd1db6b6e843ae28111e37de1e66 | 49,403 |
from operator import le
def makeServoSpeedPacket(ID, maxSpeed):
"""
Run servo between 0.0 to 1.0, where 1.0 is 100% (full) speed.
"""
if 0.0 > maxSpeed > 1.0:
raise Exception('makeServoSpeed: max speed is a percentage (0.0-1.0)')
speed = int(maxSpeed*1023)
pkt = makeWritePacket(ID, xl320.XL320_GOAL_VELOCITY, ... | 58f22a26711f17a993c0223b0e979981cbebfba6 | 49,404 |
from typing import Union
from typing import List
def rotate_translate(vertices: np.ndarray, translation: Union[np.array, List[float]], angle: Union[float, int])\
-> np.ndarray:
"""
First rotates the list of vertices around the origin and then translates the list of vertices.
:param vertices: arra... | 7fc98a491491fc366d8bd0350705d9275d5722e7 | 49,405 |
def check_set_dimension():
"""
Validate a SetDimension and return all errors and warnings.
:returns: A list of 'errors' and a list of 'warnings'
"""
return list(), list() | df27e2bac845ce1dad24c3c01388c397210a238d | 49,406 |
def slater(name):
"""In quantum chemistry, Slater's rules provide numerical values for the
effective nuclear charge concept. In a many-electron atom, each electron is
said to experience less than the actual nuclear charge owing to shielding
or screening by the other electrons.
Parameters
------... | 886fc109c9baa3dda66a3a2cb981c701fc03e211 | 49,407 |
from typing import List
from typing import Tuple
import math
def reidentify_by_pokeblink(rng:Xorshift, rawintervals:List[float], search_max=3*10**4, search_min=0, eps=0.1, dt = 0.01)->Tuple[Xorshift, float, float]:
"""Reidentify Xorshift state via intervals of Pokemon blinks
Args:
rng (Xorshift): _d... | 371ccdd57dfcaff10f4a3e2010d9a4cddc3df80e | 49,408 |
from pathlib import Path
from typing import Any
def read_gNB(
*,
db: Session = Depends(deps.get_db),
gNB_id: str = Path(..., description="The gNB id of the gNB you want to retrieve"),
current_user: models.User = Depends(deps.get_current_active_user),
) -> Any:
"""
Get gNB by ID.
"""
gN... | dc48b6fe47e1ef3f4f45aa84d938625a727e78fd | 49,409 |
import json
import sys
def __api_operation_prep(log, arguments):
"""
API Operation Common Functionality
"""
# Parse the user data
example_user_config_json = """
{
'user': <username>,
'username': <username>,
'user_name': <username>,
'user_id': <userid>
't... | f5093017c95f4c89d684dcf1c29064963889eaef | 49,410 |
from sys import path
def get_powGen(solar_cf_file, wind_cf_file):
""" Retrieve all necessary information from powGen netCDF files: RE capacity factors and corresponding lat/lons
Capacity factors are in matrix of shape(lats, lon, 8760 hrs) for 1 year
...
Args
----------
`solar_cf_fi... | cc19bbeae1e9a4e5811736e98a61b4ae2442bbcd | 49,411 |
import torch
def make_batch(points: [np.ndarray], sdfs: [np.ndarray], number_sample: int) -> {str: torch.Tensor}:
"""Make two list of points and sdfs on to GPU.
Args:
points: The list of the points.
sdfs: The list of the signed distance fields.
number_sample: The number points to be s... | d744043febec24e8fe3d27d175424d619269bf8f | 49,412 |
def h5File(path, mode='r'):
""" open a HSDS domain or HDF5 file based on the path.
if path starts with "hdf5://", use HSDS, otherwise
use h5py on a regular file path """
if path.startswith("hdf5://"):
f = h5pyd.File(path, mode=mode)
else:
f = h5py.File(path, mode=mode)
re... | 95e00515aa7a2155500d3003c8428ff052ef976a | 49,413 |
def _build_galaxy_loc_line(env, dbkey, file_path, config, prefix, tool_name):
"""Prepare genome information to write to a Galaxy *.loc config file.
"""
if tool_name:
str_parts = []
tool_conf = _get_tool_conf(env, tool_name)
loc_cols = LocCols(config, dbkey, file_path)
# Compo... | e4c80543611326650510e563ded66201f51674d5 | 49,414 |
def norx_failure():
"""
Failed ```norx```.
"""
message = request.args.get('m')
response = make_response(
render_template(
"norx.html",
success=False,
message=message
)
)
response.headers.set('Irbox-Success', 'false')
... | c2fd0937543dfab4a72f7f61b76a43fd2d8b3ec6 | 49,415 |
def full(shape, fill_value, dtype=None):
"""Main code for operation full.
Arguments:
shape: a tuple of integers
fill_value: a scalar value
dtype: either a string (e.g. 'int32')
or a numpy dtype (e.g. np.int32)
Returns:
an array
"""
if dtype is None:
... | 40e5936340c60b7ef850ebe8e69d6ed682bbbb21 | 49,416 |
def pil_to_numpy(pil_image: PILImage.Image) -> np.ndarray:
"""
Convert a Pillow image to a Numpy array.
Parameters
----------
pil_image : PILImage
Pillow image to convert
Returns
-------
image
Array representation of Pillow image.
"""
return np.asarray(pil_image... | 6bbb86b18c7d5d00381cc86fc182ae692ab678a7 | 49,417 |
def search_sequence_numpy(arr, seq):
"""Find sequence positions within array.
Parameters
----------
arr : int array, shape (n_tokens_arr)
Token array, where n_tokens_arr is the number of tokens in the array.
seq : int array, shape (n_tokens_seq)
oken sequence to be located within t... | cb47b7660daae87e6ca6e5753b034b5f527ad439 | 49,418 |
import torch
def gradcam_distillation(gradients_a, gradients_b, activations_a, activations_b, factor=1):
"""Distillation loss between gradcam-generated attentions of two models.
References:
* Dhar et al.
Learning without Memorizing
CVPR 2019
:param base_logits: [description]
... | e52125991fefc7414174a3d602c001069e51c0bb | 49,419 |
def fixture_duthosts(enhance_inventory, ansible_adhoc, tbinfo, request):
"""
@summary: fixture to get DUT hosts defined in testbed.
@param ansible_adhoc: Fixture provided by the pytest-ansible package.
Source of the various device objects. It is
mandatory argument for the class constructors.... | c302a473254d69892868c293c6659bb3257e8616 | 49,420 |
def generateReactions(database, reactants, products=None, only_families=None):
"""
Generate the reactions (and associated kinetics) for a given set of
`reactants` and an optional set of `products`. A list of reactions is
returned, with a reaction for each matching kinetics entry in any part of
the d... | 2d082f08d0372c2640a0d3ce82eea0d0e7177013 | 49,421 |
import torch
def create_runs(args, elements, n_runs, num_classes, classe=None, sample=None, sample_is_support=True, elements_per_class=[]):
"""
Define runs either randomly or by specifying one sample to insert either as a query or as a support
"""
if classe == None and sample == None:
runs = l... | 4150fd581f7d02139c4c854476b3085b57c08af3 | 49,422 |
from dateutil import tz
def nordic2Arrival(data, arrival_id):
"""
Function for converting a nordic file into a Arrival string
:param NordicData data: NordicData object to be converted
:param int arrival_id: arrival id of the assoc
:param int origin_id: origin id of the origin
:returns: arriva... | e93be2e4767fd92ca66f6b35498d6ceec8f27658 | 49,423 |
import os
def realpath(rpath):
"""Path relative to project-root -> Real path relative to project-root.
This resolves symlinks.
"""
return relpath(os.path.realpath(join(rpath))) | a52e32919e159cf1f37b14126713e238383abecd | 49,424 |
import matplotlib as mpl
def _build_discrete_cmap(cmap, levels, extend, filled):
"""
Build a discrete colormap and normalization of the data.
"""
if not filled:
# non-filled contour plots
extend = "max"
if extend == "both":
ext_n = 2
elif extend in ["min", "max"]:
... | 5b6ca935ffb5f96e37153c5f7b7bb4f5ac3df645 | 49,425 |
def _granted(provides, needs):
"""Check if user provided permissions and necessary permissions match."""
current_app.logger.debug("Provides %s and needs: %s", provides, needs)
return provides and not set(provides).isdisjoint(set(needs)) | c5343257d5258547a3cf36e0c1beaf55cb23dedb | 49,426 |
from typing import Any
def is_jsonable_array(obj: Any) -> bool:
"""Return `True` if ``obj`` is a jsonable array"""
cls = obj if isinstance(obj, type) else type(obj)
return isinstance(getattr(cls, PHERES_ATTR, None), ArrayData) | a9df3e3eda7cdf4fb67346f9e3cb868d061bb6ae | 49,427 |
import torch
def deep_Q_Learning(alpha, gamma, epsilon, episodes, max_steps, n_tests, render = False, test=False):
"""
@param alpha learning rate
@param gamma decay factor
@param epsilon for exploration
@param max_steps for max step in each episode
@param n_tests number of test episodes
"""
env = gym.make(... | 51d3e2940319d9b41f0845ba8f02483253f657cb | 49,428 |
def readFASTA(text, results=dict()):
"""
@param text in FASTA format
@param results dict where results will be put. A new dict by default.
@return dictionnary with new entry like {sequence_name: sequence_str}
@note call this function only if biopython can't be used instead
"""
string = ''
... | 15413643afdc86d14b73a07371be82c08c7cf0e4 | 49,429 |
def get_choices_from_model(model_name, only_active=True):
"""
Return the values of a model as choices to be used in the form.
Args:
model_name: (str) The name of the model inside the ``configuration`` app
only_active: (bool) If True, a filter is set to return only instances of
the... | 8b49e542fa1d326f9a102089ca660eb09499fc91 | 49,430 |
def load_dictionaries_list():
"""loading the list of credentials dictionaries"""
dictionaries_list = [f for f in listdir(config_params.CREDENTIALS_DICTIONARIES_FOLDER)
if (isfile(join(config_params.CREDENTIALS_DICTIONARIES_FOLDER, f)) and f.lower().endswith('.dic'))]
return dictionaries_... | 7af5c6cd9cc3da0af932f448483f2e4943c3ff8b | 49,431 |
def getDbLogger():
"""
This function will return the logger for CEES database queries.
"""
return getLogger(DB_LOGGER) | f364d5cd8ef9583ee42ffd6e89e814311ca7aebe | 49,432 |
import sklearn.metrics
import numpy
def calc_class_accuracy_metrics(ref_samples, pred_samples, cls_area=None, cls_names=None):
"""
A function which calculates a set of classification accuracy metrics for a set
of reference and predicted samples. Optionally, the area classified for each
class can be pr... | 10ba5c7794e8231021ad66b59c9b90d5ed7f8e3e | 49,433 |
from functools import reduce
import operator
import glob
def _files_to_copy(directory):
"""Retrieve files that should be remotely copied.
"""
with utils.chdir(directory):
image_redo_files = reduce(operator.add,
[glob.glob("*.params"),
... | dd90d694b04a2ab5e4257b0b1ea7852a1146af4f | 49,434 |
def parse(input_text, check_duplicate_keys=False):
"""Parses the input as JSON and returns its contents.
It supports Scalyr's extensions to the Json format, including comments and
binary data. Specifically, the following are allowed:
- // and /* comments
- Concatenation of string literals using ... | 94b8d2c70dc5ef47789828e3392cad1374584315 | 49,435 |
def constFactor(i, transform):
"""经过 transform 变换后的密度矩阵第 i 个对角元表达式中的常数项
"""
return np.real(
np.conj(tensorElement(transform, i, 0)) *
tensorElement(transform, i, 0)) | 131ec932d4fea9326e27da4e8217aa03134246da | 49,436 |
import torch
import math
def positional_encoding_2d(d_model, height, width, device):
"""
reference: wzlxjtu/PositionalEncoding2D
:param d_model: dimension of the model
:param height: height of the positions
:param width: width of the positions
:return: d_model*height*width position matrix
... | 3cbe2a61024500c2b75204ee1155329d58cc9875 | 49,437 |
def default_get_input_layer_fn(problem_type, feature_columns):
"""Default implementation of get_input_layer_fn."""
def _input_layer_fn(features,
is_training,
scope_name="Phoenix/Input",
lengths_feature_name=None):
with tf.compat.v1.variable_sco... | b0f9daa35320a87e96dab47a5879ba8022644122 | 49,438 |
def initiate_validator_exit(state: BeaconState,
index: ValidatorIndex) -> BeaconState:
"""
Initiate exit for the validator with the given ``index``.
Return the updated state (immutable).
"""
validator = state.validator_registry[index]
validator = validator.copy(
... | 619a477dfb1602fd67cb4230aae98d7d84613132 | 49,439 |
import time
def wait_for_test_db():
"""Pings the localstack db with describe requests
for {some time} waiting for it to come up...
"""
print('####################################')
print('Waiting for database to start.......')
print('####################################')
def try_request(... | bc157738fa9c6322740282c1f98682f98ad79560 | 49,440 |
def SHAPE_FUNCTIONS(TYPE_ELEMENT, N_NODESELEMENT, ISO_COORDINATES):
"""
This function creates the matrix of the derivatives of the shape functions
Input:
TYPE_ELEMENT | Type element in Finito algorithm | Integer
| 0 - Frame bar element ... | 37180546eb58870f47df7f60c88f12e9c7b181e3 | 49,441 |
def build_app(conf):
""" Build application with the given information
:param conf: Configuration
:return: application
"""
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = conf.SQLALCHEMY_DATABASE_URL
app.config["TESTING"] = conf.TESTING
app.config["SQLALCHEMY_TRA... | 0d2becff424c5156b5d870dbd8d976a5b33f134c | 49,442 |
def two_props_hypothesis(values1: np.ndarray,
values2: np.ndarray,
alternative: str = "two-sided") -> tuple:
"""z test for comparing two proportions
Args:
values1 (np.array): sample 1 binary(0/1) values
values2 (np.array): sample 2 binaray(0/1) ... | acd9d06efb9230b28971db90b0721ceae0107fd3 | 49,443 |
import difflib
def compare_text(text1, text2):
"""
Compare two markdown texts and return the diff as annotated HTML.
"""
d1 = _markdown(text1)
d2 = _markdown(text2)
sm = difflib.SequenceMatcher(lambda x: x == " ", d1, d2)
output = []
for opcode, a0, a1, b0, b1 in sm.get_opcodes():
... | c4dfc7391f112259b2634dbd1d3f652d0bc80fbe | 49,444 |
from typing import Dict
from typing import OrderedDict
import warnings
def share_bi123_f15_v1(s: [Dict, OrderedDict]):
"""股票15分钟123"""
v = Factors.Other.value
freq = Freq.F15.value
for f_ in [freq]:
if f_ not in s['级别列表']:
warnings.warn(f"{f_} not in {s['级别列表']},默认返回 Other")
... | 158dc7ffd742616e777400d73a7bab841abc2ed7 | 49,445 |
import subprocess
import shlex
def RunSingleCommand(command_and_env):
"""Runs a single command, and returns the return code and any info from
the run.
"""
command, env = command_and_env
try:
proc = subprocess.Popen(
shlex.split(command), stdout=subprocess.PIPE,
stde... | d5e8e9a6e4b01a8259128d9b3c79a68b6c8e0e3f | 49,446 |
def get_sample_interval(info, chan_info):
"""
Get sample interval for one channel
"""
if info['system_id'] in [1, 2, 3, 4, 5]: # Before version 5
sample_interval = (chan_info['divide'] * info['us_per_time'] *
info['time_per_adc']) * 1e-6
else:
sample_inter... | e1a397ad9221c30b70997f0cfb296305e0ca7355 | 49,447 |
def get_input_artifact_location(job):
"""
Returns the S3 location of the input artifact.
"""
input_artifact = job["data"]["inputArtifacts"][0]
input_location = input_artifact["location"]["s3Location"]
input_bucket = input_location["bucketName"]
input_key = input_location["objectKey"]
r... | 282881315313b88882f1df8019f60ae88f654cab | 49,448 |
def run_sparse_network(name, network, intersect_z_vals, intersect_pts,
intersect_ray_batch, use_random_lightdirs, **kwargs):
"""Runs a single network."""
if name.startswith('bkgd'):
intersect_light_ray_batch, intersect_raw = network_query_fn_helper_nodirs(
network=network,
... | 9cd2136e96f5a1e74d21ad81e1e5cff57aa28304 | 49,449 |
import os
def get(key):
"""get cache value"""
path = getpath(key)
if os.path.exists(path):
return open(path).read() | 6d147664420214915b03c1f6246e96657765192d | 49,450 |
import io
def _load_individual_image(f_image, downscale_size, bool_crop=False, crop_size=None):
"""
Loads an individual image into numpy array and perform resizing
:param f_image: absolute path to a single image
:param downscale_size: desired final size of the loaded images, e.g. (256, 256)
:retu... | be699ef1d2d0be54f540b15befb7c646f75e9578 | 49,451 |
def appdomconf(appdom, appname):
"""
Return domain specific application configuration
"""
conf = appdom['applications']
for sub in appname.split('.'):
conf = conf[sub]
return conf | 340f26e3611e311ef5a13e91e86cfe772b8e43b7 | 49,452 |
import os
def ForwardDirLocation(build_tool_version_name):
"""Returns location of directory for forward compatibility testing."""
return os.path.join(ThisScriptDir(), '..', 'RSTestForward',
build_tool_version_name) | 287286be2079104861e2a16589977899679e7a0a | 49,453 |
def make_fcnet_with_skips(input_, sizes, skip_conns, vocab_size, l2_penalty):
"""
Adds skip connections between layers based on the parameter `skip_conns`,
which should be a list of pairs. A connection will be added from the
output of the source layer to the output of the target layer. The outputs
will be sum... | cd8e3e90116b537c30a643a568c842f192eb016e | 49,454 |
from typing import Union
def submatrix(tensor: Union[np.ndarray, tf.Tensor], row: int, column: int) -> tf.Tensor:
""" A submatrix of a matrix is obtained by deleting any collection of rows and/or columns.
For example, from the following 3-by-3 matrix, we can construct a 2-by-2 submatrix by
removin... | 87ff9bf3effc1eeb79e41385be6735c9cd21c46f | 49,455 |
def UDS_SessionEnumerator(sock, session_range=range(0x100), reset_wait=1.5):
""" Enumerates session ID's in given range
and returns list of UDS()/UDS_DSC() packets
with valid session types
Args:
sock: socket where packets are sent
session_range: range for session ID's
re... | d4b561e3fcd01ea42735948d56e885418c7b9e20 | 49,456 |
def remove_gap_traces(st):
"""Searches for gaps in seismic data and removes affected traces from
stream.
Parameters
----------
st : Stream
Obspy object containing seismic traces read from disk.
Returns
-------
st : Stream
Obspy object containing seismic traces read from... | 10bd08a664f929d648e2a8063cf8bda87ad96283 | 49,457 |
import requests
import urllib
import json
def get_turbot_vpc_subnets(turbot_api_access_key, turbot_api_secret_key, turbot_host_certificate_verification, turbot_host, turbot_account, api_version):
""" Gets the current turbot vpc configuration for an account
:return: Returns the current turbot VPC configuratio... | 8fb4f7a66486a976ad371bf7d71d9c9d33fe5167 | 49,458 |
import os
def read_query(query_filename):
"""
Read a query from file and return as a string
Parameters
----------
query_filename: str name of the query. It will be looked for in the queries folder of this project
Returns
-------
query: str the query with placeholders for the query par... | 65981ba85363d6bd1ae7be9062b978f5e8cfcfeb | 49,459 |
def hanoi(n, a, b, c):
"""
>>> hanoi(5, "a", "b", "c")
[('a', 'b'), ('a', 'c'), ('b', 'c'), ('a', 'b'), ('c', 'a'), ('c', 'b'), ('a', 'b'), ('a', 'c'), ('b', 'c'), ('b', 'a'), ('c', 'a'), ('b', 'c'), ('a', 'b'), ('a', 'c'), ('b', 'c'), ('a', 'b'), ('c', 'a'), ('c', 'b'), ('a', 'b'), ('c', 'a'), ('b', 'c'), ... | 8b7f2a56dadc09619c24d5bcd44e3286c2727ed1 | 49,460 |
def get_all(log):
"""get all documents"""
return log.all() | 197ad6548e4fa76a8781c780918bf37e96666024 | 49,461 |
def train():
"""
Takes No Parameter
trains the LUIS Model
"""
print "Training the LUIS Model"
try:
conn = httplib.HTTPSConnection("api.projectoxford.ai")
conn.request("POST", "/luis/v1.0/prog/apps/{0}/train".format(configData["appID"]), None,
headers)... | e028eceaaf231cfe5a6e4decee4f4d9300a6faeb | 49,462 |
def lag_to_z(x,lag,xunit='ang',avgbad=True):
"""
this converts an integer pixel lag for a given x-axis into a
redshift
currently the only supported unit for the x-axis is angstroms
avgbad replaces undeterminable velocities with the average of
the others, else they are set to 0
""... | 719c47f8c222327384fe30053520ce2da346f9fe | 49,463 |
def trainA3C(file_name="A3C", env=GridworldEnv(1), update_global_iter=10,
gamma=0.999, is_plot=False, num_episodes=500,
max_num_steps_per_episode=1000, learning_rate=0.0001 ):
"""
A3C training routine. Retuns rewards and durations logs.
Plot environment screen
"""
ns = env.... | be12863ce367bfe61607e1000c495b41ddd0ac84 | 49,464 |
def search_artist(query):
"""Search artists by query. Returns an ArtistSearch object.
Use get_next_page() to retrieve sequences of results."""
return ArtistSearch(query) | 06631762424a4a6575010c18bde76d44c85ba231 | 49,465 |
def key_expansion(k):
"""AES key expansion for 128/256-bit keys."""
w = list(map(list, zip(*k)))
Nk = len(w) # Nk is 4 or 8
Nr = 10 if Nk == 4 else 14
for i in range(Nk, 4 * (Nr + 1)):
t = w[-1]
if i % Nk in {0, 4}:
t = [sbox(x) for x in t]
if i % Nk == 0:
... | a08a03b3988b9b228c5f0c4c82dbd21e461eba55 | 49,466 |
import os
def _find_tcl_tk_dir():
"""
Get a platform-agnostic 2-tuple of the absolute paths of the top-level external data directories for both
Tcl and Tk, respectively.
Returns
-------
list
2-tuple that contains the values of `${TCL_LIBRARY}` and `${TK_LIBRARY}`, respectively.
""... | 13d27dd047d81b28977be20e753f38c0ba1807bb | 49,467 |
def process_invitation_response(request, invitation_response_formset):
"""
Process an invitation response.
Helper function to view: project_home
"""
user = request.user
invitation_id = int(request.POST['invitation_response'])
for invitation_response_form in invitation_response_formset:
... | d3a964ecf54e44939e7aa094d7eb024e84971e42 | 49,468 |
def addParams(params, subparser):
"""Add params to the given subparser"""
if (params is not None):
for param in params:
flags = ["--{}".format(param.name)]
if (param.alt is not None):
flags.append("-{}".format(param.alt))
if param.choices:
... | 59fc44d9bcc18c7b2750a182f519ff3be85b20ba | 49,469 |
def getShaders(objects):
""" DEPRECATED, use getMaterials(objects) instead """
return getMaterials(objects) | 9ab3db2d4440ee6addf869fcc31ec7bf4bc9b80c | 49,470 |
import scipy
def upsample(x, factor):
"""Reverse decimation by polyphase upsampling
by the given (integer) factor"""
return scipy.signal.resample_poly(x, factor, 1) | dec67e9957ea510c540507cc8e1394623bfe0d25 | 49,471 |
import psutil
import os
def process_is_crawler(pid):
"""This is really checking if proc is the current process.
"""
try:
pid = int(pid)
except ValueError:
raise TypeError('pid has to be an integer')
try:
proc = psutil.Process(pid)
cmdline = (proc.cmdline() if hasat... | c62f90a0515304ee9dffb434d4767da2dacbf02c | 49,472 |
import os
import pytz
def _load_local_tzinfo():
"""Load zoneinfo from local disk."""
tzdir = os.environ.get("TZDIR", "/usr/share/zoneinfo/posix")
localtzdata = {}
for dirpath, _, filenames in os.walk(tzdir):
for filename in filenames:
filepath = os.path.join(dirpath, filename)
name = os.path.... | 33a371b032d55aa5025d83710434295c6fecb0bd | 49,473 |
def balance_conversion_plus_primary_constraint_rule(
backend_model, node, tech, timestep
):
"""
Balance energy carrier consumption and production for carrier_in and carrier_out
.. container:: scrolling-wrapper
.. math::
\\sum_{loc::tech::carrier \\in loc::tech::carriers_{out}}
... | 3e63c4cecb534a08a025e956125efaede01e2414 | 49,474 |
def create_objectness_label(anchor_center, resolution=0.5,
x=90, y=100, z=10, scale=4):
"""Create Objectness label"""
print(type(x[1] - x[0]))
obj_maps = np.zeros((int((x[1] - x[0]) / (resolution * scale)),
int((y[1] - y[0]) / (resolution * scale)),
... | b648047ccc21497b9f329b463f038b9f45b353b4 | 49,475 |
def weighted_rating(clean_anime, quantile, mean):
"""
:var term: gets the total users who rated each anime.
"""
term = clean_anime['members'] / (quantile + clean_anime['members'])
return clean_anime['rating'] * term + (1 - term) * mean | 757808adcce0cce5c71a79d200bbaa03b6ebb878 | 49,476 |
def mjd2doyyr(mjd):
"""
Convert mjd to (decimal) day-of-year and year
Mathew Owens, 16/10/20
"""
#convert to datetime and extract the necessary info
dt=mjd2datetime(mjd)
year=np.vectorize(lambda x: x.year)(dt)
year=year.astype(int)
doy=np.vectorize(lambda x: x.timetuple().tm_yday... | 8fb45ce62670a6aef53b7a9c22c465597a8a7da9 | 49,477 |
import subprocess
def execute(*cmd):
"""
Execute command. Returns output and error.
Raises CommandException on error
"""
with subprocess.Popen(cmd,
stderr=subprocess.PIPE,
stdout=subprocess.PIPE,
universal_newlines=True)... | 39f1705831c8158f9017089df6d134afa1b79dde | 49,478 |
def git_fetch(path='', output=False, debug=False, timeout=None, exception=True,
show=False):
"""Perform `git fetch --all --prune`
- path: path to git repo, if not using current working directory
- output: if True, return output of `git fetch --all --prune`
- debug: if True, insert breakpo... | 95e099278806f2dfc22180abf42d094a1c8272ee | 49,479 |
import sys
def parse_markdown_to_structure(markdown, replacements):
"""Convert a parsed Markdown document into a folder structure"""
file_contents, file_replacements = process_markdown_definitions(
markdown, replacements
)
replaced_file_contents = replace_file_contents(
replacements, ... | 1b71214f46d09fd06a7983c745f5ba2a3bfd5544 | 49,480 |
def map_remove_by_rank_range(bin_name, rank_start, remove_amt, return_type, inverted=False):
"""Creates a map_remove_by_rank_range operation to be used with operate or operate_ordered
The operation removes `remove_amt` items beginning with the item with the specified rank from the map.
Args:
bin_n... | 7d301f9d6fbf5955cbaac6a5c0e5aa900809dfe8 | 49,481 |
from typing import OrderedDict
def export_view_json(request):
"""
Custom view function to export full results for this game as JSON file
"""
def create_odict_from_object(obj, fieldnames):
"""
Small helper function to create an OrderedDict from an object <obj> using <fieldnames>
... | eaeec81489318f8b579a4b32e0412ec9e3cd8680 | 49,482 |
def _parse_sklearn_api(topology, model, inputs):
"""
This is a delegate function adding the model to the input topology.
It does nothing but invokes the correct parsing function according to the input model's type.
Args:
topology: The ``hummingbitd.ml._topology.Topology`` object where the model... | ca46335e5e0437e4095d2a2046637e70664337bf | 49,483 |
def even_value_doubler(array_to_double = [1,2,3,5,6,7,9,10,12]):
"""
This function allegedly takes an list array of numbers and doubles the value of every even value in the list.
"""
length = len(array_to_double)
for i in range(0, length):
if arr[i] % 2 == 0:
arr[i] *= 2
return arr | c6284beb73f3a0c8c277a281c714139457c61f93 | 49,484 |
from typing import Any
def _print_card(card: Any) -> str:
"""helper for ``_validate_msg``"""
try:
return card.write_card(size=8)
except RuntimeError:
return '' | 0d85f2b7bfec942b1ff6e5d0c80facd1bb4824a0 | 49,485 |
import tempfile
import os
import shutil
def untar(tarfile, outdir):
"""Returns True if untar content differs from pre-existing outdir content."""
tmpdir = tempfile.mkdtemp()
try:
untared = _open_archive(tarfile, tmpdir)
files = [f for f in untared if os.path.isfile(os.path.join(tmpdir, f))]
dirs = [... | 8eb3c1312abe3e62b002efbf87f1cc427be152ee | 49,486 |
import hashlib
def getImageHash(img):
""" Calculates md5 hash for a given Pillow image. """
md5hash = hashlib.md5(img.tobytes())
return md5hash.hexdigest() | d7bd7e1857f6849143f07063c045ae206985d4a3 | 49,487 |
from pathlib import Path
def fssurf_to_gifti(surf, fn=None):
"""
Converts FreeSurfer `surf` surface file to GIFTI format
Parameters
----------
obj : str or os.PathLike
FreeSurfer surface file to be converted
fn : str or os.PathLike, None
Output filename. If not supplied uses i... | 70e4709d9941da2db9b55702063503c1f692beb4 | 49,488 |
def dihedral_ranking_score(structure, residues, sec_struct_column="sec_struct_3state",
original=True):
"""
Assess quality of structure model by twist of
predicted alpha-helices and beta-sheets.
This function re-implements the functionality of
make_alpha_beta_score_table.... | 358141dce6678a25f89fc3660ae61eba6140cd77 | 49,489 |
def kernel(request):
"""Console kernel fixture"""
# Get kernel instance
kernel = get_kernel()
kernel.namespace_view_settings = {'check_all': False,
'exclude_private': True,
'exclude_uppercase': True,
... | 5f7937e5b307048cb28c38bde5c5fea7f38e35d0 | 49,490 |
from typing import Counter
def character_replacement(s: str, k: int) -> int:
"""https://leetcode.com/problems/longest-repeating-character-replacement"""
counter = Counter()
left = 0
max_length = 0
current_max_frequency = 0
for right, char in enumerate(s):
counter[char] += 1
cu... | ad67c5fbff990c0701d0c487b5aa6832d8bc2691 | 49,491 |
def build_sampler(tparams, options, use_noise, trng, sampling=True):
""" Builds a sampler used for generating from the model
Parameters
----------
See build_model function above
Returns
-------
f_init : theano function
Input: annotation, Output: initial lstm state and memory
... | 7ab927b5efd202841a4fe4a53338f0f2e9deb41a | 49,492 |
def text_match(vobject_item, filter_, child_name, ns, attrib_name=None):
"""Check whether the ``item`` matches the text-match ``filter_``.
See rfc4791-9.7.5.
"""
# TODO: collations are not supported, but the default ones needed
# for DAV servers are actually pretty useless. Texts are lowered to
... | 6ec7b0e2fbf3fe36826af41cb6f82ad563fc9995 | 49,493 |
import hashlib
import time
def generate_tag_version():
""" Generates a new unique identifier for tag version."""
hash_value = hashlib.md5("{0}{1}{2}".format(
randrange(0, MAX_TAG_KEY), get_thread_id(), time.time()
).encode('utf8')).hexdigest()
return hash_value | a74389b2ede195d80887c18cd963bcf0fbe13f98 | 49,494 |
def _stem_words_list(list_words):
"""Stem words using a nltk stemmer
:param list_words: A list of strings representing words to stem
:rtype: A list of strings representing stemmed words
"""
stemmer = snowball.SnowballStemmer('english')
list_words_stemmed = {_stem(stemmer, word) for word in list... | a10cacc95e84b0abde38b2fa15a864b9cb8587c7 | 49,495 |
def read_data(location, type):
"""
This helps us read various filetypes directly into pyspark datframes. This is an allround solution.
"""
ftype = {
'avro' : "com.databricks.spark.avro",
'parquet' : "parquet",
'csv' : "com.databricks.spark.csv",
'json' : "json"
}
... | 4cc63fe1eead340e611552fddb863062bb5faca4 | 49,496 |
from typing import Optional
def get_app_user_assignments(id: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetAppUserAssignmentsResult:
"""
Use this data source to retrieve the list of users assigned to the given Okta application (by ID).
## E... | c5662bf77b608e6396bbd98f6521f247072e48e3 | 49,497 |
def clean_hotel_location(string):
"""
"""
if string is not None:
r = HTMLParser.HTMLParser().unescape(string)
r = commons.limpieza_barras_por_espacios(r)
if r.find('(') >= 0:
r = r[:r.find('(')]
if r.find('•') >= 0:
r = r[:r.find('•')]
if r.find('Chatl') >= 0:
r='El Chalten'
r=decutf_... | 3cdaf987d4e03eaf784c48d063cec97449e43817 | 49,498 |
from spatialpandas import GeoDataFrame, GeoSeries
from shapely.geometry.base import BaseGeometry
def from_shapely(data):
"""Converts shapely based data formats to spatialpandas.GeoDataFrame.
Args:
data: A list of shapely objects or dictionaries containing
shapely objects
Returns:
... | cb8ea3c5964dd5599e18d58c370d23d5d85d7f98 | 49,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.