content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def fire_weather_index(isi, bui):
"""Fire weather index.
Parameters
----------
isi : array
Initial spread index
bui : array
Build up index.
Returns
-------
array
Build up index.
"""
fwi = np.where(
bui <= 80.0,
0.1 * isi * (0.626 * bui ** 0.809... | 50,800 |
def read_file(filename: str) -> Optional[str]:
"""
Read a common file and return its content.
Returns
-------
content
The file content
"""
try:
with open(filename, 'r') as f:
content = f.read
return content
except IOError as e:
logging.error(f... | 50,801 |
def power(b, e):
"""
@purpose: Using a binary list to calculate power of two integers
@param:
b: The base number
e: The exponent
@precondition: A valid positive base and exponent are input
@postcondition: The power of b^e is print out
@Complexity:
Best Case: O(1) if expon... | 50,802 |
def test_querying_exchange_rates(rotkehlchen_api_server):
"""Make sure that querying exchange rates works also without logging in"""
# Test with empty list of currencies
data = {'currencies': []}
response = requests.get(
api_url_for(rotkehlchen_api_server, 'exchangeratesresource'), json=data,
... | 50,803 |
def get_all_items():
"""Get all items"""
items = Item.query.all()
items_list = []
for item in items:
item_object = {
'id': item.id,
'subject': item.subject,
'status' : item.status,
'url': item.url,
'requestor': item.requestor,
... | 50,804 |
def usergenerator(no1, no2, no3, no4, mode):
"""
生成中文拼音和随机字母组成的用户名
:param no1 表示声母:
:param no2 表示韵母:
:param no3 表示第一位随机字母:
:param no4 表示第二位随机字母:
:param mode 选择姓名的次序:
:return 返回用户名:
"""
list1 = ['b', 'p', 'm', 'f', 'd',
't', 'n', 'l', 'g', 'k',
'h', 'j... | 50,805 |
def list_permissions(CertificateAuthorityArn=None, NextToken=None, MaxResults=None):
"""
Lists all the permissions, if any, that have been assigned by a private CA. Permissions can be granted with the CreatePermission action and revoked with the DeletePermission action.
See also: AWS API Documentation
... | 50,806 |
def verify_input(json_data):
"""
Verifies the validity of an API request content
:param json_data: Parsed JSON accepted from API call
:type json_data: dict
:return: Data for the the process function
"""
# callback_uri is needed to sent the responses to
if 'callback_uri' not in json_dat... | 50,807 |
def detail_slug_dct(slug):
"""
Function to localize Slug's detail properties.
:param slug: model Slug
:return: dictionary with Slug's detail properties localized
"""
return _detail_slug_form.fill_with_model(slug) | 50,808 |
def is_myst_available():
"""Whether the myst-parser package is available."""
if myst_parser is None:
return False
major, minor = myst_parser.__version__.split(".")[:2]
if int(major) < 1 and int(minor) < 8:
warnings.warn("The installed myst-parser version is less than the required 0.8")
... | 50,809 |
def CreateTrimmedSurface(trimSource, surfaceSource, multiple=False):
"""
Constructs a Brep using the trimming information of a brep face and a surface.
Surface must be roughly the same shape and in the same location as the trimming brep face.
Args:
trimSource (BrepFace): BrepFace which contains... | 50,810 |
def limits_exceeded():
"""
Check to see if we are about to exceed the maximum recursion depth. Also check to
see if emulation is taking too long (if needed).
"""
# Check to see if we are approaching the recursion limit.
level = len(getouterframes(currentframe(1)))
recursion_exceeded = (lev... | 50,811 |
def test_ADDRA():
"""
ADDRA Adds the value of a memory location to the Accumulator.
Program bytes used : 2
Status flags affected: Zero, Carry
"""
test_program = [9, 3, 0, 1]
vm = Digirule()
vm.load_program(test_program)
vm._acc = 0xFF
vm_hash = get_vm_hash_after_exec(test_... | 50,812 |
def formatdatetime(datatimes):
"""
格式化日期时间为指定格式
:param datatimes: 数据库中存储的datetime日期时间,也可以是字符串形式(2021-09-23 11:22:03.1232000)
:return: 格式化后的日期时间如:2021-09-23 11:22:03
"""
if datatimes:
try:
if isinstance(datatimes, str):
if "." in datatimes:
... | 50,813 |
def combination_sum() -> None:
"""39# Combination Sum."""
from leetcode.combination_sum import Solution
candidates, target = [2, 3, 6, 7], 7
print(f' Input: candidates = {candidates}, target = {target}')
s = Solution()
x = s.combinationSum(candidates, target)
print(f' Output: {x}') | 50,814 |
def space_tle(*argv):
"""TLE Database from Space-Track and Celestrak websites
Usage:
space-tle get <selector>...
space-tle find <text> ...
space-tle history [--last <nb>] <selector>...
space-tle stats [--graph]
space-tle dump [--all]
space-tle insert (-|<file>...)
spac... | 50,815 |
def register_extensions(app):
"""Register extensions"""
bootstrap.init_app(app)
db.init_app(app)
mail.init_app(app) | 50,816 |
async def test_device_config(wallmote_central_scene):
"""Test a device config."""
node: node_pkg.Node = wallmote_central_scene
device_config = node.device_config
assert device_config.is_embedded
assert device_config.filename == (
"/usr/src/app/node_modules/@zwave-js/config/config/devices/0x... | 50,817 |
def get_difference(stocks: pd.DataFrame) -> pd.DataFrame:
"""Calculates the gains or loss for each stock."""
stocks = stocks.astype({"closing_price": "float", "initial_value": "float"})
stocks["gain_loss"] = stocks["closing_price"] - stocks["initial_value"]
stocks["gain_loss"] = stocks["gain_loss"].ro... | 50,818 |
def random_mini_batches(X, Y, batch_size=64, seed=0):
"""
Creates a list of random minibatches from (X, Y)
Arguments:
X -- input data, of shape (number of examples, input size)
Y -- true "label" vector of shape (number of examples, number of features)
batch_size -- size of the mini-batches, int... | 50,819 |
def displaySmallMultiples(df):
"""
Function for visualizing pairs of categorical features
"""
# TODO: ADD small multiples plot | 50,820 |
def stelab(pobj: ndarray, vobs: ndarray) -> ndarray:
"""
Correct the apparent position of an object for stellar
aberration.
https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/stelab_c.html
:param pobj: Position of an object with respect to the observer.
:param vobs:
Veloc... | 50,821 |
def train(train_loader, model, args, optimizer, scheduler, epoch, device, writer=None):
"""Train for one epoch on the training set"""
# switch to train mode
model.train()
print('\nEpoch: %d' % epoch)
train_loss = 0
total = 0
correct = 0
for j, (input, target) in tqdm(enumerate(... | 50,822 |
def add_noise(input_image, noise, multiple_image_std, size=224):
"""Transformation of a single image by adding noise.
If a random gaussian distribution of noisy is specified (noise='r_normal'),
the standard deviation of the noise added is based upon the dynamic range of
the image weighed by multiple_image_std ... | 50,823 |
def test_nullpulses(fbsignal, fbsignal_nofold, ism, j1713_profile):
"""
Test pulse nulling function.
"""
# Define a pulsar
psr1 = Pulsar(1.0, 1.0, profiles=j1713_profile, name="J1713+0747")
# Test making pulses with a filterbank signal
tobs = 3.0
psr1.make_pulses(fbsignal, tobs)
dm =... | 50,824 |
def get_measures_slot(dbs: Databases, topic: str, timespan: int):
"""
Return
------
a list of measures found in the timespan
None if upper limit of the time window is reached
"""
# Fetch first doc inserted
start_timestamp = get_first_doc(dbs, topic)
# End timestamp
end_timestam... | 50,825 |
def evaluate_topic_models(data, varying_parameters, constant_parameters=None, n_max_processes=None, return_models=False,
metric=None, **metric_kwargs):
"""
Compute several Topic Models in parallel using the "gensim" package. Calculate the models using a list of varying
parameters `... | 50,826 |
def n_step_bootstrapped_returns(r_t: T, discount_t: T, v_t: T, targets: T, lambda_t: T, seq_len: int, n: int) -> T:
"""Computes strided n-step bootstrapped return targets over a sequence.
The returns are computed according to the below equation iterated `n` times:
Gₜ = rₜ₊₁ + γₜ₊₁ [(1 - λₜ₊₁) vₜ₊₁ + λₜ₊₁ Gₜ₊... | 50,827 |
def questions (category, token):
"""Contacts API and retrieves questions + answers based on category"""
# Retrieve questions and answers from API
try:
response = requests.get(f"https://opentdb.com/api.php?amount=1&category={category}&type=multiple&token={token}")
response.raise_for_status(... | 50,828 |
async def reset_clean_filter_timer(obj):
"""Reset the Clean Filter indicator timer."""
return await obj["madoka"].reset_clean_filter_timer.update(ResetCleanFilterTimerStatus()) | 50,829 |
def test_full_x_rename_half_y_full_z(init_full_x_rename_half_y_full_z, create_db_instance):
"""Test if full x half->full z is properly initialized and can fetch from its 3 parents"""
experiment = EVCBuilder().build_view_from({'name': 'full_x_rename_half_y_full_z'})
pairs = get_name_value_pairs(experiment.fe... | 50,830 |
def getFigureSpec(iteration: int, perceptual: bool):
"""
Get 2x2 Figure And Axis
Parameters
----------
iterations : int
perceptual : bool
If true, generate the axis of perceptual loss
Return
------
fig, axis : matplotlib.figure.Figure, matplotlib.axes.Axes
The plott... | 50,831 |
def ldr_vartime_blockedby_pp_hat(arr_rate, pp_mean_svctime, pp_cap, pp_cv2_svctime):
"""
Approximate unconditional variance of time blocked in ldr waiting for a pp bed.
Modeling pp as an M/G/c queue and using approximation by Whitt.
"""
pp_svcrate = 1.0 / pp_mean_svctime
vartime = qng.ggm_qwait... | 50,832 |
def identify_crossing_events(df):
"""Identifies pore crossing events in data frame of domain indices.
Given a data frame of domain indices alongside time stamps and particle IDs,
this function identifies crossing events, i.e. a particle moving from one
side of the membrane to the other THROUGH THE PORE... | 50,833 |
def timecode(acutime):
"""
Takes the time code produced by the ACU status stream and returns
a ctime.
Args:
acutime (float): The time recorded by the ACU status stream,
corresponding to the fractional day of the year
"""
sec_of_day = (acutime-1)*60*60*24
yea... | 50,834 |
def calc_timedelta_in_years(start, end) -> float:
"""Computes timedelta between start and end dates, in years
To use this function, start and end dates should come
from a series of daily frequency.
Args:
start: start date
end: end date
Returns:
float: time delta in ... | 50,835 |
def resolve_field(ctx, parent_type, source, field_asts):
"""A wrapper function for resolving the field, that catches the error
and adds it to the context's global if the error is not rethrowable."""
field_ast = field_asts[0]
field_name = field_ast.name.value
field_def = get_field_def(ctx.schema, pa... | 50,836 |
def defer_app_initialisation(app):
"""Test deferring initialising the flask app object using init_app method.
"""
api_v1 = ArrestedAPI()
api_v1.init_app(app)
assert api_v1.app == app | 50,837 |
def listen(recognizer, mic, keywords, uses_google_api):
"""
Listens for a set of (keyword, priority) tuples and returns the response
:param recognizer: speech_recognition Recognizer object
:param mic: speech_recognition Microphone object
:param keywords: Iterable of (keyword, priority) tuples
:... | 50,838 |
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Netio platform."""
from pynetio import Netio
host = config.get(CONF_HOST)
username = config.get(CONF_USERNAME)
password = config.get(CONF_PASSWORD)
port = config.get(CONF_PORT)
if not DEVICES:
hass.h... | 50,839 |
def ocs_install_verification(timeout=600, skip_osd_distribution_check=False):
"""
Perform steps necessary to verify a successful OCS installation
Args:
timeout (int): Number of seconds for timeout which will be used in the
checks used in this function.
skip_osd_distribution_chec... | 50,840 |
def ensure_devices(ctx):
"""
Check if genymotion emulator is running
"""
tprint("Start devices...")
ds = devices(ctx)
if not ds:
genymotion(ctx)
ds = devices(ctx)
if not ds:
fprint("Tried to start emulator, still no devices found. Something is wrong.")
... | 50,841 |
def imshow(inp, title=None):
"""Imshow for Tensor.
Tensor stores image as (C x H x W) in the range [0.0, 1.0].
Numpy as (C x H x W) in the range [0.0, 1.0]"""
inp = inp.numpy().transpose((1, 2, 0))
mean = np.array(mymean)
std = np.array(mystderr)
inp = std * inp + mean
inp = np.clip(in... | 50,842 |
def extract_username(message: Message) -> str:
"""
Extracts the appropriate username depending on whether
* it was mentioned in an Entity,
* it's accessible on message.author.id (discord)
* it's accessible on message.author (pyttman dev mode)
:param message:
:return: str
"""
... | 50,843 |
def application(app_plan, custom_application, request, lifecycle_hooks):
"""
Creates an application with a application plan defined in the specified fixture
"""
application = custom_application(rawobj.Application(blame(request, "limited_app"), app_plan),
hooks=lifecy... | 50,844 |
def reward_user_required(view_func):
"""
Decorator for views that checks that the user is logged in and can use
reward points.
"""
def check_user(user):
return can_reward_points_be_used_by(user)
return user_passes_test(check_user)(view_func) | 50,845 |
def dnv_registry_listing_soup(alphabetLetter, output_file_base):
"""
A method for collecting the list of ships that are in the DNV registry. From this list a list of available dnv-ids can be generated.
:param alphabetLetter: A capital letter of the alphabet
:param output_file_base: The base_name of the ... | 50,846 |
def get_cloudcare_app():
"""
Total hack function to get direct links to the cloud care application pages
"""
from corehq.apps.cloudcare import api
app = api.get_cloudcare_app(PACT_DOMAIN, PACT_CLOUD_APPNAME)
app_id = app['_id']
pact_cloudcare = [x for x in app['modules'] if x['name']['en'... | 50,847 |
async def test_internal_session(aresponses):
"""Test JSON response is handled correctly with internal session."""
aresponses.add(
MATCH_HOST,
"/api/system/status",
"GET",
aresponses.Response(
status=200,
headers={"Content-Type": "application/json"},
... | 50,848 |
def train_test_k_fold(n_folds: int, n_instances: int, rng: Generator = default_rng()) -> list:
""" Generate train and test indices at each fold.
Args:
n_folds (int): Number of folds
n_instances (int): Total number of instances
random_generator (np.random.Generator): A random generator. ... | 50,849 |
def table_append(row, category='default'):
""" Take any number of string args and put them together as a
HTML table row.
"""
html_row = '</td><td>'.join(row)
html_row = f'<tr><td>{html_row}</td></tr>'
if category == 'header':
html_row = html_row.replace('td>', 'th>')
return html_row | 50,850 |
def start(daemon: bool, debug: bool, workers: int, log_level: str):
"""
Start both server and worker on the same machine.
It starts: redis-server, site, worker_supervisor, workers
"""
# creating supervisord config
supervisor_command = 'mlcomp-worker worker-supervisor'
worker_command = 'mlco... | 50,851 |
def bookmark_show(bookmark_id_or_name):
"""
Given a single bookmark ID or bookmark name, show the bookmark details. By default,
when the format is TEXT, this will display the endpoint ID and path in
'ENDPOINT_ID:PATH' notation.
The default output is suitable for use in a subshell in another command... | 50,852 |
def before_sleep_func_accept_retry_state(fn):
"""Wrap "before_sleep" function to accept "retry_state"."""
if not six.callable(fn):
return fn
if func_takes_retry_state(fn):
return fn
@_utils.wraps(fn)
def wrapped_before_sleep_func(retry_state):
# retry_object, sleep, last_re... | 50,853 |
def _calculate_type_helper(primary_type, secondary_types):
"""
:type primary_type: :class:`mbdata.models.ReleaseGroupPrimaryType`
:type secondary_types: :class:`(mbdata.models.ReleaseGroupSecondaryType)`
"""
if primary_type.name == 'Album':
if secondary_types:
secondary_type_lis... | 50,854 |
def countDigitsInXTickLabels(adesc):
"""
This was supposed to detect when x-axis labels overlap, and reduce the
number of major ticks accordingly.
I have not gotten this to work yet, it only reads back '' as each label.
"""
xticklabels = adesc.get_xticklabels() # both of these give blank labels... | 50,855 |
def archiveName(dirName, unformatNewzbinNZB = True):
""" Extract the name of the archive from the archive's absolute path, or its .nzb file
name. Optionally remove newzbin 'msgid_99999' or 'NZB_' prefixes and the '.nzb' suffix
from a newzbin formatted .nzb filename """
from Hellanzb.PostProcessorUtil im... | 50,856 |
def detach_all_devices():
"""
Detaches all currently attached devices
"""
process = ractl.detach_all()
if process["status"]:
flash(_("Detached all SCSI devices"))
return redirect(url_for("index"))
flash(process["msg"], "error")
return redirect(url_for("index")) | 50,857 |
def basic_argument_parser(
distributed=True,
requires_config_file=True,
requires_output_dir=True,
):
""" Basic cli tool parser for Detectron2Go binaries """
parser = argparse.ArgumentParser(description="PyTorch Object Detection Training")
parser.add_argument(
"--runner",
type=str... | 50,858 |
def test_1vcpu_ht_enabled(test_microvm_with_ssh, network_config):
"""Check the CPUID for a microvm with the specified config."""
test_microvm_with_ssh.spawn()
test_microvm_with_ssh.basic_config(vcpu_count=1, ht_enabled=True)
_tap, _, _ = test_microvm_with_ssh.ssh_network_config(network_config, '1')
... | 50,859 |
def write_aims(filename, atoms):
"""Method to write FHI-aims geometry files in phonopy context."""
lines = ""
lines += "# geometry.in for FHI-aims \n"
lines += "# | generated by phonopy.FHIaims.write_aims() \n"
lattice_vector_line = "lattice_vector " + "%16.16f "*3 + "\n"
for vec in atoms.get_... | 50,860 |
def map_objects(source=None, destination=None, suffix_of_destination=None, suffix_of_source=None, keys_to_map=None):
"""
Maps an object to its destination. According to destination type it can do
a mapping to object with attributes or to a dictionary with keys.
"""
if source is None:
raise V... | 50,861 |
def test_1():
"""
"""
d = uniform(['0000', '0001', '0010', '0100', '0101', '1000', '1001', '1010'])
assert necessary_conditional_entropy(d, [0,1], [2,3]) == pytest.approx(0.68872187554086695)
assert necessary_conditional_entropy(d, [2,3], [0,1]) == pytest.approx(0.68872187554086695)
assert neces... | 50,862 |
def is_wavetable(header: bytes) -> bool:
"""Return True if Wavetable flag is set."""
# TODO: Figure out how IS_WAVETABLE and SAMPLE_PLAYBACK are linked
assert isinstance(value := _unpack(header, "IS_WAVETABLE"), bool), type(value)
if value:
assert (sample_playback := get_sample_playback(header))... | 50,863 |
def test_get_largest_z_slice() -> None:
"""
Tests `get_largest_z_slice`
"""
# An image with 2 z slices
mask = np.zeros((2, 3, 3))
# Initially there are no non-zero elements. argmax will return the lowest index
# that attains the maximum, which is 0
assert get_largest_z_slice(mask) == 0
... | 50,864 |
def md5sum(text):
"""Return the md5sum of a text string."""
return md5_constructor(text).hexdigest() | 50,865 |
def get_requests_to_user(user_id): #myrequests. Requests made to the user
"""
Returns the reviews for a listing given the listing id
"""
requests = ListingRequest.objects.filter(recipient__pk=user_id)
return requests | 50,866 |
def descriptor(request):
"""
Replies with the XML Metadata SPSSODescriptor.
"""
acs_url = saml2sp_settings.SAML2SP_ACS_URL
entity_id = _get_entity_id(request)
pubkey = xml_signing.load_cert_data(saml2sp_settings.SAML2SP_CERTIFICATE_FILE)
tv = {
'acs_url': acs_url,
'entity_id'... | 50,867 |
def type_bframe(stage, bin, data=None):
"""BFrame"""
if data == None:
return 1
if stage == 1:
return (str(data),'')
try:
v = int(data)
if 0 > v or v > 255:
raise
except:
raise PyMSError('Parameter',"Invalid BFrame value '%s', it must be a number in the range 0 to 256" % data)
return v | 50,868 |
def test_ps_s3_push_http():
""" test pushing to http endpoint s3 record format"""
if skip_push_tests:
return SkipTest("PubSub push tests don't run in teuthology")
zones, ps_zones = init_env()
bucket_name = gen_bucket_name()
topic_name = bucket_name+TOPIC_SUFFIX
# create random port for ... | 50,869 |
def last(data, ignore_nodata=UNSET) -> ProcessBuilder:
"""
Last element
:param data: An array with elements of any data type.
:param ignore_nodata: Indicates whether no-data values are ignored or not. Ignores them by default. Setting
this flag to `false` considers no-data values so that `null` ... | 50,870 |
def angle_wrap_pi(x):
"""wrap angle to [-pi, pi).
Arguments:
x -- angle to be wrapped
"""
return (x - np.pi) % (2 * np.pi) - np.pi | 50,871 |
def contains_end_of_message(message, end_sequence):
"""Función que dado un string message, verifica si es que end_sequence es un
substring de message.
Parameters:
message (str): Mensaje en el cual buscar la secuencia end_sequence.
end_sequence (str): Secuencia que buscar en el string message.
Returns:... | 50,872 |
def decisionTree(dataFrame:pandas.DataFrame,predictors,outColumn,nFolds:int):
"""
Method for computing accuray and cross-validation using decision-tree
"""
if dataFrame is None:
return None
dataFrame=_encodeLabels(dataFrame)
model = DecisionTreeClassifier()
return classificationModel... | 50,873 |
def _cv2_show_tracks(img,
bboxes,
labels,
ids,
classes=None,
thickness=2,
font_scale=0.4,
show=False,
wait_time=0,
out_file=None):
... | 50,874 |
def get_centers(bins):
"""Return the center of the provided bins.
Example:
>>> get_centers(bins=np.array([0.0, 1.0, 2.0]))
array([ 0.5, 1.5])
"""
bins = bins.astype(float)
return (bins[:-1] + bins[1:]) / 2 | 50,875 |
def scale_by_yogi(
b1: float = 0.9,
b2: float = 0.999,
eps: float = 1e-3,
eps_root: float = 0.0,
initial_accumulator_value: float = 1e-6
) -> base.GradientTransformation:
"""Rescale updates according to the Yogi algorithm.
Supports complex numbers, see
https://gist.github.com/wdphy16/118aef6f... | 50,876 |
def test_ndvi(image):
"""
Test ndvi
"""
with rasterio.open('test/data/target/ndvi.tif') as dataset:
target = dataset.read(masked=True)
result = ndxi_image(image, 'nir_ndvi')
same = result == target
assert same.all() | 50,877 |
def download(request):
"""
Serves patients full summary as a downloadable text file.
:param request: The request with user information
:return: Downloadable text file, in lieu of a conventional response
"""
Pat = Patient.objects.all().get(user=request.user)
content = MediInfoExport(Pat, re... | 50,878 |
def extract_video(file_path: str) -> int:
"""
tách lấy file ảnh từ videl
"""
print("start extract_video")
# initialize return value
ret_val = OK
# check arguments
assert os.path.exists(file_path)
cap = cv2.VideoCapture(file_path)
frame_index = 0
while cap.isOpened():
... | 50,879 |
def test_delete_account_authenticated_success(client, token, user):
"""
authenticated user can successfully delete their account
"""
query = """
mutation {
deleteAccount(
input: {
email: "eins@zwei.de",
password: "123"
}
) {
... | 50,880 |
def gradient_descent(F,x0,args=(),delta=1e-14,gamma0=1e-12,adapt=False,plot=False):
"""
Find a local minimum of a scalar-valued function of a vector (scalar field)
by the Gradient Descent method.
https://en.wikipedia.org/wiki/Gradient_descent
:param function F: Function to minimize. Initial use ca... | 50,881 |
def superop2pauli_liouville(superop: np.ndarray):
"""
Converts a superoperator into a pauli_liouville matrix. This is achieved by a linear change of basis.
:param superop: a dim**2 by dim**2 superoperator
:return: dim**2 by dim**2 pauli-liouville matrix
"""
dim = int(np.sqrt(superop.shape[0]))
... | 50,882 |
def utility_num2columnletters(num):
"""
Takes a column number and converts it to the equivalent excel column letters
:param int num: column number
:return str: excel column letters
"""
def pre_num2alpha(num):
if num % 26 != 0:
num = [num // 26, num % 26]
... | 50,883 |
def get(id=None):
"""
Returns all offline STILT stations geographica info.
Parameters
----------
id : STR, default None -> which returns ALL stations
Stilt station ID
Returns
-------
DICT
Geographical information locally stored for the Stilt station.
If lat/lon ... | 50,884 |
def binarize(query, mlb):
"""Transform a single query into binary representation
Parameters
----------
query : ndarray, shape = [n_samples, n_classes]
The tags.
n_samples : int
The number of samples in the training set.
Returns
-------
bin_query_vector : ndarray, shape ... | 50,885 |
def add_library_search_dirs(other_dirs):
"""
Add libraries to search paths.
If library paths are relative, convert them to absolute with respect to this
file's directory
"""
for path in other_dirs:
if not os.path.isabs(path):
path = os.path.abspath(path)
load_library.... | 50,886 |
def fake_schemas(app, api, es, tmpdir):
"""Fake schema."""
schemas = tmpdir.mkdir('schemas')
empty_schema = '{"title": "Empty"}'
for path in (('deposit-v1.0.0.json', ),
('deposits', 'test-v1.0.0.json'),
('test-v1.0.0.json', ), ):
schema = schemas
for sec... | 50,887 |
def no_response_from_crawl(stats: Optional[Dict]) -> bool:
"""
Check that the stats dict has received an HTTP 200 response
:param stats: Crawl stats dictionary
:return: True if the dict exists and has no 200 response
"""
if not stats or not isinstance(stats, Dict):
return False
sta... | 50,888 |
def usage():
"""Print command usage.
"""
print(
"loadguard run --project=[loadguard_library] --env=[environment_name] --home=[home_dir] --tasks=[task1][,task2][,...]") | 50,889 |
async def async_setup_entry(hass, entry, async_add_entities):
"""Set up the spa's binary sensors."""
spa = hass.data[DOMAIN][entry.entry_id][SPA]
devs = []
devs.append(BalboaSpaBinarySensor(hass, entry, FILTER, 1))
devs.append(BalboaSpaBinarySensor(hass, entry, FILTER, 2))
if spa.have_circ_pum... | 50,890 |
def queryresults(imageurl=None):
"""完成对图像的查询,并返回查询结果html(str)
Keyword Arguments:
@imageurl:待查图像URL
Returns:
结果str
"""
imagespkl = r"static/pickle/jianda1.pkl"
with open(imagespkl, 'rb') as f:
voc = pickle.load(f)
maxresults = 38
req, i = 0, 0
rehtml = '<h4><br... | 50,891 |
def evaluate_surprisals_continuous(text, window_params, tot_params):
"""
Get the probability mass functions for each token's
semantic similarity using a beta distribution.
:param text: text to analyze; results are returned token-wise
Can be a string or a spaCy-parsed document.
:param... | 50,892 |
def PrependPath(oldpath, newpath, sep = os.pathsep,
delete_existing=1, canonicalize=None):
"""This prepends newpath elements to the given oldpath. Will only
add any particular path once (leaving the first one it encounters
and ignoring the rest, to preserve path order), and will
os.pat... | 50,893 |
def _search_message_content(contents, part):
"""
recursive search of message content (text or HTML) inside
the structure of the email. Used by L{search_message_content()}
@type contents: dict
@param contents: contents already found in parents or brothers I{parts}.
The dictionary will be c... | 50,894 |
def getUSBFile():
"""
Retrieves USB.ids database from the web.
"""
url = 'http://www.linux-usb.org/usb.ids'
return urllib2.urlopen(url) | 50,895 |
def get_local_time_zone():
"""Return the current local UTC offset in hours and minutes."""
utc_offset_seconds = -time.timezone
if time.localtime().tm_isdst == 1 and time.daylight:
utc_offset_seconds = -time.altzone
utc_offset_minutes = (utc_offset_seconds // 60) % 60
utc_offset_hours = math.... | 50,896 |
def connect_genes(t_trans_to_gene, t_trans_to_q_proj, q_proj_to_q_gene):
"""Create orthology relationships graph."""
o_graph = nx.Graph()
genes = set(t_trans_to_gene.values())
o_graph.add_nodes_from(genes)
q_genes_all = []
print(f"Added {len(genes)} reference genes on graph")
conn_count = 0
... | 50,897 |
def gbsGetSelectedBounds():
""" Get bonding box of features from selection
"""
clayer = iface.mapCanvas.currentLayer()
if not clayer or clayer.type() != QgsMapLayer.VectorLayer:
return None
box = clayer.boundingBoxOfSelected()
return box.toRectF() | 50,898 |
def _serve(action, debug=False, dry_run=False):
"""Build paster command from 'action' and 'debug' flag."""
if action == 'initdb':
# First, create the tables
return _init_db(debug=debug, dry_run=dry_run)
if debug:
config = DEBUG_INI
else:
config = DEPLOY_INI
argv = ['b... | 50,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.