content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def read_images_binary(path_to_model_file):
"""
see: src/base/reconstruction.cc
void Reconstruction::ReadImagesBinary(const std::string& path)
void Reconstruction::WriteImagesBinary(const std::string& path)
"""
images = {}
with open(path_to_model_file, "rb") as fid:
num_reg_i... | 33c4237eec1820b114b391c495231cb52103bf70 | 61,900 |
import yaml
def load_file(filename):
"""
TBD
Args:
tbd
Returns:
tbd
"""
docs2 = []
vars = {}
varrefs = {}
with open(filename, 'r') as stream:
try:
docs = yaml.load_all(stream)
except yaml.YAMLError as exc:
print(exc)
do... | 2796ebb9d05be46df64215baf841e8fbe8c16a7c | 61,901 |
def get_positions(structure):
"""Wrapper to get the positions from different structure classes"""
try: # ASE structure
return structure.get_scaled_positions()
except AttributeError:
try: # diffpy structure
return structure.xyz
except AttributeError:
raise Va... | 6428139131de02b577925be9499668642a11a69c | 61,902 |
def _get_files(table, match):
"""
Return a consistently-ordered set of files for a given container query.
"""
pipeline = [
{'$match': match },
{'$unwind': '$files'},
{'$sort': {'files.name': 1}},
{'$group': {'_id':'$_id', 'files': {'$push':'$files'}}}
]
result =... | b352cb4c436f05bea31c6441b016d051125d7cbf | 61,903 |
def get_hog_features(img, orient, pix_per_cell, cell_per_block, vis=True,
feature_vec=True):
"""
cv2.imshow('before', img)
cv2.waitKey(0)
img = img*255
cv2.imshow('after', img)
cv2.waitKey(0)
"""
#print("SHAPE: {}".format(img.shape))
return_list = hog(img,
... | 7453f98cf1127a90c102e0f836b1cc935426f4df | 61,904 |
def _asChannel(channel) -> discord.channel:
"""Ensure the use of discord.channel type variable
Args:
channel (discord.channel|SlashContext): Either a channel or a SlashContext
Returns:
discord.channel: The channel corresponding
"""
if type(channel) is SlashContext:
return c... | b8db185bcf5db7e53c27fa72cf935fc13d95e7d2 | 61,905 |
from .io.gambit import GambitNeutral
def get_blk_from_sample_neu(fpdtype=None, use_incenter=None):
"""
Read data from sample.neu file and convert it into Block.
"""
kw = {'fpdtype': fpdtype}
if use_incenter is not None:
kw['use_incenter'] = use_incenter
return GambitNeutral(loadfile('s... | f1c24874570aa91b899d6c88cdc485c734d7f93d | 61,906 |
from typing import IO
def unsafePerformIO(io : IO(a)) -> a:
"""
unsafePerformIO :: IO a -> a
Unsafe performs IO.
"""
return io.i0(Star) | 8fe48f0bf8af692b4ed0ddf6350c67b25e7c409d | 61,907 |
import os
import logging
import torch
import inspect
def create_model(config, task, save_dir=None, ckptdata=None):
"""Instantiates a model based on a provided task object.
The configuration must be given as a dictionary object. This dictionary will be parsed for a 'model' field.
This field is expected to... | cd0f5dbcd8f168e2be94766153460719d53a86e9 | 61,908 |
from typing import Optional
import json
import logging
import functools
def get_dataset(*,
batch_size,
eval_batch_size,
num_shards,
dtype_str='float32',
shuffle_seed=0,
rng=None,
dataset_configs=None,
... | ce0298ed1439d62a15f05e5a4f6b3074917b0f60 | 61,909 |
def aStar(G, start, end):
"""
G: graph with admissable heuristic
start: start node
end: end node
distToGoal = heuristic for start to end distance
"""
if start==end:
return end
visited = set() # node
stack = [] # a heap of tuple (length form end of path to start, path(list))
def getPath():
... | 54fc04dc5d51f8c2e71a94ff095b7549cfd7d4b9 | 61,910 |
import json
async def _add_job(request):
"""Add job to queue."""
_logger.debug('Received request to add job')
data = await request.json()
_logger.debug('Received json: {}'.format(data))
result = await _loop.run_in_executor(None, _process_job, data, _jobs_list)
return web.Response(
tex... | 03dc8ed46eafa5bf08277e923fa2b398ba2e71b6 | 61,911 |
def _get_count_effects(effects, exog, count_ind, method, model, params):
"""
If there's a count variable, the predicted difference is taken by
subtracting one and adding one to exog then averaging the difference
"""
# this is the index for the effect and the index for count col in exog
for i in ... | c468463e82a4170593345a23e6b4aa3c879c3dc7 | 61,912 |
def improved_combination(slides_list, all_vertical_ids, all_pairs):
"""
:param slides_list:
:param all_vertical_ids:
:param all_pairs:
:return: Slides list
"""
slides_to_return = []
slides_list2 = slides_list.copy()
slides_list2.sort(
key=lambda slide: len... | 231828a4b0b9452ef61309f0879fb677501437ab | 61,913 |
def get_grid_coordinates(n_side, centre, x_width, y_width=None):
"""Return tuple of arrays that contain the coordinates on a regular grid.
Parameters
----------
n_side: int
Number of points per side. The returned arrays have n_side**2 entries.
centre: tuple of floats
Center coordina... | b3c819694254ebed043b02a84c6ac330ac21f0d2 | 61,914 |
from pathlib import Path
def fetch_earth_topography(version):
"""
Topography of the Earth at 10 arc-minute resolution
The grid is global with node spacing of 10 arc-minutes (grid-node
registered) and stored in netCDF with CF-compliant metadata.
The values are derived from a spherical harmonic mo... | 9f1b5af35c809d4744c695918bd77adbe645208c | 61,915 |
import logging
def get_specific_instance_prices(instance_type):
"""
Get pricing data for a specific instance type.
Args:
instance_type (str): The instance type tog et pricing
data for.
Returns:
dict
"""
logging.debug('Serving instance pr... | a30d4d5d10cd30befb5dd57baaabb2845c3841df | 61,916 |
def circleInsideRect(rect):
"""Returns a GSPath for a circle inscribed into the NSRect rect."""
MAGICNUMBER = 4.0 * ( 2.0**0.5 - 1.0 ) / 3.0
x = rect.origin.x
y = rect.origin.y
height = rect.size.height
width = rect.size.width
fullHeight = y+height
fullWidth = x+width
halfHeight = y + 0.5 * height
halfWidth =... | 00ffcd77a5eb2bead2d313e89c348a1f7ca0b906 | 61,917 |
import zlib
def read(path, encoding="utf-8"):
"""Read string from text file.
"""
is_gzip = is_gzip_file(path)
with open(path, "rb") as f:
if is_gzip:
return zlib.decompress(f.read()).decode(encoding)
else:
return f.read().decode(encoding) | db8eb6be868597baae1f9a9ed378c4cdc66ffb32 | 61,918 |
from datetime import datetime
def _to_datetime(message: Timestamp) -> datetime.datetime:
"""Convert a Timestamp to a python datetime."""
return well_known_types._EPOCH_DATETIME_NAIVE + datetime.timedelta( # type: ignore[attr-defined]
seconds=message.seconds,
microseconds=well_known_types._Rou... | c543e9f316ad07513197672e853b633a8614737b | 61,919 |
from typing import Dict
def password(value: str, values: Dict[str, str]) -> str:
""" make sure the password supplied meets our criteria """
# We will assume all attempts will fail so start with least intense first
if 'password' not in values or value != values['password']:
raise ValueError('passw... | 8e4951897c1ad99c3f875c8a6b9707bba901ce38 | 61,920 |
def export2(request):
"""
:param request:
:return:
"""
#logging.getLogger('update_location')
print('updating locations from File')
location_list = ["Kenya", "Nairobi", "Baringo", "Bomet", "Bungoma", "Busia", "Elgeyo Marakwet", "Embu", "Garissa", "Homa Bay", "Isiolo", "Kajiado", "Kakamega", "... | 5027f217c5edabb7106d52c410ba9762643cb17f | 61,921 |
def get_nearest_plane_point(plane):
""" Get the nearest point to the origin on the plane """
return up(get_plane_normal(plane)*get_plane_origin_distance(plane)) | a51668f3da16a916f100f1669d9668d86183b593 | 61,922 |
from typing import List
def parse_comp_internal(
comp_rules: str, top_delim: str, bottom_delim: str, rule_start: str
) -> List[str]:
"""
Do the heavy handling to parse out specific sub-sections of rules.
:param comp_rules: Rules to parse
:param top_delim: Section to parse
:param bottom_delim: ... | 5563e1eb7bbe9d738f550a220a733c6c2d11b509 | 61,923 |
import collections
def _ConvertBuilderMapToPassOrderedStringDict(builder_map):
"""Converts |builder_map| into an ordered dict split by pass type.
Args:
builder_map: A data_types.BuildStepMap.
Returns:
A collections.OrderedDict in the following format:
{
result_output.FULL_PASS: {
bui... | 0f7235b5f7df113b3cb34e99ad49126f86854983 | 61,924 |
def finish_waiting(event, messageCenter, roomGrid):
"""Events that happen at the end of some input cycle."""
if roomGrid.waitFunction[0] == "move":
location = roomGrid.waitFunction[1]["location"]
if event.location == [-1, -1]:
to_location = roomGrid.lockedSpace
else:
... | c3b74736b875e531af29d5f4c470543c0ca975ec | 61,925 |
import logging
import io
import sys
import types
def _RunMethod(dev, args, extra):
"""Runs a method registered via MakeSubparser."""
logging.info('%s(%s)', args.method.__name__, ', '.join(args.positional))
result = args.method(dev, *args.positional, **extra)
if result is not None:
if isinstance(result, io... | 34c267aa1379a81bea5c73b0a2fa9f3a9aa9b3d7 | 61,926 |
def get_interaction_type(read1, read1_chrom, resfrag1, read2,
read2_chrom, resfrag2, verbose):
"""
Returns the interaction type
For a given reads pair and their related restriction fragment, classify
the 3C products as :
- Interaction
- Self circle
- Dangling end
... | 8ad2e27aae66d9e3a146559c4b3a1dd53ad0f1d7 | 61,927 |
def as_strided(x, shape=None, strides=None, subok=False, writeable=True):
"""
Create a view into the array with the given shape and strides.
.. warning:: This function has to be used with extreme care, see notes.
Parameters
----------
x : ndarray
Array to create a new.
shape : sequ... | c023e24ffc19545774b703c9dde570d077cc72f0 | 61,928 |
from typing import Any
def get_or_create_thread() -> [Any, bool]:
"""
Get or create the local thread, will always return False as the thread
won't be created, but the local dal object will.
get_or_create to conform with the other functions.
:return: thread, created dal object?
"""
thread... | f7e73f57c9ba35245827a2263307a8bde31380af | 61,929 |
def fully_connected(input, params):
"""Creates a fully connected layer with bias (without activation).
Args:
input (:obj:`tf.Tensor`):
The input values.
params (:obj:`tuple` of (:obj:`tf.Variable`, :obj:`tf.Variable`)):
A tuple of (`weights`, `bias`). Probably obtained ... | 77815acfe17674bc20035900b75d8e4ddc982855 | 61,930 |
def _GetValidBenchmarks():
"""Returns a dict mapping valid benchmark names to their modules."""
if FLAGS.os_type in os_types.CONTAINER_OS_TYPES:
return {'cluster_boot': linux_benchmarks.VALID_BENCHMARKS['cluster_boot']}
elif FLAGS.os_type in os_types.WINDOWS_OS_TYPES:
return windows_benchmarks.VALID_BENCH... | 6be8b344c02c0618b57ad6dcd7726e04f9b90268 | 61,931 |
async def list_users(search=None, rest_client=None):
"""
List users in Keycloak.
Returns:
dict: username: user info
"""
start = 0
inc = 50
ret = {}
data = [0]*inc
while len(data) == inc:
url = f'/users?&max={inc}&first={start}'
if search:
url += ... | 8d623287c7b097d2820c7234ac272143bd671af8 | 61,932 |
def _generate_sample_indices(random_state, n_samples, n_samples_bootstrap):
"""
Private function used to _parallel_build_trees function."""
random_instance = check_random_state(random_state)
sample_indices = random_instance.randint(0, n_samples, n_samples_bootstrap)
return sample_indices | bcf7f0a5426f5a8bc836654df192a40de261d74f | 61,933 |
def ldns_rr_list_contains_rr(*args):
"""LDNS buffer."""
return _ldns.ldns_rr_list_contains_rr(*args) | 9fe859dd6e2fa21baf8c32a61f49f0c6c2b85a57 | 61,934 |
def add_spatial_semantics_attr(left_gdf,right_gdf,semColName):
"""
Explore the spatial semantic relationship between two GeoDataFrame
Parameters
----------
left_gdf : GeoDataFrame
right_gdf : GeoDataFrame
# As for both gdf, more detail cna be found in
# https://automating-gis-p... | 481585cb7feb2ffabcfa2c465eafd6252f93473e | 61,935 |
def reduce_mem_usage(df):
""" iterate through all the columns of a dataframe and modify the data type
to reduce memory usage.
"""
print('\nTriggering memory optimization.......\n')
start_mem = df.memory_usage().sum() / 1024 ** 2
print('Memory usage of dataframe is {:.2f} MB'.format... | 25499c0274af4a9b571b691ff40d277a875f94fa | 61,936 |
def gemv_rounding(A, B):
"""
chunked GEMV which converts datatypes and filters values,
converting > 127 to 127 and < -128 to -128
"""
A = A.astype("int32")
B = B.astype("int32")
C = np.matmul(A, B)
C[C > 127] = 127
C[C < -128] = -128
return C.astype(np.int8) | 6c5344bcf4bf945ce578007cb497a1afdbc5df63 | 61,937 |
import asyncio
def login(username: str, password: str, loop: asyncio.AbstractEventLoop = None) -> "DiscordLinkClient":
"""Eases logging into the API client.
For more information on this project, please join the discord server - <discord.gg/Eaja7gJ>
You must have your username and password as given on th... | 776ae036200da027fec8096437ff35375ff186b8 | 61,938 |
def contact(request):
""" A view that displays the contact page """
# render contact page
return render(request, "contact.html") | 831d3da34f5c1bebf975025cfac1e5174e0b53a6 | 61,939 |
import copy
def _fit_temporal(noise,
mask,
template,
stimfunction_tr,
tr_duration,
spatial_sd,
temporal_proportion,
temporal_sd,
noise_dict,
fit_thresh,
... | 4c3a79bf4f6328d2ee317b0a053efb564ac00b8e | 61,940 |
def in_hull(p, hull):
"""
Test if points in `p` are in `hull`
`p` should be a `NxK` coordinates of `N` points in `K` dimensions
`hull` is either a scipy.spatial.Delaunay object or the `MxK` array of the
coordinates of `M` points in `K`dimensions for which Delaunay triangulation
will be compute... | dfa7c8fef5d273903247eae2e0914d94e020d225 | 61,941 |
async def position_info(request):
"""
Positions determined experimentally by issuing move commands. Change
pipette position offsets the mount to the left or right such that a user
can easily access the pipette mount screws with a screwdriver. Attach tip
position places either pipette roughly in the ... | e3395fe40b1c83be349ae900dde727fceeb8f700 | 61,942 |
def GetIslandSlug(island_url: str) -> str:
"""该函数接收一个小岛 URL,并将其转换成小岛 slug
Args:
island_url (str): 小岛 URL
Returns:
str: 小岛 slug
"""
return island_url.replace("https://www.jianshu.com/g/", "") | 71e1b609e5bd3c703a4d5d0789fddff117969e69 | 61,943 |
def tensor2im(tensor):
""""Converts a Tensor array into a numpy image array.
Parameters:
input_image (tensor) -- the input image tensor array
imtype (type) -- the desired type of the converted numpy array
"""
tensor = tensor.cpu().numpy()
im = (tensor.transpose(1, 2, 0).cli... | fb66f87a5222dc8514591ea506bfb75ee7374261 | 61,944 |
def set_floatx(dtype: str) -> str:
"""Sets the default float type.
Parameters:
--------
dtype: String; `'float16'`, `'float32'`, or `'float64'`.
Example:
--------
>>> graphgallery.floatx()
'float32'
>>> graphgallery.set_floatx('float64')
'float64'
Raises:
--------
... | f56eaca5126390b8a0f7e69e9591bdfa08251bc9 | 61,945 |
from typing import List
import math
def is_prime(num: int, *, primes: List[int] = None) -> bool:
"""
Verify if num is prime
:param num:
:param primes: initial sorted primes table if exist (e.g. from Eratosthenes)
:return: True if prime, False otherwise
"""
if num < 2:
return False
... | c29dc210776bfef8afaa1534775d331c65f3a82a | 61,946 |
def context_encode(tag):
"""Encode the object into a tag, encode it in a PDU, return the data."""
if _debug: context_encode._debug("context_encode %r", tag)
data = PDUData()
tag.encode(data)
return data.pduData | 21dc97d6a60e0455edcc6ac4482ee8138cea9f7c | 61,947 |
def flatten(a, start=0, count=2):
""" Reshapes numpy array a by combining count dimensions,
starting at dimension index start """
s = a.shape
return np.reshape(a, s[:start] + (-1,) + s[start+count:]) | 48fc73bf707a7d52d41577d6eed821e794fdf0fe | 61,948 |
def all_users():
"""A list of all users on PokéTwitcher."""
all_users = User.query.order_by(User.user_id).all()
total_pokemon = 586
user_total_sightings = 0
dex_totals = {}
for user in all_users:
user_total_sightings = Sighting.query.filter_by(user_id=user.user_id).count()
dex... | 11125381fc11632a60094bd2f37f8a540995f2bb | 61,949 |
def expected_data():
"""
A data set with:
- multiple date types: strings, floats, dates, datetimes, times
- an empty row in the middle
- empty trailing row
- empty trailing column
- 1 row with 4 populated cells vs. header and other rows having 3 populated cells
"""
... | e25c0e2ce79dc778ee8ad4f76b9aab8147f487f7 | 61,950 |
from sys import path
def solve(start):
"""
Searches the right path and gives back the solution as the output, if it exists
"""
queue = deque([Node(start)])
seen = {start}
if start.solved():
return path(Node(start, None))
while queue:
node = queue.pop()
for move i... | 8e8741ba1fd706fe09c9d9a1e91809d578961153 | 61,951 |
def cec_module_spr_e20_327():
"""
Define SunPower SPR-E20-327 module parameters for testing.
The scope of the fixture is set to ``'function'`` to allow tests to modify
parameters if required without affecting other tests.
"""
parameters = {
'Name': 'SunPower SPR-E20-327',
'BIPV'... | 55593d3a561d6ebafba424f50406128e58406073 | 61,952 |
def get_base_classification(x: str) -> str:
"""
Obtains the base classification for a given node label.
Args:
x: The label from which to obtain the base classification.
Returns:
The base classification.
"""
return x.split('_', 1)[0] | 8122d435af8ac6aef43faab349ee98dca75469d4 | 61,953 |
def adata_define_clonotype_clusters_singletons():
"""Adata where every cell belongs to a singleton clonotype.
Required for a regression test for #236.
"""
adata = AnnData(
obs=pd.DataFrame()
.assign(
cell_id=["cell1", "cell2", "cell3", "cell4"],
IR_VJ_1_junction_a... | c8f2f77afc695481c4e0907aa3a068455a3f9701 | 61,954 |
def op_offset_ex(*args):
"""op_offset_ex(ea_t ea, int n, refinfo_t ri) -> int"""
return _idaapi.op_offset_ex(*args) | d4a4b125dddfd5ad58fa2389885c7cb20f0d180a | 61,955 |
def appliedRuleSymmetric(*args, **kwargs):
"""
appliedRuleSymetric(*args, *args,**kwargs)
Overloaded function.
1. appliedRuleSymetric() -> bool
2. appliedRuleSymetric(self: int) -> bool
"""
return DarkLogic.appliedRuleSymetric(*args, **kwargs) | 28a1b8e71dfa7fecd2f130d752c4a8515bb45dd6 | 61,956 |
def check_individuals(ped_individuals, vcf_individuals):
"""
Check if the individuals from ped file is in vcf file
Arguments:
ped_individuals (iterator): An iterator with strings
vcf_individuals (iterator): An iterator with strings
Returns:
bool: if the individuals exis... | e65b24390c8cebff7870e46790cf1c0e9b2d37c6 | 61,957 |
def support_jsonp(api_instance, callback_name_source='callback'):
"""Let API instance respond to jsonp requesta automatically.
:param str callback_name_source: can be a string or a callback
If it is a string, the system will find the argument that named by this string in `query string`.
If fou... | b56088ddf5f3b3095550acd89849aa6f17d4c8c5 | 61,958 |
from typing import Tuple
from pathlib import Path
def fresh_tissue_beads_preprocessing(zarr_grp_name: str,
parsed_raw_data_fpath: str,
processing_parameters: dict,
dark_img: np.ndarray)-> Tuple[Tuple[np.ndarray,],dict]:
"""Function used filter the reference image containing large beads
... | 908e969aa80c97702d3efb3b12e601fdba3f1726 | 61,959 |
def pdist_ortho(ux, uy, uz, a, b, c, index, dmax=8.0):
"""
Pairwise two body calculation for bodies in an orthorhombic periodic cell.
Does return distance vectors.
An orthorhombic cell is defined by orthogonal vectors of length a and b
(which define the base) and height vector of length c. All thr... | 0791753134caa91465299ff31b726a993b79ad2d | 61,960 |
import os
def get_proba_image_file(features, clf_files, image_file, labels_file, proba_file):
"""
This function...
:param features:
:param clf_file:
:param image_file:
:param labels_file:
:param proba_file:
:return:
"""
image = sitk.ReadImage(image_file)
label_image = sitk... | 87dac929b63ab84cd9bcad3b4c180d1cc87f7bb6 | 61,961 |
def _preprocess(prop, tensor, step, max_outputs, geometry_metadata):
"""Data conversion and other preprocessing.
TODO(ssheorey): Convert to half precision, compression, etc.
"""
# Check if property is reference to prior step
step_ref = _to_integer(tensor)
if step_ref is not None:
if step... | 43486203edcc31abe980ae6c5b70b6e23248f32e | 61,962 |
from typing import Optional
def get_hybrid_runbook_worker(automation_account_name: Optional[str] = None,
hybrid_runbook_worker_group_name: Optional[str] = None,
hybrid_runbook_worker_id: Optional[str] = None,
resource_group_name... | 1a5f7129c941e1b7c3be943118dd8775f639d28f | 61,963 |
def home(request):
"""Renders the home page."""
assert isinstance(request, HttpRequest)
form = UploadFileForm()
return render(
request,
'app/index.html',
context_instance = RequestContext(request,{'form':form})
) | a8bf27906aa517c7f9db7a12b796fbac8ca192a5 | 61,964 |
import logging
async def test_websocket_roundtrip(nursery):
"""
Create a WebSocket server and several clients.
"""
dispatch = Dispatch()
client_count = 0
@dispatch.handler
async def hello_world(n):
return {"mode": "hello", "client_number": n}
@dispatch.handler
async def g... | 3ba8e93d72e63c0b7b79bbb3f5f195605c866c4c | 61,965 |
def catalog_image(imagedir):
"""
Catalog the given image with syft, keeping only select artifacts in the returned results.
"""
all_results = run_syft(imagedir)
return convert_syft_to_engine(all_results) | 1e44c330dc25ab8483c7dd385bc1232ce7508b68 | 61,966 |
import dill
def load(filename):
"""
Load an instance of a bayesloop study class that was saved using the bayesloop.save() function.
Args:
filename(str): Path + filename to stored bayesloop study
Returns:
Study instance
"""
with open(filename, 'rb') as f:
S = dill.load... | 19ce91d2a4bb552362bd8f8ab67194e1241356d1 | 61,967 |
def gexport(f):
"""
Decorator for functions that need to be imported
under same name as they declared without prefix
when import is done by gimport command.
This is necessary for functions used inside quasiquotes in macro definitions.
Raises
------
InvalidParseContext
If functi... | 5903936e051d0869a8274b636ab27ed959cca8ad | 61,968 |
def par2ms_beta(alpha, beta_, a, b):
"""
Converts a mean, standard deviation, minimum and maximum to `alpha` and `beta` parameters of a beta distribution.
Parameters
----------
alpha : float
Shape parameter 1.
beta_ : float
Shape parameter 2.
a : float
Minimum.
b... | 668a6413c03e5d3b5dfc580718c61318822772af | 61,969 |
def des_magnitude_zero_point(bands=''):
"""
Sample from the distribution of single epoch zeropoints for DES
"""
dist = {'g': 26.58, 'r': 26.78, 'i': 26.75, 'z': 26.48, 'Y': 25.40}
return [dist[b] for b in bands.split(',')] | 568b6f17abb0957c22cb6c300af06d72b41e6c73 | 61,970 |
def random_string(length=6):
"""
Returns a random string of length `length` containing only ASCII letters.
"""
return ''.join([choice(ascii_letters) for _ in range(length)]) | 499f2b655683980db54b998d074b29b9d2a744c8 | 61,971 |
import webbrowser
import os
import json
import sys
def authorize():
"""
Look for tokens or client id/secret in env.
Authorizes the script.
"""
# Check if the user has an existing token stored.
if 'ASANA_CLIENT_ID' in os.environ and 'ASANA_TOKEN' in os.environ:
# Create a client with yo... | 47308838b53d94ac466c868252e147b60d10db2c | 61,972 |
def dict_diff(first, second):
""" Return a dict of keys that differ with another config object.
If a value is not found in one fo the configs, it will be represented
by KEYNOTFOUND.
@param first: Fist dictionary to diff.
@param second: Second dicationary to diff.
@return diff: Dict of Key =... | 9d83d0036b8318e57e9756bfd5f35f86c86e3609 | 61,973 |
def uid():
"""Returns an identifier that can be used when creating SageMaker entities like training jobs.
Currently returns a formatted string representation of the current time"""
return strftime("%d-%H-%M-%S", gmtime()) | 5bb2cc0ef8f28967353acb639c9f0feac83e8703 | 61,974 |
def get_instanciated_charts(discipline, chart_filters=None):
"""
Create graphs to visualize outputs of gather of Disc1
"""
instanciated_charts = []
# Overload default value with chart filter
if chart_filters is not None:
for chart_filter in chart_filters:
if chart_filter.fil... | eae2fc50eb7e115439d43ba2b842bd86a4548eb4 | 61,975 |
def trans_block(x, reduce_by):
""" Construct a Transition Block
x : input layer
reduce_by: percentage of reduction of feature maps
"""
# Reduce (compression) the number of feature maps (DenseNet-C)
# shape[n] returns a class object. We use int() to cast it into the dimension
... | b7cfccd6671eadb6507e2547bd2adfe72a3cfdb9 | 61,976 |
def resonance_avg_bond_orders(rgr):
""" resonance-dominant bond orders, by bond
"""
bnd_keys = list(_bond_keys(rgr))
bnd_ords_by_res = [
dict_.values_by_key(_bond_orders(dom_rgr), bnd_keys)
for dom_rgr in dominant_resonances(rgr)]
nres = len(bnd_ords_by_res)
bnd_ords_lst = zip(*b... | 0666ade0e2e72c35e3e550cf2e82075a246d8bc5 | 61,977 |
def check_validity_specie_tag_in_reaction_dict(k):
"""Validate key in database reaction entry"""
return not (
k == "type"
or k == "id_db"
or k == "log_K25"
or k == "log_K_coefs"
or k == "deltah"
or k == "phase_name"
) | c925e06ff1701f7ce2609ab125a58c95ee7af958 | 61,978 |
def parse_url(url):
"""
*Client.* Parses a Gopher URL and returns an equivalent Request.
"""
req = Request(host='', port=70, path='/', query='')
up = urlparse(url)
if up.scheme == '':
up = urlparse('gopher://' + url)
req.path = up.path
if up.query:
req.path += '?{}'.fo... | 2424dcec517450cdacdabc63fbed2e33e8d6f617 | 61,979 |
def check_access_token(access_token):
"""对access_token解密"""
serializer = Serializer(settings.SECRET_KEY, 3600 * 24)
try:
# 如果解密失败抛BadData异常
data = serializer.loads(access_token)
user_id = data.get('user_id')
try:
# 如果查不到信息抛DoesNotExist异常
user = User.ob... | 062df97138b5da89c3d3459e12d276cca89453d6 | 61,980 |
def exist(keyword,hdu,file,logfile):
"""does keyword exist"""
status = 0
try:
value = hdu.header[keyword]
except:
message = 'ERROR -- SALTKEY.EXIST: ' + keyword + ' does not exist'
message += ' in file ' + file
status = saltprint.err(logfile,message)
return status | 36b6b02f91371b18ff015be316032e90922b2d07 | 61,981 |
from typing import Iterator
from pathlib import Path
import appdirs
def iter_manifests() -> Iterator[Path]:
"""
Find all manifests in known location(s).
"""
mobilesync_path = Path(appdirs.user_data_dir("MobileSync"))
# on macOS, mobilesync_path would be ~/Library/Application Support/MobileSync
... | 356e97d65395bd86d71de1c6ed348dc7e87139be | 61,982 |
def basic_model_2d_cl(data_path, simple_displacement_boundary):
"""Create a basic 2D model object using an OpenCL integrator."""
mesh_file = data_path / "example_mesh.vtk"
euler = EulerCL(dt=1e-3)
model = Model(mesh_file, integrator=euler, horizon=0.1,
critical_stretch=0.05,
... | d0e9b99214e0b8b725af49a5d608a8eaf18efa92 | 61,983 |
def check_exog(X, dtype=DTYPE, copy=True, force_all_finite=True):
"""A wrapper for ``check_array`` for 2D arrays
Parameters
----------
X : array-like, shape=(n_samples, n_features)
The exogenous array. If a Pandas frame, a Pandas frame will be returned
as well. Otherwise, a numpy array ... | 9cd3845f5b45f3f147dea37d2211725dc0762ce5 | 61,984 |
import configparser
import sys
def loadAuth(path):
""" Load guthub api token form file
:param path: File's path
:type path: string
:return: token
:rtype: string
"""
try:
config = configparser.ConfigParser()
config.read(path)
return config['github']['token']
... | 1e8d78124fe5e664bfb5a7532cc71e5f5d90d9cc | 61,985 |
def build_datasets(mode,
strategy,
custom_dataset: Dataset,
task,
args=None):
""" Builds datasets and returns datasets. """
if isinstance(custom_dataset, MultipleDataset):
return {
name: task.create_and_batch_tfds(
... | a0514915ae4c622e69eb088697c06fab9dd73b11 | 61,986 |
def conv(feature_maps, input_shape, kernels, kernel_shape, activation=None):
"""
A convolutional layer.
Args:
feature_maps: list, 包含多个输入特征图.
input_shape: tuple, 包含输入特征图的形状(宽和高).
kernels: int, 卷积层的卷积核数量.
kernel_shape: tuple, 卷积核的形状(宽和高).
activation: str, 激活函数类型.
... | abe648b7ab4dacbf817c794284ccc1f4fe97172a | 61,987 |
import torch
import logging
import os
def learnable_eval(
cfg: OmegaConf, classifier, encoder: ContrastiveFastText, training_data_loader: DataLoader,
val_data_loader: DataLoader, device: torch.device
) -> tuple:
"""
:param cfg: Hydra's config instance.
:param classifier: Instance of classi... | 6d8bf9d198b32f350a252c6d0b24bd58fe4465ca | 61,988 |
from typing import List
def load_grid_from_string(grid_str: str) -> List[List[int]]:
"""Returns a grid by loading a grid passed as a string."""
array = [int(cell) for cell in grid_str.split()]
grid = [[int(cell) for cell in array[i : i + 3]] for i in range(0, len(array), 3)]
return grid | c3b9a91c9298b54226f5ef532d1948a41dc67eac | 61,989 |
def number(bus_stops):
"""
There is a bus moving in the city, and it takes and drop some people in each bus stop.
You are provided with a list (or array) of integer pairs.
Elements of each pair represent number of people get into bus (The first item)
and number of people get off the bus (The second ... | 382c0112c223a6681508ec3d7a345ec92391657d | 61,990 |
import pandas
import numpy
def sdc_pandas_dataframe_values_codegen(self, numba_common_dtype):
"""
Example of generated implementation:
def sdc_pandas_dataframe_values_impl(self):
length = len(self._data[0][0])
col_data_0 = self._data[0][0]
col_data_1 = self._data[1][0]
... | 6f00ef0483da926435b655e3c8a167957c682dd2 | 61,991 |
def QuantumRegister_to_c(self):
"""Syntax conversion for creating a quantum register."""
return f"Qureg {self.name} = createQureg({self.size}, Env);" | c11ef38ff8f3e3303eedd93fae60c2ca0bb211b7 | 61,992 |
def gen_code_inst_part(metadata, do_validate=True, code_snipet=None):
"""广度优先向下遍历所有的容器类和实例类, 生成数据的实例部分的代码。
1. 凡是遇到一个类, 都创建一次实例。
2. 凡是遇到一个类, 只要有母类, 该类的实例都作为一个属性绑定到母类的实例下。
并且将其放入 ``self._collection`` 的列表中。
"""
if do_validate:
class_def_dict = validate(metadata)
if code_snipet is No... | a5ea16e744afc291a72e567b1cb85fcf3809063b | 61,993 |
import torch
def omp(X: torch.Tensor, y: torch.Tensor, *,
k=None, device=None) -> torch.Tensor:
"""
y = Xa
:param X: (n_features, n_components)
:param y: (n_features)
:param k: n_nonzero_coefs
:param device: pytorch device
:return: (n_components)
"""
assert X.dim() == 2
... | 5f11464371401e630e0f7a37eedb53d29016bd27 | 61,994 |
import random
def generate_random_color():
"""
Generates the hexadecimal code of a random pastel color
"""
# generates random RGB
r = (random.randrange(1, 256) + 255) / 2
g = (random.randrange(1, 256) + 255) / 2
b = (random.randrange(1, 256) + 255) / 2
# clamp function
clamp = lam... | d6efcb30f1296e031ee764076b2659b0d4a7cd93 | 61,995 |
def dumps_pretty(object):
"""
Dumps (converts to JSON) the given object using the "normal"
approach.
This dumps method prints the JSON in "pretty" mode
:type object: Object
:param object: The object to be dumped.
:rtype: String
:return: The dumped JSON string (pretty).
"""
retu... | ec151bb64e70f24847b64980fbae1336e8ae94c1 | 61,996 |
import time
async def editZaznamGet(item_id: int, request: Request):
"""
zobrazí edit okno na zmenu zázanamu v DB
"""
meny = fun.citaj_pouzite_meny(fun.db)
localtime = time.asctime(time.localtime(time.time()))
print("/edit/", item_id, "; Čas:", localtime)
# debug(item_id)
riadky = fun.... | b113a5fac65a668b025fd61b8e031acc1acebd4a | 61,997 |
def parse_columns(columns, header):
"""check the provided column headers
"""
for i, column in enumerate(columns):
if isinstance(column, int):
if header:
if column >= len(header):
raise CsvSortError(
'Column index is out of range... | 97efb0cb99f2eed5eb1cffb019a9483cc82da8ca | 61,998 |
import json
def try_json(value: str) -> dict:
"""tries to parse the given value value as JSON, returns the value
untouched in case of failure.
Does not emit logs.
"""
if not isinstance(value, str):
return value
return try_convert(value, json.loads) | f29aa83a5a97b95c565fabc2a325e3e73de26b7e | 61,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.