content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import click
import sys
def find_modules(device_path, bundles_list):
"""
Extracts metadata from the connected device and available bundles and
returns this as a list of Module instances representing the modules on the
device.
:param str device_path: The path to the connected board.
:param Bun... | dc51d1ca622d33c721785a3a3f8bb30b7a3b7833 | 3,627,900 |
from typing import OrderedDict
def sort_ordered_games_list(ordered_games_lists):
""" Reverses as sorts ordered games lists alphabetically """
new_order = OrderedDict()
for group, games in reversed(ordered_games_lists.items()):
new_order[group] = OrderedDict(
sorted(games.items(), key... | bc1b40884ad450d8a2b447c2628bfe77cd2797fa | 3,627,901 |
import random
def get_challenge_id() -> int:
"""
Get the challenge ID, a number from 1 to NUMBER_OF_CHALLNEGE_VARIANTS.
"""
random_seed = get_random_seed()
random.seed(random_seed)
variant_number = random.randint(0, NUMBER_OF_CHALLENGE_VARIANTS - 1)
return variant_number | ec5e5c817841e30e6fc38129d405f0b5424c04e8 | 3,627,902 |
def _conv1(in_channels, out_channels, stride=1, bias=False):
"""point-wise convolution"""
return Conv1d(in_channels, out_channels, kernel_size=1, stride=stride, bias=bias) | 82e218f5700ad2d63d0820410707d5a69b6b0ff6 | 3,627,903 |
def mixer_b16_224_in21k(pretrained=False, **kwargs):
""" Mixer-B/16 224x224. ImageNet-21k pretrained weights.
Paper: 'MLP-Mixer: An all-MLP Architecture for Vision' - https://arxiv.org/abs/2105.01601
"""
model_args = dict(patch_size=16, num_blocks=12, hidden_dim=768, **kwargs)
model = _create_mixer... | 05fc49bd21cfa37108dcad9f99c81c4ff3eac521 | 3,627,904 |
def service_proxy_settings(private_base_url):
"""Change api_backend to echo-api for service2."""
return rawobj.Proxy(f"{private_base_url('echo_api')}/service1") | 11e23d2d1ed2cb32ccdd64c3917ae1fd409774c6 | 3,627,905 |
import time
import os
import subprocess
def get_map_mrr(qids, predictions, labels, device=0, keep_results=False):
"""
Get the map and mrr using the trec_eval utility.
qids, predictions, labels should have the same length.
device is not a required parameter, it is only used to prevent potential naming ... | 0ddc68fd12afebd2954e0c71e1bc58ffd0f6a1bf | 3,627,906 |
from pathlib import Path
from typing import Union
from typing import List
def glob_suffixes(root_path: Path, suffixes: Union[List[str], str]) -> List[Path]:
"""Returns all suffixes located in the path and in the input variable suffixes"""
if isinstance(suffixes, str):
suffixes = [suffixes]
return ... | 51847ffcc125d4307f83938e31d6cd5f049598d5 | 3,627,907 |
from niworkflows.interfaces import SimpleBeforeAfter
from niworkflows.interfaces.fixes import FixHeaderApplyTransforms as ApplyTransforms
from niworkflows.interfaces.images import extract_wm
def init_sdc_unwarp_report_wf(name='sdc_unwarp_report_wf', forcedsyn=False):
"""
Save a reportlet showing how SDC unwar... | 097d576e3df8f3c11aade2b00362ba14ce4ec32a | 3,627,908 |
def maxabs_normalization(X, *Xtest):
"""Scale features in the [-1, 1] range.
Linearly normalize each input feature in the [-1, 1] range by
dividing them by the maximum absolute value. Test features, when
given, are scaled using the statistics computed on X.
Parameters
----------
X : ndarr... | f73e689d97cb5aea59dd7340375c95c00dae4843 | 3,627,909 |
def authenticate_user(email, password):
"""Authenticate user by checking they exist and that the password is correct."""
user = get_user(email)
if not user:
return False
"""If present, verify password against password hash in database."""
password_hash = user.hashed_password
if not ver... | 307cc1b8fcb1b00d437a573f174e4b7a63bcde80 | 3,627,910 |
import os
import re
def new_files(filetype):
"""
Find new files to download from the Census' FTP webpage.
Parameters:
filetype (character): The type of file you want to search for (.txt, .zip, ect.)
Returns (list): List of files not found in local directory
"""
pattern = pub_filename... | e2ef5997629f4a05838daf3e368fd08b123922d2 | 3,627,911 |
def positive_integer(v):
""" Is arg a positive integer? """
return integer(v) and positive(v) | 553f79b2b0991b0f9fcfbaec01d715c3f46fe9d2 | 3,627,912 |
def precipitation():
"""Get the date and corresponding precipitation level or a 404 if not."""
# Query all dates
query_date = dt.date(2017, 8, 23) - dt.timedelta(days=365)
sel = [Measurement.date, Measurement.prcp]
last_twelve_months = session.query(*sel).\
filter(Measurement.date > query_da... | 9bf72cb3f5ab0f2fc8e53fbfa6b2a5241ba2d374 | 3,627,913 |
def alias_setup(probs):
"""
Build tables for the alias sampling
:param probs: the probability distribution to build alias table
Returns
-------
alias table and probability table for probs
"""
K = len(probs)
q = np.zeros(K)
J = np.zeros(K, dtype=np.int)
smaller = list()
larger = list()
for k... | bc053c4fe35571a2cc2ca31230f3fa2293ad69b1 | 3,627,914 |
def sv_variant(institute_id, case_name, variant_id):
"""Display a specific structural variant."""
data = controllers.sv_variant(store, institute_id, case_name, variant_id)
return data | 4e837d7e71173e800e9b47e564ae554615838410 | 3,627,915 |
import torch
def box_yxyx_to_cxcywh(x):
""" Converts bounding box with format [y0, x0, y1, x1] to format [center_x, center_y, w, h] """
y0, x0, y1, x1 = torch.split(x, 1, dim=-1)
b = [
(x0 + x1) / 2,
(y0 + y1) / 2,
x1 - x0,
y1 - y0
]
return torch.cat(b, dim=-1) | 631e5015d6d74fab6cd334ee0db32242e0462cb6 | 3,627,916 |
from collections import defaultdict
def deserialize_attributes(data, sep, original_class=None, original_pk=None):
"""
Deserialize the attributes from the format internally stored in the DB
to the actual format (dictionaries, lists, integers, ...
:param data: must be a dictionary of dictionaries. In t... | 21fb26c20bb1b265eb7380ebf0f7536b928b9db7 | 3,627,917 |
from typing import Union
from typing import Dict
from typing import Optional
def get_config_float(
current: Union[int, float], config: Dict[str, str], name: str
) -> Optional[float]:
"""
Convenience function to get config values as float.
:param current: current config value to use when one is not pr... | d2bb436c4b2b4aef35a8f46927bc9145ecfed04c | 3,627,918 |
import argparse
def getargs():
""" Parse program arguments.
"""
parser = argparse.ArgumentParser(
description=DESCRIPTION,
formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('ori_lst', type=str,
help='original image list')
parser.add_argumen... | a84b53ebdb54e9170c4b87fd7cda85f47691c4a2 | 3,627,919 |
import os
import io
import json
def _collect_finish_info(container_dir):
"""Read exitinfo, aborted, oom and terminated files to check how container
finished.
:returns ``(exitinfo, aborted, oom, terminated)``:
Returns a tuple of exitinfo, a ``(service_name,return_code,signal)`` if
present ... | 7084bbb7cfd36d17b7db2a91ce4edcd313fb7d89 | 3,627,920 |
def getRatingDistributionOfAMovie(ratingRDD, movieID):
""" Get the rating distribution of a specific movie
Args:
ratingRDD: a RDD containing tuples of (UserID, MovieID, Rating)
movieID: the ID of a specific movie
Returns:
[(rating score, number of this rating score)]
"""
retu... | 708c67e51d318b887deea1ec3ec4dc4a272e794e | 3,627,921 |
import math
def decode_fsw(fsw_array):
"""
Parse the array into specific faultgroups
"""
faultGroup = [0] * NUM_OF_FAULTGROUPS;
faultGroup[FAULTGROUP_TRANSIENT] = 0
faultGroup[FAULTGROUP_CRITICAL] = (fsw_array[FSW_CRITICAL_FAULTS_INDEX] & FSW_CRITICAL_FAULTS_MASK) >> FSW_CRITIC... | 421dfea23813e73d12918f361063614d3cbf33a8 | 3,627,922 |
def lower_allbutfirst_letter(mystring):
"""Lowercase all letters except the first one
"""
return mystring[0].upper() + mystring[1:].lower() | 860d1449865790e15ccc840ee85ea366b2de5a64 | 3,627,923 |
def get_world_size():
"""Replace linklink.get_world_size"""
try:
world_size = get_world_size_from_env()
if world_size is not None:
return world_size
else:
# return link.get_world_size()
return dist.get_world_size()
except Exception as e: # noqa
... | 2e308370e42d9bc847488efb8c17e46344060839 | 3,627,924 |
def orginal(S,R,RT,nNodes=20550):
"""
This function is used to calculate the reconstructed data from reduced variables using POD.
This function is used to deal with flow past cylinder data.
Parameters
----------
S : array
The array contains total data that combine two features as a col... | 1fa4bd17afdc83d8209cd1b97082594d89382d98 | 3,627,925 |
import random
def strtest(aString):
"""this function takes the string and returns the string in a random order"""
newstring = random.sample(aString, len(aString))
newstring = "".join(newstring)
return(newstring) | 28bb6ed6b9f3a10ea19fbebb8ef60091123b0fd5 | 3,627,926 |
import urllib
def build_url(base_url=DEFAULT_BASE_URL, command=None):
"""Append a command (if it exists) to a base URL.
Args:
base_url (str): Ignore unless you need to specify a custom domain,
port or version to connect to the CyREST API. Default is http://127.0.0.1:1234
and t... | 5dc322f459bdf8d4f58ab7c8da78dbcf40e2696f | 3,627,927 |
from typing import Optional
def get_first_bonding_box(boxes: BoundingBoxes) -> Optional[BoundingBox]:
"""
Get the first bounding box that belongs to the trash class.
:param boxes: the list of detected bounding boxes
:return: the first box that belongs to the trash class. If no valid box can be found... | 3c9244983af82287f6044579d813ea792c53f7cb | 3,627,928 |
def svn_diff_contains_diffs(*args):
"""svn_diff_contains_diffs(svn_diff_t diff) -> svn_boolean_t"""
return _diff.svn_diff_contains_diffs(*args) | 76a47b063dcf14088bb05d46fb1d8cf3346c5401 | 3,627,929 |
def init_shared_manager(items):
"""Initialize and start shared manager."""
for cls in items:
proxy = create_proxy(cls)
SyncManager.register(cls.__name__, cls, proxy)
manager = SyncManager()
manager.start()
return manager | 62a4ce5b2bf5eb1b178104ced772ec08ad9778c9 | 3,627,930 |
def cnn2d(image: np.ndarray,
filters: np.ndarray):
"""
Vanilla convolutions.
Args:
image: (hi, wi, cin).
filters: (hf, wf, cin, cout).
Returns:
(hi, wi, cout)
"""
filter_len, image_padded = pad_image(filters, image)
out = np.zeros([image.shape[0], image.s... | 5b3710736912fe0d7ee6b815fd8fa2e7cac013a4 | 3,627,931 |
def mongo_uses_error_check(store):
"""
Does mongo use the error check as a separate message?
"""
if hasattr(store, 'modulestores'):
return any(mongo_uses_error_check(substore) for substore in store.modulestores)
return False | 52d4a5135531ff18b0e19ac7aa91a453a2e736f1 | 3,627,932 |
def bootstrap_consensus(msa, times, tree_constructor, consensus):
"""Consensus tree of a series of bootstrap trees for a multiple sequence alignment.
:Parameters:
msa : MultipleSeqAlignment
Multiple sequence alignment to generate replicates.
times : int
Number of bootstr... | ee5aa0f4a2457a55ad9b975606c39a88f721d0cc | 3,627,933 |
def get_snapshot_seconds():
"""Returns the amount of time in seconds between snapshots of a
fuzzer's corpus during an experiment."""
return environment.get('SNAPSHOT_PERIOD', DEFAULT_SNAPSHOT_SECONDS) | fc6d1d940b64c69e202ba2e8ac32d45681c24c19 | 3,627,934 |
import random
import re
import collections
def realize_question(dialog, template, filter_objs):
"""Samples attributes for template using filtered objects.
In addition, creates scene graph for the new information added.
Args:
scene: Current scene graph
template: Text template to use to generate questio... | 512c92025ee6ac0b93ac49be9a3957df9b8f241e | 3,627,935 |
def coroutine(func):
"""
_coroutine_
Decorator method used to prime coroutines
"""
def start(*args,**kwargs):
cr = func(*args,**kwargs)
next(cr)
return cr
return start | f096958d45cb391e0f12e5bfd162e5250085bb52 | 3,627,936 |
import os
import csv
def getCountry(isoFile, tzdir, verbose):
"""Get the dictionary containing the iso3166 country code to name conversion
Args:
isoFile (string): file name of the iso3166.tab file
tzdir (string): path holding the zoneFile
verbose (string): verbosity level
Returns... | ce1f7aca4e4f4bf5f9e7515b5f99cd7cce189645 | 3,627,937 |
from typing import Union
from typing import Optional
from typing import Tuple
def image_to_tensor(
image: Union[PILImage, np.ndarray, str],
roi: Optional[Rect] = None,
output_size: Optional[Tuple[int, int]] = None,
keep_aspect_ratio: bool = False,
output_range: Tuple[float, float] = (0., 1.),
... | cadbe61514321c2bac9ba3d96d2f3243fdfcc9b0 | 3,627,938 |
from io import StringIO
import sys
def get_policy_map(policy, world_shape, mode='human'):
"""
Generates a visualization grid from the policy to be able to print which action is most likely from every state
"""
unicode_arrows = np.array([u'\u2191', u'\u2192', u'\u2193', u'\u2190' # up, right, down, lef... | 5db1f6a97cca7d90d709e8a2bcdf655e4d5ecfb1 | 3,627,939 |
def _setup_request(bucket_acl=None, object_acl=None):
"""
add a foo key, and specified key and bucket acls to
a (new or existing) bucket.
"""
bucket = _create_keys(keys=['foo'])
key = bucket.get_key('foo')
if bucket_acl is not None:
bucket.set_acl(bucket_acl)
if object_acl is no... | be9d09c6ddadaa6a55d84e3e8385bf46aa06efc9 | 3,627,940 |
def _some_lt(t1: 'Tensor', t2: 'Tensor', only_value: bool) -> bool:
"""
:param t1:
:param t2:
:param only_value:
:return:
"""
res = np.sum(t1.data < t2.data)
if only_value:
if res > 0:
return True
else:
return False
else:
raise NotIm... | 8b816eeb57a41611275c7dc2f4d018134e387a01 | 3,627,941 |
from typing import Optional
def get_folders(parent_id: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetFoldersResult:
"""
Retrieve information about a set of folders based on a parent ID. See the
[REST API](https://cloud.google.com/resource-manager/referen... | e507c2d36b20997859db55bce9a7f555d6ac122f | 3,627,942 |
def bedLine(chrom, chromStart, chromEnd, name, score=None, strand=None,
thickStart=None, thickEnd=None, itemRgb=None, blockCount=None,
blockSizes=None, blockStarts=None):
""" Give the fields, create a bed line string
"""
s = ('%s %d %d %s'
% (chrom, chromStart, chromEnd, name))
i... | dd294d5d31ea3a2f7beb8a11a7ec705eb10cf1a4 | 3,627,943 |
import pickle
def tuning(sortedfile):
"""
Fit r = a0 + a1*f1.
"""
# Load sorted trials
with open(sortedfile) as f:
t, sorted_trials = pickle.load(f)
# Get f1s
f1s = sorted(sorted_trials.keys())
# Active units
units = get_active_units(sorted_trials)
units = range(next... | 1c5c71c8ef2ce04088f164befb619ccb03eb2079 | 3,627,944 |
def balance_conversion_constraint_rule(backend_model, loc_tech, timestep):
"""
Balance energy carrier consumption and production
.. container:: scrolling-wrapper
.. math::
-1 * \\boldsymbol{carrier_{con}}(loc::tech::carrier, timestep)
\\times \\eta_{energy}(loc::tech, time... | b10fa6203eb8ae0dc5054a98bce2d4ed4412a586 | 3,627,945 |
def follow(id):
"""Follow a user"""
user = token_auth.current_user()
followed_user = db.session.get(User, id) or abort(404)
if user.is_following(followed_user):
abort(409)
user.follow(followed_user)
db.session.commit()
return {} | e88f1968f41f819bae4baecab006889f2d42eb0d | 3,627,946 |
def get_rules():
"""
Get the virtual server rules
CLI Example:
.. code-block:: bash
salt '*' lvs.get_rules
"""
cmd = "{} -S -n".format(__detect_os())
ret = __salt__["cmd.run"](cmd, python_shell=False)
return ret | 76d7e4fcb1e2fc30769011fa110cc8c98532a5ba | 3,627,947 |
def all_user_tickets(uid, conference):
"""
Cache-friendly version of user_tickets: returns a list of
(ticket_id, fare_type, fare_code, complete)
for each ticket associated to the user.
"""
qs = _user_ticket(User.objects.get(id=uid), conference)
output = []
for t in qs:
output... | 9fedff351ce896dfe6a431813c60ba7b68b4dff5 | 3,627,948 |
from typing import List
def get_titles(url: str = URL) -> List[str]:
"""List titles in feed."""
articles = _feed(url).entries
return [a.title for a in articles] | 325d431fdb350188077156e6a9541c21ce73986a | 3,627,949 |
def fatorial(num):
"""
Calcula a fatorial
:param num:
:return:
"""
fat = 1
if num == 0:
return fat
for i in range(1,num+1,1):
fat *= i # fat = fat * i
return fat | 181ea2bde3acef3f6ff4311054fb209edfad6160 | 3,627,950 |
def indent_code(*code, indent: int = 1) -> str:
"""Indent multiple lines (`*code`) by the given amount, then join on newlines."""
return "\n".join(indent_str(line, indent, end="") for line in code) + "\n" | d78fac12e726638321799142cbd68b326ebc02f0 | 3,627,951 |
import torch
def evaluate_accuracy_gpu(net, data_iter, device=None):
"""使用GPU计算模型在数据集上的精度。
Defined in :numref:`sec_lenet`"""
if isinstance(net, nn.Module):
net.eval() # 设置为评估模式
if not device:
device = next(iter(net.parameters())).device
# 正确预测的数量,总预测的数量
metric = d2l.A... | 84d78795e541b5d60c8338356952c47786a35722 | 3,627,952 |
def get_rdns_from_ip(ip):
"""Basic get RDNS via gethostbyaddr.
:param ip: IP address to lookup
:type ip: str
:return: Returns `hostname` if found, or empty string '' otherwise
:rtype: str
"""
try:
coro = resolver.gethostbyaddr(ip)
result = loop.run_until_complete(coro)
... | bf7927d97767d7ca6091a2318a8dc879ec2cda01 | 3,627,953 |
def GePacketOut(egress_port, mcast, padding):
""" Generate packet_out packet with bytearray format """
out1 = "{0:09b}".format(egress_port)
out2 = "{0:016b}".format(mcast)
out3 = "{0:07b}".format(padding)
out = out1+out2+out3
a = bytearray([int(out[0:8],2),int(out[8:16],2),int(out[16:24],2),int... | c56abb84ec067cf8abb8e69d82c1342c4f20e0e9 | 3,627,954 |
def damage_per_max_ammo(weapon_dic: dict, damage_range_arr: np.ndarray) -> np.ndarray:
"""
Calculate the damage per max ammo at varying distances.
This assumes you were to fire all ammo in the gun and in reserve at a set distance.
Parameters
----------
weapon_dic : dict
Dict of specifi... | 8724a1bbe408a58399e6547a63b3e80c5ecf7eda | 3,627,955 |
import requests
from bs4 import BeautifulSoup
import warnings
def get_PDB_summary(PDB_id, verbose=False):
"""
Similar info to get_meta, but for a PDB entry - returns info about when it was regitered etc.
Parameters
----------
PDB_id :
verbose : Bool, optional, default: False
Flag t... | 0fb0c1a2623656c0dc18067b3f52f7ee67d303a0 | 3,627,956 |
import os
import shutil
def copy_dir(src: str, dest: str) -> bool:
"""Recursively copy a directory.
Args:
src: The source directory.
dest: The destination directory.
Returns:
Indicate if the copy was success or not.
"""
if os.path.exists(dest):
shutil.rmtree(dest... | a8969138fc1c042a9ea7da8f3e452ced4d8168b2 | 3,627,957 |
import requests
import json
def distance_from_user(beer):
"""
This method is used to calculate distace from user to each store that carry
specific beer that user seached for and return list of store, beer and distance from user to
those stores sorted by distance
"""
# user_lat = 40.8200471
... | 67b0de0751a2dfd2f440bcb0595c31be3c644026 | 3,627,958 |
from mesh.Triangulation import TrivialSystem, ComposedSystem, State
def meshes2system(meshes):
"""
recursively generate system.
"""
firstKey = list(meshes.keys())[0]
mm = meshes[firstKey]
state = State(translation=mm['translate'],
rotation=mm['rotate'],
velo... | 7a6dc5a7f41735a37e54f6444148141085d9fece | 3,627,959 |
def cmp_public_numbers(pn1, pn2):
"""
Compare 2 sets of public numbers. These is a way to compare
2 public RSA keys. If the sets are the same then the keys are the same.
:param pn1: The set of values belonging to the 1st key
:param pn2: The set of values belonging to the 2nd key
:return: True i... | a91a7204412d07808dbd6d5040f6df8baa576417 | 3,627,960 |
import os
def authenticate():
"""Shows basic usage of the Gmail API.
Lists the user's Gmail labels.
"""
creds = None
# The file token.json stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.... | f99305aa81033310fb078b1531bfcc5770947add | 3,627,961 |
def phred(vals):
""" apply the phred scale to the vals provided """
return -10*np.log10(1-vals)
return -10*np.ma.log10(1-vals).filled(-3) | c09b38a5f736ddef994ea1eff8f0cc614362f3d3 | 3,627,962 |
def __get_useconds_of(stage_idx, block_idx, event_acc, wanted, block_prefix=''):
"""
gets useconds of chan/kernel of specific stage_idx & block_idx, from tensorboard event_acc
:param wanted: 'chan' or 'kernel'
"""
useconds = []
summary_prefix = block_prefix + 'use_%s_' % wanted
idx = 0
... | 1fed126224649e368694d63013643cf2fb5f4aaa | 3,627,963 |
def create_menu(*args):
"""
create_menu(name, label, menupath=None) -> bool
Create a menu with the given name, label and optional position, either
in the menubar, or as a submenu. If 'menupath' is non-NULL, it
provides information about where the menu should be positioned. First,
IDA will try and resolve ... | 0c3cb60c1193b422b11ca1ac92f7124f05086a69 | 3,627,964 |
def parse_proxy_url(purl):
"""Adapted from UStreamTV plugin (ustreamtv.py)"""
proxy_options = {}
if purl:
p = urlparse(purl)
proxy_options['proxy_type'] = p.scheme
proxy_options['http_proxy_host'] = p.hostname
if p.port:
proxy_options['http_proxy_port'] = p.port
... | 94b903cc3199b34c61f0b86c16a75bd503f13325 | 3,627,965 |
def cma(data):
"""
Cumulative Moving Average
:type data: np.ndarray
:rtype: np.ndarray
"""
size = len(data)
out = np.array([np.nan] * size)
last_sum = np.array([np.nan] * size)
last_sum[1] = sum(data[:2])
for i in range(2, size):
last_sum[i] = last_sum[i - 1] + data[i]
... | caeb4d7b30d8cc5a079532aac817bbc49ef85746 | 3,627,966 |
from pycalphad import __version__ as pycalphad_version
from typing import OrderedDict
def starting_point(conditions, state_variables, phase_records, grid):
"""
Find a starting point for the solution using a sample of the system energy surface.
Parameters
----------
conditions : OrderedDict
... | 59537ea36fa7b73e250ccbcc660f1363213109bc | 3,627,967 |
def intersects(a0, a1, b0, b1):
"""
Checks whether two line segments, each defined by two end points, will intersect.
"""
# First line is vertical
if a0[0] == a1[0]:
# Both lines are vertical
if b0[0] == b1[0]:
return (a0[0] == b0[0]) and (in_range(b0[1], a0[1], a1[1]) or... | 626a682e24358243faa43c18fefec2c7c874f10d | 3,627,968 |
def getAccident(id=None):
""" return the Accident object or None if not exist
return a list of all Accident if no id passed.
return one object if filtered by 'id'"""
if id:
return Accident.query.get(id)
return Accident.query.all() | 798b4cb51d7d15400b376ca13b77c17bb0da9568 | 3,627,969 |
def ranges(int_list):
"""
Given a sorted list of integers function will return
an array of strings that represent the ranges
"""
begin = 0
end = 0
ranges = []
for i in int_list:
# At the start of iteration set the value of
# `begin` and `end` to equal the first element
... | cc6aab9442a6f6986acccb1fa46cd61ff1e4ba07 | 3,627,970 |
def format_data(x_data=None,y_data=None):
"""
=============================================================================
Function converts a list of separate x and y coordinates to a format suitable
for plotting in ReportLab
Arguments:
x_data - a list of x coordinates (or any object that can be indexe... | 34ac418f38194644f9372f20d47535424c7bfb52 | 3,627,971 |
import math
def gaslib_to_network_data(network_file, scenario_file, contract_aux_elements=True, debug=False):
"""Read a gaslib instance from files and create network data.
The function returns data that can be passed immediatley to the
constructor of Network.
Parameters
----------
networ... | 3979d4345eb01f8fc49ade176e8b2303f98b8c72 | 3,627,972 |
import json
import os
import sys
def write_plugins_index(file_name, plugins):
"""
Writes the list of (name, version, description) of the plugins given
into the index file in JSON format.
Returns True if the file was actually updated, or False if it was already
up-to-date.
"""
# separators ... | 52d110bb0e90c661f95b144fa95d6143d7e719a7 | 3,627,973 |
from typing import List
from typing import Counter
def explicit_endorsements(user: domain.User) -> List[domain.Category]:
"""
Load endorsed categories for a user.
These are endorsements (including auto-endorsements) that have been
explicitly commemorated.
Parameters
----------
user : :cl... | 1e70415443a6f9a0bd27a8e2bbac3998dab090b5 | 3,627,974 |
def detec_apache_root(binPath):
"""
根据apachectl -V 获得apache的安装路径
"""
result = commands.getoutput(binPath + """ -V | grep -i "HTTPD_ROOT"
| awk -F '[="]' '{print $3}'""")
return result | dfa07a0311dbc3cc9ee74425c103ed94d768da83 | 3,627,975 |
def hindu_zodiac(tee):
"""Return the zodiacal sign of the sun, as integer in range 1..12,
at moment tee."""
return quotient(float(hindu_solar_longitude(tee)), deg(30)) + 1 | 87c293c20ee0880ac844e27000e2f8f774b2bbb1 | 3,627,976 |
def SearchRelativeLongitude(body, targetRelLon, startTime):
"""Searches for when the Earth and another planet are separated by a certain ecliptic longitude.
Searches for the time when the Earth and another planet are separated by a specified angle
in ecliptic longitude, as seen from the Sun.
A relativ... | effce7c99297e183182b8142e0dc037bb9c924da | 3,627,977 |
import time
def _fitFunc2(x, *pfit, verbose=True, follow=[], errs=None):
"""
for curve_fit
"""
global pfitKeys, pfix, _func, Ncalls, verboseTime
Ncalls +=1
params = {}
# -- build dic from parameters to fit and their values:
for i,k in enumerate(pfitKeys):
params[k]=pfit[i]
... | 1f61a3746761d47ffa43dcfdb370b756df9733b8 | 3,627,978 |
import io
import numpy
def sendForward(cwt,solver):
"""Use this function to communicate data between nodes"""
if solver.nodeMasterBool:
cwt = io.sweptWrite(cwt,solver)
buff = numpy.copy(solver.sharedArray[:,:,-solver.splitx:,:])
buffer = solver.clusterComm.Sendrecv(sendobj=buff,dest=so... | b47c1a2db202a2bfead6f76e2e2c8b9eb03dc50a | 3,627,979 |
import re
def get_parameters(img_path_complete):
"""
Get the parameters of an hyper-spectral image from file.
:param img_path_complete: complete path of the bil file to get the parameters. Ex. <path>/img.bil
:return: array of totals of [lines, samples, bands]
"""
file_info = img_path_complete ... | 26fb411d737b259801681fb7152d7570583df969 | 3,627,980 |
def phone_move_handler(pid):
"""
@api {post} /v1/asset/phone/move/{int:id} 流转 资产设备
@apiName MovePhone
@apiGroup 项目
@apiDescription 流转 资产设备
@apiParam {int} id
@apiParam {int} borrow_id 流转人 ID
@apiParamExample {json} Request-Example:
{
"borrow_id": 2
}
@apiSuccessExampl... | fd6e36849f9461544144bea5f60fcc8a174c54c0 | 3,627,981 |
def extractLargestRegion(actor):
"""Keep only the largest connected part of a mesh and discard all the smaller pieces.
.. hint:: |largestregion.py|_
"""
conn = vtk.vtkConnectivityFilter()
conn.SetExtractionModeToLargestRegion()
conn.ScalarConnectivityOff()
poly = actor.GetMapper().GetInput(... | d481cdd5975eb9c8d7e835d24c49deb9a0a5961a | 3,627,982 |
import zlib
def query_stock_concept(code="", date=""):
"""获取概念分类
@param code:股票代码,默认为空。
@param date:查询日期,默认为空。不为空时,格式 XXXX-XX-XX。
"""
data = rs.ResultData()
if code is None or code == "":
code = ""
if code != "" and code is not None:
if len(code) != cons.STOCK_CODE_LENGTH:... | 4ca53f065564fd78855e94a89d43f4590c51e89a | 3,627,983 |
def checkForVideoRetainment(op, graph, frm, to):
"""
Confirm video channel is retained in the resulting media file.
:param op:
:param graph:
:param frm:
:param to:
:return:
@type op: Operation
@type graph: ImageGraph
@type frm: str
... | d04296adc58611798007066e26cf1a784949520c | 3,627,984 |
def get_console_scripts(entry_points):
"""pygradle's 'entrypoints' are misnamed: they really mean 'consolescripts'"""
if not entry_points:
return None
if isinstance(entry_points, dict):
return entry_points.get("console_scripts")
if isinstance(entry_points, list):
result = []
... | 4ca1f6bb50959570c1c6d28312aabb939fe9daf8 | 3,627,985 |
def create_deepcopied_groupby_dict(orig_df, obs_id_col):
"""
Will create a dictionary where each key corresponds to a unique value in
`orig_df[obs_id_col]` and each value corresponds to all of the rows of
`orig_df` where `orig_df[obs_id_col] == key`.
Parameters
----------
orig_df : pandas D... | 5af41d6410adf643ccd7f5f2072a7e6539609ccb | 3,627,986 |
from typing import Optional
def _create_configuration(
user_agent: Optional[str] = None,
user_agent_config_yaml: Optional[str] = None,
user_agent_lookup: Optional[str] = None,
hdx_url: Optional[str] = None,
hdx_site: Optional[str] = None,
hdx_read_only: bool = False,
hdx_key: Optional[str]... | 4ef7a985b8507e3e710a0465101d5db01c1329ed | 3,627,987 |
import os,sys
def import_path(fullpath):
"""
Import a file with full path specification. Allows one to
import from anywhere, something __import__ does not do.
"""
path, filename = os.path.split(fullpath)
filename, ext = os.path.splitext(filename)
sys.path.append(path)
module = __impo... | e9cb5365434f9fa82c121fbeb7a264f703fb86f8 | 3,627,988 |
def batch_autocorr(data, lag, starts, ends, threshold, backoffset=0):
"""
Calculate autocorrelation for batch (many time series at once)
:param data: Time series, shape [n_pages, n_days]
:param lag: Autocorrelation lag
:param starts: Start index for each series
:param ends: End index for each se... | 8c6b9cdb3a62a4e8d1bd613414bda54f3fa75c9a | 3,627,989 |
import yaml
def merge_yaml(y1, y2):
""" Merge two yaml HOT into one
The parameters, resources and outputs sections are merged.
:param y1: the first yaml
:param y2: the second yaml
:return y: merged yaml
"""
d1 = yaml.load(y1)
d2 = yaml.load(y2)
for key in ('parameters', 'resource... | 08351fcbd6ba5d5350b166224a33d558df6c8010 | 3,627,990 |
def infix(token_list):
"""
Parses Infix notation and returns the equivilant RPN form (Pseudocode used from: https://en.wikipedia.org/wiki/Shunting-yard_algorithm)
Parameters
==========
token_list : list
The list of infix tokens
Returns
--------
output : list
This is t... | 97fc5c75b173aeed42c9383625037374caddf261 | 3,627,991 |
import os
def download(isamAppliance, filename, id=None, comment=None, check_mode=False, force=False):
"""
Download one snapshot file to a zip file.
Multiple file download is now supported. Simply pass a list of id.
For backwards compatibility the id parameter and old behaviour is checked at the begin... | 0e58fa59515b8b7f943f5b7e17d5daaa810251e9 | 3,627,992 |
from typing import Union
from typing import Tuple
from typing import Dict
def pre_process_steps(
draw, return_kwargs: bool = False
) -> Union[
st.SearchStrategy[pre_process_step_pb2.PreProcessStep],
st.SearchStrategy[Tuple[pre_process_step_pb2.PreProcessStep, Dict]],
]:
"""Returns a SearchStrategy for... | d13cf4343abd670ffd0be4ec83db36483fd761ee | 3,627,993 |
def _decode(hdf5_handle):
"""
Construct the object stored at the given HDF5 location.
"""
if 'symmetries' in hdf5_handle:
return _decode_symgroup(hdf5_handle)
elif 'rotation_matrix' in hdf5_handle:
return _decode_symop(hdf5_handle)
elif 'matrix' in hdf5_handle:
return _de... | ea9420799b8abe435ce7d5d98dd156356d790e1f | 3,627,994 |
def r_network():
"""Loads network from the R library tmlenet for comparison"""
df = pd.read_csv("tests/tmlenet_r_data.csv")
df['IDs'] = df['IDs'].str[1:].astype(int)
df['NETID_split'] = df['Net_str'].str.split()
G = nx.DiGraph()
G.add_nodes_from(df['IDs'])
for i, c in zip(df['IDs'], df['NE... | 5dc728cef2118c981b78da29e73308fbc8ce8cab | 3,627,995 |
def _legend_with_triplot_fix(ax: plt.Axes, **kwargs):
"""Add legend for triplot with fix that avoids duplicate labels.
Parameters
----------
ax : matplotlib.axes.Axes
Matplotlib axes to apply legend to.
**kwargs
These parameters are passed to :func:`matplotlib.pyplot.legend`.
R... | 565fb3937aa0d1deb8f07d0f632354135282389c | 3,627,996 |
from typing import Dict
from typing import Any
def gjson_from_tasks(tasks: Dict[TileIdx_txy, Any],
grid_info: Dict[TileIdx_xy, Any]) -> Dict[str, Dict[str, Any]]:
"""
Group tasks by time period and compute geosjon describing every tile covered by each time period.
Returns time_period... | bb82ec50d79e7425db83ce6b55b7a089b0456cec | 3,627,997 |
import logging
def getLogLevelNumber(loglevelname):
"""Parses log level name into log level number.
Returns int value of log level. On failure, DEBUG level value is returned."""
number = getattr(logging, loglevelname, None)
if not isinstance(number, int):
module_logger.debug("failed to par... | 61eb798cd760437249a8dfc5b0bfd8b0397ff7f7 | 3,627,998 |
def arcz_to_arcs(arcz):
"""Convert a compact textual representation of arcs to a list of pairs.
The text has space-separated pairs of letters. Period is -1, 1-9 are
1-9, A-Z are 10 through 36. The resulting list is sorted regardless of
the order of the input pairs.
".1 12 2." --> [(-1,1), (1,2),... | 80f37daaa57f7b7ae1a89385a22df8e17c3bf46a | 3,627,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.