content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def get_rdf_lables(obj_list):
"""Get rdf:labels from a given list of objects."""
rdf_labels = []
for obj in obj_list:
rdf_labels.append(obj['rdf:label'])
return rdf_labels | 2bcf6a6e8922e622de602f5956747955ea39eeda | 4,700 |
import json
def _create_model_fn(pipeline_proto, is_chief=True):
"""Creates a callable that build the model.
Args:
pipeline_proto: an instance of pipeline_pb2.Pipeline.
Returns:
model_fn: a callable that takes [features, labels, mode, params] as inputs.
"""
if not isinstance(pipeline_proto, pipeli... | f29e86a0bc1355a7cf509e57ad0262bc5a9ca1e5 | 4,701 |
def boolean_automatic(meshes, operation, **kwargs):
"""
Automatically pick an engine for booleans based on availability.
Parameters
--------------
meshes : list of Trimesh
Meshes to be booleaned
operation : str
Type of boolean, i.e. 'union', 'intersection', 'difference'
Returns... | 7e5b1a483862bb05bb4cd78d21ec22c835f218e6 | 4,702 |
from .workflow import WorkSpec
def get_context(work=None):
"""Get a concrete Context object.
Args:
work (gmx.workflow.WorkSpec): runnable work as a valid gmx.workflow.WorkSpec object
Returns:
An object implementing the :py:class:`gmx.context.Context` interface, if possible.
Raises:
... | 838de2ce25dbe44c058f5360a59e48a68fa7dc2a | 4,703 |
def test_data():
"""Get the `CIFAR-10` test data."""
global _MEAN # pylint: disable=global-statement
_np.random.seed(1)
view = _skdc10.view.OfficialImageClassificationTask()
permutation = _np.random.permutation(range(10000))
if _MEAN is None:
_MEAN = view.train.x.reshape((50000 * 32 * 3... | e20acfc0e46dba2441b03d0d1443fc193c500e62 | 4,704 |
def normalize_key_combo(key_combo):
"""Normalize key combination to make it easily comparable.
All aliases are converted and modifier orders are fixed to:
Control, Alt, Shift, Meta
Letters will always be read as upper-case.
Due to the native implementation of the key system, Shift pressed in
c... | e242c6d9177d31c60a534e9734917c6fdf2de9f7 | 4,705 |
def shape_to_np(shape, dtype="int"):
"""
Used to convert from a shape object returned by dlib to an np array
"""
return np.array([[shape.part(i).x, shape.part(i).y] for i in range(68)], dtype=dtype) | 6d3d0205a8ac90dc8fb17b844fd5e150e25bdde1 | 4,706 |
def inet_pton(space, address):
""" Converts a human readable IP
address to its packed in_addr representation"""
n = rsocket.inet_pton(rsocket.AF_INET, address)
return space.newstr(n) | d015f76ab252e8f1f9f8f764bb7a2131f9ca9b92 | 4,707 |
def delete_routing_segmentation_maps_from_source_segment(
self,
segment_id: int,
) -> bool:
"""Delete D-NAT policies for specific source segment
.. list-table::
:header-rows: 1
* - Swagger Section
- Method
- Endpoint
* - vrf
- DELETE
- /v... | 32064ca159928ccc0802791e161a614f3303555f | 4,708 |
import os
def load_bounding_boxes(dataset_dir):
"""
Load bounding boxes and return a dictionary of file names and corresponding bounding boxes
"""
# Paths
bounding_boxes_path = os.path.join(dataset_dir, 'bounding_boxes.txt')
file_paths_path = os.path.join(dataset_dir, 'images.txt')
# Read... | ed6e4b1d049da25dc975fcd1406e4c17dbe09a70 | 4,709 |
def _identifier(name):
"""
:param name: string
:return: name in lower case and with '_' instead of '-'
:rtype: string
"""
if name.isidentifier():
return name
return name.lower().lstrip('0123456789. ').replace('-', '_') | fbbbc9dd3f2bc5b6e43520c0685f63a10ee95f0a | 4,710 |
def roots(p):
"""
Return the roots of a polynomial with coefficients given in p.
The values in the rank-1 array `p` are coefficients of a polynomial.
If the length of `p` is n+1 then the polynomial is described by
p[0] * x**n + p[1] * x**(n-1) + ... + p[n-1]*x + p[n]
Parameters
----------
... | 02e3f37a81c84aac9ac949662ec64b85e24432c9 | 4,711 |
from typing import List
def calculate_trade_from_swaps(
swaps: List[AMMSwap],
trade_index: int = 0,
) -> AMMTrade:
"""Given a list of 1 or more AMMSwap (swap) return an AMMTrade (trade).
The trade is calculated using the first swap token (QUOTE) and last swap
token (BASE). Be aware that an... | 55071041fd0cab3fd2c0cb89f24cd9267a4e164a | 4,712 |
def tokenize(s):
"""
Tokenize a string.
Args:
s: String to be tokenized.
Returns:
A list of words as the result of tokenization.
"""
#return s.split(" ")
return nltk.word_tokenize(s) | 8dcc01364b3442539dbcc979d3238492bb7904d1 | 4,713 |
from datetime import datetime
def evaluate(request):
"""Eval view that shows how many times each entry was tracked"""
# default filter
end_date = datetime.date.today()
start_date = datetime.date(year=end_date.year, month=end_date.month - 1, day=end_date.day)
num_entries = 5
# get custom filte... | 44708b65846fd9e21ebc7baf1fe0377054ae2221 | 4,714 |
def plot_af_correlation(vf1, vf2, ax=None, figsize=None):
"""
Create a scatter plot showing the correlation of allele frequency between
two VCF files.
This method will exclude the following sites:
- non-onverlapping sites
- multiallelic sites
- sites with one or more missing ge... | aadf3b7cd226e04c0bdbf26c737831b515d7e6c9 | 4,715 |
def significant_pc_test(adata, p_cutoff=0.1, update=True, obsm='X_pca', downsample=50000):
"""
Parameters
----------
adata
p_cutoff
update
obsm
downsample
Returns
-------
"""
pcs = adata.obsm[obsm]
if pcs.shape[0] > downsample:
print(f'Downsample PC matrix ... | c8e367c53330bcb959fb7baba9649d090de91389 | 4,716 |
from sys import path
import tqdm
def files_from_output(folder):
"""Get list of result files from output log."""
files = []
with open(path.join(folder, "OUTPUT.out")) as out_file:
for line in tqdm(out_file.readlines(), desc="Read files from output"):
if line.find("+ -o") != -1:
... | a76db67ef6484773f216163b8f27e1741856892d | 4,717 |
def unique_hurricanes(hurdat):
"""
Returns header info for each unique hurricanes in HURDAT2-formatted text
file hurdat.
"""
#split on returns if hurdat is not a list
if not isinstance(hurdat, list):
hurdat = hurdat.split('\n')
header_rows = [parse_header(
line, line_num
... | c87561b80f6c8b70c33d64834c4d289508a2c120 | 4,718 |
import os
def find_package_data():
"""
Find package_data.
"""
theme_dirs = []
for dir, subdirs, files in os.walk(pjoin('jupyterlab', 'themes')):
slice_len = len('jupyterlab' + os.sep)
theme_dirs.append(pjoin(dir[slice_len:], '*'))
schema_dirs = []
for dir, subdirs, files i... | b0becf06f363723723d99ca58819cd1311a918ef | 4,719 |
def delete_models_shares_groups(id, group_id, client=None):
"""Revoke the permissions a group has on this object
Use this function on both training and scoring jobs.
Parameters
----------
id : integer
The ID of the resource that is shared.
group_id : integer
The ID of the group... | 59f3391e6e92fe0bf2f4c204a9da7c55a8ac8c6c | 4,720 |
def step1ddiffusionanalytical(q, dt, alpha, beta, prng=np.random, **kwargs):
"""Analytical time stepping as proposed in Jenkins, Spano arXiv:1506.06998
Uses the asymptotic normality of the death process for small times
(see Griffiths, J. Math. Bio, 1984)
"""
theta = alpha+beta
beta_ =... | ae1034488250a7a0afc184878496cd656b239016 | 4,721 |
def no_vtk():
""" Checks if VTK is installed and the python wrapper is functional """
global _vtk_version
return _vtk_version is None | 654dfd0f10a36bbfd3e46c5a93f84a9234e8c0ca | 4,722 |
def get_request_list(flow_list: list) -> list:
"""
将flow list转换为request list。在mitmproxy中,flow是对request和response的总称,这个功能只获取request。
:param flow_list: flow的列表
:return: request的列表
"""
req_list = []
for flow in flow_list:
request = flow.get("request")
req_list.append(request)
... | a70e0120ef2be88bd0644b82317a2a0748352c6c | 4,723 |
from typing import Tuple
import logging
def query_total_production(start_date, end_date) -> Tuple[int]:
"""Total count of semi production on the given time interval"""
semi_count = None
fg_count = None
try:
with stSession() as s:
semi_count = (
s.query(ProductionSc... | 4ecf7b2e70feaa75456550deca6a5b8a326adc11 | 4,724 |
import pytz
def add_fields(_, level, event_dict):
""" Add custom fields to each record. """
now = dt.datetime.now()
event_dict['timestamp'] = TZ.localize(now, True).astimezone(pytz.utc).isoformat()
event_dict['level'] = level
if session:
event_dict['session_id'] = session.get('session_id'... | 3efbffc2808a048fde80a3655e28417c39f2ad04 | 4,725 |
def Smith_set(A,P,params,election_ID,printing_wanted=False):
"""
Compute and return a list of the candidates in the Smith set.
This is the smallest set of candidates such that every candidate in the
Smith set beats every candidate not in the Smith set in one-on-one contests.
In this implementation, ... | eb71ee5ae402d732a3bea804aad5b39fe3bd92a2 | 4,726 |
from typing import Callable
from typing import Coroutine
from typing import Any
def run_async_from_thread(func: Callable[..., Coroutine[Any, Any, T_Retval]], *args) -> T_Retval:
"""
Call a coroutine function from a worker thread.
:param func: a coroutine function
:param args: positional arguments for... | 829a9008e8aa058b66cb637db71f8f8eb8499374 | 4,727 |
def check_tensor_shape(tensor_tf, target_shape):
""" Return a Tensorflow boolean graph that indicates whether
sample[features_key] has the specified target shape. Only check
not None entries of target_shape.
:param tensor_tf: Tensor to check shape for.
:param target_shape: Target shape to compare t... | 8b9938c67f2e3655f9ff4dac08261fb6e5803af2 | 4,728 |
def LabelAddressPlus(ea, name, force=False, append_once=False, unnamed=False, nousername=False, named=False, throw=False):
"""
Label an address with name (forced) or an alternative_01
:param ea: address
:param name: desired name
:param force: force name (displace existing name)
:param append_onc... | 4772fa25c482eb10abdfea6aa9542f50827c9346 | 4,729 |
def do_match(station1, station2, latitude, elevation, distance):
"""
Perform the match between two stations.
Do initial latitude check to speed up the test
(not longitude as this isn't a constant distance)
Return probabilities for elevation, separation and Jaccard Index
:param Station Class... | 078d04117363087a512449497713c487bc1180e4 | 4,730 |
def rotation_matrix_from_vectors(vec1, vec2):
""" Find the rotation matrix that aligns vec1 to vec2
Args
----
vec1 (numpy.ndarray): A 3d "source" vector
vec2 (numpy.ndarray): A 3d "destination" vector
Returns
-------
numpy.ndarray: A transform matrix (3x3) which when applie... | 9568378e309c5da6e6dffee4788e07eb0c2ea189 | 4,731 |
import os
def get_file_from_cache_if_exists(file_path,
update_modification_time_on_access=True):
"""Get file from nfs cache if available."""
cache_file_path = get_cache_file_path(file_path)
if not cache_file_path or not file_exists_in_cache(cache_file_path):
# If the file d... | 98bb16eb964483b2bcb9bcad02463042fc2c18b2 | 4,732 |
def audio(src, type="audio/ogg", other_attr={}):
"""
add audio file
args:
src <str> : source file
type <str> : type of audio file
other_attr <dict> : other attributes
"""
return f"""
<audio {_parse_attr(other_attr)}>
<source src="{src}" type="{type}">
</audi... | 3ccd8aea6d7257c46336bb81184cf4b7f379624e | 4,733 |
def test_triangle(dim):
"""
Tests if dimensions can come from a triangle.
dim is a list or tuple of the three dimensions
"""
dim = [int(x) for x in dim]
dim.sort()
if dim[0] + dim[1] > dim[2]:
return True
else:
return False | fc5bc8f7d3830da0ae8692d7cf65a72bcfe2ba7d | 4,734 |
from typing import List
def arg_parser(data: str):
"""parse "x[a1, a2, a3], y[k1=a1, a2, k3=a3], z"
nested [] are ignored.
"""
res: List[NameWithAttrs] = _ARG_WITH_ATTR_PARSER.parse(data)
return res | fa530584a96829944562d2c08bdfed34bfa3eec4 | 4,735 |
def _get_resource(span):
"""Get resource name for span"""
if "http.method" in span.attributes:
route = span.attributes.get("http.route")
return (
span.attributes["http.method"] + " " + route
if route
else span.attributes["http.method"]
)
return sp... | 71b4d2e568350ccfb436bbff6e7a2cff1f3cb251 | 4,736 |
def get_draw_title(kdata):
"""根据typ值,返回相应的标题,如 上证指数(日线)
参数:kdata: KData实例
返回:一个包含stock名称的字符串,可用作绘图时的标题
"""
if not kdata:
return ""
query = kdata.getQuery()
stock = kdata.getStock()
if stock.isNull():
return ""
s1 = ''
if query.kType == KQuery.KType.DAY:
... | 7c661b63cedb477224d7f5ea9d7c182108f801a5 | 4,737 |
def _B(slot):
"""Convert slot to Byte boundary"""
return slot*2 | 97f13e9fd99989a83e32f635193a0058656df68b | 4,738 |
import torch
def nll(perm, true):
"""
perm: (n, n) or (s, n, n)
true: (n)
"""
n = true.size(-1)
# i = torch.arange(n, device=perm.device)
# j = true.to(perm.device)
# print("perm.nll:", perm.size(), true.size())
elements = perm.cpu()[..., torch.arange(n), true]
# elements = per... | a63c95e814529539ecd964f4309ea96f78cfcbb1 | 4,739 |
def _peaks_colors_from_points(points, colors=None, points_per_line=2):
"""
Returns a VTK scalar array containing colors information for each one of
the peaks according to the policy defined by the parameter colors.
Parameters
----------
points : (N, 3) array or ndarray
points coordinate... | 7abc5be4739164dc225081ec321d1cb591f74bae | 4,740 |
def epi_reg(epi, t1, t1brain, out='epi_reg', **kwargs):
"""Wrapper for the ``epi_reg`` command.
:arg epi: Input EPI image
:arg t1: Input wholehead T1 image
:arg t1brain: Input brain extracted T1 image
:arg out: Output name
"""
asrt.assertIsNifti(epi)
asrt.assertIsNi... | 1d19f0efcfb4fcfc7293f294978d11811861a06b | 4,741 |
import pathlib
import json
def load_towns():
"""Sample of Wikipedia dataset that contains informations about Toulouse, Paris, Lyon and
Bordeaux.
Examples
--------
>>> from pprint import pprint as print
>>> from cherche import data
>>> towns = data.load_towns()
>>> print(towns[:3])
... | 72aa393cfc40db5f254059d78679ea5615f494d2 | 4,742 |
def nonce_initialization(params: InitializeNonceParams) -> TransactionInstruction:
"""Generate an instruction to initialize a Nonce account.
Args:
params: The nonce initialization params.
Returns:
The instruction to initialize the nonce account.
"""
return TransactionInstruction.f... | 99fc70fd7965443b508923013a988f96ecf7b222 | 4,743 |
def to_weeknr(date=''):
"""
Transforms a date strings YYYYMMDD to the corresponding week nr (e.g. 20200713 becomes w29)
"""
week_nr = pd.to_datetime(date).to_pydatetime().isocalendar()[1]
return f"w{week_nr}" | f9699e735be8d92e4340a23464ee54247c355ffd | 4,744 |
def build_logisticregression(X_loc, y_loc, args):
"""finds best parameters for logistic regression"""
Printer(colored('(training) ', 'green') +
'searching for best parameters for logistic regression')
# specify parameters and distributions to sample from
param_dist = {"C": np.logspace(-9, 3, 13),
"solver":... | f63f67bc9debd2adccac39910b29ed705498dd4b | 4,745 |
import re
def load_data(experiments,
remove_outlier=True,
peptides=["A5cons",
"A6cons",
"phage_ctl_0",
"phage_ctl_1",
"phage_ctl_2",
"phage_ctl_4",
... | b9d7c7be8e0bbe5f5aee785cc0b525d9a57acc8b | 4,746 |
def get_lines(clearance):
"""
Add lines per reference well interval between the closest points on the
reference well and the offset well and color them according to the
calculated Separation Factor (SF) between the two wells at these points.
Parameters
----------
clearance: welleng.clea... | 2ec0ef039647b9c72219989d00b3e92092a79c16 | 4,747 |
import hashlib
def generate_md5_hash(filepath):
"""Returns md5 hash of file.
Args:
filepath: str. Absolute path to the file.
Returns:
str. Hexadecimal hash of specified file.
"""
m = hashlib.md5()
with python_utils.open_file(filepath, 'rb', encoding=None) as f:
while ... | d615d9ec14b79eac72168db616664f5878ca8e21 | 4,748 |
def status():
"""Return status."""
return jsonify(STATUS) | de396fdf35e42a36ed40b294a26645efba29c27a | 4,749 |
from typing import Optional
def get_entitlement(account_id: Optional[str] = None,
customer_id: Optional[str] = None,
entitlement_id: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetEntitlementResult:
"""
Returns the ... | 8cc10901b90a05a4bc0089758ce297c54af48569 | 4,750 |
def skip_to_home(fxn):
""" Skips past page straight to home page if logged in
"""
@wraps(fxn)
def skipped_page_fxn(*arg, **kwargs):
if session.get('logged_in'):
return redirect(url_for('home'))
else:
return fxn(*arg, **kwargs)
return skipped_page_fxn | 9edbbc186caa93046d17c179610a9c1309f281db | 4,751 |
from pathlib import Path
def get_all_paths_from_directory(directory: Path, recursive: bool, paths: [str] = [], ) -> [Path]:
"""
Gets a list of file paths for all files in the given directory (and its subdirectories if recursive is true)
:param directory: The starting directory to get file paths from
:... | 95f26d94ff1656fa5e4c656ecf3e424bf29f21b0 | 4,752 |
def check_contigs_for_dupes(matches):
"""check for contigs that match more than 1 UCE locus"""
node_dupes = defaultdict(list)
for node in matches:
node_dupes[node] = len(set(matches[node]))
dupe_set = set([node for node in node_dupes if node_dupes[node] > 1])
return dupe_set | f20ab684388e38b51e193567b14a2a610d87f227 | 4,753 |
def substitute(P, x0, x1, V=0):
"""
Substitute a variable in a polynomial array.
Args:
P (Poly) : Input data.
x0 (Poly, int) : The variable to substitute. Indicated with either unit
variable, e.g. `x`, `y`, `z`, etc. or through an integer
matching the unit va... | dd176877f8663e7efb3ae99babf29726dbda025b | 4,754 |
def munkres(costs):
"""
Entry method to solve the assignment problem.
costs: list of non-infinite values entries of the cost matrix
[(i,j,value)...]
"""
solver = Munkres(costs)
return solver.munkres() | 583dfc977c8f97fd5a3c4c82e21ae6626f4a763b | 4,755 |
import torch
def compute_mean_std(dataset):
"""
https://stats.stackexchange.com/questions/25848/how-to-sum-a-standard-deviation
"""
# global_mean = np.zeros((3 * 64), dtype=np.float64)
# global_var = np.zeros((3 * 64), dtype=np.float64)
n_items = 0
s = RunningStatistics()
for image_... | 83f10fc58e83b41a542fbd088895304b0d0521b5 | 4,756 |
def test_clean_connections_p0(monkeypatch):
"""Add a connection, fake a closed thread and make sure it is removed."""
db_disconnect_all()
class mock_connection():
def __init__(self) -> None: self.value = _MOCK_VALUE_1
def close(self): self.value = None
def mock_connect(*args, **kwargs)... | 9c8c7155566170a3598edcb8a9d7441630545522 | 4,757 |
def add(request):
"""
Add contact information.
**Templates:**
* ``rolodex/add.html``
**Template Variables:**
* form
* results: the list of similar names to allow user to check for dupes
* name: the new name that is submitted
"""
results = []
name = None
if request.m... | b0fdb73f2362dc0a82d46529727cfb3b0093b8e0 | 4,758 |
def convert_total (letter1,number1, letter2, number2):
"""
Description
-----------
Converting the letter of a column and the number of a line from an exceldata to a range
Context
----------
is called in wrapp_ProcessUnits and wrapp_SystemData
Parameters
----------
le... | 51cf6480d92fa1d23841dd5605d024548837df5c | 4,759 |
def scale_facet_list(facet_list, scale):
"""
Scale list of facets by the given scaling factor
"""
new_facet_list = []
for facet in facet_list:
new_facet_list.append(scale_facet(facet, scale))
return new_facet_list | 1b1d34803db191b94fc082685718c08895e2ba28 | 4,760 |
def move_lines_to_index(uwline_index_to, lineno, uwlines, lines):
"""Method moves all lines in the list to the proper index of uwlines and
update lineno on these lines. This is useful when you want to change the
order of code lines. But note: it is not updating lineno on other lines
@:returns positi... | e96f3b9da77468a31275e6255cd08ffa9309fc60 | 4,761 |
def birch(V, E0, B0, BP, V0):
"""
From Intermetallic compounds: Principles and Practice, Vol. I: Principles
Chapter 9 pages 195-210 by M. Mehl. B. Klein, D. Papaconstantopoulos paper downloaded from Web
case where n=0
"""
E = (E0
+ 9.0/8.0*B0*V0*((V0/V)**(2.0/3.0) - 1.0)**2
+... | 6515e2b0b78dfcdc1d7743f3d5a7010fce920aea | 4,762 |
from typing import Set
from typing import Tuple
def debloat(edges: set, nodes: int, threshold: tuple = (0.95, 0.95)) -> Set[Tuple[str, str]]:
"""Remove nodes with inflow and/or ourflow > threshold"""
df = pd.DataFrame(list(edges), columns=["source", "target"])
checkpoint_shape = df.shape[0]
df_inflow ... | 5be2dec388086b10409a3de008f357540019c5cf | 4,763 |
def result(jid):
""" Displays a job result.
Args:
jid (str): The job id.
"""
job = q.fetch_job(jid)
statuses = {
'queued': 202,
'started': 202,
'finished': 200,
'failed': 500,
'job not found': 404,
}
if job:
job_status = job.get_statu... | 2919be693949dd4e873834530565fd28aefcf5d5 | 4,764 |
from typing import Callable
def fd_nabla_1(
x: np.ndarray,
fun: Callable,
delta_vec: np.ndarray,
) -> np.ndarray:
"""Calculate FD approximation to 1st order derivative (Jacobian/gradient).
Parameters
----------
x: Parameter vector, shape (n_par,).
fun: Function returning function valu... | 32363e04bbd22627c7e5c21e02b48154dbfc030a | 4,765 |
def get_ref_len_from_bam(bam_path, target_contig):
"""
Fetch the length of a given reference sequence from a :py:class:`pysam.AlignmentFile`.
Parameters
----------
bam_path : str
Path to the BAM alignment
target_contig : str
The name of the contig for which to recover haplotype... | e80cb3c50f4408b2a614621ff3d688852931e75b | 4,766 |
def vstd(df, n=10):
"""
成交量标准差 vstd(10)
VSTD=STD(Volume,N)=[∑(Volume-MA(Volume,N))^2/N]^0.5
"""
_vstd = pd.DataFrame()
_vstd['date'] = df.date
_vstd['vstd'] = df.volume.rolling(n).std(ddof=1)
return _vstd | 97b448d00bcbe89d17339f9ed1155786d9ccd0ab | 4,767 |
def createMonatomicGas(elm, pascal):
"""createMonatomicGas(elm, pascal)
Create a gas of single atoms of the specified element at the specified pressure in Pascal and 300 K"""
return epq.Gas((elm,), (1,), pascal, 300.0, elm.toString() + " gas at %f Pa" % pascal) | 4552f551c27e0f10dea72c96bc32b9927649f749 | 4,768 |
import torch
def boxes_to_central_line_torch(boxes):
"""See boxes_to_central_line
Args:
boxes (tensor[..., 7]): (x, y, z, l, w, h, theta) of each box
Returns:
boxes_lp (tensor[..., 3]): (a, b, c) line parameters of each box
"""
# in case length is shorter than width
bmask = b... | e96667177cee058fe5f5cd1e8446df97d976474e | 4,769 |
from pyspark.sql import SparkSession
def load_as_spark(url: str) -> "PySparkDataFrame": # noqa: F821
"""
Load the shared table using the give url as a Spark DataFrame. `PySpark` must be installed, and
the application must be a PySpark application with the Apache Spark Connector for Delta Sharing
inst... | d427f71530b982703853146cbaa1ce3585b8f195 | 4,770 |
def calClassSpecificProbPanel(param, expVars, altAvMat, altChosen, obsAv):
"""
Function that calculates the class specific probabilities for each decision-maker in the
dataset
Parameters
----------
param : 1D numpy array of size nExpVars.
Contains parameter values.
expVars : 2D ... | ccb867b44db9f0d7f9b35c92ef66a96097b4b881 | 4,771 |
def build_expression_tree(tokens):
"""Returns an ExpressionTree based upon by a tokenized expression."""
s = [] # we use Python list as stack
for t in tokens:
if t in '+-x*/': # t is an operator symbol
s.append(t) ... | b54ce3c3d784ff80f380774135c7353d6ebd1078 | 4,772 |
import json
def unpack_blockchain(s: str) -> block.Blockchain:
"""Unapck blockchain from JSON string with b64 for bytes."""
blocks = json.loads(s)
return [_unpack_block(block) for block in blocks] | ed43ea73df866489e814fd1bdff357c158aade91 | 4,773 |
import re
def parse(options,full_path):
"""
Parse the data according to several regexes
"""
global p_entering_vip_block, p_exiting_vip_block, p_vip_next, p_vip_number, p_vip_set
in_vip_block = False
vip_list = []
vip_elem = {}
order_keys = []
if (options.input_file !=... | 08177b0ab18c77154053249c2308c4705d1dbb65 | 4,774 |
def update_wishlist_games(cur, table, wishlist_args, update_delay):
"""A function to update wishlist games.
:param cur: database cursor object
:type cur: Cursor
:param table: name of table to work on
:type table: str
:param wishlist_args: list of wishlist g... | fcd80f19065112893af84d0a9862888a13bde372 | 4,775 |
from re import M
def WrapSignal(signal):
"""Wrap a model signal with a corresponding frontend wrapper."""
if type(signal) is M.BitsSignal:
return BitsFrontend(signal)
elif type(signal) is M.ListSignal:
return ListFrontend(signal)
elif type(signal) is M.BundleSignal:
return Bun... | 374c47d5053853bc2b23d56d40a2752521a1351f | 4,776 |
from typing import Any
def is_array_like(element: Any) -> bool:
"""Returns `True` if `element` is a JAX array, a NumPy array, or a Python
`float`/`complex`/`bool`/`int`.
"""
return isinstance(
element, (jnp.ndarray, np.ndarray, float, complex, bool, int)
) or hasattr(element, "__jax_array_... | acb681e329883742009e3e2543158cd602839ae8 | 4,777 |
def parse(javascript_code):
"""Returns syntax tree of javascript_code.
Syntax tree has the same structure as syntax tree produced by esprima.js
Same as PyJsParser().parse For your convenience :) """
p = PyJsParser()
return p.parse(javascript_code) | 295a6d5683b975a9229e27d06cc1369e6a6f0a95 | 4,778 |
def twitterAuth():
""" Authenticate user using Twitter API generated credentials """
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
return tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True) | c0522247e22b2a029c7f954960b1f9f91e71e3cb | 4,779 |
def GetInstalledPackageUseFlags(pkg_str, board=None):
"""Gets the list of USE flags for installed packages matching |pkg_str|.
Args:
pkg_str: The package name with optional category, version, and slot.
board: The board to inspect.
Returns:
A dictionary with the key being a package CP and the value b... | 0b203ebe078d56053c4e2c3b23db91492399de55 | 4,780 |
def make_cursor():
"""
Creates a cursor for iterating through results
GetParams:
account: an account
user: a user
handle: a shark client handle
Returns:
a json object container the cursor handle
"""
data, statusCode = cursor()
return jsonify(data), statusCo... | 225cf3bdcb001f90041cb94dc5fd89c935daaf24 | 4,781 |
from typing import Any
def run_result_factory(data: list[tuple[Any, Any]]):
"""
We need to handle dt.datetime and agate.table.Table.
The rest of the types should already be JSON-serializable.
"""
d = {}
for key, val in data:
if isinstance(val, dt.datetime):
val = val.isofor... | 25462e0eaf87d4fcdd1f48161dfa5be4643485f4 | 4,782 |
def compute_steepness(zeroth_moment, peak_wavenumber):
"""Compute characteristic steepness from given peak wave number."""
return np.sqrt(2 * zeroth_moment) * peak_wavenumber | e1cb0beb19ff73e7d2b6a6879d4a388d04644953 | 4,783 |
def secondary_side_radius(mass_ratio, surface_potential):
"""
Side radius of secondary component
:param mass_ratio: float;
:param surface_potential: float;
:return: float; side radius
"""
return calculate_side_radius(1.0, mass_ratio, 1.0, surface_potential, 'secondary') | 3353d5b9cb76f9127ed1066a20a3328fea9b8a46 | 4,784 |
def pts_from_rect_inside(r):
""" returns start_pt, end_pt where end_pt is _inside_ the rectangle """
return (r[0], r[1]), ((r[0] + r[2] - 1), (r[1] + r[3] - 1)) | 51f5ea39763e9f16a2bb3a56eebef4dfe06c5746 | 4,785 |
import numpy as np
def minimum_distance(object_1, object_2):
""" Takes two lists as input
A list of numpy arrays of coordinates that make up object 1 and object 2
Measures the distances between each of the coordinates
Returns the minimum distance between the two objects, as calculated using a vector n... | e61fbb1ab83c5147f69351022f59ebab3295cb5a | 4,786 |
def retrieve_pkl_file(filename, verbose = False):
"""
Retrieve and return contents of pkl file
"""
if verbose == True:
start_time = timelib.time()
print("\n * Retrieving %s file ..."%filename)
data = pd.read_pickle(filename)
if verbose == True:
print("\n %s retrie... | aa7c108d32ea387c2677c0fccf285437d149ec01 | 4,787 |
def extractIpsFile(containerFile,newSimName):
"""
Given a container file, get the ips file in it and write it to current
directory so that it can be used
"""
oldIpsFile=os.path.splitext(containerFile)[0]+os.extsep+"ips"
zf=zipfile.ZipFile(containerFile,"r")
foundFile=""
# Assume that c... | a8135c7d3a10825e539819dfdb62d5f677680e44 | 4,788 |
import torch
def nplr(measure, N, rank=1, dtype=torch.float):
""" Return w, p, q, V, B such that
(w - p q^*, B) is unitarily equivalent to the original HiPPO A, B by the matrix V
i.e. A = V[w - p q^*]V^*, B = V B
"""
assert dtype == torch.float or torch.cfloat
if measure == 'random':
d... | 0451fa5ed1eeb60bef386991b2d953c190282e0e | 4,789 |
def read_data(oldest_year: int = 2020, newest_year: int = 2022):
"""Read in csv files of yearly covid data from the nytimes and concatenate into a single pandas DataFrame.
Args:
oldest_year: first year of data to use
newest_year: most recent year of data to use
"""
df_dicts = {} # diction... | 7b8e55ae41890eef3e4f0ac5a9502b8b19f1ad20 | 4,790 |
def ip_is_v4(ip: str) -> bool:
"""
Determines whether an IP address is IPv4 or not
:param str ip: An IP address as a string, e.g. 192.168.1.1
:raises ValueError: When the given IP address ``ip`` is invalid
:return bool: True if IPv6, False if not (i.e. probably IPv4)
"""
return type(ip_addr... | d0fa8351921e34ee44c1b6c9fecf14c0efe83397 | 4,791 |
def kdump(self_update=False, snapshot=None):
"""Regenerate kdump initrd
A new initrd for kdump is created in a snapshot.
self_update
Check for newer transactional-update versions.
snapshot
Use the given snapshot or, if no number is given, the current
default snapshot as a base... | fd49bf6bfb4af52625b4e479eca60594edb59d9e | 4,792 |
import logging
from datetime import datetime
def register_keywords_user(email, keywords, price):
"""Register users then keywords and creates/updates doc
Keyword arguments:
email - email for user
keywords - string of keywords
price -- (optional) max price can be set to None
"""
logging.in... | 09c0d3ff12fbd99d6e6a6c23906a74b525f91649 | 4,793 |
def plot_distribution(df, inv, ax=None, distribution=None, tau_plot=None, plot_bounds=True, plot_ci=True,
label='', ci_label='', unit_scale='auto', freq_axis=True, area=None, normalize=False,
predict_kw={}, **kw):
"""
Plot the specified distribution as a function of t... | f5f6eb29597abb34b4e0c634112370824cedf907 | 4,794 |
def profitsharing_order(self, transaction_id, out_order_no, receivers, unfreeze_unsplit,
appid=None, sub_appid=None, sub_mchid=None):
"""请求分账
:param transaction_id: 微信支付订单号,示例值:'4208450740201411110007820472'
:param out_order_no: 商户分账单号,只能是数字、大小写字母_-|*@,示例值:'P20150806125346'
:para... | 8885a953de7e74a562fc57ac242fafbf79ada7a8 | 4,795 |
def merge_time_batch_dims(x: Tensor) -> Tensor:
"""
Pack the time dimension into the batch dimension.
Args:
x: input tensor
Returns:
output tensor
"""
if xnmt.backend_dynet:
((hidden_dim, seq_len), batch_size_) = x.dim()
return dy.reshape(x, (hidden_dim,), batch_size=batch_size_ * seq_len)... | 73b09ca714870f18523c07b82e544b208fcde680 | 4,796 |
def get_log_likelihood(P, v, subs_counts):
"""
The stationary distribution of P is empirically derived.
It is proportional to the codon counts by construction.
@param P: a transition matrix using codon counts and free parameters
@param v: stationary distribution proportional to observed codon counts... | b7ed78e1e111a74f08b36f5ac41618318539d1c7 | 4,797 |
def union(l1, l2):
""" return the union of two lists """
return list(set(l1) | set(l2)) | 573e3b0e475b7b33209c4a477ce9cab53ec849d4 | 4,798 |
def actual_kwargs():
"""
Decorator that provides the wrapped function with an attribute 'actual_kwargs' containing just those keyword
arguments actually passed in to the function.
Based on code from http://stackoverflow.com/a/1409284/127480
"""
def decorator(function):
def inner(*args... | 37477edecb9442f759f4a234ea9037f7568f9770 | 4,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.