content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import List
import pickle
def decode_aov_mime_data(mime_data: QtCore.QMimeData) -> List:
"""Decode AOV data from the mime data.
:param mime_data: The mime data to decode from.
:return: A list of AOV related items.
"""
return pickle.loads(mime_data.data(_AOV_MIME_TYPE).data()) | 83e4e3ffa771ebfa04357ee441e32adadd3b7502 | 79,706 |
def isprimitive(body):
"""
Given the body of a request will return a boolean to indicate if the
value is a primitive value type.
See:
http://doc.fluidinfo.com/fluidDB/api/tag-values.html
&
http://bit.ly/hmrMzT
For an explanation of the difference between primitive and opaque
val... | 8b94aa878a04740de0cebe6a53b9027f5ef55b17 | 79,707 |
def getTimeseries():
""" """
lat = request.json.get('lat')
lng = request.json.get('lng')
filename = app.config['TS_FILENAME']
ts = timeseries(filename, lng, lat)
return jsonify({
'timeseries': ts,
'regression': []
}), 200 | 2bf2b26649aaaf1ef290a212205275fe5f853d8f | 79,708 |
def get_overpass_area_id(place):
"""
Geocode a place with Nominatim and get the matching ID to use in Overpass
queries.
:param place: Place name.
:returns: The ID to use as an Overpass place id.
"""
osm_type, osm_id = nominatim.geocode_place(place)
# See https://wiki.openstreetmap.org/w... | 2ac0d8669a63c17cca7ef7126d24d143e5d7e11c | 79,709 |
def _default_inner_shape_for_pylist(pylist, ragged_rank):
"""Computes a default inner shape for the given python list."""
def get_inner_shape(item):
"""Returns the inner shape for a python list `item`."""
if not isinstance(item, (list, tuple)):
return ()
elif item:
return (len(item),) + get... | 33ef55f87c65707ff2f92989ba6874964042fddf | 79,710 |
def get_progress_string(tag, epoch, minibatch, nbatches, cost, time,
blockchar=u'\u2588'):
"""
Generate a progress bar string.
Arguments:
tag (string): Label to print before the bar (i.e. Train, Valid, Test )
epoch (int): current epoch to display
minibatch (i... | 9c5a927433795426fe6466708d24b925ae37e4a5 | 79,711 |
import traceback
def delete_menu_role():
"""
删除页面权限
:return:
"""
result = None
try:
data = request.get_data(as_text=True)
sql = "select deletemenurole('{}');".format(data)
result = current_app.db.query(sql)[0]['deletemenurole']
except Exception as e:
curren... | 9f9b294754930517c2ee7cab54f9d0f993014d44 | 79,712 |
def get_matching_led(led: str) -> hex:
"""
Returns a mathching Led object from the :class:`luxafor.Leds` based
on the user input in the CLI.
If no valid input is given defaults to all leds.
"""
led_group = getattr(luxafor.Leds, led.upper(), False)
if led_group:
return led_group
... | 11ed0dca647161cf97dd0cc80935c9036cbd262e | 79,713 |
def _gu_sum(a, **kwds):
"""Sum over last axis for the use in generalized ufuncs.
`np.sum` is more accurate over the fast axis,
so we ensure the array to be c-contiguous.
"""
return np.sum(np.ascontiguousarray(a), axis=-1, **kwds) | d52a626221a1f6fb68695f4daa7c3f8db385dc9a | 79,714 |
import functools
def build_query_encoder(problem, data_dir, embed_code=False):
"""Build a query encoder.
Args:
problem: The name of the T2T problem to use
data_dir: Directory containing the data. This should include the vocabulary.
embed_code: Whether to compute embeddings for natural language or cod... | 36bce180e99063070f8cc6c06b095cbb0c7d4eff | 79,715 |
import csv
import logging
def _getSyncSpecsFromCsv():
"""Returns a list of tuples of the form (source name, source environment,
destination name, destination environment, exclude file, set of paths to
sync) taken from the CSV configuration file if one was specified.
"""
results = []
with open(... | 4a45b9a19889b6e06c9d4836c64158103042ff5c | 79,717 |
import random
def coin_toss():
"""Simulates a coin toss."""
coin = random.randint(0,1)
if coin == 0:
return 0
else:
return 1 | 4b02cf069963d53b5cafd75bbdcfcdeb55d8eb4d | 79,718 |
import csv
def file2dict(filename,key_fields,store_fields,delimiter='\t'):
"""Read file to a dictionary.
key_fields: fields to be used as keys
store_fields: fields to be saved as a list
delimiter: delimiter used in the given file."""
dictionary={}
with open(filename, newline='') as csvfile:
... | 1b2d980c9c1c45b635c8d73302ba1c155baf4f1d | 79,719 |
def expand_contractions(sentence):
"""
Replaces the contractions by the equivalent meaning, but without contraction
Input=sentence Output=sentence
"""
# init
i = 0
while i < len(sentence):
if case_apostrophe_s_to_is(sentence[i]) == 1:
sentence = c... | 2d200c1607e25f1eb9a8220eea09c35b8fbb32f8 | 79,720 |
from typing import Any
def build_get_enum_def_by_name_request(
name: str,
**kwargs: Any
) -> HttpRequest:
"""Get the enum definition by its name (unique).
See https://aka.ms/azsdk/python/protocol/quickstart for how to incorporate this request builder into your code flow.
:param name: The name of... | 6d5e7ef5606bae4ff04fd5217029ab110a8303e4 | 79,722 |
import json
def interface_format_params(params_list):
"""
格式化存入数据库中的参数
:param params_list:
:return:
"""
if params_list:
var = []
params_list = eval(params_list)
for i in range(len(params_list)):
var.append({"var_name": "", "var_remark": ""})
var[... | 9663b07c2ad19e4f51118441babf1ef2b04e239a | 79,723 |
def list_items_from_an_order(order_id):
""" Returns all items from an Order
---
tags:
- Orders
produces:
- application/json
description: The Orders endpoint allows you to query Orders to get all items in that order
parameters:
- name: order_id
in: path
descripti... | ca6e2e96e07102daa1831bf38001d0b7407dca46 | 79,724 |
import regex
import collections
import math
def gpt3mix_complete(prompt, n, labels_list, exp_dict, name2id):
"""
Given a seed_text and its corresponding seed_intent (name, not id),
1. generate x_dash (n augmentations per seed_text)
2. generate y_dash (soft label using name2id)
"""
pattern = r... | db885d0300e65f8387a6d175e4e8b7ca87aeea6d | 79,726 |
def pypi_metadata(scoped_pkgs, pkg_list, private_ns=None):
"""
Method to query pypi for the package metadata
:param pkg_list: List of packages
:param private_ns: Private namespace
"""
return metadata_from_registry("pypi", scoped_pkgs, pkg_list, private_ns) | 78a56f5ca2a57ae44093f2d39042c159cea2fd8a | 79,727 |
def is_terminal(state):
"""Return true if the task reached terminal state."""
return state in [
mesos_pb2.TASK_FINISHED,
mesos_pb2.TASK_KILLED,
mesos_pb2.TASK_FAILED,
mesos_pb2.TASK_LOST] | 8d4d815db591f1a4c8d8329d43acf0a5eb05ebbe | 79,728 |
def collect_dual_representation(block, fixed_modelvars):
"""
Process linear terms from a block and return information that is
used to define the dual. This function does not change the block.
Note that variable bounds are treated as constraints unless they are zero. For example,
a variable X with ... | 72df823827b97a35edb88c21fe1c966ad7a1c030 | 79,730 |
def svn_fs_unlock(*args):
"""
svn_fs_unlock(svn_fs_t fs, char path, char token, svn_boolean_t break_lock,
apr_pool_t pool) -> svn_error_t
"""
return _fs.svn_fs_unlock(*args) | 85678ea41ade46dab8face919d73c775e5b9b558 | 79,731 |
def _get_hive_connection_by_rt_id(result_table_id):
"""
:param result_table_id: 结果表id
:return: hive conn
"""
geog_area_code = util.query_result_table_geog_area(result_table_id)
return hive_util.get_hive_connection(geog_area_code) | 456bf7e8c21d516541e2e35e561ef06db79ff267 | 79,732 |
def create_pqu_spectra_RMthin(freqArr_Hz, fracPol, psi0_deg, RM_radm2):
"""Return fractional P/I, Q/I & U/I spectra for a Faraday thin source"""
# Calculate the p, q and u Spectra
lamSqArr_m2 = np.power(C/freqArr_Hz, 2.0)
pArr = fracPol * np.ones_like(lamSqArr_m2)
quArr = pArr * np.exp( 2j * (n... | e496175d0b7f893538b4b90faf1358360830f1f2 | 79,734 |
def run_single_batch_em(models, num_components_per_model, filename_prefix, i_max, seed=42,
batch_size=None, step_size=1.0, known_covariance=False):
"""
Performs batch EM with random initialization defined by a given seed, and saves plots of the log-likelihood (ll)
curve and gmm spati... | 174a74b4eecf2afdcd1d1ab1234a442ce4496bca | 79,735 |
import math
def dihedral(r1,r2,r3,r4):
"""
dihedral
=======
Calculate dihedral angle associated with 4 sets of ordered 3-D Cartesian coordinates r1,r2,r3,r4.
Returns value in radians.
"""
q1 = [r2[0]-r1[0],r2[1]-r1[1],r2[2]-r1[2]] # vector r1-r2
q2 = [r3[0]-r2[0],r3[1]-r2[1],r3[2]-r2[2... | 4d83cabf31679542fd452338d1d2c427a8df37d8 | 79,736 |
import test
def calibration(y_true, pred_proba, n_bins=10, in_sample=False):
"""Calibration and test of predictive model.
Parameters
----------
y_true : `np.array` or `pandas.Series`
True label.
pred_proba : `np.array` or `pandas.Series`
Predicted label.
n_bins : int
N... | 08d63a69b6c9596b17a045c3fdffe0bcd914c2e6 | 79,737 |
def parseString(string, parser=None):
"""Parse a file into a DOM from a string."""
builder = ExpatBuilderNS()
return builder.parseString(string) | 56ec8acac86bcfcf34503a72c3b5f883da83be90 | 79,738 |
from typing import Union
from pathlib import Path
from typing import Optional
from typing import List
from typing import OrderedDict
import csv
def read_csv_file(file_name: Union[str, Path],
base_dir: Optional[Union[str, Path]] = 'csv_files') \
-> List[OrderedDict]:
"""Reads a CSV file.
... | e4f9d88101d373a1b40f8c81b55529223fd097df | 79,739 |
from typing import List
from typing import Dict
from typing import Any
def _create_trial_frame_list(
trial: List[Dict[str, Any]]
) -> List[Dict[str, Any]]:
"""Return all the frames in the given trial that we want to keep in the
final MCS scene using the agent's movement. Skip about half of the frames
... | b6632c01ea32a5f311e7433bf8319a5d537902e6 | 79,740 |
import itertools
def dict_from_matrix(mat, alphabet=parasail_aa_alphabet):
"""
Converts substitution matrix to a dict for use
by str_subst_metric. Does not store (aa1, aa2) and
(aa2, aa1), so user needs to check for both. Similarity
for any symbol not present in the aplhabet is stored in
key "... | da7ede4153edbd04a6737115caf915828847738b | 79,741 |
def cell_has_code(lines):
"""Is there any code in this cell?"""
for i, line in enumerate(lines):
stripped_line = line.strip()
if stripped_line.startswith('#'):
continue
# Two consecutive blank lines?
if not stripped_line:
if i > 0 and not lines[i - 1].str... | c7094accae4d7c1a9f8eae3aa33eda2e980993bb | 79,742 |
def get_user_info():
"""
从session中得到用户的access_token和openid得到用户的基本信息
:return:
"""
if 'qq_access_token' in session:
openid = session.get('openid')
access_token= session.get('qq_access_token')
logger.info("【openid】" + str(openid))
logger.info("【access_token】" + str(acces... | eeb8980dc5386a15f7c4f1edeadd0c912a621687 | 79,743 |
def validate_device_cookie(request, email) -> bool:
"""
Validating device cookie.
https://www.owasp.org/index.php/Slow_Down_Online_Guessing_Attacks_with_Device_Cookies
"""
cookie = request.COOKIES.get(settings.DEVICE_COOKIE_NAME)
user_email = None
date_period = timezone.now() - timezone.tim... | c19a45b33cc779a3f539bd96a9c5c716a3cced1a | 79,744 |
def pointsInRect(array, rect):
"""Determine which points are inside a bounding rectangle.
Args:
array: A sequence of 2D tuples.
rect: A bounding rectangle expressed as a tuple
``(xMin, yMin, xMax, yMax)``.
Returns:
A list containing the points inside the rectangle.
... | 53fdd42520c38b3ffcb19edc655955caf063ebfc | 79,745 |
def _get_nearest_value(value, step_width):
"""
helper function. Sould not be used from the api.
:param value:
:param step_width:
:return:
"""
steps = value // step_width
return min(steps * step_width, (steps + 1) * step_width, key=lambda new_value: abs(new_value - value)) | c2af02e059ec62911bf549b4b5d6013e02e34df9 | 79,746 |
def compute_cost(Z3, Y):
"""
Computes the cost
Z3 - output of forward propagation (output of the last LINEAR unit), of shape (6, number of examples)
Y - "true" labels vector placeholder, same shape as Z3
cost - Tensor of the cost function
"""
cost = tf.nn.softmax_cross_entropy... | 9555484fb9c2b6fe0fa9e95013932b09bcf194f9 | 79,747 |
def advisory_lock(curs, schemaname, tablename):
"""
Table locking for protection against parallel processing
"""
query = """
select
pg_try_advisory_lock('pg_catalog.pg_class'::regclass::integer,
(quote_ident('{schemaname}') || '.' || quote_ident('{tablename}'))::regclas... | fbdd57617f5311733532bd05c0d45b4dba0f5fdb | 79,748 |
import torch
def symmetric_edge_weights(source: torch.LongTensor, target: torch.LongTensor) -> torch.FloatTensor:
"""Normalize messages by product of inverse sqrt of in-degree and out-degree.
:param source: shape: (num_edges,)
The source indices.
:param target: shape: (num_edges,)
The tar... | e2efbf8d5fb8d1f40b7715c08078e16e31540aae | 79,749 |
from typing import Iterable
def make_pythran_code_functions(
functions: Iterable[str], signatures_func: dict, codes_functions: dict
):
"""Create the pythran code for all functions
Parameters
----------
functions : list
signatures_func : dict
codes_functions: dict
"""
code_pyth... | b8c7572ecd89bde6ffcd2dfbda52dbcbf8118718 | 79,750 |
def numtocn(data, cny=True):
"""
算法说明:要求字符串输入,现将字符串差费为整数部分和小数部分生成list[整数部分,小数部分]
将整数部分拆分为:[亿,万,仟]三组字符串组成的List:['0000','0000','0000'](根据实际输入生成阶梯List)
例如:600190000010.70整数部分拆分为:['600','1900','0010']
然后对list中每个字符串分组进行大写化再合并
最后处理小数部分的大写化
"""
cdict = {1: '', 2: '拾', 3: '佰', 4: '仟'} if cny els... | e7c07b19d426b3c0abeaa4a6ae8058f6391b316e | 79,751 |
def filter_val(pic, width, height, tol=20.):
"""Compute the barycenter of a point cloud which pixel grey value is above a given threshold
:param pic: picture array grey values
:param width: picture width
:param height: picture height
:param tol: filter tolerance (default 20)
:return: barycenter x and y coordinat... | 60c3a40909424e25ab99e78d21e5d71a67c103c1 | 79,753 |
from ...utils.misc import trim
def format_help(cls):
"""
Prints help text of a Nipype interface
>>> from nipype.interfaces.afni import GCOR
>>> GCOR.help() # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
Wraps the executable command ``@compute_gcor``.
<BLANKLINE>
Computes the average correla... | 75f24f2a4b703a1feecdeaaea35e05a8b1f04528 | 79,754 |
def get_vnetwork_hosts_rpc(self, vcenter=None, datacenter=None, name=None, last_rcvd_instance=None, api_timeout=''):
"""
This is an auto-generated method for the PySwitchLib.
**Supported Versions**:
* NOS: 6.0.2f, 7.2.0
* SLXOS: 17r.1.01a, 17r.2.00, 17s.1.02
**Instance Argument(s)... | 35a8ef564088319c37d1e60e27976564ff492371 | 79,755 |
def find_min_doubling_time_ci(model_fit, param_samples, ci=0.95):
"""Estimates a confidence interval for the minimal doubling time from the model fit.
The minimal doubling time for each parameter sample is calculated.
The confidence interval of the doubling time is the lower and higher percentiles such tha... | 3cac83e569c9d26109829c9e62e9edcf0d575d6a | 79,756 |
import pandas
import requests
def get_trailhead_df():
"""
Convert the current "Donohue Exit Quota and Trailhead Space Available" HTML table
to a pandas.DataFrame.
"""
pandas_version = parse_version(pandas.__version__)._version.release
if pandas_version[:2] == (0, 23):
# read_html malfu... | d8ada9613c6cefd9734803bb295318dae77df7ae | 79,757 |
def get_timestep(config):
"""Get the model timestep from a configuration dictionary.
Args:
config (dict): a configuration dictionary
Returns:
datetime.timedelta: the model timestep
"""
return timedelta(seconds=config["namelist"]["coupler_nml"]["dt_atmos"]) | b645b1d8a6cf423d5b5c8cb4507ef99b20c4c800 | 79,759 |
def build_get_negative_ten_billion_request(
**kwargs # type: Any
):
# type: (...) -> HttpRequest
"""Get '-10000000000' 64 bit integer value.
See https://aka.ms/azsdk/python/protocol/quickstart for how to incorporate this request builder
into your code flow.
:return: Returns an :class:`~azure.... | 05c7916671bb86a4d6afe50b6a91557582da3b44 | 79,760 |
def clip(number,start,end):
"""Returns `number`, but makes sure it's in the range of [start..end]"""
return max(start, min(number, end)) | c2fed329f855e36c08a05cc5e72d33e743c183c4 | 79,761 |
from typing import Optional
def get_dicom_store(dataset_id: Optional[str] = None,
dicom_store_id: Optional[str] = None,
location: Optional[str] = None,
project: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> Awaitab... | 3ff1a74acea7947cb6d8f29b32609c8da9f9774d | 79,762 |
def get_downsample_pct(in_bam, target_counts, data):
"""Retrieve percentage of file to downsample to get to target counts.
Avoids minimal downsample which is not especially useful for
improving QC times; 90& or more of reads.
"""
total = sum(x.aligned for x in idxstats(in_bam, data))
with pysam... | d3eb841cd2a536f2f0db72375dc92f7725460a6a | 79,763 |
def index():
"""administration home page"""
blog_entries = db.session.query(BlogEntry).order_by(BlogEntry.created.desc())
return render_template('admin/index.html', blog_entries = blog_entries) | ef29a04c3446dfc92f6348d29d1cb8b394e667a7 | 79,764 |
def crbf_bump_scaled(sq_d: tf.Tensor, sq_r: tf.Tensor) -> tf.Tensor:
"""
Bump function, the function is scaled so that the maximum at r=0 has value 1.
:param sq_d:
:param sq_r:
:return:
"""
return crbf_base(sq_d=sq_d, sq_r=sq_r, core=lambda r: tf.exp(-1./(1 - tf.square(r)))/tf.exp(-1.)) | 3f5d18c2d6171f05f41fbe2534c936f588ea9bd6 | 79,765 |
def mean_feat(col_list, feature, feat_table):
"""
trace_df() can output for eg. TR and SI values off nn nearest neighbour
positions. This function calculates the mean of all neighbouring positions
and also the zero position and returns a pandas Series of the means for
each read
Parameters
-... | 4acbddc86aceb69d4e6f624c9c5927084020d44f | 79,766 |
def prettify(elem):
"""Return a pretty-printed XML string for the Element
"""
rough_string = ET.tostring(elem, 'utf-8')
reparsed = minidom.parseString(rough_string)
return reparsed.toprettyxml(indent="".join([' '] * 4)) | 1181b04834dd54be52ad4731e0df6c2982027091 | 79,767 |
from operator import sub
def optkey(axisName, suffix):
"""
Returns a string suitable for a key to an axis-opts sub-dict,
uniquely determined by the I{axisName} and I{suffix}.
"""
return sub("{}_{}", axisName.lower(), suffix) | 457d3de85edf28a78b201565b93d429556acf9ad | 79,768 |
def jwt_payload_for_user(user: "User") -> dict[str, any]:
"""Get payload for creating user's JWT"""
return {"id": user.id} | 8c17a8155f5a98e619cff63a2a4a21948c086704 | 79,769 |
from arviz import utils
from unittest.mock import Mock
def utils_with_numba_import_fail(monkeypatch):
"""Patch numba in utils so when its imported it raises ImportError"""
failed_import = Mock()
failed_import.side_effect = ImportError
monkeypatch.setattr(utils.importlib, "import_module", failed_impo... | b96e57670db731ecad8ed076b789a36df2987781 | 79,770 |
import time
def setup_bootstrap_in_namespace(namespace, bs_deployment_info, bootstrap_config, gen_time_del, oracle=None, poet=None,
file_path=None, dep_time_out=180):
"""
adds a bootstrap node to a specific namespace
:param namespace: string, session id
:param bs_depl... | 4e9f2d1263df03856b373935015ab81c645d96b1 | 79,771 |
import tokenize
def condense_lines(code):
"""Take an array of code, join lines ending with a \, and return"""
"""the new array"""
s = ''
r = []
for line in code:
if line.endswith(' \\\n'):
s = s + ' ' + line[:-2].strip()
else:
s = s + ' ' + line.strip()
... | d0ed3bdb689cf0568f2f6b3eeaa363037120855a | 79,773 |
def get_display_name(word: np.array) -> str:
"""Returns the uppercase string of byte array.
e.g. np.array(b's', b't', b'o', b'a', b'e') -> 'STOAE'
"""
return ''.join([l.decode("utf-8") for l in word]).upper() | 6a4c6b705d97c8b6cc84ed8e981e093b72d649c9 | 79,774 |
def coordiate_match_offset_arrays(bbox1, array1, bbox2, array2):
"""
given two image regions with slightly different bounding boxes.
this function transorms each image so that it is within a common bounding box and
returns a tuple containing both origional images and the new bounding box coords.
pa... | 877fac8248cb9d67de13ef1802ce253d9fa22504 | 79,775 |
def temp_date_range(startDate,endDate):
"""Fetch the TMIN, TAVG and TMAX given a start/end date
variables supplied by the user, or a 404 if not."""
if isinstance(endDate,str):
print(f"Both Dates passed - Determine agg funcs over date range")
validate(startDate)
validate(endD... | e1b26cda9a42f271750dcc61e87f2eeaf9b912ce | 79,776 |
import textwrap
def sphere(r, maxh, save_result=True, filename='', directory=''):
"""
Returns a dolfin mesh object describing a sphere with radius `r`
and given mesh coarseness maxh.
If `save_result` is True (the default), both the generated geofile
and the dolfin mesh will be saved to disk. By d... | 3cb6a69f61e28182a8bbfec3b98facdba52f3511 | 79,777 |
def _gl_attr(x):
"""Helper to return gl.GL_x enum"""
y = 'GL_' + x.upper()
z = getattr(gl, y, None)
if z is None:
raise ValueError('gl has no attribute corresponding to name %s (%s)'
% (x, y))
return z | d1b46f189e5c043d8f3d2de445acacc611e9a8f5 | 79,778 |
def autodiff_bprop(n):
"""get bprop function"""
return bprop_factory.get(n) | 74fb5d37153900785031c38b28be6018dcbcc83e | 79,779 |
def _transform_filter_to_sql(filter_block, node, context):
"""Transform a Filter block to its corresponding SQLAlchemy expression.
Args:
filter_block: Filter, the Filter block to transform.
node: SqlNode, the node Filter block applies to.
context: CompilationContext, global compilation ... | e36578ca8acba1a05f266230714da38e53bc0ab9 | 79,780 |
def sumByKey(keys, vals, dim=-1, nan_val=None):
"""
Calculate the sum of elements along a specified dimension according to a key.
Parameters
----------
keys : af.Array
One dimensional arrayfire array with reduction keys.
vals : af.Array
Multi dimensional arrayfire array that... | 4f48b68260a2f4f4dbcf1a77e85a49e35568df30 | 79,781 |
def sparseFeature(feat, feat_num, embed_dim=4):
"""
create dictionary for sparse feature
:param feat: feature name
:param feat_num: the total number of sparse features that do not repeat
:param embed_dim: embedding dimension
:return:
"""
return {'feat_name': feat, 'feat_num': feat_num, '... | 69a145ed5a40fb63f38e23c1279289fdb97656a7 | 79,784 |
def initialize_db(
arango_url=ARANGO_URL,
arango_user=USER,
arango_password=PASSWORD):
"""Initialize database"""
# Initialize the ArangoDB client.
client = ArangoClient(hosts=arango_url)
# Connect to "_system" database as root user.
# This returns an API wrapper for "_syste... | 2068bfb7d1be7623e09c61250ff0d3cf8c8514e0 | 79,785 |
def get_nested_value(d: dict, path: dict):
"""
Retrieves value from nested dictionary
:param d: {key: {key_2: {key_2_1: hey}, key_1: 1234}
:param path: {key: {key_2: key_2_1}} path to take through the dictionary d
:return: d[key][key_2][key_2_1]
"""
if isinstance(path, dict):
for k, ... | a9eaf03cd549b6794b4ea7ffd9bb3ab853a7d35d | 79,787 |
from typing import Dict
from typing import Any
def serialize_dict(data: Dict[str, Any]) -> Dict[str, Any]:
"""Serializes UFP data dict"""
for key in list(data.keys()):
data[to_camel_case(key)] = serialize_unifi_obj(data.pop(key))
return data | f0ae46701b410a68db52b34a5e6ddbd0b16f9871 | 79,788 |
def get_class_by_tablename(tablename):
"""Return class reference mapped to table.
:param tablename: String with name of table.
:return: Class reference or None.
"""
for c in Base._decl_class_registry.values():
if hasattr(c, '__tablename__') and c.__tablename__ == tablename: #c.__table__.fullname == table... | 233380b51bdcec393e67165eb9b22066690306fc | 79,789 |
def field_anti_helmholtz(coil_turns, R, D, I, r):
"""Calculate field inside anti-helmholtz coils.
Their normal vector points in the z direction.
First coil is in the position [0, 0, D] and its normal vector n points in
the +z direction.
The current I direction follows the right hand-rule regarding... | 7c3f6fcaf2d0641c9b9e7577f7716ca81998a27c | 79,790 |
import itertools
def color_reducer(c1, c2):
"""Helper function used to add two colors together when averaging."""
return tuple(v1 + v2 for v1, v2 in itertools.izip(c1, c2)) | 7be3c6a526fa072c7ed6a31792db2f7bf7d64494 | 79,791 |
def make_tensor_annotation(tensor_name, zero_point_name, scale_name):
"""
Helper function to make_tensor_annotation
"""
annot = TensorAnnotation()
annot.tensor_name = tensor_name
quant_param_scale = StringStringEntryProto()
quant_param_scale.key = "SCALE_TENSOR"
quant_param_scale.value ... | 9b591156e859918292679b3fe199ef0c936b1862 | 79,792 |
def is_quadrupture_class(d):
"""
Check if JSON file fulfills QuadRupture class criteria:
- Are top and bottom edges horizontal?
- Are the four points in each quad coplanar?
Args:
d (dict): Rupture JSON dictionary.
Returns:
bool: Can the rupture be represented in the Qu... | 1960f61ac420ead4cb30677177024b36b1f80644 | 79,793 |
import json
def render_json(packages, dcos_version, repo_version):
"""Returns the json
:param packages: package dictionary
:type packages: dict
:param dcos_version: version of dcos
:type dcos_version: str
:param repo_version: version of universe repo
:type repo_version: str
:return fi... | bd88fe763e55b326094a809848656243d2ddef86 | 79,794 |
import math
def entropia(p):
"""Entropía de una Bernoulli de parámetro p."""
if p == 0 or p == 1:
return 0
else:
return - p * math.log(p, 2) - (1 - p) * math.log(1 - p, 2) | 2ded93b09f5199fbd9d7564d45d1937735fb73eb | 79,796 |
from typing import Hashable
def observed_heterozygosity(
ds: Dataset,
*,
call_heterozygosity: Hashable = variables.call_heterozygosity,
merge: bool = True,
) -> Dataset:
"""Compute per cohort observed heterozygosity.
The observed heterozygosity of a cohort is the mean of individual
hetero... | 4ef0bdf0cf695591658920541ad083b57c725e78 | 79,797 |
def tanh(var):
"""
Returns variable representing tanh applied to the input variable var
"""
result = Var(np.tanh(var.val))
result.parents[var] = var.children[result] = 1 / (np.cosh(var.val) ** 2)
return result | a2cf68bb4d1a8cb86295a949799a840715eecd2e | 79,799 |
def predict(data, best_stump):
"""
Predicting data through decision stumps
@param data: Data to be predicted
@param best_stump: Decision stump
@return:
"""
if (best_stump["unequal"] == 'lt' and data[best_stump["feature"]] <= best_stump["threshold"]) or (
best_stump["unequal"] == ... | 6b80ca7ce12541de1ddd21648050861c74afe36a | 79,800 |
def get_values(cluster):
"""returns the value in the cluster (if leaf)
or all values in leaf clusters below"""
if is_leaf(cluster):
return cluster
else:
return [value
for child in get_children(cluster)
for value in get_values(child)] | 70e5679cf2a9089add21723656b261ec98f9c8e4 | 79,801 |
def get_user_photo(facebook_user_id, pic_type='large'):
"""
:param pic_type: should be one of
- 'square' (50x50) default
- 'small' (50 pixels wide, variable height)
- 'normal' (100 pixels wide, variable height), and
- 'large' (about 200 pixels wide, variab... | 6556e4a3dc09db7b2c7782da664ea5c9105a6f2a | 79,802 |
def get_modules(course):
"""Returns all modules from specified course
Makes a call to the CanvasAPI through Python API wrapper.
Calls make_modules_dataframe() to convert response to properly formatted
Pandas dataframe. Returns it.
Args:
course (canvasapi.course.Course): The course obj.
... | ffb847c95d1d991a99d5852c29d4241ea4a118a4 | 79,803 |
def uniform(tensor, a=0, b=1):
"""Fills the input Tensor or Variable with values drawn from the uniform distribution :math:`U(a, b)`.
Args:
tensor: an n-dimensional torch.Tensor or autograd.Variable
a: the lower bound of the uniform distribution
b: the upper bound of the uniform distrib... | 77b1f3dd7a8904cd961a51447e6a4b60bd478ab6 | 79,805 |
def img_to_pencil(raw_image, threshold=15):
""" Convert color map to simple pencil style.
Args:
raw_image: Image path to be processed.
threshold: Thresholds are defined between 0 and 100.
Returns:
array.
"""
if threshold < 0:
threshold = 0
if threshold > 100:
... | 8d56d4b88db1d33d31d40c23ce0a6058e69c2c53 | 79,806 |
import pkg_resources
def to_pep440(version: str) -> str:
"""Derive pep440 compliant version string from PyCalVer version string.
>>> to_pep440("v201811.0007-beta")
'201811.7b0'
"""
return str(pkg_resources.parse_version(version)) | 91a5c19a95320b04fbdcf0917058168d7d1e2704 | 79,807 |
def load_embedding_model(model_type: str,
embedding_dimension: int = 200) -> gensim.models.keyedvectors.KeyedVectors:
"""
Loads a pre-trained word embedding model via gensim library.
:param model_type: name of the word embedding model to load.
:param embedding_dimension: size o... | c46f3e85b92c637b117e0421ba9f4fcf4a2f912d | 79,809 |
from datetime import datetime
def renew_oauth_token_if_needed(panopto_site_address, panopto_oauth_credentials, oauth_token, expiration_date):
"""
Returns the current oauth token if it is present and valid, else gets a new one if it is missing
or soon to expire
:returns: oauth_token, expiration_date
... | a4938fe59033600075c2f40589a1ddd4698ca0e3 | 79,811 |
def error_response(message_type, message=None):
"""
Formats the error message and send the correct error code
:param message_type: the message type for the particular error
:param message: optional custom message for the given error type
:return: json response, status code
"""
response_messa... | 9dd0ecb82d22e410fde82b8a78517a6c943633f4 | 79,812 |
def hartmann6_func(x, d, a, c, p):
"""
Compute Hartmann6 function at a given point with given arguments.
Parameters
----------
point : 1-D array with shape (d, )
A point used to evaluate the function.
d : integer
Dimension
a : 2-D array with shape (4, 6)
c : 1-D arra... | 5949de9988556d3fce6d9e0ab9554e332f6ad3cf | 79,813 |
def create_logistic_vector(input_vector, cutoff):
"""
Creates a vector of 0s and 1s based on an input vector of numbers with a cut-off point
"""
output_vector = np.zeros(len(input_vector))
n=0
for i in range(len(input_vector)):
if (input_vector[i] > cutoff):
output_vector[i] ... | 811ae63b2e4d8a8ea9082f2d67d172cf025fb978 | 79,814 |
from Cycle import ORCClass
def Write2CSV(Class,filename,append=False):
"""
This function takes in a class and a file pointer
"""
def OL2Strings(OL):
head=str(OL[0][0])
units=str(OL[0][1])
vals=str(OL[0][2])
for i in range(1,len(OL)):
head+=','+str(OL[i][0])
... | 72a1b625edd6a713281deb38075c514e35b2f80d | 79,815 |
def tokenize(sentence):
"""Tokenize a sentence."""
sentence = str(sentence)
words = sentence.strip().split()
tokenized = [] # return this
for word in words:
if word.lower() in ['mr.', 'ms.']:
tokenized.append(word)
continue
# Split special chars at the star... | 0bab08bfb2cee35d07039a8e5081418f9b9e1b13 | 79,816 |
import random
def p2ps_advertise(r_dev, r_role, svc_name, srv_info, rsp_info=None):
"""P2PS Advertise function"""
adv_id = random.randrange(1, 0xFFFFFFFF)
advid = hex(adv_id)[2:]
if rsp_info is not None and srv_info is not None:
if "OK" not in r_dev.global_request("P2P_SERVICE_ADD asp " + str... | f84e785aede7f41e514c8c68d1fabb3d4f82dc6b | 79,817 |
def getIdForMember(member):
"""
Returns the member's unique id as a string.
"""
return member['@Member_Id'] | 5aca8b6413581313fffee8ca21761a23c9315e38 | 79,818 |
def default_smooth_aperpar_k(newx_lst, ypara, fitmask, group_lst, npoints):
"""Smooth *k* of the four 2D profile parameters (*A*, *k*, *c*, *bkg*) of
the fiber flat-fielding.
Args:
newx_lst (:class:`numpy.ndarray`): Sampling pixels of the 2D profile.
ypara (:class:`numpy.ndarray`): Array of... | 6b9807ae9f6063201639667961be95749daf24c9 | 79,819 |
def puzzle_screen():
""" Renders the puzzle screen """
# Get the existing puzzle from the session
puzzle = Puzzle.from_json(session['puzzle'])
puzzlename = session.get('puzzlename', None)
# Get the clues
clues = {
"across": [
{"seq": seq, "text": word.get_clue() or ""}
... | fda8b890508e12e99d494b8c021603ccbecfeba6 | 79,820 |
import itertools
def getMyStackXPath(element): #My XPath code modified with Stack Overflow's one
"""
Generate xpath of soup element
:param element: bs4 text or node
:return: xpath as string
"""
components = []
child = element if element.name else element.parent
for parent in child.pare... | 986b76a479756be75f8e848ee62f8c40efefc0d0 | 79,821 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.