content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def retrieve_document(url, document_id):
"""
Wrapper around retrieve function
:param url: the base url of the REST server
:param document_id: document id to be retrieved
:returns response.text: document is returned if successful
"""
url += "/documents/" + document_id
return retrieve(url... | 8d31db80572c7b84e306a63609272e878f1bffcf | 75,743 |
from typing import Any
from typing import Optional
from typing import Tuple
def _get_values(
values: np.ndarray,
skipna: bool,
fill_value: Any = None,
fill_value_typ: Optional[str] = None,
mask: Optional[np.ndarray] = None,
) -> Tuple[np.ndarray, Optional[np.ndarray], np.dtype, np.dtype, Any]:
... | 15ae24fa251e71cd152950d107086e5c4bbcd37f | 75,744 |
def convert_to_date(datetime: str):
"""Convert the date-time string(dd/mm/yyyy) to date time object"""
if type(datetime) == str:
date_, *_ = datetime.split()
dd, mm, yyyy = [int(val) for val in date_.split("/")]
return date(year=yyyy, month=mm, day=dd)
return datetime | 1083174f4accfbc5a1dddac881116cd78a8d5860 | 75,745 |
def find_hparam_regression (estimator, X, y, param_grid, cv, scaler = None, n_jobs = 1):
"""
Task: find the hyper-parameter from a set of parameters (param_grid),
that performs best in an cross-validation setting for the given
estimator.
:param estimator: Estimator object, e.g. KernelRa... | 59e3fe679f4da880b4adeb11e87c25a8606da5e7 | 75,746 |
def reduce_mem_usage(name, df):
"""
https://www.kaggle.com/gemartin/load-data-reduce-memory-usage
iterate through all the columns of a dataframe and modify the data type
to reduce memory usage.
"""
start_mem = df.memory_usage().sum() / 1024**2
for col in df.columns:... | 0739d2b0c880a1470910fe96abcc513814361c38 | 75,747 |
def predictLogisticGrowth(logGrowthModel: StanModel,
regionTrainIndex: int = None,
regionName: str = None,
confirmedCases = None,
target = 'confirmed',
... | c3adb82c27a4dc8ec207191b28432ed4b4a3706f | 75,748 |
from typing import Union
from typing import Tuple
import torch
def randomMask4D(
out_channels: int,
kernel_size: Union[int, Tuple],
in_channels: int,
groups: int,
params_per_channel: int,
):
"""
Creates a 4d mask with a number of nonzero elements per out channels (index 0) equals to the p... | 6c0d23a71860ca81fedcaec2d74b02febc428eaa | 75,750 |
from typing import Tuple
from typing import List
def discretize_2d_monomial(n_x: int,
n_y: int,
points: Tuple[List[float], List[float]],
) -> np.ndarray:
"""Discretize the differential operator d^{n_x + n_y}/{dx^n_x dy^n_y}."""
x... | 2c03fe98dd132c71914f286f4c68e9c65ffc31b8 | 75,751 |
def is_mena_tweet(tweet):
"""
Check if the tweet from MENA countries.
"""
n = tweet
for k in ['twitter', 'place', 'country_code']:
if n and k in n:
n = n[k]
return n in MENA_LIST | f3e6b68bc51c5ec34c0aeb48c9e68956e27b2e38 | 75,752 |
from typing import Dict
def get_data_lookup_table() -> Dict[str, str]:
""" Get lookup table (country references for iso2) """
lookup_table_url = JHU_CSSE_FILE_PATHS['BASE_URL_LOOKUP_TABLE']
lookup_df = pd.read_csv(lookup_table_url)[['iso2', 'Country_Region']]
# Create referral dictionary
data... | 5a4522d04fb84ecb1504f31b07936dcf0bfaf24c | 75,753 |
def upload_log():
"""POST request to upload log files"""
return log_controller.upload() | 67d0075dfb9f1a8b5b6c0b179fe2afd90c3b98d4 | 75,755 |
def getAveragedValues(interval):
"""catches all data in the given interval steps and calculates the average speed for each interval."""
timeValues = range(0, 86410, interval)
fcdValues = [[] for i in range(0, 86410, interval)]
simFcdValues = [[] for i in range(0, 86410, interval)]
vtypeValues = [[] ... | fe20fd00e8816e05d59699f5106ff41b3254e5b7 | 75,756 |
def _rescale(numpy_array):
""" Rescale the numpy array by 10000. The maximum value achievable is 32737
This will bring the values between -n and n
"""
return numpy_array / 10000 | 8edc9823c6ad62af102a8ddf0b9ab61cdaa59350 | 75,757 |
def compose_permutations(permA, permB):
"""Compose two permutations.
Parameters
----------
permA : list or ndarray of int
First permutation.
permB : list or ndarray of int
Second permutation.
Returns
-------
ndarray of int
Composition of the two permutations.
... | 64b7f5ead31cd25aaecb9939da7f9e0b05de823f | 75,758 |
def calculate_frechet_distance(mu1, sigma1, mu2, sigma2, eps=1e-6):
# taken from https://github.com/mseitzer/pytorch-fid/blob/master/fid_score.py
"""Numpy implementation of the Frechet Distance.
The Frechet distance between two multivariate Gaussians X_1 ~ N(mu_1, C_1)
and X_2 ~ N(mu_2, C_2) is
... | 509655225d0cb319779cfd7d694bc6bc2d1db74d | 75,759 |
def choose_inn(ips):
"""
Return a list of all internal ip from `ip_list`.
:param ips: is a list of ipv4 addresses.
:return: a list of internal ipv4 addresses.
"""
return [x for x in ips if ip_class(x) == INN] | 5b4139792f22352d0da1eebefff532ba5136ee14 | 75,761 |
def filterAlns(alns, poaConfig):
"""
Given alns (already clipped to the window bounds), filter out any
that are deemed insufficiently high-quality for POA.
By and large we avoid doing any filtering to avoid potential
reference bias in variant calling.
However at the moment the POA (and potenti... | 02ef82e4fcaa2236347b47dcf34df72ae570154a | 75,762 |
from tempfile import mkdtemp
def create_temporary_directory(prefix_dir=None):
"""Creates a temporary directory and returns its location"""
return mkdtemp(prefix='bloom_', dir=prefix_dir) | b2a1ddeb8bcaa84532475e3f365ab6ce649cd50c | 75,763 |
def get_account_details(acc_path):
"""
Return container_list and container_count.
"""
container_list = []
for entry in gf_listdir(acc_path):
if entry.name.startswith('.fc_meta'):
continue
if entry.is_dir() and \
entry.name not in (TEMP_DIR, ASYNCDIR, TRAS... | e6dffab8f3fd2de3fedd40045185596a2e274d94 | 75,764 |
def create_gpu_device(which):
""" Create device for running on GPU card
.. note::
At least one of :py:func:`create_cpu_device` or :py:func:`create_gpu_device` should be called
before using any ``owl`` APIs.
:param int which: which GPU card the code would be run on
:return: A unique id ... | c7da80b9112158dcea90b9b68feaf8afc0198aba | 75,765 |
def get_num_clones(pop_size, clone_factor):
"""
:param pop_size: 100
:param clone_factor: 0.1
:return:
"""
return int(pop_size * clone_factor) | 2cc9639b4aa598793d305980ad76aecb59157f8b | 75,766 |
def index():
"""Step 1: User Authorization.
Redirect the user/resource owner to the OAuth provider using an URL with a few key OAuth parameters.
"""
mautic = OAuth2Session(current_app.config.get("MAUTIC_CLIENT_ID"),
redirect_uri=current_app.config.get("MAUTIC_REDIRECT_URI"))
authori... | 68052f925a3327441b311403b7645fc0428e53ed | 75,767 |
import random
import string
import uuid
def create_customer():
"""
Create a customer entity.
:return: A dict with the entity properties.
"""
name = "".join(random.choice(string.ascii_lowercase) for _ in range(10))
return {
'entity_id': str(uuid.uuid4()),
'name': name.title(),... | 48434187249164992d81694070f027f5ca8b862c | 75,768 |
def QueueOps(opts, args):
"""Queue operations.
@param opts: the command line options selected by the user
@type args: list
@param args: should contain only one element, the subcommand
@rtype: int
@return: the desired exit code
"""
command = args[0]
client = GetClient()
if command in ("drain", "und... | b143da5f6bdfe360aa2f04133a47b4e09ebc653f | 75,769 |
from typing import Sequence
def in_bbox(point: Sequence, bbox: Sequence):
"""
Checks if point is inside bbox
:param point: point coordinates [lng, lat]
:param bbox: bbox [west, south, east, north]
:return: True if point is inside, False otherwise
"""
return bbox[0] <= point[0] <= bbox[2] ... | fb95e2506adee4ff425997a0211ee53095894f35 | 75,770 |
from typing import List
import numpy
import torch
def plot_embeddings(
input_dictionary: dict,
embedding_key: str,
annotation_keys: List[str],
sup_title: str = None,
n_col: int = 3,
cmap: Colormap = 'inferno') -> plt.Figure:
"""
Takes a dictionary with embedding... | 66c5a09b1d4a4e0139fa16d34a8a7fc3f5cf4ea0 | 75,771 |
def post(data):
"""Create a new writing relation."""
paper = data['paper']
author = data['author']
write = Write.query.filter_by(paper=paper).filter_by(author=author).first()
if write:
response = {
'status': 'Failure',
'message': 'The writing relation already exists.'... | 4cee8392add7e42b69070a7cbddedd09f668cae3 | 75,772 |
from pathlib import Path
def plot_common(time, lon, lat, u, v, *,
output_file=None,
meshgrid=True, sub=2, velocity_min=None, velocity_max=None, markers=None, title='HF Radar'):
"""
param markers: a list of 3-tuple/lists containng [lon, lat, marker kwargs] as should be
... | f950b34e9155a25eaad950877012cfa349561ad6 | 75,773 |
def getPiperMainMenu():
"""
Used to create or get the Piper Main Menu, there can only be ONE in the scene at a time.
Returns:
(_PiperMainMenu): Piper main menu class.
"""
_PiperMainMenu.instance = _PiperMainMenu() if _PiperMainMenu.instance is None else _PiperMainMenu.instance
return _P... | c1e1ebfc638758762a987f72b017ec5826b08dcb | 75,774 |
def euclid(series1, series2):
"""
Compute a distance between two numerical series using Euclidian distances
between their points at the same index.
"""
ds = [abs(series1[i] - series2[i])
for i in range(min(len(series1), len(series2)))]
return avg(ds) | a9e63a5fd38df8bb3ebd1490d94f8f9e812d1261 | 75,775 |
def group(extracted_iter, sample_names, gene_ids):
"""Given the raw dictionary results, group into per-sample,
per-gene dictionary."""
samples = {s: {} for s in sample_names}
dns = ("vep", "varscan")
for lined in extracted_iter:
for sampled in lined:
sample = sampled["sample"]
... | 1e5360a5d67636c46f60bcb440ef6c6d185b94de | 75,776 |
from operator import index
def delete_record(request):
"""View function for deleting attendance record."""
report_id = request.GET.get('id', -1)
if report_id == -1:
return redirect(index)
_query = Attendance_Record.objects.filter(id=report_id).first()
try:
_query.del... | a5314fa60a49c74fb025eaaf4d84f750e1075d9b | 75,777 |
import ipaddress
def _ip_binding():
"""Create IPv4 / IPv6 binding for Gunicorn.
Args:
None
Returns:
result: bind
"""
# Initialize key variables
config = CONFIG
ipv4 = False
ip_address = config.listen_address()
# Check IP address type
try:
ip_object =... | d4c44957cffe5c8e576c01a5004b7522471e34e8 | 75,778 |
def get4User(user=None, session_key=None):
"""
Get the capabilities for the given user.
"""
roles = []
capabilities = []
# Get user info
if user is not None:
#logger.info('Retrieving role(s) for current user: %s', user)
userDict = entity.getEntities(
'authentica... | e06905b1948692981fd0a24c607a17e712f23b6b | 75,780 |
def calculateGamma(f, k, r, t, v, cp, n=15):
"""计算Gamma值"""
delta1 = calculateDelta(f*STEP_UP, k, r, t, v, cp, n)
delta2 = calculateDelta(f*STEP_DOWN, k, r, t, v, cp, n)
gamma = (delta1 - delta2) / (f * STEP_DIFF) * pow(f, 2) * 0.0001
return gamma | 33ea4ec5e4ff676250635e707b5d5bc436465f9e | 75,781 |
def setup_model_and_optimizer(args, model_type=None, multi_token=True, num_labels=None, spell_length=None):
"""Setup model and optimizer."""
model = get_model(args, model_type=model_type, multi_token=multi_token, num_labels=num_labels,
spell_length=spell_length)
param_groups = get_opt... | c434788b6235e8555194e76961dd5f5fda62ca65 | 75,782 |
def impact_resolution(true_x, reco_x, true_y, reco_y,
percentile=68.27, confidence_level=0.95, bias_correction=False, relative_scaling_method=None):
"""
Compute the shower impact parameter resolution as the Qth (68 as standard) containment radius of the square distance
to the simulated... | 3cb0332d24108e7e11c8902d3d52911f4175ae4a | 75,783 |
def VGG19(pretrained=False, use_ssld=False, **kwargs):
"""
VGG19
Args:
pretrained: bool=False or str. If `True` load pretrained parameters, `False` otherwise.
If str, means the path of the pretrained model.
use_ssld: bool=False. Whether using distillation pretrained model... | 637a6f77bc7629fda8f1826a737082596a871ea7 | 75,784 |
from typing import List
from typing import Union
from typing import Tuple
def _aligned_key_properties(
key: Key,
current_labels_size: List[Union[int, float]],
) -> Tuple[int, List[str], List[str], List[Union[int, float]]]:
"""More space efficient text labels, text colors, text sizes.
:param key: the ... | 58fc686b11d9948bae58c4206f07cbe85eea861b | 75,785 |
def e_choo_siow_gender_heteroskedastic(muhat: Matching) -> np.ndarray:
"""Returns the values of the parameter-dependent part $e$
for the Choo and Siow gender-heteroskedastic model; we normalized $\sigma=1$.
Args:
muhat: a Matching
Returns:
the (X,Y,1) array of the parameter-dependent ... | 3147095bbe23b30a2d4dec45a9db222ff8971292 | 75,786 |
from typing import Callable
from typing import Dict
from datetime import datetime
def construct_response(handler: Callable[..., Dict]) -> Callable[..., Dict]:
""" Construct a JSON response for an endpoint's results. """
@wraps(handler)
def wrap(request: Request, *args, **kwargs) -> Dict:
response... | 8abdfd44d4e6b11371f1182622c5403b2accfd36 | 75,787 |
def cookie_dict_from_cookie_str(cookie_str):
"""cookie_dict_from_str Cookie字符串返回成dict
:param cookie_str: cookies string
"""
cookie = SimpleCookie()
cookie.load(cookie_str)
return {key: morsel.value for key, morsel in cookie.items()} | 0f2fd0b4bd6c898602a3908037df4c58d573f4df | 75,788 |
def DisplayName(*args):
"""Display name of the object (not necessarily unique)"""
# Getter
if len(args) == 0:
return get_string(lib.CktElement_Get_DisplayName())
# Setter
Value, = args
if type(Value) is not bytes:
Value = Value.encode(codec)
lib.CktElement_Set_DisplayName(V... | 2a041a171fc0ce31d165a00a5bd29834523efea9 | 75,789 |
def calc_ecart(c):
""" calculate the algebraic distance between the 2D points and the mean circle centered at c=(xc, yc) """
Ri = calc_R(c)
return Ri - Ri.mean() | ecce0ca1b07f42983cbe0fdcd354b668a553818f | 75,790 |
from typing import Union
def create_tf_dataset(
session_data: SessionDataType,
batch_size: Union["tf.Tensor", int],
label_key: Text,
batch_strategy: Text = "sequence",
shuffle: bool = False,
) -> "tf.data.Dataset":
"""Create tf dataset."""
shapes, types = get_shapes_types(session_data)
... | 3fdbeed4adc9263047f78bf0508da67e01acd300 | 75,791 |
import pandas
def stddev_from_average(timeseries):
"""
A timeseries is anomalous if the absolute value of the average of the latest
three datapoint minus the moving average is greater than three standard
deviations of the average. This does not exponentially weight the MA and so
is better for dete... | 7d01ba7e47cc70c834726f6f1150d084af4375cc | 75,792 |
def detect_peaks(hm, filter_size=3, order=0.5):
"""
Detect peaks from a heatmap.
Args:
hm (ndarray, HW) : input heatmap
filter_size (int): kernel size
order (float)
Returns:
List of detected peaks [[x0, x1, ..], [y0, y1, ..]]
"""
local_max = maximum_filter(hm, ... | c592f8ad74cf81791083ddbaf2c404e2dac03b4d | 75,793 |
def CheckFontInfo(doc, xref):
"""Return a font info if present in the document.
"""
for f in doc.FontInfos:
if xref == f[0]:
return f
return None | e4b0f1f4106e344dbc86f73b406e576c60a12f31 | 75,794 |
def dataTypesToFormat(dataTypes):
""" Convert data schema types to format for use in struct packing/unpacking. """
format = "<"
for t in str(dataTypes).split(','):
if t.startswith('string') & (len(t.split('_')) > 1):
format += t.split('_')[1] + 's'
else:
format += dat... | a65929cd448e264d08440caea80c9edf3bcfe07d | 75,795 |
def _all_children_checked(item):
"""Set the checkstate of all children of an item."""
nrOfChildren = item.childCount()
for n in range(nrOfChildren):
child = item.child(n)
checked = child.checkState(0) == Qt.Checked
if not checked: return False
return True | a7b01f3791805700a813f3b6cb7c7c8f3676b95c | 75,796 |
import re
def get_cell_pin_info(parasitic_netlist_path):
"""
Get the pin locations of each logic cell
:param parasitic_netlist_path: the path to the parasitic netlist used to create the file
:return: cell name, x and y pins
"""
parasitic_netlist_file = open(parasitic_netlist_path, 'r')
# ... | 85ab33c93999e93e35bb35c6e70c4b3531d7aa15 | 75,797 |
def create_pascal_color_map():
"""Create a label color map used in PASCAL VOC segmentation benchmark.
Returns:
cmap: Color map for visualizing segmentation results.
"""
cmap = np.zeros([_PASCAL_COLOR_MAP_MAX_ENTRY, 3], dtype=np.uint8)
for i in range(_PASCAL_COLOR_MAP_MAX_ENTRY):
r = 0
g = 0
... | e9caca27e30617682bae2ca956e7a8603829c310 | 75,798 |
def process_graph_from_file(path: str) -> Graph:
"""Load network from path."""
if path.endswith(CSV) or path.endswith(TSV):
graph = get_graph_from_df(path, CSV)
elif path.endswith(TSV):
graph = get_graph_from_df(path, TSV)
elif path.endswith(PICKLE):
graph = pybel.from_pickle(p... | e63a37ccdb478dee27e5cf1acba02b6c17c7aa7a | 75,799 |
from typing import Dict
from typing import Tuple
from typing import List
def create_layer(films: pd.DataFrame, name: str) -> folium.FeatureGroup:
"""creates layer for web map
Args:
films (pd.DataFrame): films for layer
name (str): name of the layer in the web map
Returns:
folium.... | f6e07e4c52291e59529520bda574a31888d3f8d3 | 75,800 |
def mock_spam_check(mocker):
"""Mock the check_comment_for_spam task"""
return mocker.patch("channels.task_helpers.check_comment_for_spam") | 9d8eb28a1e960771ab600c225d843a5ebe3b2379 | 75,801 |
def index_to_position(index: int, size: int):
"""
Converts an index in the observation.halite list to a 2d position in the form (x, y).
"""
y, x = divmod(index, size)
return Point(x, (size - y - 1)) | 9c28ebf71e95aff431e193a0c0f166cb926037e9 | 75,802 |
def oscdetect_thresh(x, f_range, Fs, thresh_hi = 3, thresh_lo = 1.5, magnitude = 'power', baseline = 'median',
min_osc_periods = 3, filter_fn = bandpass_default, filter_kwargs = {}, return_normmag=False):
"""
Detect the time range of oscillations in a certain frequency band.
Based on Fei... | 3de009630348a2beb5da84fbc385bdde6a688234 | 75,804 |
def mpdist(ts, ts_b, w, threshold=0.05, n_jobs=1):
"""
Computes the MPDist between the two series ts and ts_b. For more details
refer to the paper:
Matrix Profile XII: MPdist: A Novel Time Series Distance Measure to Allow
Data Mining in More Challenging Scenarios. Shaghayegh Gharghabi,
Shima I... | e3c6601a09b8568ce3884d08fe32020241a347bf | 75,805 |
def find_member(guild: discord.Guild, name, steps=3, mention=True):
""" Find any member by their name or a formatted mention.
Steps define the depth at which to search. More steps equal
less accurate checks.
+--------+------------------+
| step | function |
+--------+-----------------... | 65d20f2cf3fd316169220e80ba4c99b9274f930c | 75,809 |
def _check_nested_exog(small, large):
"""
Check if a larger exog nests a smaller exog
Parameters
----------
small : ndarray
exog from smaller model
large : ndarray
exog from larger model
Returns
-------
bool
True if small is nested by large
"""
if s... | 0e23f32bd91504773d983f5cb7544b45db6615bf | 75,811 |
def get_states(iQ,Lx,Ly,lattice):
"""
return a vector with the number of particles
along the x-direction, with total iQ number
of states.
"""
x = np.zeros(Lx,dtype=int)
for i in range(1,iQ+1): # skip 0-state
x += get_state(i,Lx,Ly,lattice)
return x | 0507b4eb9be2d1ece02cc149d8e6301cd6f1a1ee | 75,812 |
def landmark_colors(n_landmarks):
"""Compute landmark colors.
Returns:
An array of RGB values.
"""
cmap = cm.get_cmap('hsv')
landmark_color = []
landmark_color.append((0., 0., 0.))
for i in range(n_landmarks):
landmark_color.append(cmap(i/float(n_landmarks))[0:3])
landmark... | 8fdf502b9ece0421b4fe7f573e06dec4d0769d57 | 75,813 |
def munge_passwd(passwd=None):
"""Return new 'passwd' string and boolean 'require_reset'.
If passwd provided, set 'require_reset' to False.
"""
if passwd:
require_reset = False
else:
passwd = pwgenerator.generate()
require_reset = True
return passwd, require_reset | 5db9cfd06399121cb6c623b8b3226da5a8e6b415 | 75,814 |
import ctypes
def isrchi(value, ndim, array):
"""
Search for a given value within an integer array. Return
the index of the first matching array entry, or -1 if the key
value was not found.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/isrchi_c.html
:param value: Key value to be fo... | dfa276af384a7eedaf6054bf0cd2130b89f803dc | 75,815 |
def _FinalElement(key):
"""Return final element of a key's path."""
return key.path().element_list()[-1] | 80ecac3fe3eb3d2587d64dd759af10dcddb399fe | 75,816 |
from typing import Dict
def get_connected_objects(sha1: str, object_graph: Dict = None) -> Dict:
"""
Starting from a sha1 of an object e.g commit/tree
Return an object_graph
where object_graph is a dictionary of {sha1: unpacked_object}
"""
if object_graph is None:
object_graph = {}
... | 879734f0eec09ab8b0bb18d9eff4a06100fc4541 | 75,817 |
import base64
def base32hex_decode(hex_hash):
"""Decode an hash encoded in base32hex"""
b32hash = ''.join(BASE32_FROM_HEX_MAP[c] for c in hex_hash.lower())
return base64.b32decode(b32hash) | 2d9259dc1bc4df042e0cb2673fd637117a9b0ac7 | 75,818 |
def calculate_discounted_sum(x, dones, discount, x_last=None):
"""
Computing cumulative sum (of something) for the trajectory, taking episode termination into consideration.
:param x: ndarray of shape [num_steps, num_envs]
:param dones: ndarray of shape [num_steps, num_envs]
:param discount: float i... | 39b222b4dbe5b1c2bb1504403ad792e36a9410d4 | 75,819 |
def cs_metadata(cursor, cs_id):
"""Get metadata for a given ``cs_id`` in a NEPC database.
Parameters
----------
cursor : cursor.MySQLCursor
A MySQLCursor object. See return value ``cursor`` of :func:`.connect`.
cs_id : int
The ``cs_id`` for a cross section dataset in the NEPC databa... | 57262d8e22be7cf9166d4edd0a658fe4662f68f6 | 75,820 |
def _recurrence(mode, config, inputs, num_stepss):
"""Recurrent layer
Transforms inputs (like primary sequences) into an internal representation.
Args:
mode: train or predict
config: dict of params
inputs: input to feed the layers [num_steps, batch_size, FEATURES]
num_steps... | 1876f4c789a7ff29cd3ac7a6d8d4eee284461294 | 75,821 |
from typing import Tuple
def get_provider(catalog, **kwargs) -> Tuple[Provider, BaseProvider]:
"""Retrieve the bdc_catalog.models.Provider instance with the respective Data Provider."""
provider = Provider.query().filter(Provider.name == catalog).first_or_404(f'Provider "{catalog}" not found.')
ext = cur... | 608ebe5b434a9c7fa528fbb7c53e64826c8784bb | 75,822 |
def proj4_to_wkt(projection):
"""Converts a pyproj.Proj object to a well-known text string"""
srs = osgeo.osr.SpatialReference()
srs.ImportFromProj4(projection.srs)
return srs.ExportToWkt() | ed8fe01bd35ca0bf0ccea581527df3ced25fb4ec | 75,823 |
def frames_iter(socket, tty):
"""
Return a generator of frames read from socket. A frame is a tuple where
the first item is the stream number and the second item is a chunk of data.
If the tty setting is enabled, the streams are multiplexed into the stdout
stream.
"""
if tty:
return... | 67b69410877e9f5cfc94d8ff2157272714722214 | 75,825 |
def recount_view(request):
"""
Recount number_of_messages for all threads and number_of_responses for all requests.
Also set the change_date for every thread to the post_date of the latest message
associated with that thread.
"""
requests_changed = 0
for req in Request.objects.all():
... | d341c24f2b4ee67814fd87d932d3ee984dd3906a | 75,826 |
def calculate_ranking(officials):
"""
Allows the views:
officials_ranking
officials_to_engage
to display the assessed importance of offcials.
Returns:
a list of named tuples.
"""
officials_list = list()
for official in officials:
official_rank... | ee5e41c059e9f5271bfd8fbfed56d5fe5a0c1810 | 75,827 |
def populate_fields_from_attributes(apps, schema_editor):
"""
converts attributes for portrait_height, portrait_width, pose_count,
previous_pose_count, briefmode, and dice_string to columns on RosterEntry
"""
Attribute = apps.get_model("typeclasses", "Attribute")
attr_names = [
"portrait... | 8ae199462f4c685b1275040b9c7b1d647bf2740a | 75,828 |
import torch
from typing import Optional
def clamp(data: torch.Tensor, min: float, max: float, out: Optional[torch.Tensor] = None) -> torch.Tensor:
"""
Clamp tensor to minimal and maximal value
Args:
data: tensor to clamp
min: lower limit
max: upper limit
out: output tenso... | 3e835f134fd9eedefb5ca7841d8c3a9960063389 | 75,829 |
def set_line(line=None):
"""When True, it plots straight lines between each data points. The default value is False"""
if line==None:
h.line=False
else:
h.line=line
return h.line | b6dbd423d21a965fa8ac9f1f582144ea9addeae9 | 75,831 |
def FrontnetModel(h=96, w=160, c=32, fc_nodes=1920):
"""
This is the model referred in the paper as Frontnet
Possible configurations are:
input size 160x96 (w,h) - c=32, fc_nodes=1920 (default)
input size 160x96 (w,h) - c=16, fc_nodes=960
input size 80x48 (w,h) - c=32, fc_nodes=768... | 960070c381373257c72458581f37aaca7ca42b22 | 75,832 |
from typing import Dict
def shift_target_sequence(inputter, data: Dict[str, tf.Tensor]) -> Dict[str, tf.Tensor]:
"""Prepares shifted target sequences.
Given a target sequence ``a b c``, the decoder input should be
``<s> a b c`` and the output should be ``a b c </s>`` for the dynamic
decoding to start ... | d121d094fba0699bf5e9b724098f5a20ebb9b4a6 | 75,833 |
def fit_pca(X, weights=None):
""" Fit line parameters to points using weighted PCA """
if weights is None:
weights = np.ones(X.shape[0])
A = np.mean(X*weights.reshape(-1,1), axis=0) / weights.mean() # A - anchor point
U, E = wpca(X-A, weights/weights.sum())
return A, U, E | 569606fb04bab4d3497f62edd214d178ce12d9fc | 75,834 |
def shrink(feats_dict,freq):
"""
Shrink the "feats_dict" according to frequency of the feature in
"feats_dict".
"""
for key in feats_dict.keys():
if feats_dict[key]<=freq:
del feats_dict[key]
if feats_dict=={}:
print "Erro... | 0875c42b0dd1b0916c55b5b4e5683e0bdd27f9f8 | 75,835 |
def minimize(
criterion,
params,
algorithm,
*,
criterion_kwargs=None,
constraints=None,
algo_options=None,
derivative=None,
derivative_kwargs=None,
criterion_and_derivative=None,
criterion_and_derivative_kwargs=None,
numdiff_options=None,
logging=False,
log_option... | 38344208614d14e2b2e71af917df1ef1e2471b22 | 75,837 |
def generate_export_state_message_payload(
snapshot_type,
correlation_id,
collection_name,
export_date,
shutdown_flag,
reprocess_files,
file_name,
):
"""Generates a payload for a monitoring message.
Arguments:
snapshot_type (string): full or incremental
correlation_i... | 2c903f43ef50e91352fc19e19e9f797e277034c8 | 75,838 |
from typing import Sequence
from typing import OrderedDict
from typing import Counter
def assert_no_duplicate_frameworks(
state: MesosState, framework_list: Sequence[str] = ["marathon"]
) -> HealthCheckResult:
"""A function which asserts that there are no duplicate frameworks running, where
frameworks are... | a359601828ffc9bdb2b8735976c568e2dbd4d1ba | 75,839 |
def format_group_value(entry, attrs):
""" Helper that formats grouped attribute to be presented in the table output.
Args:
entry (Dict[str, str]): CONFIG DB entry configuration.
attrs (List[Dict]): Attributes metadata that belongs to the same group.
Returns:
str... | 4222ef2b8f70a3bd550be0a8b5d723e408a499e3 | 75,840 |
def get_cluster_manager(params, config_proto):
"""Returns the cluster manager to be used."""
return cnn_util.GrpcClusterManager(params, config_proto) | ff2a8425957223ad0028a5766b7f11f0fb1b3ace | 75,841 |
def get_chart_data() -> pd.DataFrame:
"""## Chart Data
Returns:
pd.DataFrame -- A DataFrame with dummy data and columns=["Day", "Orders"]
"""
chart_data = {
"Day": ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday",],
"Orders": [15539, 21345, 18483, 2... | af28769f45251c8ec8e2316eb51a21c526ad3098 | 75,842 |
def get_prob( past_state, next_state, seg, equip_2_shape_map, shape_dict, SHAPE_LEN = 50, var_measurement = 800, verbose = 0 ):
"""calculate the probability that seg is generated by any pathway from past_state to next_state"""
all_possible_shape = [[0] * SHAPE_LEN]
all_possible_shape_path = [ [] ]
... | 3d5c74654379379b3a32140ef27c184ea15211b4 | 75,843 |
def buildTag(parts_list):
"""Concatenate tags comprised of multiple parts."""
return TAG_SEP.join(parts_list) | c59057f81aebdc08e481a655fe5a6f6454b6a0be | 75,846 |
import re
import copy
def get_rsIDsnp(snp_id, temp_dir):
"""
This function takes as input a snp identifiers and a temporary directory to save temp files to
and returns a parsed dictionary of their data from Entrez.
"""
Entrez.email = 'A.N.Other@example.com'
try:
handle = Entrez.efetch(db='SNP', id=snp_id)
... | 0b1515409d2d79c497934ef93cf895c96274506e | 75,847 |
def gauss(x, x0, A, fwhm):
"""
normalised gaussian function
A ... integral
x0 ... position
fwhm... full widht half maximum
[http://mathworld.wolfram.com/GaussianFunction.html]
"""
sigma = fwhm / 2.354820045; # fwhm / 2*sqrt(2 ln(2))
# normalis. const 1/sqrt(2pi)
... | f46e8c0c1fee16beb1f67462cc087b6ad85fbba0 | 75,848 |
def _mirror_coordinates_at_axis(c, mirror_at_axis_coordinate=None):
"""
Mirror or reflect a 1-dimensional array of coordinates on a mirror plane.
Mirror or reflect a 1-dimensional array of coordinates on a plane (perpendicular to the axis) at the given axis coordinate. If no coordinate is given, the minimu... | cce721b5bbddf999e5308078db1fdbb653f1a01f | 75,849 |
def _generate_zero_filled_state_for_cell(cell, inputs, batch_size, dtype):
"""Generate a zero filled tensor with shape [batch_size, state_size]."""
if inputs is not None:
batch_size = K.shape(inputs)[0]
dtype = K.shape(inputs)
return K.zeros(shape=(batch_size, cell.state_size), dtype=dtype) | 61901e3e4a10c1bc9b9e4e389501c3a7642bf032 | 75,850 |
def count(collection, terms=[], **kwargs):
"""Sends a count request."""
# Create a new Request object
request = Request(collection=get_collection(collection),
verb='get',
**kwargs)
return request | e6d8bf17fe28d8dd1487dbde4d2b421f348f6510 | 75,851 |
def clean_command_level(text: str) -> str:
"""Remove parents from the command level"""
return text.replace("Command.", "") | 0fbe2a82fa9f802e2e2118c5adb6dd5057a3f490 | 75,852 |
import random
def sel_random(individuals, k):
"""
Implementation credit to DEAP: https://github.com/DEAP/deap
Select *k* individuals at random from the input *individuals* with
replacement. The list returned contains references to the input
*individuals*.
Args:
individuals (list): A l... | 0213dddbd3238a78d8f82edb340e7152e91e6464 | 75,853 |
def get_phased_path(n, path):
"""Obtain the phased path."""
return np.unravel_index(path, (n, n)) | 18e30dd6b682bd43a691a263687ffd395aa6d82d | 75,854 |
from flask import current_app
def get_redis_and_queue():
"""
We need to mock redis and rq when we test. Sadly this means we have to mix
test code with the app, but it works for us.
Returns tuple of (redis, q)
"""
if is_flask_in_testing_mode():
redis_conn = FakeStrictRedis()
... | ddbc27b3dd53c1aeafe1e7800502b1f483560118 | 75,857 |
import json
def export_to_json(dict_data,e):
"""Fonction export au format json"""
try:
with open(e.path, "w") as outfile:
json.dump(dict_data, outfile)
return True
except IOError:
return False | b18d6c9ecebb83a4f69514af381e6a01f5a4529c | 75,858 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.