content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import io
def _read_sub_atoms(atom: tuple) -> list:
"""
A special method for parsing a stream that isn't from the
original file.
:param atom: a tuple containing atom data
:return: a set of sub atoms
"""
byte_stream = io.BytesIO(atom[2])
atoms = _read_atoms(byte_stream, atom[0] - 8)
... | 36faa5ae07f52671b2b9f407b690feb074321cdf | 3,629,299 |
def bassGura(A, B, desiredPoles, C=None, E=None):
"""
use Bass-Gura formalism to compute gain matrix, G, that places poles of the closed-loop meta-system \hat A- \hat B*G
at desired locations
Inputs:
A (numpy matrix/array, type=real) - system state matrix
B (numpy matrix/array, type=rea... | df3dffdfddebd0681835aff1939103c210198852 | 3,629,300 |
def get_marks(record, transcript):
""" (str, str) -> list of float
Return a list of final course marks from transcript that can be used for
admission, computed based on information in record.
>>> record = 'Eyal de Lara,Fort McMurray Composite High,2016,MAT,90,92,ENG,92,NE,BIO,77,85,BSci'
>>> trans... | 5737dc0c05a20bc5bbdd5f10206b3eb3ed690a11 | 3,629,302 |
from typing import Any
from typing import Tuple
from re import T
def zip(*iterables: Any) -> "Iter[Tuple[T, ...]]":
""" Replacement for the builtin ``zip`` function. This version returns
an instance of Iter_ to allow further iterable chaining."""
return Iter(_zip(*iterables)) | 589c44a2976240c7bebb5d4d52203c081b6dce6c | 3,629,303 |
def loadConversations(fileName, lines,
fields=["character1ID", "character2ID", "movieID", "utteranceIDs"],
delimiter=" +++$+++ "):
"""
Args:
fileName (str): file to load
field (set<str>): fields to extract
Return:
dict<dict<str>>: the extra... | 9f6da36dd648d1b64cabc7725701a3704dc938a9 | 3,629,304 |
from typing import OrderedDict
def optimize_schedule_rotations(schedule, sregistry):
"""
Transform the schedule such that the tensor temporaries "rotate" along
the outermost Dimension. This trades a parallel Dimension for a smaller
working set size.
"""
# The rotations Dimension is the outermo... | 2a36d58774e5e5bad6893815fa9b058bdb93c70e | 3,629,305 |
def parse_config(config_fn):
"""Deprecated.
Called from pbsmrtpipe, for now.
"""
return parse_cfg_file(config_fn) | c6e0505b2d664c5302ccf8a85e72571429f6326d | 3,629,306 |
def transformer_decoder_layers(name,
n_layers,
decoder_input,
**kwargs):
"""A transformation block composed of transformer decoder layers."""
with tf.variable_scope(name, reuse=tf.AUTO_REUSE):
hparams = kwargs["hparams"... | 7d47acb38cd1f6b0e77b4901ab80c040c169b331 | 3,629,307 |
def check_can_unpublish_activity(user, activity_rights):
"""Checks whether the user can unpublish given activity.
Args:
user: UserActionsInfo. Object having user_id, role and actions for
given user.
activity_rights: ActivityRights or None. Rights object for the given
act... | 6de5451497e75cb369fab5b1c8d09d809fa41929 | 3,629,309 |
def gql_add_user_attendance(time: str, user_id: int = None, date: str = None, attendance_id: int = None,
is_clock_in: bool = True, comment: str = None):
"""
GQL mutation to insert/update attendance
:param time: time string in HH:MM:SS format
:param user_id: unique user id
... | 7dd070824486408dcdab15fa29f385a83d2ad826 | 3,629,310 |
def make_pipeline(steps, params):
"""
Args:
steps (dict): (name, module_name, method_name) Tuples to specify steps of the pipeline to fit.
params (dict): string -> object. Parameters passed to the fit method of
each step, where each parameter name is ... | feffe00156f0735bf0a59ef6cb0733b3f332a453 | 3,629,311 |
def format_fields(field_data, include_empty=True):
"""Format field labels and values.
Parameters
----------
field_data : |list| of |tuple|
2-tuples of field labels and values.
include_empty : |bool|, optional
Whether fields whose values are |None| or an empty |str| should
be... | cce4b5279e01c33fec0f83c6f86141c33012fc4c | 3,629,312 |
def loadDecomposition(name):
"""Load a tree decomposition in the PACE-2016 format"""
B = 0 # number of bags
TW = 0
Bags = []
f = open(name, "r")
lines = f.readlines()
for l in lines:
s = l.split()
if len(s) < 1:
continue
if s[0] == "c":
cont... | 7463ee6117bacc2fe07f6937fbdbd35073fea5f0 | 3,629,313 |
def testing_report():
""" Testing Site Daily Summary Report: RESTful CRUD Controller """
return crud_controller() | 9dbe01c4e5cd490dc3dd9b507320efd7bce2c798 | 3,629,314 |
def virtual_network_present(
name,
address_prefixes,
resource_group,
dns_servers=None,
tags=None,
connection_auth=None,
**kwargs
):
"""
.. versionadded:: 2019.2.0
Ensure a virtual network exists.
:param name:
Name of the virtual network.
:param resource_group:
... | fea32c4afa44b1e1c1b9d72290e4892e9dd2c484 | 3,629,315 |
def parse_config_yaml(current_config, first_run=False):
"""This function parses the configuration values contained in the
configuration dictionary obtained by reading the YAML file."""
config_options = current_config
used_options = {}
if config_options is None:
return validate_config(
... | 74f021f3f8b1c290d32527b931da863a23958706 | 3,629,316 |
def acf(x, length=20):
""" Compute autocorrelation. """
return np.array([1] + [np.corrcoef(x[:-i], x[i:])[0,1] for i in range(1, length)]) | 7d32fdc2365b621b53c4c91ff4191781f0350c02 | 3,629,317 |
def normalizeInfinity(a):
"""
Normalize array a so that the maximum absolute value is 1.
Parameters
----------
a : ndarray of float
The array to be normalized.
Returns
-------
ndarray of float, same shape as a
The normalized array.
"""
return a / xplib.xp.ma... | 449e437925f28181aacd62d22896edb8a3670c6a | 3,629,318 |
def getConfigPath():
"""
Returns the config location (either default or user defined)
"""
global args, ConfigPathDefault
if args.config_location:
return args.config_location
return ConfigPathDefault | b53f1dc76f08859bd261f5f76ab6832a5193fe5a | 3,629,319 |
import re
def only_bf(txt):
""" Strip a string from all characters, except brainfuck chars """
return re.sub(r"[^\.,<>\+-\]\[]", "", txt) | 8c32b11d511f5c7b92d7454dcbfea09627ddf172 | 3,629,320 |
def create_ice_connection(user_token):
"""Creates an instance of the ICE API using common settings."""
# Use getattr to load settings without raising AttributeError
key_id = getattr(settings, "ICE_KEY_ID", None)
url = getattr(settings, "ICE_URL", None)
verify = getattr(settings, "ICE_VERIFY_CERT", F... | 04a81fd1c1b6a55d68bc854e942c8cbd2b5e3306 | 3,629,322 |
def sr_inverse_org(J, k=1.0):
"""Return SR-inverse of given J
Definition of SR-inverse is following.
:math:`J^* = J^T(JJ^T + kI_m)^{-1}`
Parameters
----------
J : numpy.ndarray
jacobian
k : float
coefficients
Returns
-------
sr_inverse : numpy.ndarray
... | 63d2dc829be258c32ba00f345124a0d0a36472ea | 3,629,325 |
def get_embeddingset(veclist, textlist):
"""gets a whatlies.embeddingset from the encoding given by the language model
Args:
veclist (numpy.ndarray): ndarray of all encodings
textlist (list): vector of encoded texts
Returns:
whatlies.EmbeddingSet: whatlies EmbeddingSet for easier t... | e5a48d817d5195ce5f6c02f8d66453e22821fa3d | 3,629,326 |
from typing import Sequence
from typing import List
def render_quoted_form(compiler, form, level):
"""
Render a quoted form as a new hy Expression.
`level` is the level of quasiquoting of the current form. We can
unquote if level is 0.
Returns a two-tuple (`expression`, `splice`).
The `spli... | e3ec7a37e1d00fb185a7bfd7e22d07716a33213c | 3,629,327 |
def get_index_portfolio_deposit_file(date: str, ticker: str) -> list:
"""지수구성종목을 리스트로 반환
Args:
date (str): 조회 일자 (YYMMDD)
ticker (str): 인덱스 ticker
Returns:
list: ['005930', '000660', '051910', ...]
"""
df = 지수구성종목().fetch(date, ticker[1:], ticker[0])
if df.empty:
... | 2336fcf17e1bd6c00581c41e41354f3e50bc7b59 | 3,629,328 |
from typing import Optional
def get_account_by_path(
path_string: str, dongle: Optional[Dongle] = None
) -> LedgerAccount:
"""Return an account for a specific `BIP-44`_ derivation path
:param path_string: (:code:`str`) - HID derivation path for the account to
sign with.
:param dongle: (:class... | 043ac11f355c939ce18c5b0ee675454a863a0e45 | 3,629,329 |
def down_capture_nb(returns, factor_returns, ann_factor):
"""2-dim version of `down_capture_1d_nb`."""
result = np.empty(returns.shape[1], dtype=np.float_)
for col in range(returns.shape[1]):
result[col] = down_capture_1d_nb(returns[:, col], factor_returns[:, col], ann_factor)
return result | f59aeda7483dcf5b615223fa34a1a4fc0a5d10f4 | 3,629,331 |
import re
import string
def validate_word(word, text):
"""Check if something is a valid "word" submission with previous existing text.
Return (valid, formatted_word, message), where valid is a boolean, formatted_word is
the word ready to be added to existing text (adding a space if applicable for example)... | 658873c8cbf446cbe53ec5f806db668ceecaa2cf | 3,629,332 |
def process_content_updates(results):
"""Process Content Updates
Args:
results (Element): XML results from firewall
Returns:
max_app_version (str): A string containing the latest App-ID version
"""
app_version_list = []
version_list = results.findall('./result/content-updates/e... | 021c9ac9246034874a1fe274fb49aabfa0f15d61 | 3,629,333 |
import pickle
def load_synthetic(name):
"""
Loads expression data from pickle file with the given name (produced by save_synthetic function)
:param name: name of the pickle file in SYNTHETIC_DIR containing the expression data
:return: np.array of expression with Shape=(nb_samples, nb_genes) and list o... | 62d85dd427b0e233572eab44d43ecef33e9e2d23 | 3,629,334 |
def cell_count(ring):
"""
>>> cell_count(0) == contour_len(0)
True
>>> cell_count(1) == contour_len(0) + contour_len(1)
True
>>> cell_count(2) == contour_len(0) + contour_len(1) + contour_len(2)
True
>>> cell_count(2)
25
>>> cell_count(3)
49
"""
if ring == 0:
... | 90eaaaea4544f0db6f3216bea4971ce82004a9c4 | 3,629,335 |
def exponential_search(ordered_list, x):
"""
implementation of an exponential search algorithm
taken from: https://en.wikipedia.org/wiki/Exponential_search
"""
list_size = len(ordered_list)
bound = 1
while bound*2 < list_size and ordered_list[2*bound-1] < x:
bound = bound ... | 5cf0870c00807405a5b4df8811b9ecf95aa34aaa | 3,629,336 |
import base64
def verify(payload, signature, public_key):
"""
Verify payload using (base64 encoded) signature and verification key. public_key should be obtained from load_public_key
Uses RSA-PSS with SHA-512 and maximum salt length.
The corresponding openssl command to create signatures that this fun... | 10491642bf5f793d776931ae212141c395049d86 | 3,629,337 |
from re import T
import torch
def prepare_segment(net, source, dev='cuda'):
"""
Prepares target image before foreground and background separation
Parameters:
net (pytorch_vision.model): Segmentation Model
source (cv2.Mat): Hand image
dev (str): Computation device, default GPU
R... | ec5ebdb822494c655b674d34a86345b258501512 | 3,629,339 |
import csv
import json
def extract_information_per_turker(filename):
"""
Extracts dictionary with turker's details
Returns:
user_information: dictionary with user details
"""
user_information = {}
with open(filename) as file:
csv_reader = csv.DictReader(file)
for row in... | 8e5fb7ee742f1ca9456b5b4b35faaee48d66ad6c | 3,629,340 |
def upload_str(name: str, content: str, bucket_name: str):
"""
:param name: Name of file including directories i.e. /my/path/file.txt
:param content: UTF-8 encoded file content
:param bucket_name: Name of GCS bucket, i.e. deepdriveio
:return: Url of the public file
"""
key = name
bucket... | 7a7eabb207f95257bd9e917290e70338ced8d173 | 3,629,341 |
def inverso(x):
"""
El inverso de un número.
.. math::
\\frac{1}{x}
Args:
x (float): Número a invertir.
Returns:
float: El inverso.
"""
return 1 / x | 16f2cb9466efa661d3ee8b10b6a0d637273f6b7c | 3,629,343 |
from typing import Union
def _scale(scale:bool,X:Union[pd.Series,np.ndarray]):
"""
Normalization of the Time Serie
Parameters
----------
scale : bool
X : pd.Serie or Numpy Array
Returns
-------
global_mean : float, mean of the Time Serie
global_sdt : float, sdt of the Time Serie
X : numpy ... | b86149deddefc22f1776f5de424f413790f8b2d2 | 3,629,344 |
def update_user_count_eponymous(set_of_contributors, anonymous_coward_comments_counter):
"""
Eponymous user count update.
Input: - set_of_contributors: A python set of user ids.
- anonymous_coward_comments_counter: The number of comments posted by anonymous user(s).
Output: - user_count: ... | 4d96d5f22c489a9bae9e0958bd83346df9d60b6c | 3,629,345 |
def translation(component, direction=1, kernel=interpolation.lanczos, padding=3):
"""Shift the morphology by a given amount
"""
dy, dx = component.shift
dy *= direction
dx *= direction
_kernel, _, _ = interpolation.get_separable_kernel(dy, dx, kernel=kernel)
component.morph[:] = interpolatio... | a185fb15eaa92f46a4ee66f344044f02fbda51a0 | 3,629,347 |
from typing import Optional
def workflow(
user_id: Optional[int] = None,
screen_name: Optional[str] = None,
total_followers: int = 100000,
batch_size: int = 5000,
output_csv: Optional[str] = None
) -> pd.DataFrame:
"""
Pull a user's Twitter following and map each follow... | a70524d21d83de7c2a24948e2aaec16353c5556a | 3,629,348 |
def dcaFuse(X, Y, L):
"""
X (p*n)
Y (q*n)
L (n)
"""
# X = np.array([[1,2,3,4],
# [4,5,6,7],
# ])
# Y = np.array([[4,4,4,4],
# [1,1,1,1]]
# )
# L = np.array([0,1,2,2])
p, n = X.shape
q = Y.shape[0]
# N... | 2ae41b829de7bde8d8d4b55c91806ac65b05ba1e | 3,629,349 |
def flowRate(t):
""" gives fixed flow rate as a function of time
notice that it depends on pump coastdown time constant, so
be sure to change that if needed. right now, it's set to 5s """
tau = 5.0
return 21.7 * np.exp(-t/tau) | 9b72b58e6e1334e6813b115876d71fac69898fed | 3,629,350 |
def generator_from_atom_argument(arg: AtomSpec) -> IndexGenerator:
"""
Returns a generator function for selecting a subset of sites from a pymatgen :obj:`Structure` object.
Args:
arg (various): Argument used to construct the generator function.
Returns:
(func): Generator function that ... | 64216cf7dcd0328d9cad2df9ca35881417fc13f1 | 3,629,351 |
def get_total_memory():
"""
get_total_memory()
Returns the total memory in GBs
"""
total_memory = shell_tools.run('sysctl -a | grep hw.memsize')['stdout']
return (int(total_memory.split('=')[-1]) / (1024 * 3)) | eb977d7aad8ced4d0e824a5a6e4b7f28f312c860 | 3,629,352 |
from labml_nn.transformers.primer_ez import MultiDConvHeadAttention
def _d_conv_mha(c: TransformerConfigs):
"""
Add the [option](https://docs.labml.ai/api/configs.html#labml.configs.option)
of [**Multi-DConv-Head Attention**](index.html) to
[configurable transformer](../configs.html#TransformerConfi... | 2e2e73d20da2082c120cd5737ecca3343eb82190 | 3,629,354 |
def c_commands(context, commands):
"""
The c in c_commands refers to the c file.
This function filters a list of commands for the generated .c file.
WGL core functions are not dynamically loaded but need to be linked,
this functions filters out wgl core functions for the .c file.
:param contex... | 06ddacdcd01c7dada78f814175ff484ceaeea2da | 3,629,355 |
from util import Stack
def depthFirstSearch(problem):
"""
Search the deepest nodes in the search tree first.
Your search algorithm needs to return a list of actions that reaches the
goal. Make sure to implement a graph search algorithm.
To get started, you might want to try some of these simple ... | f9263a944574c902a7a9c2122cf6d03c4307f53b | 3,629,358 |
from distributed.client import default_client
import tokenize
def read_bytes(urlpath, delimiter=None, not_zero=False, blocksize=2**27,
sample=True, compression=None, **kwargs):
""" Convert path to a list of delayed values
The path may be a filename like ``'2015-01-01.csv'`` or a globstring
... | f65dc33b8fbc699187ffd49483b07363c94d1bf0 | 3,629,359 |
from dials.algorithms.scaling.scaler_factory import TargetScalerFactory
def scale_against_target(
reflection_table,
experiment,
target_reflection_table,
target_experiment,
params=None,
model="KB",
):
"""Determine scale factors for a single dataset, by scaling against a target
reflectio... | 619952e066470f66b334791989d901892d51765d | 3,629,360 |
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
from sklearn.cluster import DBSCAN
def billing_pattern(data, params, hitlist):
"""
In this model, outliers from the general billing pattern (see below) are flagged,
based on how far away from the nearest cluster they are.
The p... | 567ad6cef171d5055dc13a0af879575f52704189 | 3,629,361 |
def partition_annots_into_singleton_multiton(ibs, aid_list):
"""
aid_list = aid_list_
"""
aids_list = ibs.group_annots_by_name(aid_list)[0]
singletons = [aids for aids in aids_list if len(aids) == 1]
multitons = [aids for aids in aids_list if len(aids) > 1]
return singletons, multitons | 7d062644923b12a59ef2e4bffd76ec4caf0bcaeb | 3,629,362 |
def teaser_block(parser, token):
"""
Template tag that takes a model instance and returns the given instance as
a template-formatted block. Inserts two objects into the context:
``instance`` - The model instance
``fields`` - A list of (name, label, value) tuples representing the
... | 481eba0978cd052575975295ad6d10197265fa5a | 3,629,363 |
def galeshapley(suitor_pref_dict, reviewer_pref_dict, max_iteration):
""" The Gale-Shapley algorithm. This is known to provide a unique, stable
suitor-optimal matching. The algorithm is as follows:
(1) Assign all suitors and reviewers to be unmatched.
(2) Take any unmatched suitor, s, and their most p... | 5b52cb165d15a0992b58c38958daf222d8d642cd | 3,629,364 |
def geom_bar(mapping=None, *, data=None, stat=None, position=None, show_legend=None, sampling=None, tooltips=None,
**other_args):
"""
Display a bar chart which makes the height of the bar proportional to the
number of observed variable values, mapped to x axis.
Parameters
----------
... | 818e8ba7cd30913168acf11a8267a630dbd2d8d3 | 3,629,365 |
def diff_string(old, new):
"""given a old and new int value, return a string representing the
difference
"""
diff = abs(old - new)
diff_str = "%s%s" % (CMPS[cmp(old, new)], diff and ('%.2f' % diff) or '')
return diff_str | dc6d4a6456c6399307aca8cd4c609e64fd6ad02a | 3,629,366 |
def _tile_grid_to_cesium1x_source_options(tile_grid: TileGrid, url: str):
"""
Convert TileGrid into options to be used with Cesium.UrlTemplateImageryProvider(options) of Cesium 1.45+.
See
* https://cesiumjs.org/Cesium/Build/Documentation/UrlTemplateImageryProvider.html?classFilter=UrlTemplateImageryPr... | 24363d34f1d0fe590eac648fc1a1d1c584dd069f | 3,629,367 |
def update_code(code_id: int, code: schemas.CodeUpdate, db: Session = Depends(get_db)):
"""
Update Code
"""
db_code = crud.get_code(db=db, code_id=code_id)
if db_code is None:
raise HTTPException(status_code=404, detail="Code not found")
db_device = crud.get_device(db=db, device_id=code... | 5a9be20a25a584d2ea95e057049d8b354848ca81 | 3,629,368 |
def vgg19_lstar():
"""
Setup the VGG19 neural network, protect it using Gu and Rigazio's L* defense
mechanism and perform an inference on an example input.
"""
model = networks.VGG19()
dm = dms.GuRigazio(
keras_model = model.wrapped_model(),
noise_stddev = 4.71e-4,
how = ... | ad5c1a0cd57e40aff24e6fe2b2eaf2edc418fcdc | 3,629,369 |
def isoslice(var,prop,isoval, grd, Cpos='rho', masking=True, vert=False):
"""
isoslice, lon, lat = isoslice(variable,property, isoval, grd)
optional switch:
- Cpos='rho', 'u' or 'v' specify the C-grid position where
the variable rely
- masking=True mask the output... | 50bbac87cfadcd3aa1a280b17551721788456723 | 3,629,371 |
def get_solution(x):
"""
Args:
x (numpy.ndarray) : binary string as numpy array.
Returns:
numpy.ndarray: graph solution as binary numpy array.
"""
return 1 - x | dd4c92baeaab0d3231f9b24cd950a42d589218aa | 3,629,372 |
from typing import Any
async def async_get_config_entry_diagnostics(
hass: HomeAssistant, config_entry: ConfigEntry
) -> dict[str, Any]:
"""Return diagnostics for a config entry."""
controller = hass.data[DOMAIN][config_entry.entry_id]
diag: dict[str, Any] = {}
diag["entry"]: dict[str, Any] = {}
... | af70d72e804c8946015e5a3d6e74ec0105de6168 | 3,629,373 |
from pathlib import Path
def create_upload_file(tmp_path):
"""Create temporary text file for upload."""
file_path = Path(tmp_path, "test_upload_1.txt")
with open(file_path, "w") as f:
f.write("Hello World")
return file_path | 50b707f59736ae1b1e06018aedec451b578eafc8 | 3,629,374 |
def makeFigure():
"""Get a list of the axis objects and create a figure"""
ax, f = getSetup((10, 8), (3, 4), multz={8: 1, 10: 1})
subplotLabel(ax)
Tcell_pathname = path_here + "/data/flow/2019-11-08 monomer IL-2 Fc signaling/CD4 T cells - IL2-060 mono, IL2-060 dimeric"
NK_CD8_pathname = path_here ... | 6849598c09e9367c2702b0ee47232e9f2c69d1a3 | 3,629,375 |
def KimKim2011(medium="Water", p_steam=120, deltaT_sub=5, Theta=90, CAH=10,
Theta_a=None, Theta_r=None, k_coat=15, delta_coat=0, h_i=None,
c=1, N_s=250, print_properties=False, **kwargs):
""" main function, calculates dropwise condensation heat flux as described in:
Kim, S., & Kim,... | b2723d279ef8eee3a51fabde4462cbcad2ccd521 | 3,629,376 |
def cumall(series):
"""
Calculates cumulative all of values. Equivalent to
`series.expanding().apply(np.all).astype(bool)`.
Args:
series: column to compute cumulative all for.
"""
alls = series.expanding().apply(np.all).astype(bool)
return alls | 6d660dae0760f1157d91a21739729d91880761c1 | 3,629,377 |
def manhattan_distance(a: Point, b: Point) -> int:
"""Return the Manhattan distance between two points."""
return abs(a[0] - b[0]) + abs(a[1] - b[1]) | 627d846b6aaea04d98d75dd04ca082578c090b5d | 3,629,378 |
import json
def gen_new_dns_json():
"""
Generate json file with IPs and their respective domains.
:return: Stats about domains
"""
json_dict = []
for ip in DATA.keys():
entry = {'ip': ip, 'domain': DATA.get(ip)}
json_dict.append(entry)
dist = {"domains": json_dict}
with... | 69ca6e7471f864cb0e3f224f93a24546fa314b6e | 3,629,379 |
def recorderLocations(year = 2014):
"""
This function returns all survey locations and recorder abbreviations for a given year. Only valid from 2009 onwards.
"""
if year > 2009:
stryear = str(year)
groups = loadTable('groups')
recorderids = loadTable('recorderinstall')
... | 759ad3de6369ed7ee20e1f02fba5e06b54373294 | 3,629,380 |
def ensure_rng(rng=None):
"""Simple version of the ``kwarray.ensure_rng``
Args:
rng (int | numpy.random.RandomState | None):
if None, then defaults to the global rng. Otherwise this can be an
integer or a RandomState class
Returns:
(numpy.random.RandomState) : rng -
... | a58d9aac689e89dfda7fa0b0b389a3a1e2a913e0 | 3,629,381 |
def def_grad_surf(surf, u, v):
""""
Compute deformation gradient via a NURBS surface interpolation of control point displacement at u, v
parametric coordinates
:param surf: NURBS surface interpolating control point displacements
:type surf: NURBS surface object
:param u: u parametric location
... | 892e1a9adc825e784b17b98cd400963e45ca949c | 3,629,382 |
def assign(tensor, val):
"""
Compatibility assignment operation
Args:
tensor: Tensor, to be assigned value of T2.
val: Tensor or python value, which will be assigned to T1.
Returns:
Assigned Tensor
"""
if _VERSION == 1:
tf.assign(tensor, val)
else:
... | d5ef567bad80f663c04d53214578a798a10adb22 | 3,629,383 |
from django.contrib.auth import get_user_model
def get_v3_users_from_v2_user_ids(v2_user_ids):
"""
Get v3 users with last_login==null and has a matching v2 user id
"""
return get_user_model().objects\
.filter(last_login__isnull=True)\
.filter(id__in=v2_user_ids) | 378ad4e1e8904fe57d91b8657994f5965d5bebbb | 3,629,384 |
def filter_intersection(data, hoax_pages, print_results=False):
"""returns the dataset filtered with only the users who liked at least
one post belonging to a hoax page and one post belonging to a non-hoax page
print_results: if True, prints the filtering effect
output: sparse like_matrix and page/hoax ... | 6ebaec0eb520098ad9f85ce79bf4a93e75ea70f0 | 3,629,385 |
def get_path_up_down(path_source, path_target):
"""paths for up/down
NOTE: both lists always show the LOWER level element
even for the so for path up, it shows the source,
for path down the target!
Args:
path_source(list)
path_target(list)
"""
# find common part of pat... | ba4719b42e0703ea0ac885de29b36466b7eb3676 | 3,629,386 |
def hsitogramEqualize(imgOrig: np.ndarray) -> (np.ndarray, np.ndarray, np.ndarray):
"""
Equalizes the histogram of an image
:param imgOrig: Original Histogram
:return
"""
num_of_pixels = imgOrig.shape[0] * imgOrig.shape[1]
if len(imgOrig.shape) == 2:
norm_255 = normalize_image(imgOri... | b196d3ffe8b6323883591960e0627a9e7eb40735 | 3,629,387 |
def findCentroid(points):
"""
Compute the centroid for the vectors of a group of Active Site instance
Input: n ActiveSite instances
Output: the centroid vector
"""
centroid = [0.0,0.0,0.0]
for item in points:
centroid = [centroid[0]+item.vector[0],centroid[1]+item.vector[1],centroid[... | 16f0c4b0052edad8c37ca4abee93bff7c1d5937b | 3,629,389 |
def weth_instance(web3_eth): # pylint: disable=redefined-outer-name
"""Get an instance of the WrapperEther contract."""
return web3_eth.contract(
address=to_checksum_address(
NETWORK_TO_ADDRESSES[NetworkId.GANACHE].ether_token
),
abi=abi_by_name("WETH9"),
) | d0dbbeb33e9d0679196b9e1c6f0c2cdac3a3dc30 | 3,629,391 |
def get_editops_stats(alignment, gap_char):
"""Get stats for character level edit operations that need to be done to
transform the source string to the target string. Inputs must not be empty
and must be the result of calling the runing the align function.
Args:
alignment (tuple(str, str)): the... | 90a902fa3dadd05c064f9853ce94fc680e5177a9 | 3,629,392 |
def conv(inputs, out_filters, ksize=(3, 3), strides=(1, 1), dilation=(1, 1),
use_bias=True):
"""
Convolution layer
Parameters
----------
inputs: Input tensor
out_filters: Number of output filters
ksize: Kernel size. One integer of tuple of two integers
strides: Strides for movi... | e8e6ca7be7463106e1bbe67381b36eeffeebb7f2 | 3,629,393 |
def is_active(host, port):
"""Check if server is active.
Send HTTP GET for a fake /style.css which server will respond to if it's
alive.
Args:
host: server ip address
port: server port
Returns:
Boolean for server state.
"""
try:
url = 'http://{}:{}/style.c... | 8c6af3307326ddcf9c57bc7745d26103ed5ded2e | 3,629,394 |
def norm_lrelu_conv(feat_in, feat_out):
"""InstanceNorm3D + LeakyReLU + Conv3D block"""
return nn.Sequential(
nn.InstanceNorm3d(feat_in),
nn.LeakyReLU(),
nn.Conv3d(feat_in, feat_out, kernel_size=3, stride=1, padding=1, bias=False)
) | d62c2becb6f88b1f925c2ddbb8395937eadc2174 | 3,629,395 |
import pandas
from typing import Optional
def dataframe_divisions(
request: Request,
reader=Depends(reader),
format: Optional[str] = None,
serialization_registry=Depends(get_serialization_registry),
):
"""
Fetch the Apache Arrow serialization of the index values at the partition edges.
"""... | c42e6208e5fbbe1cf8383d2df66f8f0899c35f90 | 3,629,396 |
def get_integer_array(obj,name):
"""
Retrieves the value of a resource that uses a one-dimensional integer array.
iarr = Ngl.get_integer_array(plotid, resource_name)
plotid -- The identifier returned from Ngl.open_wks, or any PyNGL
function that returns a PlotId.
resource_name -- The name of the resource... | fb694d87e7de8f674be5a5d3326b94b2127d071b | 3,629,398 |
def EvalCode(code_str, parse_ctx, comp_lookup=None, mem=None, aliases=None):
"""
Unit tests can evaluate code strings and then use the resulting
CommandEvaluator.
"""
arena = parse_ctx.arena
comp_lookup = comp_lookup or completion.Lookup()
mem = mem or state.Mem('', [], arena, [])
parse_opts, exec_opts... | 181ea721a788da2a56a2cf1c1df6bfc35cdfbefc | 3,629,400 |
import csv
def read_forces(fname):
"""Read .forces file format from Cortex MAC.
The .forces file in ASCII contains force plate data. The data is saved
based on the forcepla.cal file of the trial and converts the raw force
plate data into calibrated forces. The units used are Newtons and
Newton-me... | 62b7c8050be5fd9cb79d2edfb2b459e4d705f704 | 3,629,401 |
def mpw_plot_points(slope, years, values):
"""
Calculate start and end points for line describing MPW best fit
:param float slope: line slope
:param float array years: x-coordinates
:param float array values: y-coordinates
:returns: [[x1,x2], [y1,y1]]
"""
mu_x = np.ma.mean(years)
... | 4265b26485e22ba8306edd0b647292eba2803b6b | 3,629,402 |
def get_target(module, array):
"""Return Pod or None"""
try:
return array.get_pod(module.params['target'])
except Exception:
return None | ee95f125073c852bdef11b42e9e9dda394fec9e1 | 3,629,403 |
def int_kinenergy(basis):
"""Calculates the kinenergy matrix for a given basis.
Parameters
----------
basis : BasisSet
Returns
-------
kinenergy : np.ndarray
Kinetic energy matrix with shape M x M, where `M = len(basis)`.
"""
M = len(basis)
kinenergy = np.zeros((M, M))
... | 0dfd6777bea20620d20f08578d61e6961777a10c | 3,629,404 |
from datetime import datetime
import requests
def test_commit_in_last_year_yes(monkeypatch):
"""
11. Has there been a commit in the last year?
"""
headers = {}
def mock_get(*args, **kwargs):
return MockResponseCommitsYes()
today = datetime.now()
test_date = datetime.strptime(GOOD... | 2473c6a86322749f26e3c9086d822799fa6d48fd | 3,629,405 |
def all_columns_functional(use_cache = True, update_cache = True):
""" Returns all functional categories identified in the data set. """
return get_columns('pathabundance_columns.pickle', 'pathabundance_relab', use_cache, update_cache) | b30bb59556f2597eda0821490515cd855c31c293 | 3,629,406 |
def json_replace(json_obj, **values):
"""
Search for elements of `{"{{REPLACE_PARAM}}": "some_key"}` and replace
with the result of `values["some_key"]`.
"""
if type(json_obj) is list:
return [json_replace(x, **values) for x in json_obj]
elif type(json_obj) is dict:
new = {}
... | f6a8b44b5dd10d37140445b9dc8ebd71107df0a2 | 3,629,407 |
def diff(f, *x, allowed_nonsmoothness="discontinuous"):
"""
A differentiator which computes :math:`\\partial f / \\partial x` and understands
:class:`Field`\\ s. If ``x`` is one of ``t``, ``x``, ``y``, or ``z`` and ``f``
is a :class:`DynamicField`, the corresponding derivative :class:`Field` is
retu... | 2031ae7cea5b36b4c660116ff82ee3570eb647d9 | 3,629,409 |
def append_store_prices(ticker_list, loc, start = '01/01/1990'):
"""
Given an existing store located at ``loc``, check to make sure
the tickers in ``ticker_list`` are not already in the data
set, and then insert the tickers into the store.
:ARGS:
ticker_list: :class:`list` of tickers to ad... | b7aa347eaa84b79342d44db2c5b757f56d831cf9 | 3,629,410 |
from typing import List
def trace_for_kbps(kbps: int) -> List[int]:
""" Returns Mahimahi trace lines whose average kbps approximates the passed in value """
# - convert kbps to a Fraction representing # packets per line of a Mahimahi trace file
# - Fraction will also simplify the ratio, giving us exactly ... | 80c16739ae85a5c236aa03cf23ce63fcf51a226f | 3,629,411 |
def barotropic_input_qref_to_compute_lwa(ylat,qref,vort,area,dmu,planet_radius = 6.378e+6): # used to be Eqlat_LWA
"""
This function computes LWA based on a *prescribed* Qref instead of Qref obtained from the vorticity field on a barotropic sphere.
Parameters
----------
ylat : sequence or array_lik... | aae459dd30fa4fbf8f1ab2a5ff29ed2e36f34878 | 3,629,412 |
def merge_models(old, new):
"""docstring for merge_model"""
if old.rowCount() == 0:
return new
if new.rowCount() == 0:
return old
old_crcs = [(old.item(row, COLUMN_CRC).text(), row) for row in
xrange(old.rowCount())]
new_crcs = [(new.item(row, COLUMN_CRC).text(), row) f... | 985f8ac5aa43409dab2d31859125b1d3d64a79fb | 3,629,413 |
import torch
def get_operator_norm(*ops):
""" Computes the l2-operator norm of a product of linear operators. """
if all([hasattr(op, "get_matrix") for op in ops]):
mat = ops[-1].get_matrix()
for op in ops[:-1][::-1]:
mat = torch.matmul(op.get_matrix(), mat)
return np.linal... | 4a1030d64fbdd0431a6351aa408b927dae98480b | 3,629,414 |
def fileexistspolicy(
overwrite_if_exists: bool, skip_if_file_exists: bool
) -> FileExistsPolicy:
"""Return the policy for overwriting existing files."""
return (
FileExistsPolicy.RAISE
if not overwrite_if_exists
else FileExistsPolicy.SKIP
if skip_if_file_exists
else ... | d8bd5e07c7f46aa9036460884ae5e1c588765cc2 | 3,629,415 |
import requests
def createDummy(name, type):
"""
Create a dummy entry to the SSRQ Person db.
:param name:
:param type:
:return link_id (string):
"""
try:
print("Requesting dummy id for " + name)
if type == "person":
r = requests.get("https://www.ssrq-sds-fds.ch/... | e7a6a124dbf49a51fa3971206fb9d630c9e2221c | 3,629,416 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.