content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def get_secrets(secret_name):
"""
Get secrets from AWS Secrets Manager
"""
session = boto3.session.Session(profile_name="platform-dev")
client = session.client(
service_name="secretsmanager", region_name="eu-west-1"
)
try:
response = client.get_secret_value(SecretId=secret_n... | 5,313,500 |
def make_mesh_dynamic_with_abs_displacement(mesh,deforms_f,origin,dim ='z',motion='amplitude',radius=1.0,**kwargs):
""" Create Mesh object with color values from mesh, e.g. of vessel
Input: origin from volume
deforms forward??
invertZ, True of False. Inverts vertices value for z
Out... | 5,313,501 |
def test_StoreIO_type_check__raises_TypeError():
"""
_type_check() should raise Type erorr if attr is not correct type
"""
abcd = namedtuple('abc', ['a','b','c',"d"])
x = abcd(1,2.0,"3",{"k":1})
S = StoreIO(**x._asdict())
with pytest.raises(TypeError):
assert S._type_check("a", str)
... | 5,313,502 |
def is_piped_output():
"""
Checks the piped output.
This function checks if this script
is being executed with a piped output.
E.g.: python dnsrato.py -d domain.com --format json > outfile.json
Returns
-------
bool
True if the is a piped output, False otherwise.
"""
re... | 5,313,503 |
def load(savime_element: LoadableSavimeElement) -> str:
"""
Get the load query string for a loadable element.
:param savime_element: A loadable savime element.
:return: The load query for the savime element.
"""
return savime_element.load_query_str() | 5,313,504 |
def topo_flat(x,y):
"""
flat
"""
z = where(x < 204.91213, 30., -30.)
return z | 5,313,505 |
def softmax_xent(*, logits, labels, reduction=True, kl=False):
"""Computes a softmax cross-entropy (Categorical NLL) loss over examples."""
log_p = jax.nn.log_softmax(logits)
nll = -jnp.sum(labels * log_p, axis=-1)
if kl:
nll += jnp.sum(labels * jnp.log(jnp.clip(labels, 1e-8)), axis=-1)
return jnp.mean(nl... | 5,313,506 |
def activate_WS_VCC(activation,
Q_cooling_unmet_W,
Qc_water_body_remaining_W,
Qc_DailyStorage_to_storage_W,
Qc_DailyStorage_from_storage_W,
T_district_cooling_supply_K,
T_district_cooling_return_K,
... | 5,313,507 |
def sign_block_data(
data: Dict[str, Any], private_key: str, hash_alg: str = 'keccak256'
) -> Dict[str, str]:
"""sign block data
:param data: dict
:param private_key: hex str (private key)
:param hash_alg: `keccak256` or `sha256`, the default value is `keccak256`
:return: dict, {'hash': _h... | 5,313,508 |
def convert_label(label_img):
""" covert label """
label_processed = np.zeros(label_img.shape[0:]).astype(np.uint8)
for index in range(label_img.shape[2]):
label_slice = label_img[:, :, index]
label_slice[label_slice == 10] = 1
label_slice[label_slice == 150] = 2
label_slice... | 5,313,509 |
def update_hand(hand, word):
"""
Does NOT assume that hand contains every letter in word at least as
many times as the letter appears in word. Letters in word that don't
appear in hand should be ignored. Letters that appear in word more times
than in hand should never result in a negative count; ins... | 5,313,510 |
def list_zeroes(line):
"""
Takes a list of integers and removes all non-zero elements.
"""
zeroes = []
for item in line:
if item == 0:
zeroes.append(item)
return zeroes | 5,313,511 |
def ecef_to_lla2(x_m, y_m, z_m):
"""Convert ECEF cartesian coordinates to WGS84 spherical coordinates.
This converts an earth-centered, earth-fixed (ECEF) cartesian position to a
position on the Earth specified in geodetic latitude, longitude and altitude.
This code assumes the WGS84 earth model.
... | 5,313,512 |
def ObjectToDict(obj):
"""Converts an object into a dict."""
keys = [ k for k in dir(obj) if not k.startswith("__") ]
return { k : getattr(obj, k) for k in keys } | 5,313,513 |
def writeCmd(cmd):
"""Take in a single integer value (command), try sending it to the arduino
command is wrapped in '<>'. Then wait for confirmation from the uC
"""
# Needed? TODO
while ser.in_waiting > 0:
readLine()
print("Write command: " + str(cmd))
cmd = '<' + str(cmd) + '>'
... | 5,313,514 |
def ortho(subj_coord, obj_coord, subj_dim, obj_dim):
""" It returns a tuple of 3 values: new dim for combined array,
component of subj_origin in it, component of obj_origin in it. """
if subj_coord > obj_coord:
return (subj_coord + (obj_dim - obj_coord), 0,
subj_coord - obj_coord)
... | 5,313,515 |
def _unravel(nodes,tets,index):
"""Returns a list containing the node coordinates of the tet
stored in the 'index' position in the 'tets' list."""
return [nodes[tets[index][0]],nodes[tets[index][1]],nodes[tets[index][2]],nodes[tets[index][3]]] | 5,313,516 |
def save_vtk(res_dir_conf):
"""
Loads arrays from files in results directory. If reciprocal array exists, it will save reciprocal info in tif format. It calls the save_CX function with the relevant parameters.
Parameters
----------
res_dir_conf : tuple
tuple of two elements:
res_dir... | 5,313,517 |
def pairwise(accuracy_balanced, method_names, out_results_dir, num_repetitions):
"""
Produces a matrix of pair-wise significance tests,
where each cell [i, j] answers the question:
is method i significantly better than method j?
The result would be based on a test of choice.
The... | 5,313,518 |
def extract_coverage_per_chr(input_folder, output_folder):
"""
Coverage of location across chromosome for all patient: same as before but trying to figure out if
there is something different between chromosome, we can also export this information to image
:param input_folder: The path of all the files
... | 5,313,519 |
def process_temperature(temperature):
"""
"""
global config_max_temperature
global config_min_temperature
global config_night_max_temperature
global config_gpio_heater
global isNightTime
gpio_state = GPIO.input(int(config_gpio_heater))
maxTemp = 0.00
# Establish what the Max T... | 5,313,520 |
def visdom_image(vis, image,win_name):
"""
eg :
visdom_image(vis=vis, image=drawn_image, win_name='image')
:param vis: 由 setup_visdom 函数创建
:param image: 单幅图片张量,shape:[n,w,h]
:param win_name: 绘图窗口名称,必须指定,不然会一直创建窗口
:return:
"""
vis.image(img=image, win=win_name)
... | 5,313,521 |
def generate_splits_type3(in_data,
slot_data,
intent_data,
instance_types_per_client=3,
clients_per_instance_type=3):
"""Creates non-IID splits of the dataset. Each client is given only a fixed number
of inte... | 5,313,522 |
def is_module_installed(module_name, version=None, installed_version=None,
interpreter=None):
"""Return True if module *module_name* is installed
If version is not None, checking module version
(module must have an attribute named '__version__')
version may star... | 5,313,523 |
def file_num2size(num_size, h=True):
"""文件大小数值变为 MB 的显示
:param num_size: 文件大小
:param h: 是否 human 显示
:return: {'value': 数值,'measure': 单位,'str': 字串, 'org_size': 原始大小}
"""
measure_list = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']
fsize = num_size
i = 0
while (fsize >= 1) and (i < len(measure... | 5,313,524 |
def cartopy_ylim(var=None, geobounds=None, wrfin=None, varname=None, timeidx=0,
method="cat", squeeze=True, cache=None):
"""Return the y-axis limits in the projected coordinates.
For some map projections, like :class`wrf.RotatedLatLon`, the
:meth:`cartopy.GeoAxes.set_extent` method d... | 5,313,525 |
async def test_turn_off_without_entity_id(opp):
"""Test light turn off all lights."""
await opp.services.async_call(
"light", "turn_on", {"entity_id": "all"}, blocking=True
)
assert light.is_on(opp, ENTITY_LIGHT)
await opp.services.async_call(
"light", "turn_off", {"entity_id": "al... | 5,313,526 |
def get_user_csc_name():
"""Get user csc name from saml userdata.
Returns:
[string] -- The users CSC username.
"""
if not is_authenticated() or not is_authenticated_CSC_user() or 'samlUserdata' not in session:
return None
csc_name = session.get('samlUserdata', {}).get(SAML_ATTRIBU... | 5,313,527 |
def get_ip_representations_info(_, identifier):
"""
get:
Get data set structure
"""
try:
dpts = DirectoryPairtreeStorage(config_path_storage)
object_path = dpts.get_object_path(identifier)
package_path = os.path.join(object_path, representations_directory)
tar_fil... | 5,313,528 |
def on_delete(req, resp, user_name):
"""Delete the secret key that grants public access to user_name's
oncall calendar for the logged-in user.
Current policy only allows the logged-in user to get its own key,
so user_name parameter must be the same as the logged-in user.
"""
challenger = req.c... | 5,313,529 |
def precision_Approximation(*args):
"""
* Returns the precision value in real space, frequently used by approximation algorithms. This function provides an acceptable level of precision for an approximation process to define adjustment limits. The tolerance of approximation is designed to ensure an acceptable com... | 5,313,530 |
def get_args():
"""Get command-line arguments"""
parser = argparse.ArgumentParser(
description='Rock the Casbah',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('file',
help='Input file',
metavar='FILE',
... | 5,313,531 |
def get_population_data(read_data=dd.defaultDict['read_data'],
file_format=dd.defaultDict['file_format'],
out_folder=dd.defaultDict['out_folder'],
no_raw=dd.defaultDict['no_raw'],
split_gender=False,
... | 5,313,532 |
def getEpoch( ):
"""
Return the Unix epoch divided by a constant as string.
This function returns a coarse-grained version of the Unix epoch. The
seconds passed since the epoch are divided by the constant
`EPOCH_GRANULARITY'.
"""
return str(int(time.time()) / const.EPOCH_GRANULARITY) | 5,313,533 |
def main(dargs):
"""Will create window with only PlotPower widget, load file and read from it.
Use only of testing or examples
"""
app = QtGui.QApplication(sys.argv)
wid = PlotPower()
wid.fileReader = FileReader.FileReader(dargs['--file'])
wid.startTimer(50)
wid.show()
sys.exit(app.... | 5,313,534 |
def processHyperParamTuningResults(study):
"""
this function depicts the results of the optuna hyperparameter tuning process.
Args:
study (Study): instance of optuna class Study
"""
for key in study.best_params.keys():
print('# ### maximiser ({}) = {}'.format(key, study.best_par... | 5,313,535 |
def build_py_idiv(builder, a, b, name):
"""Build expression for floor integer division.
As seen in Cython:
long q = a / b;
long r = a - q*b;
q -= ((r != 0) & ((r ^ b) < 0));
return q;
"""
q = BuildSDiv(builder, a, b, name + "_q")
r = BuildSub(builder, a, BuildMul(... | 5,313,536 |
def readrec(f,recform='',dumphdr='',numrec=0,skiprec=0, ecodec='cp037',debug=0):
""" readrec - Generator function to read records
with special record format specified in recform
:param f: filehandle of open file
:param recform: record format to process
- 'RDW' variable record forma... | 5,313,537 |
def plot_voltages(cwd='./'):
"""
Routine to plot the numerical solution of the model
"""
f = open(cwd + 'battery.dat', 'rb')
stats = dill.load(f)
f.close()
# convert filtered statistics to list of iterations count, sorted by process
cL = get_sorted(stats, type='current L', sortby='... | 5,313,538 |
def moveeffect_02C(score: int, move: Move, user: Pokemon, target: Pokemon, battle: AbstractBattle) -> int:
"""
Move Effect Name: Increases user's special attack and special defense (Calm Mind)
"""
if user.first_turn:
score += 40
if user.boosts.get("spa", 0) == 6 and user.boosts.get("spd", ... | 5,313,539 |
def all_players_are_ready(game_id):
"""Returns true if the game exists and all players are ready."""
# TODO: acquire lock for game_id
game_json_string = redis.get(game_id)
if game_json_string is None:
# TODO: release lock for game_id
return
game_json = json.loads(game_json_string)
... | 5,313,540 |
def divergence_test(a=0, b=4, steps=100):
"""Compare the q-divergences for various values to illustrate that q_1-div > q_2-div if q_1 > q_2."""
points = []
x = numpy.array([1./3, 1./3, 1./3])
y = numpy.array([1./2, 1./4, 1./4])
d = float(b - a) / steps
for i in range(0, steps):
q = a + i... | 5,313,541 |
def copy_file(src, dst):
"""
Copy the file (or folder) to the specified directory.
You can copy multiple files to the specified directory by listing.
"""
src_type = typeof(src)
dst_type = typeof(dst)
if not src_type == 'str' or 'list':
return 'SRC_INVAILD'
if not dst_type == 'st... | 5,313,542 |
def get_dataset_subsampling_slices(
dataset: xr.Dataset,
step: int,
xy_dim_names: Optional[Tuple[str, str]] = None
) -> Dict[Hashable, Optional[Tuple[slice, ...]]]:
"""
Compute subsampling slices for variables in *dataset*.
Only data variables with spatial dimensions given by
*xy... | 5,313,543 |
def loop_apply_coroutine(loop, func: types.FunctionType, *args, **kwargs) -> object:
"""
Call a function with the supplied arguments.
If the result is a coroutine, use the supplied loop to run it.
"""
if asyncio.iscoroutinefunction(func):
future = asyncio.ensure_future(
func(*arg... | 5,313,544 |
def zipmap(keys, vals):
"""
Return a ``dict`` with the keys mapped to the corresponding ``vals``.
"""
return dict(zip(keys, vals)) | 5,313,545 |
def run_webapp():
"""Run web app."""
from wsgiref import simple_server
httpd = simple_server.make_server(
conf['listen_address'], conf['listen_port'], api)
httpd.serve_forever() | 5,313,546 |
def _create_thingy(sql_entity, session):
"""Internal call that holds the boilerplate for putting a new SQLAlchemy object
into the database. BC suggested this should be a decorator but I don't think
that aids legibility. Maybe should rename this though.
"""
session.add(sql_entity)
#Note t... | 5,313,547 |
def mix_estimator(states, actions, disc_rewards, mask, policy, result='mean'):
"""
states: NxHxm
actions: NxHx1
disc_rewards, mask: NxH
"""
upsilon_scores = policy.loc_score(states, actions) #NxHxm
G = torch.cumsum(upsilon_scores, 1) #NxHxm
sigma_scores = policy.scale_score(states, actio... | 5,313,548 |
def date_range(
start: pandas._libs.tslibs.timestamps.Timestamp,
periods: int,
freq: pandas._libs.tslibs.offsets.YearEnd,
):
"""
usage.statsmodels: 1
"""
... | 5,313,549 |
def test_init(historylog):
"""
Test HistoryLog
Test that the initialization created the expected instance variables
and widgets for a new HistoryLog instance.
"""
hl = historylog
assert hl.get_widget().editors == []
assert hl.get_widget().filenames == []
assert len(hl.get_actions())... | 5,313,550 |
def weighted_loss(func):
"""
A syntactic sugar for loss functions with dynamic weights and average
factors. This method is expected to be used as a decorator.
"""
@wraps(func)
def _wrapper(pred,
target,
weight=None,
reduction='mean',
... | 5,313,551 |
def similarity(s, theta, axis, tx, ty, tz):
"""
Create a 4x4 similarity transformation matrix.
Parameters:
-----------
s: isotropic scaling ratio.
theta: angle of rotation about `thetaaxis`.
axis: a vector (not necessarily a unit vector along the axis of rotation.
tx: translation in... | 5,313,552 |
def compute_sequences_weight(alignment_data=None, seqid=None):
"""Computes weight of sequences. The weights are calculated by lumping
together sequences whose identity is greater that a particular threshold.
For example, if there are m similar sequences, each of them will be assigned
a weight of 1/m. No... | 5,313,553 |
def parameter_bank_names(device, bank_name_dict=BANK_NAME_DICT):
""" Determine the bank names to use for a device """
if device != None:
if device.class_name in bank_name_dict.keys():
return bank_name_dict[device.class_name]
else:
banks = number_of_parameter_banks(device)... | 5,313,554 |
def maxsubarray(list):
"""
Naive approach to calculating max subarray
Iterating all possible subarrays
Complexity (n = list size)
Time complexity: O(n^2)
Space complexity: O(1)
"""
maxStart = 0
maxEnd = 0
maxSum = list[0]
for i in range (len(list)):
currentSum = 0
... | 5,313,555 |
def configureOptions(options, fastqDF):
"""Update the FastQDataframe object with the options given.
Args:
options: A string with options extracted from tsv file.
fastqDF: A FastQDataframe object that needs to be updated.
"""
preprocess, blast = makeOptionsDict(options)
if blast:
... | 5,313,556 |
def time_stats(df):
"""Displays statistics on the most frequent times of travel."""
print('\nCalculating The Most Frequent Times of Travel...\n')
start_time = time.time()
# display the most common month
common_month = df['month'].mode()[0]
print('The most common month: {}'.format(MONTH_LIST[c... | 5,313,557 |
def test_duplicate_ids_2():
"""Node moved and ways/rels with same ID are still present."""
node = t.query_row(t.db_conf, 'osm_all', 31101)
assert node['geometry'].type == 'Point', node['geometry'].type
assert node['tags'] == {'amenity': 'cafe'}
assert node['geometry'].distance(t.merc_point(81, 47)) ... | 5,313,558 |
def deserialize_transaction_data(f):
"""
Deserialize transaction data
More info: https://learnmeabitcoin.com/technical/transaction-data
:param f: buffer, required
:return: dict
"""
transaction = Transaction()
start_transaction_data = f.tell()
transaction.version = f.read(4)[::-1].he... | 5,313,559 |
def test_get_associated_domains(requests_mock):
"""
Given:
- an Expanse client
- Comman Name of the certificates to look for
When
- running !expanse-get-domain
Then
- context prefix should be Expanse.IP and keys should be ip, type, assetType, assetKey
- outputs sh... | 5,313,560 |
def parse_string(string: str) -> list:
"""Parsing specified string
:param string: File content for parsing
:type string: str
:rtype: list
:raises: ParseException
"""
parsed = create_grammar().parseString(string, parseAll=True)
return parse_tokens(parsed) | 5,313,561 |
def reset_config():
"""Reset the configuration.
An endpoint that accepts a POST method. The json request object
must contain the key ``reset`` (with any value).
The method will reset the configuration to the original configuration files that were
used, skipping the local (and saved file).
.. ... | 5,313,562 |
def is_sequence(obj):
"""Is the object a *non-str* sequence?
Checking whether an object is a *non-string* sequence is a bit
unwieldy. This makes it simple.
"""
return isinstance(obj, Sequence) and not isinstance(obj, str) | 5,313,563 |
def sample_points(rng, N=None, conc=None, lower=None, upper=None, start=0, ndim=3):
"""Generate points distributed uniformly.
Args:
rng (numpy.RandomState, optional): A random number generator.
N (int or list, optional): The number of points to be generated.
conc (float or list, optiona... | 5,313,564 |
def make_exponential_statistics(state):
"""Make ExponentialMovingStatistics object from state."""
return ExponentialMovingStatistics.fromstate(state) | 5,313,565 |
def destination_writer(oqueue, destination, use_destination_tuple=False, **kwargs):
"""
Reads items from the oqueue and writes them to the destination. If we get an error during writing,
we pass the exception on to the caller which should abort the worker processes immediately.
:param oqueue: the queue ... | 5,313,566 |
def DetectAio(timeout=1.1):
"""Detect AIO nodes on the network, present all options if none detected."""
sources = aio.aio_node_helper.Names()
types = aio.message_type_helper.Names()
client = aio.AioClient(types, timeout=0.1, allowed_sources=sources)
ip_list = []
version_list = []
timer_start = time.time(... | 5,313,567 |
def getAxisList(var):
"""
Returns a list of coordinates from: var
"""
return [var.coords[key] for key in var.dims] | 5,313,568 |
def listify(fn=None, wrapper=list):
"""
From https://github.com/shazow/unstdlib.py/blob/master/unstdlib/standard/list_.py#L149
A decorator which wraps a function's return value in ``list(...)``.
Useful when an algorithm can be expressed more cleanly as a generator but
the function should return an... | 5,313,569 |
def skip_nothing(name, dirpath):
"""Always returns :obj:`False`.
"""
return False | 5,313,570 |
async def test_form_cannot_connect(hass):
"""Test we handle cannot connect error."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
mock_pynut = _get_mock_pynutclient()
with patch(
"homeassistant.components.nut.PyNUTClie... | 5,313,571 |
def get_nightly_stats():
"""
A periodic task (probably running nightly) to get counts of user types, disk usage.
Write them into a DB for our stats view
"""
# Five types user accounts
total_count_regular_users = LinkUser.objects.filter(is_staff=False, organizations=None, registrar_id=None).... | 5,313,572 |
def _load(fpath):
"""Get content of json file at <fpath>."""
if not pth.__is_file(fpath):
log.critical("\"{0}\" doesn\'t exist, can\'t load data from it".format(fpath))
log.debug("Loading data from \"{0}\"".format(fpath))
fjson = pth.__open_file(fpath)
ret = json.load(fjson)
pth.__clos... | 5,313,573 |
def get_version_number(klocwork_path):
"""This function determines the Klocwork version number.
Inputs:
- klocwork_path: Absolute path to the bin directory of the Klocwork installation [string]
Ouputs:
- version_number: The version number of the Klocwork instance being tested [string]
... | 5,313,574 |
def titlecase(string):
"""Titlecase all words in the string.
Words with quote (') titlecased only in the beginning, as opposed to
built-in ``str.title()``. Roman numerals are uppercased.
"""
def f(mo):
roman_mo = ROMAN_PATTERN.match(mo.group())
if roman_mo:
return mo.gro... | 5,313,575 |
def register(key=None):
"""Returns a decorator registering a widget class in the widget registry.
If no key is provided, the class name is used as a key.
A key is provided for each core Jupyter widget so that the frontend can use
this key regardless of the language of the kernel.
"""
def wrap(w... | 5,313,576 |
def load_data_dict(project_dir_string):
"""Load data from a colab_zirc_dims project folder into a dictionary.
Parameters
----------
project_dir_string : str
Path to a colab_zirc_dims project folder.
Returns
-------
Dict
A dict of dicts containing data from project folder w/... | 5,313,577 |
def invoke_commandlet(name, arguments):
"""Generic function for running a commandlet with its arguments."""
if os.name == "nt":
sys_name = "Win64"
elif os.name == "posix":
sys_name = "Linux"
ue4_path = os.environ["UE4_ROOT"]
editor_path = "%s/Engine/Binaries/%s/UE4Editor" % (ue4_path... | 5,313,578 |
def run(arg):
"""Run the command. """
make_directories()
make_config_file(arg)
make_bashrc(arg)
update_entries(pth.abspath('.')) | 5,313,579 |
def make_interactive(multiple: bool = True) -> None:
"""Enable interaction with the current Matplotlib figure."""
mplcursors.cursor(multiple=multiple) | 5,313,580 |
def _postgresql_remove_query_funcs():
"""
Drops the following functions that were intented to make queries effective:
is_numeric(TEXT) RETURNS BOOLEAN
orcm_comma_list_to_regex(list TEXT, comma BOOLEAN DEFAULT TRUE) RETURNS TEXT
query_event_data(ts_from TIMESTAMP, ts_to TIMESTAMP, nodes T... | 5,313,581 |
def find(pattern):
"""
Find all instances where the pattern is in the running command
.. code-block:: bash
salt '*' nxos.cmd find '^snmp-server.*$'
.. note::
This uses the `re.MULTILINE` regex format for python, and runs the
regex against the whole show_run output.
"""
... | 5,313,582 |
def get_center(arcs):
"""Centre of the arc
Args:
arcs: tensor [batch_size, num_arcs, 7]
arcs[b, i] = [x_start, y_start, dx, dy, theta, sharpness, width]
Returns: tensor [batch_size, num_arcs, 2]
"""
x_start = arcs[..., 0]
y_start = arcs[..., 1]
dx = arcs[..., 2]
dy ... | 5,313,583 |
def get_urls_towns(url_index_by_letter):
"""Provides from the page corresponding to a city index the pages corresponding to the cities of the index.
Args:
url_index_by_letter (string): Url corresponding to a city index
e.g. : "https://elections.interieur.gouv.fr/municipales-2020/080/080G.html"... | 5,313,584 |
async def test_get_next_pickup_event_type2(aresponses):
"""Test getting the next pickup event from data sample 2."""
aresponses.add(
"api.recollect.net",
f"/api/places/{TEST_PLACE_ID}/services/{TEST_SERVICE_ID}/events",
"get",
aresponses.Response(
text=load_fixture("p... | 5,313,585 |
def simple_app(global_config, **settings):
"""This function returns a Pyramid WSGI application."""
with Configurator(settings=settings) as config:
config.set_security_policy(TestingSecurityPolicy())
apps = global_config.get('apps', '')
if not isinstance(apps, (list, tuple)):
... | 5,313,586 |
def _sized_dataframes(dataframe: pd.DataFrame) -> tuple:
""" Determines optimal chunks to publish the dataframe in. In smaller dataframes
this may be the whole dataframe.
This is determined by the hard values of 60MB being ideal for Spectrum, and
assumed compression ratio for dataframes to parquet bein... | 5,313,587 |
def imgs_preds(model_config: tuple[Model, tuple[int, int]], path: str, slc: Optional[slice] = None) -> list[
list[str, str]]:
"""
Get the predicted class for each image
:param model_config: model object and image dimensions that the model expects to receive
:param path: path to image directory
... | 5,313,588 |
def custom_config(app):
"""Configs that don't follow flask documentation but are required by our domain."""
# Related to https://flask-restful.readthedocs.io/en/0.3.6/quickstart.html?highlight=ERROR_404_HELP
app.config["ERROR_404_HELP"] = False | 5,313,589 |
def vertical_cross(in_field, lon, lat, line_points, npts=100):
"""
Interpolate 2D or multiple dimensional grid data to vertical cross section.
:param in_field: 2D or multiple dimensional grid data,
the rightest dimension [..., lat, lon].
:param lon: grid data longitude.
:param ... | 5,313,590 |
def write_wordlist(wordlist):
"""
Write a wordlist to a temporary file.
"""
handler = NamedTemporaryFile("w", encoding="utf-8", delete=False)
writer = csv.DictWriter(
handler, delimiter="\t", fieldnames=list(wordlist[0].keys())
)
writer.writeheader()
writer.writerows(wordlist)
... | 5,313,591 |
def add_sha256_to_csv(csv_file_path):
""""Opens CSV as dataframe, then adds sha256 column, then saves CSV."""
dataframe = pandas.read_csv(csv_file_path)
new_dataframe = return_dataframe_with_added_sha256_hash(dataframe)
new_dataframe.to_csv(csv_file_path, index=False) | 5,313,592 |
def swap_to_main_menu_screen():
"""
Show the main menu screen
"""
delete_element_next_frame(ui_data.focused_element_name)
screen = MainMenuScreen(ui_data.gui, Rect((0, 0), (BASE_WINDOW_WIDTH, BASE_WINDOW_HEIGHT)))
ui_data.new_elements["main_menu"] = screen
set_focused_element("main_menu")
... | 5,313,593 |
def get_promotions_pmu():
"""
Affiche les promotions proposées sur pmu
"""
url = "https://paris-sportifs.pmu.fr/promotions/3"
soup = BeautifulSoup(urllib.request.urlopen(url), features="lxml")
out = ""
for line in soup.find_all():
if "class" in line.attrs and "node-pmu-promotions" in... | 5,313,594 |
def pytest_configure(config: PyTestConfig):
"""
Configuration hook which reconfigures the logging and calls the global setup function.
"""
_reconfigure_logging()
helpers.setup()
Log.info("Pytest configuration hook finished successfully") | 5,313,595 |
def hasfield(model_cls, field_name):
"""
Like `hasattr()`, but for model fields.
>>> from django.contrib.auth.models import User
>>> hasfield(User, 'password')
True
>>> hasfield(User, 'foobarbaz')
False
"""
try:
model_cls._meta.get_field(field_name)
return True
e... | 5,313,596 |
def get_distance(point_a, point_b):
"""Receives two coordinates by parameter, and returns the geodesic distance between them (in km).
Params:
- point_a: tuple or list expected, first coordinate
- point_b: tuple or list expected, second coordinate
Returns:
- Formatted string indicati... | 5,313,597 |
def test_get_part_count_lambda_b_no_type():
"""get_part_count_lambda_b() should raise a KeyError when passed an unknown type
ID."""
with pytest.raises(KeyError):
efilter.get_part_count_lambda_b(14, 8) | 5,313,598 |
def __substitute_controller_variables(config):
"""Substitute variables and set defaults for config
Arguments:
config {dict}
Raises:
Exception: [description]
Returns:
[dict]
"""
global_variables = config.get("variables", {})
set_master_password = global_variables.ge... | 5,313,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.