content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def delete_app_env(appname, envname):
"""Delete the specified environmental variable set"""
app = _get_app(appname)
deleted = app.remove_env_set(envname)
if not deleted:
abort(404, 'App `%s` has no env `%s`' % (app.name, envname))
return DEFAULT_RETURN_VALUE | c967ee5b8ffa3a66c97179c9386e27cd8f6bc7f7 | 3,609,800 |
def _angle(p,q,r):
"""
compute the positive angle formed by PQR
"""
return np.abs(get_angle_between(Ray(q,p),Ray(q,r))) | 1c0933c1cd8f7385be6942d57bca71b50ff9c3ce | 3,609,801 |
from typing import Sequence
def plotMatrix(matrix, title, xticklabels: Sequence[str], yticklabels: Sequence[str], xlabel: str, ylabel: str, normalize=True, figsize=(9,9),
titleAdd: str = None) -> matplotlib.figure.Figure:
"""
:param matrix: matrix whose data to plot, where matrix[i, j] will be rendere... | 868b884b27054129716e397b3a308cd870b5cd7f | 3,609,802 |
def _sample_flux_snr(distances, fwhm, plsc, n_injections, flux_min, flux_max,
nproc=10, random_seed=42, wavelengths=None, spectrum=None,
mode='median', scaling='temp-standard',
svd_mode='randsvd'):
"""
Sensible flux intervals depend on a combination... | cfd94d10870d599fd4c786aff87f600397debf44 | 3,609,803 |
def addBrightness(image, scale):
"""Adds Brightness to an image.
Parameters:
image (PIL.Image.Image) = The image to be modified.
Returns:
bright.enhance(1.1) = The modified image.
"""
#Use the pillow brightness method to add brightness
bright = ImageEnhan... | de91ca415f03a82c431b67e1fe059ea307362f21 | 3,609,804 |
import requests
import shutil
def download_log_simple():
"""
Download the log of job types that have a single console log
:return: 0 in case of success, -1 in case of an error
"""
response = requests.get("{}/job/{}/{}/consoleText".format(jenkins_url, job_name, build_id), stream=True,
... | 0630bec178113ef11c120ccef9142ab13d6e25d3 | 3,609,805 |
async def _compose(choice):
"""Figure out exactly what resource we're requesting and return the correct
class."""
nchoice = list(choice.keys())[0]
id = list(choice.values())[0]
if '_id' in nchoice:
nchoice = nchoice[:-3]
return ('/'.join([base_uri, nchoice, str(id), '']), nchoice) | c82afd7129068c6f80acb3d61e30031078c59c38 | 3,609,806 |
def validate(guess: str, solution: str) -> str:
"""Validates the user guess against the solution, coloring correct characters"""
return "".join([validate_char(i, guess, solution) for i in range(WORD_LENGTH)]) | 58af7fd7ba42bf591b9689f74e9f5007b5e70d0d | 3,609,807 |
def infection_rate_symptomatic_80x40():
"""
Real Name: b'infection rate symptomatic 80x40'
Original Eqn: b'Susceptible 40*Infected symptomatic 40x80*contact infectivity symptomatic 40x80*(self quarantine policy SWITCH self 40\\\\ * self quarantine policy 40+(1-self quarantine policy SWITCH self 40))/non con... | aca50b41f7241c1c357feee21048e0942e980545 | 3,609,808 |
import re
def input_text(frame_r: tk.Frame,
label_text: str,
text_width: int,
initial: str = None,
side_: constants = TOP,
side_label: constants = LEFT,
fmt: str = None):
"""テキストの入力ボックスを作成
Args:
frame_r (tkinter... | 57d4fb91627b24172991d28eac5e8182a100009e | 3,609,809 |
def plot_pca_variance(data):
"""Runs PCA on passed data and creates the plot figure to visualize the
variance corresponding to each component and returns finally the figure object.
Consider that the method matplotlib.pyplot.show is called inside this function
and the plot is showed if the regarding exec... | 22e03892aa47ef3bbb87c76c6cf5a2874f6fb7ee | 3,609,810 |
import sys
def connect_to_database(user: str, database: str):
""" Connects to the PostgreSQL database
Creates connection to the backend PostgreSQL database.
Args:
user: PostgreSQL username to acces the database.
database: Name of the database to connect to.
Todo:
* Add supp... | 4387775d4e375ef7c5517c130c34a6fa7dd8fb00 | 3,609,811 |
from typing import Optional
from typing import List
import argparse
import logging
import os
import shutil
def _get_validated_args(input_args: Optional[List[str]] = None) -> argparse.Namespace:
"""validate arguments"""
parser = argparse.ArgumentParser()
# These parameters are always required
parser.a... | c6e7e5fc452dff9fc3993be00fd7a019eccb8f88 | 3,609,812 |
def on_volume_balance_vec(data_df, window=14):
"""
On Volume Balance (OBV).
:param data_df: Unstacked for one symbol only.
:param window: An integer number of days to look back.
:return: A pandas Series with the values of OBV for all the valid dates.
"""
obv_delta = data_df['Volume'] * np.si... | fba02e8c0416e2b0e5871a207fb20cc9b94f7852 | 3,609,813 |
def centroidCalculator(cell):
"""
Centroid is assumed to be roundish so the euclidean distance will always
be larger at that region than along protrusions.
"""
edt = distance_transform_edt(cell)
centroid = np.where(edt == np.max(edt))
centroid = [centroid[0][0], centroid[1][0]]
return ... | 0cdca26bed775e792bd761cb5aa484c633041d1f | 3,609,814 |
def is_ethernet_port(interface):
"""Judge whether it is ethernet port"""
ethernet_port = ['ge', '10ge', '25ge', '4x10ge', '40ge', '100ge', 'meth']
if_type = get_interface_type(interface)
if if_type in ethernet_port:
return True
return False | 668826ae07161ecd64714c065bd67adf9e9dd6e2 | 3,609,815 |
import itertools
def cross_product_configs(**configs):
"""
Given configs from users, we want to generate different combinations of
those configs
For example, given M = ((1, 2), N = (4, 5)),
we will generate (({'M': 1}, {'N' : 4}),
({'M': 1}, {'N' : 5}),
... | 74bab0078008f1dc8675dba9469ed56dab1061af | 3,609,816 |
def parse_distribution(s):
"""
Parses the distribution from the given string
"""
segments = s.split(' ')
dist = segments[0]
args = segments[1:]
# Check to see if the given distribution is supported
if dist not in distributions.keys():
raise ValueError('Unsupported distribution %... | 0a7bcfaa6f7385e09bfc5e4de4474a2b02eb6048 | 3,609,817 |
import os
import subprocess
def run_cgi(cgi, req_type, req_content, cookie=None):
"""CGI handler. It maps the given request to appropriate place, and run it"""
print("running: " + WWWROOT + cgi)
new_env = os.environ.copy()
if cookie is not None:
new_env['HTTP_COOKIE'] = cookie
runner_stdin... | 4d9abe2345c1b26d8d52e380b37fc0cfa2f7b28a | 3,609,818 |
def calculate_p_b(*args):
"""
Determines how difficult a text is according to the number of words that are, most likely, unknown to readers.
The other formulas we referred to based the score on the number of words and sentences only
"""
words_count, sentences_count, diff_words_count = args[0... | 420b8269390f50b163c89e97f95b27a282f6f829 | 3,609,819 |
def part1(entries: tuple) -> int:
"""part1 solver"""
card_key, door_key = entries
loop_size = 0
key = 1
while key not in (card_key, door_key):
loop_size += 1
key = (key * 7) % 20201227
if key == card_key:
return pow(door_key, loop_size, 20201227)
return pow(card_key,... | cb4e38704229c3a67a67d7ffd7d8a7e0d2d72628 | 3,609,820 |
def id_function(fixture_value):
"""Convert a param from the use_case fixture to a nicer name.
By default, the name (used in the test generated from the parameterized
fixture) will use the fixture name and a number.
Eg: test_foo[use_case0]
Providing explicit 'ids' (either as strings, or as a functi... | 3db81ccf652a82249f2455d695b563c12017b654 | 3,609,821 |
def application_create(request, name, redirect_uris, scopes=['all_info'],
client_type='confidential', description=None,
grant_type='authorization_code', **kwargs):
""" Registers a new consumer in the Keystone OAuth2 extension.
In FIWARE applications is the name OAu... | a36fec62ac062abd6a3fdf9d4fc109241646359b | 3,609,822 |
def create_spreadsheets_json(worksheet_title=None):
"""
create base parameters json for spreadsheets api call
"""
if worksheet_title is None:
raise ValueError('Missing worksheet_title parameter')
return {
"spreadsheet_key": SPREADSHEET_KEY,
"worksheet_title": worksheet_t... | 8177cb3749399b1ff367cc198d27aaed54e2d06e | 3,609,823 |
import platform
import sys
def os_version_arch():
"""Return OS name, version and platform architecture."""
system = platform.system()
version = ""
arch = platform.machine()
if system == "Darwin":
return "darwin", "", arch
if system == "Windows":
return "windows", "", arch
... | 4febff2b63541436da857b26243db010102586d7 | 3,609,824 |
def constraint_configure_mentoring(model, tracks, v_tdh):
"""Configure the mentoring of onboarders appropriately."""
# If agent is on, he/she to be paired with exactly 1 mentor:
for d in range(num_days):
for h in agents_onb:
model.Add(
sum(v_mentors.loc[(d, h)].values.tol... | 69c97ee94bf040ce853d25e5c5cf6184e33e0418 | 3,609,825 |
def _parts_span_selector(pspec):
"""
Selector for `System`Span` part specification
"""
if len(pspec.leaves) > 3:
raise MessageException("Part", "span", pspec)
start = 1
stop = None
step = 1
if len(pspec.leaves) > 0:
start = pspec.leaves[0].get_int_value()
if len(pspec... | 0144c5aeb31225a5ed46a5e95a3c4d2c0c7f970f | 3,609,826 |
def selection(triple, variables):
"""Apply selection on a RDF triple"""
bindings = set()
if variables[0] is not None:
bindings.add((variables[0], triple[0]))
if variables[1] is not None:
bindings.add((variables[1], triple[1]))
if variables[2] is not None:
bindings.add((variab... | 7f237f271d7c980e5ece21eacde671ee0f8a1d05 | 3,609,827 |
from typing import Type
from pydantic import BaseModel # noqa: E0611
from typing import List
def schema_factory(
schema_cls: Type[BaseModel],
name: str = "",
excludes: List[str] = ["id", "created_at", "updated_at"],
) -> Type[BaseModel]:
"""
Is used to create a CreateSchema which does not contain... | 729971dc3c2bbab4926da8acd5690678152d666d | 3,609,828 |
def daily_std_error(merged_data):
"""Calculates daily seasonal standard error of the timeseries data in a DataFrame
Parameters
----------
merged_data: DataFrame
A pandas DataFrame with a datetime index and columns containing float type values.
Returns
-------
DataFrame
A p... | 11b5f72ff1a68425cd17d7638590290f5ac883d8 | 3,609,829 |
def bruteforce(model, c, max_iter=1000):
"""
Generiere Zufallsdaten, bis diese eine Klasse maximieren oder die maximale Anzahl an Iterationen verbraucht ist.
"""
shape = (1,) + model.input_shape[1:]
for i in range(max_iter):
image = np.random.random(shape)
prediction = model.predict(... | ccf6d4b899237511b5799c5682de5387108122ab | 3,609,830 |
def process_logic(op):
"""
Parse the binary operation binary expression.
Convert operator to fabric of AST-classes 'AndBexp' / 'OrBexp'.
"""
if op == '&&':
return lambda l, r: AndBexp(l, r)
elif op == '||' or op == '!!':
return lambda l, r: OrBexp(l, r)
else:
raise Ru... | 4f1b5af939b3909ea25bdb95cdffa1da44fd1fc5 | 3,609,831 |
def _build_chef_properties(env, config_file):
"""
Build python object representation of the Chef-solo node.json file from
node_extra.json in config dir and the fabric environment.
"""
json_properties = _parse_json(config_file)
return build_properties(env, "chef", json_properties) | 0c012c55895597abcd4c82cadd43113dacdb5e68 | 3,609,832 |
def bond_vector(xi, xi_neig, box_length):
""" Determine the normalized bond vector between atoms i and j.
"""
bond = xi - nearest_atom_image(xi_neig, xi, box_length)
bond /= np.linalg.norm(bond)
return bond | 13211c0bfd63971edad8f5839cdbe320d901b572 | 3,609,833 |
def get_activation_fn(name, framework="tf"):
"""Returns a framework specific activation function, given a name string.
Args:
name (str): One of "relu" (default), "tanh", or "linear".
framework (str): One of "tf" or "torch".
Returns:
A framework-specific activtion function. e.g. tf.... | 51306d72aa3f1d05111929c841befdd8807318a7 | 3,609,834 |
def rolling_weighted_triangle_conv(values, weights, window_size):
"""Smoothes the data with a window and given the weights
Original algorithm: stackoverflow.com/a/46232913/1257075
Returns:
Smoothed values
Args:
values: data to smoothen
weights: weights for each data point
window_s... | fec4c0bd655d774a5ff138a801edd2a465a2c319 | 3,609,835 |
def par(q):
"""Parameterize using t^3 + t, where t is the polar angle."""
t = np.arctan2(q[1], q[0])
# A simple diffeomorphism from R^1 -> R^1.
return t**3 + t | 9d37a105a66cc9908284a1501fa89fc5c75f3541 | 3,609,836 |
def tanimoto_sparse(str1, str2):
"""!
Calculate the tanimoto coefficient for a pair of sparse vectors
@param str1 str: String of 1s and 0s representing the first compound fingerprint
@param str2 str: String of 1s and 0s representing the second compound fingerprint
@return Returns float
"""
n... | 2a7a6e7c585ceb3aaaa4dfed7e98b01f151e7c06 | 3,609,837 |
import itertools
import time
def perform_experiment(relax: bool, spring_constant: Vector, random_strength: Vector, seed: Vector):
"""
A function that takes potential values of parameters and returns a dataframe with experiment results
for all possible combinations of these parameters.
Parameters
... | 7d6b89993f8df97a0424077569d443598d31bd89 | 3,609,838 |
from bs4 import BeautifulSoup
import codecs
def get_saml_response(html):
"""
Parse SAMLResponse from Shibboleth page
>>> get_saml_response('<input name="a"/>')
>>> get_saml_response('<body xmlns="bla"><form><input name="SAMLResponse" value="eG1s"/></form></body>')
'xml'
"""
soup = Beauti... | 24800c318f7f5f6000c6652d15421c68a97a04a6 | 3,609,839 |
def _is_namespace_visible(context, namespace):
"""Return true if namespace is visible in this context"""
if context.is_admin:
return True
if namespace.get('visibility', '') == 'public':
return True
if namespace['owner'] is None:
return True
if context.owner is not None:
... | 4f3119684681aa2f3c34a62e1674aaa58d26105e | 3,609,840 |
def create_quantum_model():
"""Create a QNN model circuit and readout operation to go along with it."""
data_qubits = cirq.GridQubit.rect(4, 4) # a 4x4 grid.
readout = cirq.GridQubit(-1, -1) # a single qubit at [-1,-1]
circuit = cirq.Circuit()
# Prepare the readout qubit.
circuit.a... | 3574dec302b4a3c0b5bf3767ff66936af2eaaf70 | 3,609,841 |
def get_aa_subseq_df(sg_designs, aa_seq_df, width, id_cols,
transcript_base_col='Transcript Base',
target_transcript_col='Target Transcript',
aa_index_col='AA Index'):
"""Get the amino acid subsequences for a design dataframe
:param sg_designs: Dat... | 181b16fd9887ffe41fea9bbefafa02e0a3e6e557 | 3,609,842 |
def _exception_to_dict(exception):
"""Convert exception to an error object to be sent as response to APIs."""
return {"error": {"type": type(exception).__name__,
"message": exception}} | 4abb81516b604bdfd2f6360a1272556b0b6f6932 | 3,609,843 |
import torch
from typing import List
def get_depth_prediction(
depth_logits: torch.Tensor,
use_dgc_scaling: bool,
camera_matrix: torch.Tensor = None,
real_camera_height: torch.Tensor = None,
panoptic_seg: torch.Tensor = None,
road_class_id: int = -1,
depth_filter_class_ids: List[int] = Non... | 8839c1873c0fd6cd04bc9add7e9cb16b1bfb87af | 3,609,844 |
from typing import Optional
def sync_wait_and_get_s3_object(
uri: Optional[str]=None,
bucket: Optional[str]=None,
key: Optional[str]=None,
sess: Optional[boto3.session.Session]=None,
region_name: Optional[str]=None,
max_wait_seconds: float=DEFAULT_S3_OBJECT_WAIT_TIMEOUT_SECONDS, # ... | 57379f99ce4add147a1570d6e419f1dab47a330b | 3,609,845 |
import os
import scipy
import itertools
def compute_validation_summary(ot_model, day_pairs_triplets=None, save_interpolated=False,
interp_size=10000, compute_full_distances=False):
"""
Compute the validation summary for the given OTModel
Parameters
----------
ot_mod... | b3730fe95df2eaf95afd5ab2d1958b96382a2d4e | 3,609,846 |
def read_ceps_test(test_file):
"""
Reads the MFCC features from disk and
returns them in a numpy array.
"""
X = []
y = []
ceps = np.load(test_file)
num_ceps = len(ceps)
X.append(np.mean(ceps[int(num_ceps / 10):int(num_ceps * 9 / 10)], axis=0))
return np.array(X), np.array... | c235d222e610d17f5302cc467867f6989891da3b | 3,609,847 |
def dict_to_object(dictionary):
"""
parse a dictionary and return a dynamic object
:param dictionary: dict
:return: dynamic_object
"""
obj = DynamicClass()
for key in dictionary:
setattr(obj, key, dictionary[key])
return obj | 31135f58545c000a7ee64d71a7938222028d63e6 | 3,609,848 |
import torch
def batchify(fn, chunk):
"""
Constructs a version of 'fn' that applies to smaller batches.
"""
if chunk is None:
return fn
def ret(inputs):
return torch.cat([fn(inputs[i:i + chunk]) for i in range(0, inputs.shape[0], chunk)], 0)
return ret | 4629520fb5aef3a6e280e2eaee30e39baad51f98 | 3,609,849 |
def log_loss(y, p):
""" Compute the log loss by tensorflow from binary truth and predicted score
Parameters
----------
y:
The binary truth: 0 or 1
p:
The predicted score in [0, 1]
Returns
-------
the value of the log loss
"""
return -( y*log(p) + (1-y)*log(1-p) ... | 2e8d02b3a1a1542f5be24df0c0e3ffdbc860e206 | 3,609,850 |
def cleanstrings(df, columns, stringmaps, unmapped=None, simplify=True):
"""Consolidate freeform strings in several dataframe columns.
This function will consolidate freeform strings found in `columns` into
simplified categories, as defined by `stringmaps`. This is useful when
a field contains many dif... | f9fd09efd5f27b19ef275dfc4ff62aa18a4bbbf0 | 3,609,851 |
import datasets
import torch
def get_tst_loader(
data_dir: str,
batch_size: int,
shuffle: bool = True,
num_workers: int = 4,
pin_memory: bool = False,
):
"""
Utility function for loading and returning a multi-process
test iterator over the CIFAR-100 dataset.
If using CUDA, num_work... | ed6bf3a4cab0717e6f2de6c2caa4b40e05d9ee9b | 3,609,852 |
def _any_none(*args):
"""Returns a boolean indicating if any argument is None"""
for arg in args:
if arg is None:
return True
return False | fadb9330fc1f4ffca2cf0105d8513d0be0d5fae1 | 3,609,853 |
def precision(judged_data):
"""
Our relevance judgments are on a graded scale of 0-3, where scores of 1-3 are considered
relevant, and less than 1 is irrelevant. We compute precision of the result set based on
this quanitization.
Args:
judged_data (pandas.DataFrame): A DataFrame with at a m... | 6d4c4ee7793625e4590c01120318afe33cba0b0c | 3,609,854 |
def filter_cycles(cycle_list, **filters):
"""Puts cycles through filters to meet specific requirements.
cycle_list is a list of tuples where the first item is an intake and
the second action is a placement or drop.
filters are the specifications that certain data points inside the
cycles must fit t... | 1abdcf76365cbaced4ac1dcfff96a91282c38370 | 3,609,855 |
def ansi_escape(text):
"""
Replace characters with a special meaning.
"""
return text.replace('\x1b', '?').replace('\b', '?') | 86ff3e7cfce8fcc17e826896e32c28e0d30ee83c | 3,609,856 |
def ajax_get_commandes(request):
"""
This view comes before the feature of sending mass mails to customers. It goes up the number of customers selected by status.
"""
if request.method == 'POST':
try:
event = request.POST.get('event').split(',') if request.POST.get('event').split(',... | 9953c6bff7dd1b5476ee0a17e57f208d1a234bbd | 3,609,857 |
def global_counter() -> int:
""" A really dumb global counter.
This is useful for giving output files a unique number, so if we run the
same command multiple times we can keep their output separate.
"""
global _global_counter
_global_counter += 1
return _global_counter | 8771b81f459ab116998e6927c8e2d0d71676ac0f | 3,609,858 |
def _GetAndroidVersionFromMetadata(metadata):
"""Return the Android version from metadata; None if is does not exist.
In Android PFQ, Android version is set to metadata in master
(MasterSlaveLKGMSyncStage).
"""
version_dict = metadata.GetDict().get('version', {})
return version_dict.get('android') | e1d1ed9d0bbf2f65d646c11007739f6b5a9b78ec | 3,609,859 |
from functools import reduce
def get_in(d, t, default=None):
"""
look up if you can get a tuple of values from a nested dictionary,
each item in the tuple a deeper layer
example: get_in({1: {2: 3}}, (1, 2)) -> 3
example: get_in({1: {2: 3}}, (2, 3)) -> {}
"""
result = reduce(lambda d, t: d... | f92e6c94e3485f4b02a8487f832064de7a42eba5 | 3,609,860 |
def divisible_by_five(n: int) -> bool:
"""Return True if an integer is divisible by 5, and false otherwise."""
if n % 5 > 0:
return False
return True | e4cd2adf7067000f10aa655bb9fd819e525527d2 | 3,609,861 |
import os
import json
def saveJSON(g, data, backup=False):
"""
Saves the current setup to disk.
g : hcam_drivers.globals.Container
Container with globals
data : dict
The current setup in JSON compatible dictionary format.
backup : bool
If we are saving a backup on close, don't promp... | 0bfdddf33ac02e4f42cf5e95b951a22121500fb7 | 3,609,862 |
def get_imaging_root_data_dir() -> str:
"""
get_imaging_root_data_dir() -> str
Retrieve the root data directory - e.g. containing all subject/sessions data
:return: a string for full path to the root data directory
"""
return _linking_module.get_imaging_root_data_dir() | 9a697c7665de45ba235d3584898799c77e91591d | 3,609,863 |
from typing import Union
from typing import List
def _input_is_valid(
dataset: np.ndarray, predictive_model: object, as_probabilistic: bool,
categorical_indices: Union[None, List[Index]],
class_names: Union[None, List[str]], classes_number: Union[None, int],
feature_names: Union[None, ... | 38f473129ce0ead9831024351f2b084c68f60bd6 | 3,609,864 |
def cvPtr1D(*args):
"""cvPtr1D(CvArr arr, int idx0, int type=None) -> uchar"""
return _cv.cvPtr1D(*args) | db40872eed3bda3a859ccc11838a3ea0a65d4a2d | 3,609,865 |
def _should_package_clang_runtime(ctx):
"""Returns whether the Clang runtime should be bundled."""
# List of crosstool sanitizer features that require packaging some clang
# runtime libraries.
features_requiring_clang_runtime = {
"asan": True,
"tsan": True,
"ubsan": True,
}
... | 7f54b903f4acc288abca294d857e774ce3daa8b3 | 3,609,866 |
import math
def round_nearest_towards_infinity(x, infinity=1e+20):
""" Rounds the argument to the nearest integer.
For ties like 1.5 the ceiling integer is returned.
This is called "round towards infinity"
Args:
x: the value to round
infinity: the model's infinity value. All values a... | e3edd7dfca255648f02eb9845f411f52c24d3120 | 3,609,867 |
def json_schema(request, ref: str):
"""Return a JSON Schema for a given reference."""
if ref not in SCHEMA_REFS:
return HttpResponseBadRequest("Unknown ref")
return SCHEMA_REFS[ref].schema_json(indent=2) | 2530d31ed2aab344f5a4fc7d1208b3f9f91cfdca | 3,609,868 |
def emprestimo(id):
"""
Deleta uma reserva e gera um empréstimo.
Certifica que a reserva existe.
Atualiza o status do livro para emprestado
"""
reserva = get_reserva(id)
try:
livro = db.query_one('select * from livro where tombo = %s' % reserva['tombo'])
print(livro)
... | 0dba34551b4c6d0e2f85319abf85ad0ed83efc27 | 3,609,869 |
import os
def update_cache_needed(filenames, cachefile=None):
"""Returns True if the cache file needs to be updated.
:param filenames:
:param cachefile: (Default value = None)
"""
for filename in filenames:
if cachefile is None:
current_cachename = cache_file(filename)
... | 2507930b10c672e09e02ca3cdb41a08e276803f4 | 3,609,870 |
def intersection(line1, line2):
"""Finds the intersection of two lines given in Hesse normal form.
Returns closest integer pixel locations.
See https://stackoverflow.com/a/383527/5087436
"""
rho1, theta1 = line1[0]
rho2, theta2 = line2[0]
A = np.array([
[np.cos(theta1), np.sin(theta... | be158fbffdcbcd35134af7fbab83106ad9b2a94b | 3,609,871 |
from typing import Any
from typing import Dict
def make_kwargs(proxy_info: ProxyInfo, *, nosave: bool = False,
**kwargs: Any) -> Dict[str, Any]:
"""Form the proxy kwargs for requests or urllib
:param proxy_info: ProxyInfo
a namedtuple of the form
(server: str, port: int, d... | 9be26e1b9382eb616f999b8a2553cbdf88c17029 | 3,609,872 |
def get_moonboard(year: int) -> MoonBoard:
"""
Factory function. Given a year, return a Moonboard object encapsulating the
Moonboard layout info of that year.
:param year: Year of the desired Moonboard layout
:type year: int
:return: Moonboard object encapsulating the Moonboard layout info
... | abce08b0fdbb3157509281a615572c3a2526d484 | 3,609,873 |
import re
import copy
def model_to_estimator(model):
"""given a model , return a estimator"""
tf=model.copy()
tp=type(tf)
from1=re.search(r'(pyspark.*)\.',str(tp)).group(1)
from2=re.search(r'(pyspark.*)\.(\w+)',str(tp)).group(2)
from2=re.sub(pattern='DecisionTreeRegressionModel', repl='Decisio... | ccb414b8ae8745c31eaa6060e36eb064e8778923 | 3,609,874 |
import types
import numpy
import pandas
def sdc_pandas_series_operator_mod(self, other):
"""
Pandas Series operator :attr:`pandas.Series.mod` implementation
Note: Currently implemented for numeric Series only.
Differs from Pandas in returning Series with fixed dtype :obj:`float64`
.. only:: ... | 12b3dcf8efd10d7ece98c0df96003f4adb0f8e26 | 3,609,875 |
def regex_chomp(regex, state, tracker):
"""
:param regex: regex object to match with
:param state: ChompState
:param tracker: FroParseErrorTracker
:return: Match object of regex match, or throws ChompError
"""
line = state._curr # state.current()
index = state._column # state.column()
... | d39963a632bd99afe1b9d50f60ebb3203b6b5d21 | 3,609,876 |
def create_html_popup(friends: list) -> str:
"""creates html popup for markrer
Args:
friends (list): list of names
Returns:
str: html in string format
"""
html_template = "Friends:"
for friend in friends:
html_template += f"""<br>
<p>{friend}</p><br>
"""... | 54b1ac02cf59a086a711dcb0b47f14c0ea4e782d | 3,609,877 |
from typing import List
from datetime import datetime
from typing import Union
from pathlib import Path
from typing import Tuple
def collect_radolan_data(
date_times: List[datetime],
time_resolution: TimeResolution,
prefer_local: bool = False,
write_file: bool = False,
folder: Union[str, Path] = D... | 77395e1fea8fd2b6f089e9a9bbba10f0faf91661 | 3,609,878 |
def SetFlags(ea, flags):
"""
Set new value of flags
This function should not used be used directly if possible.
It changes properties of a program byte and if misused, may lead to
very-very strange results.
@param ea: adress
@param flags: new flags value
"""
return idaapi.setFlags(e... | 7ca8b70c1cf0eb1e5236c613cafdae38c7ff2f1d | 3,609,879 |
import os
def evaluate(ts, not_found_list):
"""
The function evaluates the embeddings. It gets a folder name as input. If embeddings are generated by the triplet model,
the input folder name is a time stamp.
The function then reads all the image level embedding csv files within that folder. Normally,... | c0804768ed768b38a1c57a2be26e6635c3e82ac2 | 3,609,880 |
def createMiddleWare(app, exporter):
"""
Configure a flask middleware that listens for each request and applies automatic tracing.
This needs to be set up before the application starts.
:param app: WSGI application
:param exporter: Exporter instance object (StackdriverExporter)
:return:
"""
... | 62e7eb512ebf86f761f9f35df2a47b94418f658f | 3,609,881 |
import requests # top-level import fails pip install, only required for make dist
import sys
import re
def get_long_description() -> str:
"""Extract the content of the sdk/README.md and replace relative links when
running `python3 setup.py sdist`. Return the abbreviated LONG_DESCRIPTION when
running `pip... | bcd13eb128e6cbac4f8711410f62fcbb07ba63bd | 3,609,882 |
def euler_step(theta,dtheta,ddtheta,dt):
"""
Euler Step
Parameters
----------
theta (tf.Tensor):
Joint angles
(N,nq)
dtheta (tf.Tensor):
Joint velocities
(N,nq)
ddtheta (tf.Tensor):
Joint accelerations
(N,nq)
dt (float):
Delta t
... | 402b30a3f24440707ef56b7113b545eb827c704e | 3,609,883 |
def get_cif(ams_id):
"""
get CIF Structure by AMS ID
"""
db = get_amscifdb()
return db.get_cif(ams_id) | 3003f360a3a24574b1d672032d71b376b8df1baf | 3,609,884 |
import os
import collections
def generate_scheme_caps(metadata_define, metadata_request, arguments, pset_schemes, ccpp_field_maps, caps_dir):
"""Generate scheme caps for all schemes parsed."""
success = True
# Change to caps directory
os.chdir(caps_dir)
# List of filenames of scheme caps
schem... | 4ccc72fa822f5ea65c91400a9a88176fa2d64103 | 3,609,885 |
def no_xray_disturbance(nodist,hole):
"""
takes an archive measurement DataFrame and removes disturbed intervals using XRAY disturbance files
Parameters
__________
nodist : Pandas DataFrame
data frame filtered by iodp_funcs.remove_disturbance
hole : str
IODP hole
Return... | f2023b06b7a7014d0259a8f08625346bcac1cf52 | 3,609,886 |
import subprocess
def git_diff_files(oldrev, newrev):
"""Get list of files in diff."""
files_modified = subprocess.check_output(["git",
"diff",
"--name-only",
oldrev + ".."... | 4bfe2982a66b2bdb2c186cced1f4619965f58064 | 3,609,887 |
def beta1() -> float:
"""Mock beta1."""
return 0.9 | 1152a45a891c749b196cab780f8f76afc70c2a65 | 3,609,888 |
def dhcp_relay_show(dut, family="ipv4", interface=None, cli_type=""):
"""
API to show the DHCP relay brief output
Author Chaitanya Vella (chaitanya-vella.kumar@broadcom.com)
:param dut:
:return:
"""
cli_type = st.get_ui_type(dut, cli_type=cli_type)
if cli_type in ['click', 'klish']:
... | 9cd1d95b61687fc53a5e93d06bc4e5d8affa8435 | 3,609,889 |
def split_condition_code(tree, fields, field, depth,
pre_condition, term_analysis_fields,
item_analysis_fields, cmv):
"""Condition code for the split
"""
predicate = get_predicate(tree)
optype = fields[field]['optype']
operator = PYTHON_OPERATOR[pre... | 88fbf23740e71819e4b0a455637f10b6aa9be26c | 3,609,890 |
from typing import List
def get_cases_country(path: str) -> List[int]:
"""
Counts the number of cases based on the COUNTRIES for the parameter of interest.
Arguments:
path {str} -- path to the dataset csv file for the parameter of interest
Returns:
List[int] -- an ordered list of the number of cases for e... | 2018db97c6ca932b1fe28fcbeb73c8ce04afe716 | 3,609,891 |
def tf_optimize(inputs, outputs, graph_def, fold_constant=None):
"""Optimize tensorflow graph for inference."""
transforms = []
if fold_constant:
transforms.extend([
"fold_constants(ignore_errors=true)",
"remove_attribute(attribute_name=_class)", # remove node colocation att... | bedd14414cce8f6364869b18e831274ab2001d70 | 3,609,892 |
def parse_mask(line):
""" parses the string formated as the PASCAL pixel mask annotation
e.g. Pixel mask for object 1 "PASpersonWalking" :
"PennFudanPed/PedMasks/FudanPed00001_mask.png"
line: string
line in the PASCAL annotation file with mask information
returns: ... | 1db8aa18fa85f3b7a952ba24247ecfa10e1c9245 | 3,609,893 |
import argparse
import sys
def get_args():
"""Get arguments from CLI"""
parser = argparse.ArgumentParser(
description="""Program description""")
parser.add_argument(
"input",
type=is_dir,
action=FullPaths,
help="""The path to a directory of PHYLI... | d5a709a21f43cd9f92b07dbb3296cee805daee38 | 3,609,894 |
def parse_assignments(lines, lineNo=0, input_vars=None):
"""
Parse given `lines` as an assignment title and either single oder double lines of assignments.
A single line of assignment is "<var> = <value[;]".
A double line of assignment is "<var> =\n<value>[;]".
:param lines: array of strings to be ... | 38a41ad49af3bbfd66dd7097bf011c3369045345 | 3,609,895 |
def delete_node_layout(node_id):
"""
API entry point to delete the layout for a node.
"""
return node_layout.delete_node_layout(node_id) | 326ebb3fa1a6d0ce75ed2f791a54ff10318f3014 | 3,609,896 |
from typing import Dict
from typing import Tuple
import functools
def _create_nodes_map(
graph_dict: Dict[str, Dict[str, PCollection]]
) -> PCollection[Tuple[NodeId, Node]]:
"""Create a map from Node ID to Node from the given `graph_dict`.
Args:
graph_dict: The map returned from a `unigraph` graph readin... | 05a2d4950325be8d9d8b4d0def7cbb698644b01f | 3,609,897 |
def generatePosSeqList(length):
""" Generates HALF of the possible weaves of a given length or less """
posSeqList = [] # list that will contain the generated weaves
curSeq = [0]*int(length//2) # We devide by 2 as the sigmas have pair powers
endSeq = [4]*int(length//2)
while curSeq != endSeq:
... | 74b3ed4ce5f08ff30ba8f665d1655b8269c3c280 | 3,609,898 |
def prepare_script_args(spec):
"""
Uses the default script args if those items are not specified for
the script.
Args:
spec (dict): Script args to modify with defaults as needed.
Returns:
dict: Modified dictionary with values as needed.
"""
spec['run_in'] = spec.pop... | c2f206d5dba6e4b5727dd7d2f5f1732a582b54b2 | 3,609,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.