content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def get_crypto_quote(symbol, info=None):
"""Gets information about a crypto including low price, high price, and open price
:param symbol: The crypto ticker.
:type symbol: str
:param info: Will filter the results to have a list of the values that correspond to key that matches info.
:type info: Opt... | db10e7493ef6e98ad0876d30357c6b5be8269776 | 7,800 |
from .tools.forms import digest as digest_forms
from .multitool import convert
from .protonation import add_missing_hydrogens
from .model_loops import add_loop
def fix(item, missing_atoms=True, missing_residues=True, nonstandard_residues=True,
missing_terminals=True, missing_loops=False, missing_hydrogens=Tru... | 10bc29a4006e8bc1b18fba126dde7152672b7a24 | 7,801 |
def data_split(*args, **kwargs):
"""A function to split a dataset into train, test, and optionally
validation datasets.
**Arguments**
- ***args** : arbitrary _numpy.ndarray_ datasets
- An arbitrary number of datasets, each required to have
the same number of elements, as numpy arrays.... | e2ad6e52d2868020cc0bcb960533348a1f93ed31 | 7,802 |
def compare(isamAppliance1, isamAppliance2):
"""
Compare Policy Sets between two appliances
"""
ret_obj1 = get_all(isamAppliance1)
ret_obj2 = get_all(isamAppliance2)
for obj in ret_obj1['data']:
del obj['id']
del obj['userlastmodified']
del obj['lastmodified']
de... | a727eac5efb4e117413d70191e7a74921e3ac284 | 7,803 |
def capacity(quantity, channel, gamma, dim, basis, eps, **kwargs):
"""
Runs the Blahut-Arimoto algorithm to compute the capacity given by
'quantity' (which can be 'h', 'tc', 'coh' or 'qmi' taking the channel,
gamma, dim, basis and tolerance (eps) as inputs).
With the optional keyword arguments 'plot... | 6624d045fb953d536b082f183a6c1536dcd9ca50 | 7,804 |
def get_Teq_from_L(L: ArrayLike, d: ArrayLike, A: ArrayLike) -> np.ndarray:
"""Calculates the equilibrium temperature of a planet
given the stellar luminosity L, planetary semi-major axis d
and surface albedo A:
Args:
L (ArrayLike): Stellar luminosity in erg/s.
d (ArrayLike): Planetary ... | 9f140c554059074d9569e48ae2f971bc430e2fba | 7,805 |
from typing import Type
def lookup_container_plugin_by_type(container: IContainer, plugin_type: Type[ContainerResolutionPlugin]):
"""
Given a container, finds the first plugin that is an instance of the specified type.
:param container: The container to perform the lookup on.
:param plugin_type: The ... | b41cfc2e1e1328a8f54e938b7944d3f16924d3cf | 7,806 |
from scipy.ndimage import shift
def shift_map_longitude(mapdata, lonshift, spline_order=1):
""" Simple shift of the map by wrapping it around the edges
Internally uses scipy's ndimage.shift with spline interpolation order as
requested for interpolation
Parameters
----------
mapdata : 2D ... | 72373800f3a53785989cc2e2da4dab08d0976b30 | 7,807 |
def aalogoheights(aahistObj, N=20):
"""For a objhist of AA frequencies, compute the heights
of each AA for a logo plot"""
aahistObj = deepcopy(aahistObj)
keys = list(aahistObj.keys())
for aa in BADAA:
if aa in keys:
dummy = aahistObj.pop(aa)
keys = [aa for aa in aahistObj.sor... | 8020605d6c2a9a618e5faed57ba7af5e1315dfec | 7,808 |
def cmdline_opts( request ):
"""PyMTL options parsed from pytest commandline options."""
opts = _parse_opts_from_request( request )
# If a fixture is used by a test class, this seems to be the only
# way to retrieve the fixture value.
# https://stackoverflow.com/a/37761165/13190001
if request.cls is not No... | 8b3af4ab15a1a5a11a633fa322e4484f2d8257bc | 7,809 |
def replace(index, ndim, axes, rindices):
"""Replace indexing for a specified dimension
Args:
index(index): object used in slicing
ndim(num): number of dimensions
axes(list): dimension to be replaced
rindex(list): new indexing for this dimensions
Returns:
index
"... | 3a8c9ac8b9bf12a5d416e422ddfb0f4458cf9417 | 7,810 |
import select
def _closed(sock):
"""Return True if we know socket has been closed, False otherwise.
"""
try:
rd, _, _ = select([sock], [], [], 0)
# Any exception here is equally bad (select.error, ValueError, etc.).
except:
return True
return len(rd) > 0 | 4de2aee7743cac8e660ab01f2920935faf0ee3e9 | 7,811 |
def get_forest_connection(device_name: str, seed=None):
"""Get a connection to a forest backend
Args:
device_name: the device to connect to
Returns:
A connection to either a pyquil simulator or a QPU
"""
if device_name == "wavefunction-simulator":
return WavefunctionSimulat... | 291c92508b097908fa86fb957b42d73066d65ebd | 7,812 |
def get_slack_colour(level):
"""Return Slack colour value based on log level."""
level = level.upper()
colours = {
"CRITICAL": "ff0000",
"ERROR": "ff9933",
"WARNING": "ffcc00",
"INFO": "33ccff",
"DEBUG": "good"
}
return colours.get(level, "good") | 5a75bc103361b3724921d2b9c03c32f63b9b8115 | 7,813 |
def add_suffix(path, suffix=""):
"""Adds a suffix to a filename *path*"""
return join(dirname(path), basename(path, ext=False) + suffix + extname(path)) | dd95548e06e29c91f0a35c5dd0979889ab945076 | 7,814 |
def MdAE_np(preds, labels):
"""
Median Absolute Error
:param preds:
:param labels:
:return:
"""
preds = np.reshape(preds, [-1])
labels = np.reshape(labels, [-1])
return np.median(np.abs(preds - labels)) | 4a725eb35e5f7bd1f77b8433b7ea7393bbdae92e | 7,815 |
from botocore.exceptions import ClientError, BotoCoreError
async def s3_fetch_object(url, s3, range=None, **kw):
""" returns object with
On success:
.url = url
.data = bytes
.last_modified -- last modified timestamp
.range = None | (in,out)
.error = None
On failu... | 0da8fadb248abe8c4c23e75367b3ddc884df71d3 | 7,816 |
from . import darwin
from . import linux
from . import windows
import platform
def mss(**kwargs):
# type: (Any) -> MSSMixin
""" Factory returning a proper MSS class instance.
It detects the plateform we are running on
and choose the most adapted mss_class to take
screenshots.
... | 057916bf6b13bd6089ccb6f46b1a2ceb583d5bf8 | 7,817 |
def reshape_fps(X):
"""Reshape 4D fingerprint data to 2D
If X is already 2D, do nothing.
Returns: reshaped X
"""
if len(X.shape) == 4:
num_factors = X.shape[3]
num_fps = np.prod(X.shape[:3])
X.shape = (num_fps,num_factors)
else:
num_factors = X.shape[1]
... | ab2cd286194dd6d35fb27a540378a132d25db575 | 7,818 |
def df_fc_overlap_2():
"""Scenario case with 2 fragments overlapping, bound to a common fragment."""
mol = Chem.MolFromSmiles('NC1CC(CCC1O)C1CCC1')
return DataFrame([
['mol_fc_overlap_2', 'XXX', 'O1', 0, 'O1:0', 'O2', 0, 'O2:0', 'ffo', 'fusion', 'false_positive', 'overlap', (7, 6, 5, 4... | 7ee533aa1c7bb821ae6a73a27d39d6a7e796087f | 7,819 |
def show_toolbar(request):
"""Determines whether debug toolbar should be shown for the request.
Requires settings.DEBUG=True, 'debug_toolbar' GET param present,
and request ip in settings.INTERNAL_IPS.
Args:
request: HttpRequest object.
Returns:
Boolean.
"""
if ('debug_too... | 7a3fec348f5d37adcafd29d5cdd757e5e8de6cad | 7,820 |
from datetime import datetime
def strfnow(fmt=HUMAN_DATETIME):
"""
Returns a string representation of the current timestamp
"""
return datetime.now(tzlocal()).strftime(fmt) | 50fe38d37dfe8581f6cfa07aaaeb588a2e6e72a9 | 7,821 |
def tag_to_dict(node):
"""Assume tag has one layer of children, each of which is text, e.g.
<medalline>
<rank>1</rank>
<organization>USA</organization>
<gold>13</gold>
<silver>10</silver>
<bronze>9</bronze>
<total>32</total>
</medalline>
"""
d =... | e2131e070dce8620630e994cc25578a9a8438c64 | 7,822 |
from typing import Any
def compute_contact_centroid(molecular_complex: Any,
cutoff: float = 4.5) -> np.ndarray:
"""Computes the (x,y,z) centroid of the contact regions of this molecular complex.
For a molecular complex, it's necessary for various featurizations
that compute voxel g... | 53b83e6814f6f59645d84c36de458952918123fc | 7,823 |
def general_operator_gamma_norm(matrix, gamma, max_j, max_q):
""" Returns the gamma operator norm of matrix, summing up to max_j and
considering the sup up to max_q. Assumed that matrix is a function
accepting two arguments i,j and not an array () for efficiency.
"""
max_j_sum = -1
q = ... | 56993d0f406af3cead83e662aecb19d9082878fa | 7,824 |
def crop_image_single(img, device):
"""
Implementation of the MTCNN network to crop single image to only show the face as shown in the
facenet_pytorch doc:
https://github.com/timesler/facenet-pytorch/blob/master/examples/infer.ipynb
:param device: pytorch device
:param img: s... | b2755a1bf464dca74cbfc32a5bf5c61f106758ae | 7,825 |
def tf2zpk(b, a):
"""Return zero, pole, gain (z,p,k) representation from a numerator,
denominator representation of a linear filter.
Parameters
----------
b : ndarray
Numerator polynomial.
a : ndarray
Denominator polynomial.
Returns
-------
z : ndarray
Zeros... | 3d83d4053a89be19c3738650a11216d38845d6a6 | 7,826 |
def gpiod_line_is_free(line: gpiod_line) -> bool:
"""
@brief Check if the calling user has neither requested ownership of this
line nor configured any event notifications.
@param line: GPIO line object.
@return True if given line is free, false otherwise.
"""
return line.state == _L... | 939320d0737406789bbb81bc9c73023dff71fb51 | 7,827 |
import random
def train_step(optimizer, inputs, learning_rate_fn, dropout_rng=None):
"""Perform a single training step."""
weights = jnp.where(inputs > 0, 1, 0)
# We handle PRNG splitting inside the top pmap, rather
# than handling it outside in the training loop - doing the
# latter can add some stalls to... | 2dae63fcfb9fc5bc059b084bf748886d3d257c4c | 7,828 |
def doublet_line_polar_u(rcp,zcp,dmz_dz, bSelfInd=False):
"""
Velocity field induced by a semi-infinite doublet line (on the z axis) of intensity `dmz_dz`
Control points defined by polar coordinates `rcp` and `zcp`.
\int 1/(r^2 + (z-x)^2 )^(3/2) dx
\int 1/(r^2 + (z-x)^2 )^(5/2) dx
"""
i... | 9dcee49192273a6482b269120af01683a11916b6 | 7,829 |
def paginate(text: str):
"""Simple generator that paginates text."""
last = 0
pages = []
for curr in range(0, len(text)):
if curr % 1980 == 0:
pages.append(text[last:curr])
last = curr
appd_index = curr
if appd_index != len(text) - 1:
pages.append(... | f40b97e0f221b4c6afffcc4dd707daf48685d04a | 7,830 |
def get_batch_copy(vocab_size, batch_size, seq_len):
"""Generates random data for copying."""
batch = np.random.choice(
vocab_size - 1, size=[batch_size, seq_len // 2 - 1]) + 1
batch = np.concatenate([np.zeros([batch_size, 1], dtype=int), batch], axis=1)
batch = np.concatenate([batch] * 2, axis=1)
batc... | f1b6092393a0b8e7cb6c2a2ae191c29d28d2d89f | 7,831 |
import pandas
def buildCompareDFs(strTodayFileName):
"""read in and return today's CSV as DF, determine appropriate old CSV as DF, and the old file name for use later"""
# get today's file
dfTodaysCards = pandas.read_csv(
DATA_DIR_NAME + strTodayFileName, dtype={'Card Number': object})
dfToda... | 488afcd0704b9c73a83cab3bd898703d290ac557 | 7,832 |
def _vj_stat(v = None, j = None, freq_type = 'vj_occur_freq', ts = None):
"""
Return estimate of a single v-gene, j-gene, or vj-gene-pairings frequency
specified < v > and <j> argumens , given a tcrsamper instance < ts >
Parameters
----------
v : str
j : str
e.g.,
freq_type :... | 99228d17714c5ba403071ad0251f8642bc3148e6 | 7,833 |
def __cvx_eda(y, delta, tau0=2., tau1=0.7, delta_knot=10., alpha=8e-4, gamma=1e-2, solver=None,
options={'reltol': 1e-9, 'show_progress': False}):
"""
CVXEDA Convex optimization approach to electrodermal activity processing
This function implements the cvxEDA algorithm described in "cvxEDA: a
... | 5d4b333c7ab99a339d20adc379ea48792e2b43aa | 7,834 |
import torch
def pulsar_from_opencv_projection(
R: torch.Tensor,
tvec: torch.Tensor,
camera_matrix: torch.Tensor,
image_size: torch.Tensor,
znear: float = 0.1,
) -> torch.Tensor:
"""
Convert OpenCV style camera parameters to Pulsar style camera parameters.
Note:
* Pulsar does ... | 854349a4442e5e57554995439e62de74000c9b3d | 7,835 |
def identity(gender:str = None) -> dict:
""" Generates a pseudo-random identity.
Optional args
gender: 'm' for traditionally male, 'f' for traditionally female.
Returns a dict with the following keys:
name -> full name
given -> given name / first name
family -> family name ... | 1917b6723a5bfe2c0b7477dca18f450c8a0e07c3 | 7,836 |
def matthews_corrcoef(y_true, y_pred):
"""Returns matthew's correlation coefficient for binary classes
The Matthews correlation coefficient is used in machine learning as a
measure of the quality of binary (two-class) classifications. It takes
into account true and false positives and negatives and is ... | b4af31bac942a99fabb6f20c29ed59aa7b55e32d | 7,837 |
import os
def convert_image_link(image):
"""Convert an image link specification into a Markdown image link
Args:
image (Match): A Match object corresponding to an image link
Returns:
str: Markdown formatted link to the image
"""
image_name = str(image.group(1))
file_ext = ... | 7ef746cc9d062107b4d8f6fa79d544e75ee00e9b | 7,838 |
from typing import Dict
from typing import Any
import yaml
def yaml_dump(dict_to_dump: Dict[str, Any]) -> str:
"""Dump the dictionary as a YAML document."""
return yaml.safe_dump(dict_to_dump, default_flow_style=False) | 4635514ba8ff901656b8a4b5869a6ae101528fa8 | 7,839 |
def completeness(importance_matrix):
""""Compute completeness of the representation."""
per_factor = completeness_per_code(importance_matrix)
if importance_matrix.sum() == 0.:
importance_matrix = np.ones_like(importance_matrix)
factor_importance = importance_matrix.sum(axis=0) / importance_matrix.sum()
re... | 39407833b501e974f2ddb421ecad59055153260e | 7,840 |
def image_stat(image_id):
"""
Return the statistics ofd an image as a pd dataframe
:param image_id:
:return:
"""
counts, total_area, mean_area, std_area = {}, {}, {}, {}
img_area = get_image_area(image_id)
for cl in CLASSES:
polygon_list = get_polygon_list(image_id, cl)
... | a20c1d702f983c576ab506061ab19181b90c8684 | 7,841 |
def delete_original():
"""
Decorator that deletes the original
Discord message upon command execution.
:return: boolean
"""
async def predicate(ctx):
if ctx.invoked_with != "help": # Don't try to delete if help command
if isinstance(ctx.message.channel, discord.TextChannel... | 08f71c271b679fb6389754c21a896e11ae6f05c0 | 7,842 |
import os
def list_template_dirs():
"""List names of directories containnig parallel programming templates."""
dirs = []
for templates_dir in settings.TEMPLATE_DIRS:
for template_dir in os.listdir(templates_dir):
path = os.path.join(templates_dir,template_dir)
if os.path.i... | 2af89460be234e3c649b1a0c67db150062299f14 | 7,843 |
def get_H_OS():
"""屋根又は天井の温度差係数 (-)
Args:
Returns:
float: 屋根又は天井の温度差係数 (-)
"""
adjacent_type = '外気'
return get_H(adjacent_type) | cb3b68063d2c734b03d96b261e5cba23b79c3bc7 | 7,844 |
def forward_softmax(x):
"""
Compute softmax function for a single example.
The shape of the input is of size # num classes.
Important Note: You must be careful to avoid overflow for this function. Functions
like softmax have a tendency to overflow when very large numbers like e^10000 are computed.
... | 8c0f54294c2dc5b385466398726b67a3acd674b0 | 7,845 |
import numpy
def applySpectralClusters(kmeansObj, img, imgNullVal):
"""
Use the given KMeans object to predict spectral clusters on
a whole image array.
The kmeansObj is an instance of sklearn.cluster.KMeans,
as returned by fitSpectralClusters().
The img array is a numpy array of... | 2b2fb5616c20c4e5d9278bf8555c888bfab80cb8 | 7,846 |
from sys import path
def get_config_and_project_dir(config_file: str):
"""Guess config file name and project dir"""
if config_file is not None:
config_file = path.abspath(config_file)
project_dir = path.dirname(config_file)
else:
project_dir = find_project_dir()
config_file... | 2b3e7e219c97ef504e76468512a90926c351b949 | 7,847 |
def get_config() -> ConfigParser:
"""
Parse the config file.
:return: config
"""
cfg = ConfigParser()
cfg.read(CONFIG_PATH)
return cfg | 14f9ce4719bf665d62f1a2d06c980f4e85d2b8a5 | 7,848 |
from calendra.registry import registry
def iso_register(iso_code):
"""
Registers Calendar class as country or region in IsoRegistry.
Registered country must set class variables ``iso`` using this decorator.
>>> from calendra.core import Calendar
>>> from calendra.registry import registry
>>>... | 7fcb55a37f5af948ff6be8baf797d00328f241a8 | 7,849 |
def dict_check_defaults(dd, **defaults):
"""Check that a dictionary has some default values
Parameters
----------
dd: dict
Dictionary to check
**defs: dict
Dictionary of default values
Example
-------
.. ipython:: python
@suppress
from xoa.misc import d... | 8edc3fdb351f7ec2d4ec3b1e788e6aa5cc0f8787 | 7,850 |
import os
def construct_search_params():
"""Iterates through user-defined Entrez Search settings to assemble the search parameters.
Envars hold the most recent user-defined Entrez settings, such as rettype, retmax, database,
etc. These settings are iterated through, and their values are returned and appe... | 0c6c2fd566246d86cf9225ca2ba2404451b79d2c | 7,851 |
def get_invested_and_worth(account):
"""Gets the money invested and the actual worth of an account"""
data = query_indexa(f"accounts/{account}/performance")
invested = data["return"]["investment"]
worth = data["return"]["total_amount"]
return {"invested": round(invested, 2), "worth": round(worth,... | fc1542f54c8954622aff86d59d7d6fb82e63832b | 7,852 |
def make_album(singer, name, number = ''):
"""Return singers' names and album"""
album = {'singer': singer, 'name': name}
if number:
album['number'] = number
return album | 1f1bfaaeb501be0aa6fefd358177922246488b31 | 7,853 |
from typing import Dict
from typing import List
from typing import Generator
def fit_ctmp_meas_mitigator(cal_data: Dict[int, Dict[int, int]],
num_qubits: int,
generators: List[Generator] = None) -> CTMPExpvalMeasMitigator:
"""Return FullMeasureErrorMitigator... | 2dab6ca0da19acb174b6d0e8b96c7833d5de74e8 | 7,854 |
def discounted_item(data):
"""
DOCSTRING: Classifies item purchases as 'Promoted' or 'Not Promoted' based on 'Item Discount' column. Also 'COD Collectibles' column gets restructured by eliminating undesired default values, like 'Online'.
INPUT:
> data : Only accepts Pandas DataFrame or TextParser, that ... | 178c5e7d8e9c2e3bdd91d4606ea52c34c7cf099c | 7,855 |
def NamespacedKubernetesSyncer(namespace, use_rsync=False):
"""Wrapper to return a ``KubernetesSyncer`` for a Kubernetes namespace.
Args:
namespace (str): Kubernetes namespace.
use_rsync (bool): Use ``rsync`` if True or ``kubectl cp``
if False. If True, ``rsync`` will need to be
... | 9da5a049a12a248623040c1ace79c2ebedd3400c | 7,856 |
def _cons8_88(m8, L88, d_gap, k, Cp, h_gap):
"""dz constrant for edge gap sc touching 2 edge gap sc"""
term1 = 2 * h_gap * L88 / m8 / Cp # conv to inner/outer ducts
term2 = 2 * k * d_gap / m8 / Cp / L88 # cond to adj bypass edge
return 1 / (term1 + term2) | 7c48c4999ce2dd3dbdec799edd7ad441a6f66e7b | 7,857 |
import hashlib
def cache_key(path):
"""Return cache key for `path`."""
return 'folder-{}'.format(hashlib.md5(path.encode('utf-8')).hexdigest()) | 6b9afe1267e0cc0c7168bf3b0d5c7536e2b3c768 | 7,858 |
def ref_731(n):
"""Reference number calculator. Returns reference number
calculated using 7-3-1 algorithm used in Estonian banks.
:param string n: base number (client id, etc)
:rtype: string
"""
return "%s%d" % (n,((10 - (sum(map(\
lambda l: int(n[-l])*(7,3,1)[(l-1) % 3], \
... | b1958511947d9f369db2547cde15222603dc0773 | 7,859 |
import traceback
async def exception_as_response(e: Exception):
"""
Wraps an exception into a JSON Response.
"""
data = {
"message": str(e),
"traceback": "".join(traceback.TracebackException.from_exception(e).format())
}
return web.json_response(data, status=500) | 60f226cb7cd4c3aba3026d44d28e774928e6bbf7 | 7,860 |
def canvas_merge_union(layers, full=True, blend=canvas_compose_over):
"""Blend multiple `layers` into single large enough image"""
if not layers:
raise ValueError("can not blend zero layers")
elif len(layers) == 1:
return layers[0]
min_x, min_y, max_x, max_y = None, None, None, None
... | ffbb3b78e908ed1e131a1f0827f2d3097415edc9 | 7,861 |
import json
def exception_response(request, code=400, exception=None):
"""
Create a response for an exception
:param request: request instance
:param code: exception code
:param exception: exception instance
:return: exception formatted response
"""
code = code if code in [400, 403, 40... | 1ef145ea4b07557fbc31a9d5c52621e79c2b99ff | 7,862 |
import os
def get_jira_issues(jira, exclude_stories, epics_only, all_status, filename,
user):
"""
Query Jira and then creates a status update file (either temporary or named)
containing all information found from the JQL query.
"""
issue_types = ["Epic"]
if not epics_only:
... | c495326f0790f3bec8c95a2fae1c645409100d27 | 7,863 |
def entropy(series):
"""Normalized Shannon Index"""
# a series in which all the entries are equal should result in normalized entropy of 1.0
# eliminate 0s
series1 = series[series!=0]
# if len(series) < 2 (i.e., 0 or 1) then return 0
if len(series1) > 1:
# calculate the maximu... | 30f8f3cc6fed73d8cfa0b3705008891a60af028a | 7,864 |
def spatially_whiten(X:np.ndarray, *args, **kwargs):
"""spatially whiten the nd-array X
Args:
X (np.ndarray): the data to be whitened, with channels/space in the *last* axis
Returns:
X (np.ndarray): the whitened X
W (np.ndarray): the whitening matrix used to whiten X
"""
... | a0c9ae88e8f451378503754e4768ee554e50ed3e | 7,865 |
from pathlib import Path
import yaml
def get_settings(basename: str="settings.yml", path: Path=PROJECT_ROOT / "conf") -> dict:
"""
Loads settings file
Args:
basename (str, optional): Basename of settings file. Defaults to "settings.yml".
path (Path, optional): Path of seetings file. Defau... | 2317f9fbd125a16a7c34086d35b02973f1be5d8f | 7,866 |
import torch
def quaternion2rotationPT( q ):
""" Convert unit quaternion to rotation matrix
Args:
q(torch.tensor): unit quaternion (N,4)
Returns:
torch.tensor: rotation matrix (N,3,3)
"""
r11 = (q[:,0]**2+q[:,1]**2-q[:,2]**2-q[:,3]**2).unsqueeze(0).T
r12 = (2.0*(q[:,1]*q[:... | feeed764ee179b31674790f9d2afc7b606a02aef | 7,867 |
def _expand_and_tile(tensor, multiple, dim=0, name=None):
"""Slice `tensor` shape in 2, then tile along the sliced dimension.
A new dimension is inserted in shape of `tensor` before `dim`, then values are
tiled `multiple` times along the new dimension.
Args:
tensor: Input `Tensor` or `SparseTensor`.
m... | aa9840fdaee56fee19937c8f632c72628fbd3995 | 7,868 |
import random
def eval_model(opt, print_parser=None):
"""Evaluates a model.
:param opt: tells the evaluation function how to run
:param bool print_parser: if provided, prints the options that are set within the
model after loading the model
:return: the final result of calling report()
""... | 153dbead7ebd37ba2f61d745bc499f9eddfa0d03 | 7,869 |
def login(request):
"""
Login with Dummy Test Account.
"""
if 'user' in request.environ['beaker.session']:
return app.redirect('index')
users.store_to_session(request, users.create())
return app.redirect('index') | 0f2d06e7a6ac2fed0daee73e4c2e216012452e08 | 7,870 |
def safe_plus(x,y):
"""
Handle "x + y" where x and y could be some combination of ints and strs.
"""
# Handle Excel Cell objects. Grrr.
if excel.is_cell_dict(x):
x = x["value"]
if excel.is_cell_dict(y):
y = y["value"]
# Handle NULLs.
if (x == "NULL"):
x = 0
... | e3f5e43ee3e083669d0b744c7fb46a4ae62b4eec | 7,871 |
import types
def full_like(a, fill_value, dtype=types.float32, split=None, device=None, comm=None, order="C"):
"""
Return a full array with the same shape and type as a given array.
Parameters
----------
a : object
The shape and data-type of 'a' define these same attributes of the returne... | 4a615e493ae20d925eeda7c0bd6ca9508c338bc2 | 7,872 |
import glob
def gather_pulled_downloads(input_dir, output_dir):
"""
Gather MPEG stream files from input_dir into a single MP4 file in output_dir
"""
dash_globstr = f"{input_dir.absolute() / '*.dash'}"
dash_glob = glob(dash_globstr)
if len(dash_glob) < 1:
raise ValueError(f"No dash file... | a1b9c334ab717292db006666bdcdd0749b2620d7 | 7,873 |
import functools
def Parallelize(ListIn, f, procs = -1, **kwargs):
"""This function packages the "starmap" function in multiprocessing, to allow multiple iterable inputs for the parallelized function.
Parameters
----------
ListIn: list
each item in the list is a tuple of non-keywor... | 84fc1509c96c7bf765246e46983f2fa01745f4b2 | 7,874 |
def method_not_found(e):
""" Custom response for methods not allowed for the requested URLs :param e: Exception :return: """
return response('failed', 'The method is not allowed for the requested URL', 405) | 18a48d53d602c1a90017e3f00adc75c4c33479b5 | 7,875 |
def get_total_trainsets(df_anual_data, segments):
"""
# Fill the training_sets dict
:param df_anual_data:
:return:
"""
rows_per_day = int(((60 / 15) * 24))
training_sets = {'ID_SEGMENT': [], 'MES': [], 'COD_LABORALIDAD': [], 'TRAINING_SET': []}
for seg_id in segments: # 1) Particionar ... | 968c3af1fdba5eb759eb93618ed48e3ca3ce5223 | 7,876 |
def uni2diff(u):
"""Convert speed and angular rate to wheel speeds."""
v = u[0]
omega = u[1]
v_L = v - ELL / 2 * omega
v_R = v + ELL / 2 * omega
return np.array([v_L, v_R]) | 83b743758aa7a549eda9067843a03eb57efde523 | 7,877 |
import re
def extract_service_and_module(repo_url):
"""Extract service and module from repository url.
:param str repo_url: repository url
:return (service, module)
:rtype (str, str)
"""
m = re.match(r'.+[/@]([^\.]+\.[^\.]+)[:/]([^/]+/[^/]+)\.git/?$', repo_url)
if not m:
m = re.m... | eafe6cf39fc2fe4153830c491147633fb07f95dd | 7,878 |
import numpy
def triangular(left, mode, right, size=None):
"""Triangular distribution.
Draw samples from the triangular distribution over the interval
[left, right].
For full documentation refer to :obj:`numpy.random.triangular`.
Limitations
-----------
Parameter ``left``, ``mode`` and ... | c92d1461fe9052648e0b141e8b962f350e1d23b4 | 7,879 |
def format_hexa(value: str) -> ColorBytes:
"""
Examples:
"bda" => (187, 221, 170, 255)
"4fcd" => (68, 255, 204, 221)
"60B0C4" => (96, 176, 196, 255)
"2BEA40D0" => (43, 234, 64, 208)
"""
if len(value) in {3, 4}:
expanded_color = ''.join(s * 2 for s in value)
else:
... | 4865e1498ed87c933160e5666adcc41b45162fdd | 7,880 |
def normalize_community_features(features):
"""
This performs TF-IDF-like normalization of community embedding features.
Introduced in: Tang, L., Wang, X., Liu, H., & Wang, L. (2010, July).
A multi-resolution approach to learning with overlapping communities.
In Procee... | 9f5018ad3e20810d2bb66443bac4c2f7f6359d0f | 7,881 |
def __extend_prefixed(pu):
"""
:param pu:
:return:
"""
parts = pu.split(':')
if len(parts) == 1:
parts = ('', parts[0])
try:
return URIRef(_prefixes[parts[0]] + parts[1])
except KeyError:
return BNode(pu) | d6e5c25c94e8b3252d8b0925e8d37747caceebdd | 7,882 |
def angle(u: Vec, v: Vec) -> float:
"""
Returns the cosine (angle) between two vectors u and v
:param u: (Vec) vector u
:param v: (Vec) vector v
:return: The scaled dot product, cosine of u and v's angle
"""
if u.is_zero or v.is_zero:
raise ValueError("Angle with lower dimensional 0 ... | 6c79390af1ed38fc1a99006165684234dabb0b4a | 7,883 |
def find_most_similar(top_k, probs, cache_dict, num=10):
"""返回最相似的num张照片的文件名,如果找到相似的,
则返回一个包括匹配元组的列表,否则返回一个空列表
top_k : 包含最佳分类的索引的列表
probs : 包含最佳分类索引对应的概率
cache_dict: 缓存中的索引和概率
num : 返回最近匹配的数目
"""
similar = []
for filename in cache_dict:
score = 0
count =... | 471083e1ed2b0fadb98cafad64d314ba779aa9e6 | 7,884 |
def load(url_or_handle, allow_unsafe_formats=False, cache=None, **kwargs):
"""Load a file.
File format is inferred from url. File retrieval strategy is inferred from
URL. Returned object type is inferred from url extension.
Args:
url_or_handle: a (reachable) URL, or an already open file handle
... | 89fec9684dda24b6b16b63e6b478bc4f67d00f07 | 7,885 |
import time
import torch
def evaluate_full_batch(model, minibatch, mode='val'):
"""
Full batch evaluation: for validation and test sets only.
When calculating the F1 score, we will mask the relevant root nodes.
"""
time_s = time.time()
loss, preds, labels = model.eval_step(*minibatch.one_batch... | b1d183118b304edf6f076caefa2b1160316ad92c | 7,886 |
from operator import mul
from operator import inv
def berlekamp_massey(s):
"""Given a sequence of LFSR outputs, find the coefficients of the LFSR."""
C, B, L, m, b = [1], [1], 0, 1, 1
for n in range(len(s)):
d = s[n]
for i in range(1, L + 1):
d ^= mul(C[i], s[n - i])
if... | 351f52dce7e4a95b986cc169f380347f317f851a | 7,887 |
import json
import sys
def vocab_from_file(vocabfile):
"""
Generates vocabulary from a vocabulary file in JSON
Outputs vocabulary and inverted vocabulary
"""
with smart_open(vocabfile, 'r') as f:
inv_vocab = json.loads(f.read())
vocabulary = {}
for no, word in enumerate(inv_vocab)... | a75fab1e94f5091aa691ad2ab188f0ada406f6ea | 7,888 |
from typing import Optional
def sample(image: type_alias.TensorLike,
warp: type_alias.TensorLike,
resampling_type: ResamplingType = ResamplingType.BILINEAR,
border_type: BorderType = BorderType.ZERO,
pixel_type: PixelType = PixelType.HALF_INTEGER,
name: Optional[... | c9a202a6415d13bddac38cfa75e280ad45f1bda6 | 7,889 |
def normalize_parameter(kv):
"""
Translate a parameter into standard form.
"""
(k, v) = kv
if k[0] == 'requiressl' and v in ('1', True):
k[0] = 'sslmode'
v = 'require'
elif k[0] == 'dbname':
k[0] = 'database'
elif k[0] == 'sslmode':
v = v.lower()
return (tuple(k),v) | 933ea71f452a16c1d4ae2630d6b58a92da1cbec0 | 7,890 |
def pulse_broadening(DM, f_ctr):
"""
pulse_broadening(DM, f_ctr):
Return the approximate pulse broadening (tau) in ms due to scattering
based on the rough relation in Cordes' 'Pulsar Observations I' paper.
'f_ctr' should be in MHz. The approximate error is 0.65 in log(tau).
"""
... | 48830e02774247e551605e5e8ad693ece68634ad | 7,891 |
from amset.tools.wavefunction import wave
from pathlib import Path
from click.testing import CliRunner
def generate_wavefunction_coefficients(dir_name: str):
"""
Generate wavefunction.h5 file using amset.
Parameters
----------
dir_name : str
Directory containing WAVECAR and vasprun.xml fi... | 0119d18436373753d9e2a1202f185c983fa83963 | 7,892 |
def logged_in_student(browser, override_allowed_hosts, base_test_data):
"""
Fixture for a logged-in student user
Returns:
User: User object
"""
return LoginPage(browser).log_in_via_admin(base_test_data.student_user, DEFAULT_PASSWORD) | 4513e8c8356cd8fbd643e9018e1019c5ec403bcd | 7,893 |
import numpy as np
import tqdm
def test_model(data_set=None, langider=None, lang_to_idx=None, ) -> np.ndarray:
"""
Tests a given langid.py model on the given data set.
:param data_set: data set to test on
:param langider: model to test
:param lang_to_idx: mapping of languages to ids
"""
la... | 2b955b637a289d0596c0584ac0761d8014e27e86 | 7,894 |
from bs4 import BeautifulSoup
def search(querry, lim=5):
"""Search the querry in youtube and return lim number of results.
Querry is the keyword, i:e name of the song
lim is the number of songs that will be added to video array and returned
"""
# Replace all the spaces with +
querry = querry.... | 92771e6aaa88ea65034981ff0c0c3b203addacec | 7,895 |
def calculate_center_of_mass(symbols, coordinates):
"""Calculate the center of mass of a molecule.
The center of mass is weighted by each atom's weight.
Parameters
----------
symbols : list
A list of elements for the molecule
coordinates : np.ndarray
The coordinates of ... | 34a32e86c42875db59ad9d1bd1a6801d6fd51eb1 | 7,896 |
def __iadd__(self, other):
"""Pythonic use of concat
Example:
xs += ys
Returns self.concat(self, other)"""
return self.concat(self, other) | 713980aed9713c2882a19ae9837315a431611bbc | 7,897 |
def remove_stopwords(texts, stop_words):
"""
Define functions for stopwords
:param texts: Processed texts from main module
:return: Texts that already removed a stopwords
"""
return [[word for word in simple_preprocess(str(doc)) if word not in stop_words] for doc in texts] | 9e2f4bcf87886a35c3877de34d6746942af19065 | 7,898 |
import json
def dumps(obj):
"""Output json with formatting edits + object handling."""
return json.dumps(obj, indent=4, sort_keys=True,
cls=CustomEncoder) | a9ad97c589a8f610d3186723566420604d99f4de | 7,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.