content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import math
def triangleSum(n):
"""
Finding the sum of 1+2+...+n
:param n: the last interger to be added
:return: the sum
"""
n = math.floor(n)
if n > 1 :
return n+triangleSum(n-1)
return 1 | 4bffb8d8d758730b161a572fad447e5420c30490 | 51,200 |
def replace_database_in_url(db_url: str, db_name: str) -> str:
"""
replaces the database portion of a database connection URL with db_name
@param db_name database name to replace with
"""
db_url_parsed = urlparse(db_url)
db_url_parsed = db_url_parsed._replace(path=f"/{db_name}")
return db... | de8d2303b84e9172fc28f02d1650afd5f4f8148e | 51,201 |
import sys
def main( argv ):
"""
Parses the supplied command line arguments and renders IWP data as on-disk
images for labeling via an external tool.
See print_usage() for details on execution and command line arguments.
Takes 1 argument:
argv - List of command line arguments and options,... | 80fbbfcca5c33a2d95ac5f8b539e31a576b12413 | 51,202 |
import re
def detect_arxiv(txt):
"""
Extract an arXiv ID from text data
"""
regex = r'arXiv:[0-9]{4,4}\.[0-9]{5,5}(v[0-9]+)?'
m = re.search(regex, txt)
if m is not None:
return m.group(0)
else:
return None | a855497b6eb1f027085a301096735e860e76fbe7 | 51,203 |
from operator import and_
async def get_contributor_by_username(
*,
username: str,
session: Session = Depends(dal.get_session)
) -> contributor_schemas.Details:
""" Get contributor record from DB """
conditions = and_(
User.username == username,
)
db_contributor = contributor_ops... | b220cac092f3daf384ffb574a8cdd8142ecfef90 | 51,204 |
def display(image, title=' ', resolution=(960, 540)):
"""Uses cv2 to display an image then wait for a button press
pts is either None or an integer specifying the number of point
and click events you'd like to capture"""
cv2.namedWindow(title, cv2.WINDOW_KEEPRATIO)
cv2.resizeWindow(title, *... | a6ab9b462b1d253a99c303f9bfab20250a3a04a4 | 51,205 |
from pathlib import Path
import sys
import os
def get_current_dir_path():
"""获取当前执行文件的目录路径"""
return Path(sys.argv[0]).parent if is_exe() else "{}".format(os.getcwd()) | 4c8877321458e687ba6726e7cfe543f1b9ba211c | 51,206 |
def get_narrative_cell_counts(wsadmin, narrative_ref):
"""
Gets the number of App Cells and Code Cells in the narrative
See documentation for WS administer here
https://github.com/kbase/workspace_deluxe/blob/02217e4d63da8442d9eed6611aaa790f173de58e/docsource/administrationinterface.rst
"""
app_c... | d00bd855459fbd9ea5a7824ae85462c9df2e2a13 | 51,207 |
def calculate_emotions(labeled_emotions, labeled_intensities):
"""
Calculate the emotions that are present in each sentence taking into consideration the values given
by the different annotators.
Args:
labeled_emotions (np.ndarray): Emotions labeled as list of string numbers.
labeled_int... | 0e872ee65af6a5a48fc6a6afb7e71314b16d603d | 51,208 |
from typing import Tuple
def xiang_dsp_kernel(X: ndarray, y: ndarray) -> Tuple[ndarray, ndarray, ndarray, ndarray]:
"""dsp algorihtm based on paper[1].
Parameters
----------
X : ndarray
EEG data assuming removing mean, shape (n_trials, n_channels, n_samples)
y : ndarray
labels, sh... | 35b7a449cb1493645bd6e0ab2137bdcbe13d62c3 | 51,209 |
from typing import List
def get_free_remote_ports(count: int, node: Node) -> List[int]:
"""Returns several free remote ports.
See :func:`.get_free_remote_port`.
:param count: Free port count.
:param node: Node to find a port on.
"""
result = {get_free_remote_port(node=node) fo... | 727766eb04aa1c709ded7a003c7e2afc5a5e0369 | 51,210 |
def precipitation():
"""Return dictionary using date as the key and prcp as the value."""
# Create our session (link) from Python to the database
session = Session(engine)
# Query all prcp and dates
results = session.query(Measurement.prcp, Measurement.date).all()
# Close out our link
sessio... | c1d6577e8d783a8744636a85a36dd7d55e0d1554 | 51,211 |
def canonical_source(spec, filter_multimethods=True, source=None):
"""Get canonical source for a spec's package.py by unparsing its AST.
Arguments:
filter_multimethods (bool): By default, filter multimethods out of the
AST if they are known statically to be unused. Supply False to disable.
... | 557e24ae26ec54b72825bd80957647b6647f872b | 51,212 |
def pointsEqual(a, b):
"""
checks if 2 [x, y] points are equal
"""
for i in range(0, len(a)):
if a[i] != b[i]:
return False
return True | 7341c1aa417ef8979662c1ef3e67cad1e902422e | 51,213 |
from operator import add
def move(directions):
"""Meh
>>> move(parse_directions(EXAMPLE))
[100 10] [10 1]
[100 10] [10 4]
[170 38] [10 4]
[170 38] [ 4 -10]
[214 -72] [ 4 -10]
286
"""
wpt = np.array((10, 1), dtype=int)
pos = np.array((0, 0), dtype=int)
for where... | f089443ad3848fdc622af7e90ed396e85118a6ee | 51,214 |
def _choose_convolve(z_i, ds):
"""Choose between _dense_convolve and _sparse_convolve with a heuristic
on the sparsity of z_i, and perform the convolution.
z_i : array, shape(n_atoms, n_times_valid)
Activations
ds : array, shape(n_atoms, n_times_atom)
Dictionary
"""
assert z_i.s... | efced323dfbaca84b3b1a9500f30f3752e5e943f | 51,215 |
from pathlib import Path
from typing import Sequence
from typing import Optional
def find_and_test_all(root_dir: Path, file_templates: Sequence,
timeout: Optional[float] = None) -> bool:
"""Run standard sanity tests on all files.
Args:
root_dir: Find all files that satisfy the t... | 6a85ca729b95fedb22fd24f2f9b2cac0b5fd4441 | 51,216 |
import requests
def healthy2_check_in(token, custom_id, post_dict):
"""
第二类健康打卡
:param token: 用户令牌
:param custom_id: 健康打卡id
:param post_dict: 健康打卡数据
:return:
"""
if not post_dict.get("whereabouts"):
errmsg = f"完美校园第二类健康打卡方式错误,请选第一类健康打卡"
log.warning(errmsg)
retur... | ad4b78ac1d433ad244fbde569407f3c3a95ce27a | 51,217 |
from dtale_desktop import app
def app(monkeypatch, tmpdir):
"""
Sets environment variables before importing the app.
"""
monkeypatch.setenv("DTALEDESKTOP_ROOT_DIR", tmpdir.strpath)
return app | a3d7d1074e399360fa902edac2f3e9dccb7f2ea1 | 51,218 |
async def remove_subscriber(request):
"""Handler to remove subscriber."""
subscribers = request.app['subscribers']
subscriber_id = (request.match_info['subscriber_id'])
_logger.debug('API: DELETE /subscribers/{}'.format(subscriber_id))
# Check if subscriber is already present
if subscribers.is... | e235e8feb792cf142ed9c0461d3568f6d009985a | 51,219 |
def allowed_file(filename):
"""
Return true if a file is allowed.
Args:
filename: (str): write your description
"""
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS | 4d576787e9761b08a89baa1ca42939bc0f1bd29b | 51,220 |
def refine(window_priors, window_info, null_variance=0.42 ** 2, cs_val=0.95,
cs_merge_buffer=200000, cov_df=None, jac_cutoff=0.8):
"""
Refines a set of windows given their prior probability and effect size estimates
Inputs:
window_priors : dict of windows with prior probabilities
... | 64708f1e450de974f3fb5c023cbac51aa683af2d | 51,221 |
def signup(request, template='signup.html', login_url=''):
"""
Processes original signup to create a user on the site
once validated successfully logs the user in and redirects to default user page
"""
response_dict = {}
response_dict['error_message'] = ''
response_dict['debug'] = 'yes'
... | 15d7cf0131a474eb2ccbb903728667423ecb7ae6 | 51,222 |
def get_google_client(credentials_file):
"""
Return this module's Google API client, creating a connection is one
does not already exist.
"""
global _client
if not _client:
# Connecting to google's API
logger.info("Connecting to Google API using credentials file {}".format(creden... | 224220752e64c32a78d72cfe38acb3e23d52221a | 51,223 |
def cut_sentences(text):
"""
将文本切成句子
:param text: 待切分文本
:return: 句子列表
"""
text = text.translate(str.maketrans('!?!?\r\n', '。。。。 '))
return [sen for sen in text.split('。') if len(sen.strip()) > 1] | 06e8b503c2c6e3ea73901bb19f2b4fba2f443e19 | 51,224 |
def _setup_conduction_constants(rr, ht_consts):
"""Set up numpy arrays to accelerate conduction calculation
Notes
-----
Creates dictionary attribute "_cond" which has keys "adj"
and "const". Usage is as follows:
dT_conduction = (self._cond['const']
* (self.temp['coolant_in... | 2876bd7e877f0b799f24508858802134c52cd7dd | 51,225 |
def full_justify(*args, **kwargs):
"""
Usage: $full_justify(<text>)
Returns <text> filling up screen width by adding extra space.
"""
if args:
return base_justify(args[0], align='f')
return "" | c5766245eca848e135a7987422e46d10750b0d24 | 51,226 |
import os
def fetch_ranks_from_azureml():
"""Look up distributed arguments from Azure ML environment variables.
Assumes OpenMPI image.
Note:
Sets up NCCL environment variables used by Azure ML:
- NCCL_SOCKET_IFNAME
- NCCL_IB_DISABLE
"""
ranks = DistributedTrainingArgumen... | c3109134594051643f0fd15639a07bda26a25924 | 51,227 |
def translation(translation):
""" Construct a homogeneous 2D translation matrix.
# Arguments
translation: the translation 2D vector
# Returns
the translation matrix as 3 by 3 numpy array
"""
return np.array([
[1, 0, translation[0]],
[0, 1, translation[1]],
[0,... | e397417c1d8b91c280386f005250be06b0337845 | 51,228 |
import itertools
def get_pairs(self, data, linked_clusters):
"""
Return pairs of linked clusters and establish which can be merged and which
cannot
"""
_linked_clusters = [_cluster.antecessor for _cluster in linked_clusters]
pairs = [pair for pair in itertools.combinations(_linked_clusters, ... | 1de2f8db3bd05665b05849fcbf09794f7fe843d9 | 51,229 |
import glob
def list_files(directory, reverse_sort=False, smart_sort=None, relative=False,
extension=None):
"""
Returns all the files from a directory.
Can set the filetype using extension.
Parameters
----------
directory : str
Filepath pointing to the dir... | 6dfc966eb58438be779d06d2220c46d9482d2718 | 51,230 |
def SubjectArgs(*args, **kwargs):
"""
Decorator that overrides the default arguments to the subject
initialiser.
:param args: The positional arguments to the subject initialiser.
:param kwargs: The keyword arguments to the subject initialiser.
"""
def applicator(method):
... | 66a972775d45d5668b4f2af49dc3a4b05aa17a25 | 51,231 |
def convert_words_to_chars(tokens: list) -> list:
"""
:param tokens:
:return:
"""
return list(set(chain.from_iterable(tokens))) | 1712f186aeaecc9f25bd1afcce4b078deea81aec | 51,232 |
def handler_supports_service(handler, service=None):
""" Convenience method to check whether or not a handler supports a service.
"""
if isinstance(handler.service, basestring):
return handler.service.upper() == service
else:
return service in handler.service | 5b256aae85b51ec3e676cc9f65d79a426e141729 | 51,233 |
from functools import reduce
def solution(input_str):
""" Solution to the problem """
inputstr = str(input_str)
rotated = inputstr+inputstr[0]
result = reduce(reducer, zip(rotated, rotated[1:]), 0)
return result | 9a4d2f3de42c804b610c510499698209337faf02 | 51,234 |
import os
def create_nerf(args):
"""Instantiate NeRF's MLP model."""
embed_fn, input_ch = get_embedder(args.multires, args.i_embed)
input_ch_views = 0
embeddirs_fn = None
if args.use_viewdirs:
embeddirs_fn, input_ch_views = get_embedder(
args.multires_views, args.i_embed)
... | 0e05651ab552c666259553a7c89ba15718a0695f | 51,235 |
def get_persona_page(persona):
"""Obtains the html of the page for `peronsa`."""
# using firefox-geckodriver
driver = webdriver.Firefox()
# Persona 5 Royal Fusion Calculator website
driver.get(
"https://chinhodado.github.io/persona5_calculator/indexRoyal.html#/list")
searchbox = driver.f... | 1e9f702160517c56c44d958b89cef883fca7a909 | 51,236 |
def parse_signature_file(sig_file):
"""
Parses signatures from a file of signatures
:param sig_file: file-like object to pares
:return: list of signatures
"""
res = []
part_sig = ""
for signature in sig_file:
signature = part_sig + signature
part_sig = ""
if not s... | a41ed0bb65c67573f444da37c83018dea80a2a87 | 51,237 |
import functools
def single_format(func):
"""Manage format of dhcp response
"""
@functools.wraps(func)
def formatter(*args, **kwargs):
iface = args[0]
ans = func(*args, **kwargs)
#scapy stores all sequence of requests
#so ans[0][1] would be response to first request
... | 39ee3a135d0cecb87625be57a9c9bce0a95badc0 | 51,238 |
def to_literal(typ, always_tuple=False):
"""Convert a typestruct item to a simplified form for ease of use."""
def expand(params):
return (to_literal(x) for x in params)
def union(params):
ret = tuple(sorted(expand(params), key=str))
if len(ret) == 1 and not always_tuple:
ret, = ret # pylint:... | a628676073a09042689f64ab1aa4d12a2a87c463 | 51,239 |
def powmod(a, b, m):
""" Returns the power a**b % m """
# a^(2b) = (a^b)^2
# a^(2b+1) = a * (a^b)^2
if b==0:
return 1
return ((a if b%2==1 else 1) * powmod(a, b//2, m)**2) % m | 33b4cadc1d23423f32e147718e3f08b04bd2fd17 | 51,240 |
def test_module(client: Client) -> str:
"""
If a client was made then an accesses token was successfully reached,
therefore the username and password are valid and a connection was made
additionally, checks if not using all the optional quota
:param client: the client object with an access token
... | 977f6d2ba3e37ca428c90b63666b509ba92f1447 | 51,241 |
import numpy as np
def str_to_array(s):
"""
Simplistic converter of strings from repr to float NumPy arrays.
If the repr representation has ellipsis in it, then this will fail.
Parameters
----------
s : str
The repr version of a NumPy array.
Examples
--------
>>> s = "ar... | 858491f8c7279630951b1244a3ea630d932eb7c6 | 51,242 |
def check_cores(func):
"""
Checks how many cores the search has been configured to
use and then returns None instead of calling the pool
creation function in the case that only one core has
been set.
Parameters
----------
func
A function that creates a pool
Returns
----... | 5ecba37910e024cbf213adb04d2ed4fd7f5479c0 | 51,243 |
def get_potential_versions(servicename, **_):
"""
List the different versions of a service stored in the system
Variables:
servicename => Name of the service to get the versions
Arguments:
None
Data Block:
None
Result example:
['3.1.0', '3.2.0', '3.3.0', '4.0.0', ...] ... | b972908777bb07d40c4a25da34e05405c1c6f72b | 51,244 |
import functools
def generate_decorator(exception):
"""Ddecorator generator"""
def expected_error(test):
@functools.wraps(test)
def inner(*args, **kwargs):
try:
test(*args, **kwargs)
except exception:
assert True
else:
... | 7089aabfb4ad9ce51b08ec43ada1c27d6fe529f0 | 51,245 |
def app_env():
"""
Create a dict of environment variables.
Mirrors the testing environment for use in subprocesses.
"""
return {
'DB_HOST': TEST_DATABASE_CONFIG.host,
'DB_PORT': str(TEST_DATABASE_CONFIG.port),
'DB_NAME': TEST_DATABASE_CONFIG.name,
'DB_USER': TEST_DAT... | ebc4c3e000a916c5506655f96047dd4c53714853 | 51,246 |
def determine_key_type(bucket, key, profile):
"""Return values : 'File', 'Folder' or 'Does not exist'"""
if profile:
s3 = boto3.session(profile_name=profile).client('s3')
else:
s3 = boto3.client('s3')
if not key:
raise Exception("Cannot determine key type - no key is specified")
... | a3c2f70da06e1cb1757454b8e7b8cdb9a1ffdc00 | 51,247 |
def correct_brenda_dtypes(r: pd.DataFrame):
"""Make sure the columns have the right dtypes.
:param r: dataframe of reports
"""
df_out = r.copy()
float_cols = ["ph", "mols", "temperature", "km", "kcat"]
for col in float_cols:
if col in r.columns:
df_out[col] = r[col].astype(f... | f5c083e3b4422df58dea5b4c6e797d2d04d2c0ab | 51,248 |
def vmtkmarchingcubes(image, level=0.0):
"""Generate an isosurface of given level from a 3D image.
Args:
image: vtkImageData object.
level: Graylevel at which to generate the isosurface.
Returns:
Surface mesh of the isosurface.
"""
marcher = vmtkscripts.vmtkMarchingCubes()... | 32182ff8cee665008ce84c4a8c18b0dd7840f370 | 51,249 |
def _update_dict(d, **kwargs):
"""little helper to modify and return a dict in one line"""
d.update(kwargs)
return d | 0a28c5f82d439ceb65aa3afc39d30a29b589004e | 51,250 |
def svg_icon(loader, name, css_class=""):
"""
Return inline SVG markup for an icon.
This is a helper for generating inline SVGs for rendering icons in HTML
that can be customized via CSS.
See https://github.com/blog/2112-delivering-octicons-with-svg
To color an icon dynamically (eg. on hover),... | 1cddcecc954c6d8956c7e029bd4a99c86a33d98b | 51,251 |
import requests
def _check_task(taskid):
"""Check Spinnaker Task status.
Args:
taskid (str): Existing Spinnaker Task ID.
Returns:
str: Task status.
"""
try:
taskurl = taskid.get('ref', '0000')
except AttributeError:
taskurl = taskid
taskid = taskurl.spli... | 1bc7e2e7d8d209083d15bb4d070c6fcab4553a2e | 51,252 |
def right_stop(G, adorn=True):
"""
Compute the (adorned) right stop of G.
Parameters
----------
G : Game
The Game of interest.
adorn : bool
Whether to adorn the stop or not. Defaults to True.
Returns
-------
RS : Game
The right stop of G.
initiative : st... | 1c1c48cfacd1b86511b38fb91694cc892a9dbae4 | 51,253 |
def value_and_multigrad(fun, argnums=[0]):
"""Returns a function that returns both value and gradients wrt multiple
arguments simultaneously."""
def combined_arg_fun(multi_arg, *args, **kwargs):
extra_args_list = list(args)
for argnum_ix, arg_ix in enumerate(argnums):
extra_args_... | 5d55a547c6309d2db3324ebd05fe19f1c9d6c1f0 | 51,254 |
def deploy_disk_image(address, port, iqn, lun,
image_path, node_uuid, configdrive=None,
conv_flags=None):
"""All-in-one function to deploy a whole disk image to a node.
:param address: The iSCSI IP address.
:param port: The iSCSI port number.
:param iqn: The ... | 0eb796b5089597c916393bbbaf6f314460a8a856 | 51,255 |
from typing import Union
from pathlib import Path
from typing import Dict
from typing import Tuple
def read_tracking_data_txt(
filepath_txt: Union[str, Path],
links: Dict[str, Dict[int, int]] = None,
) -> Tuple[XY, XY, XY, XY, XY, XY]:
"""Parses a StatsPerform .txt file and extracts position data.
I... | 8ba9f17374eea860fa434e170e7d1ca6b6b22f9a | 51,256 |
from typing import Optional
from typing import Union
from typing import List
from typing import Dict
def _estimate_segments(df: pd.DataFrame, target_field: str = None, max_segments: int = 30) -> Optional[Union[List[Dict], List[str]]]:
"""
Estimates the most important features and values on which to segment
... | ebdd75b64616da497a73004d502acd320322935b | 51,257 |
def show_images(images, file_to_save, cols=1, titles=None):
"""Display a list of images in a single figure with matplotlib.
Parameters
---------
images: List of np.arrays compatible with plt.imshow.
cols (Default = 1): Number of columns in figure (number of rows is
set to n... | 14f31b182ef2c80d1da720461cb994cb15b2493a | 51,258 |
def WT_EC50s(unkVec_2_15, Traf=True):
"""Returns dataframe of the Wild Type EC50s"""
df = pd.DataFrame(columns=["Time Point", "Cell Type", "IL", "Data Type", "EC50"])
x0 = [1, 2.0, 1000.0]
tps = np.array([0.5, 1.0, 2.0, 4.0]) * 60.0
data_types = []
cell_types = []
EC50s_2 = np.zeros(len(cel... | 88f8f57617ec9666a8c574e289bfccbcee0ee461 | 51,259 |
def implicit_op(op):
""" implicit constant operand promotion """
if isinstance(op, ML_Operation):
return op
elif isinstance(op, SollyaObject) or isinstance(op, int) or isinstance(op, float):
return Constant(op)
elif isinstance(op, ML_FloatingPointException):
return Constant(op, p... | 31e7c36d47e8885631b79d74ae1cfb003f5fd848 | 51,260 |
def ToHex(data):
"""Return a string representing data in hexadecimal format."""
s = ""
for c in data:
s += ("%02x" % ord(c))
return s | 1566962a89967ae0d812ef416d56867a85d824fb | 51,261 |
def set_legend(ax, size=12,
color=COLORS['black'], alpha=ALPHAS['translucent'],
loc='best', frame=False, ncol=1, nscatter=1, **kwargs):
"""
Add and modify legend settings.
:param ax: (mpl.axes) - plot axis
:param size: (str) - size of legend labels
:param color: (str) ... | e40db57e44692eb2c4852f3e173eef2f0cf137a9 | 51,262 |
from typing import List
from typing import Tuple
def fill_missing_test(parameters: List[Parameter]) -> Tuple[str]:
"""Convenience function for testing job parameter fill missing"""
param_set = JobParameterSet(parameters)
param_set.fill_missing_parameters()
return (
param_set.get_param_by_type(... | 5ef2566d535ef8dc877430337ecadc78d142a240 | 51,263 |
import re
import os
def start_dcd_server():
"""Start dcd server."""
def filter_nondirs(server_args):
"""Remove non existent dirs from server args."""
f_args = []
for item in server_args:
m = re.match(r"-I(.+)", item)
if m:
dir_name = m.group(1)
... | e44beae04dc539c30f9273da0e1a9886a4970079 | 51,264 |
def test_PostPlot():
"""Validation of the PostPlot class to plot airgap flux automatically as postprocessing at the end of the simulation"""
IPMSM_A = load(join(DATA_DIR, "Machine", "IPMSM_A.json"))
simu = Simu1(name="PostPlot", machine=IPMSM_A)
# Definition of the enforced output of the electrical m... | 111e2ef836659057e3db452a1bcf3309caa8bf6e | 51,265 |
from datetime import datetime
def parse_date(date_str: str, sep: str = None, format: str = None) -> datetime.date:
"""Returns a ``datetime.date`` if possible
Args:
date_str (str): The date which may not be in standard ISO format
sep: Optional. The separator used to separate each time unit
... | 0b6725b60cd8ce945a2c5d625bc5afe911f88c04 | 51,266 |
def scrub_properties(orig_props):
"""Scrubs fields in API object properties for use in DM properties.
Scrubbed fields include:
- output-only fields common for most resources
- output-only fields specific to a particular resource type
Args:
orig_props: the resource properties that need to be scrubbed
... | d34d115c685123f88d921abc0d0a88bc49ed9bc3 | 51,267 |
def _trend_grid(concentration_cube, weight_cube, *, clipping_threshold):
"""Build a grid for a decadal trend."""
assert concentration_cube.shape == weight_cube.shape
assert clipping_threshold
rows, cols, periods = weight_cube.shape
# Flatten rows and cols of the concentration/weight cubes
# A ... | 24b76b0959713c837e7288faced8d98e15f274e1 | 51,268 |
def uniquify_reference_names(comp):
"""Replaces all the bound reference names in `comp` with unique names.
Notice that `uniquify_reference_names` simply leaves alone any reference
which is unbound under `comp`.
Args:
comp: The computation building block in which to perform the replacements.
Returns:
... | e5022b9ac377ff5397101ab75570faf0137f7dd7 | 51,269 |
def load_csv_data(train_path, test_path=None, sep=',', nrows=None,
x_cols=None, y_cols=None, drop_cols=None,
onehot_cols=None, n_cols=None, random_cols=False,
shuffle=False, scaling=None, dtype=None,
validation_split=None, return_dataframe=True,
... | 9a873f0a7acf7f39675f6865b9cda79c82613908 | 51,270 |
def fclayer(in_features, out_features):
"""
fully connected layers or dense layer
:param in_features: input_dimension => channels * features
:param out_features: output_dimension
:return: (batch, windows, channels * features) => (*, *, output_dimension)
"""
fc = nn.Linear(in_features, out_fe... | a723222d4ef045e329079832073302c077622761 | 51,271 |
def visual_mask(mask_img=None, mask_path=None):
"""
:param mask_path:
:param palette:
:return:
"""
palette = get_palette()
if mask_img is None:
mask_img = Image.open(mask_path)
else:
mask_img = Image.fromarray(np.array(mask_img, dtype=np.uint8))
mask_img.putpalette(p... | c65b612412b8c7ad6930da127a7a09dc6bb3e2e2 | 51,272 |
from typing import Callable
def window_replaced_message(callback: Callable[[HWND, HWND], None]) -> MessageEntry:
"""Listens for when a window is hung, and needs to be recreated.
The first HWND will be set to the HWND of the new window handle, and
the second is the HWND of the replaced window.
The cal... | 01404005f7591673509fc6ae0891a941c533df7d | 51,273 |
from typing import Iterable
def get_sse_mat(mats: Iterable[sp.spmatrix]) -> sp.spmatrix:
"""
Given multiple matrices, return the matrix of position-wise sum of
squared errors to median. All input matrices must have the same shape,
nonzero coordinates and format. Output matrix will have the same format... | 8fb8bd6b4ef162399a2ef87fd9a7377910302fc7 | 51,274 |
def energy_sum(
df: pd.DataFrame, network: NetworkSchema, power_column: str = "generated"
) -> pd.DataFrame:
"""Takes the energy sum for a series of raw duid intervals
and returns a fresh dataframe to be imported"""
# These are the networks that run through the compat func
COMPAT_NETWORKS = [Networ... | a4733c70f6e3d710e2d5f83a33aafd1b6ba01b39 | 51,275 |
import unicodedata
def tokenise_word(string,
strict=False, replace=False, tones=False, unknown=False):
"""
Tokenise the string into a list of tokens or raise ValueError if it cannot
be tokenised (relatively) unambiguously. The string should not include
whitespace, i.e. it is assumed ... | 0c2ed6fc6f0f3748b63922a7743da3350ba58f4f | 51,276 |
def latsrf(method, target, et, fixref, lonlat):
"""latsrf(ConstSpiceChar * method, ConstSpiceChar * target, SpiceDouble et, ConstSpiceChar * fixref, ConstSpiceDouble [1][2] lonlat)"""
return _cspyce0.latsrf(method, target, et, fixref, lonlat) | a8f8705918caedb7477e6fa022fc1deead6cf6e6 | 51,277 |
def _parse_common(xml, the_dict):
"""
Parse things in common for both variables and functions. This should
be run after a more specific function like _parse_func or
_parse_variable because it needs a member dictionary as an input.
Parameters
----------
xml : etree.Element
The xml re... | a6606366ce9b0e4d2c848b16bc868532684b4abe | 51,278 |
import collections
import itertools
def sliding_window(n, seq):
"""
Copied from toolz
https://toolz.readthedocs.io/en/latest/_modules/toolz/itertoolz.html#sliding_window
A sequence of overlapping subsequences
>>> list(sliding_window(2, [1, 2, 3, 4]))
[(1, 2), (2, 3), (3, 4)]
This functi... | 67e65fa6690ecc6974713a0559d596718e7c6361 | 51,279 |
def change_course(request, pk):
""" Изменение данных в курсе """
course = get_object_or_404(Course, pk=pk)
if request.method == 'POST':
form = CourseForm(request.POST, request.FILES, instance=course)
if form.is_valid():
course = form.save()
for csa in CourseStudentAc... | 64c244eee6ea687d88757a621809f0b90f911229 | 51,280 |
def interaction(multiindex):
"""
Return tuple of interaction between variables which this multiindex
represents. Eg. (a) (1,1,1) -> (), (b) (1,2,1) -> (1,), (c) (2,3,1) -> (0,1)
Tuple is always ordered smallest dim-index to largest.
"""
return tuple(np.where(np.array(multiindex, dtype=np.int8)... | 28dbe2161bc30f4bfba72625434b7d170b68722f | 51,281 |
def home(request):
"""Dashboard home."""
return render(
request,
'dashboard/home.html',
{
'quests': Questionnaire.objects.filter(
created_at__year=date.today().year,
)
},
) | 765582081a8d23a90dad7962a662f325be608203 | 51,282 |
def get_entities(config):
"""
Get a dictionary of lambda functions that create entity URLs
:param config: dict
:return: dict
"""
server = config['api']
entities = dict(project=lambda project: server + '/projects/{0}'.format(project),
subject=lambda project, subject: serve... | 2fa3aa0d42ecb027dee4f2610c5eaf5c72f55d44 | 51,283 |
def crypto_secretbox(message, nonce, key):
"""
Encrypts and returns the message ``message`` with the secret ``key`` and
the nonce ``nonce``.
:param message: bytes
:param nonce: bytes
:param key: bytes
:rtype: bytes
"""
if len(key) != crypto_secretbox_KEYBYTES:
raise exc.Valu... | 6ce8bc311427e52568110bccec6747cc6b5f3149 | 51,284 |
def create_bins(bin_info_list, shuffle):
"""Creates a list of bins based on a string list of bin info."""
bins = []
for bin_info in bin_info_list:
bins.append(DataBin(bin_info[0], bin_info[1], shuffle))
return bins | 89273361df4fd8e1dff6145400685faf5a788818 | 51,285 |
def getEmissionSelf(dataDirBase, NCVariable, RCPScenario, decade):
"""This function uses makeEmissionNCFile() to get the nc file path
of the desired species arguemnt and returns the nc connection to
that species.
Parameters: Same as makeEmissionNCFile()
dataDirBase: Working hardrive
NCVariable... | b4f93bc4266020a4044a3a1f4c4cf50a288402e8 | 51,286 |
def from_plus(path):
"""
Given the path to a CoNLL-U Plus file, return the corresponding plain
CoNLL-U string.
"""
with open(path) as f:
plus_fields = [field.upper() for field in parse_conllu_plus_fields(f)]
plus_content = f.read()
plus_sentences = parse(plus_content, plus_f... | d2c7e8dccf63c0d90416dbff7237cc6b7f6216a3 | 51,287 |
def __coord_n(n, **_kwargs):
"""Get bare positions"""
return np.arange(n + 1) | 697963a802598e4d3d1ec20c610760398eecbf3f | 51,288 |
def vectorized_gaussian_logpdf(X, means, covariances):
"""
Compute log N(x_i; mu_i, sigma_i) for each x_i, mu_i, sigma_i
https://stackoverflow.com/a/50809036/8395138
Args:
X : shape (n, d)
Data points
means : shape (n, d)
Mean vectors
covariances : shape (... | 80dfd7618647e2b00ff5b98693820aad5226c342 | 51,289 |
def elementWise(A, B, operation):
"""
execute an operate element wise and return result
A and B are lists of lists (all lists of same lengths)
operation is a function of two arguments and one return value
"""
return [[operation(x, y)
for x, y in zip(rowA, rowB)]
for row... | 39e78ca7730bf8367daf3a55aeb617b2c0707a44 | 51,290 |
def create_test_baymodel(context, **kw):
"""Create and return a test baymodel object.
Create a baymodel in the DB and return a BayModel object with appropriate
attributes.
"""
baymodel = get_test_baymodel(context, **kw)
try:
baymodel.create()
except exception.BayModelAlreadyExists:
... | eeed0905d907856593faa2b992492cbb0250b4fc | 51,291 |
def test_forward_with_parameter_in_sub_cell():
"""
Feature: Custom cell bprop
Description: Get the gradients of inputs when the forward net using Parameter in the sub-cell.
Expectation: Get the correct gradients.
"""
class Net(nn.Cell):
def __init__(self):
super(Net, self)._... | aaf570a83c29ec98e09b96377c2179a869f1d89c | 51,292 |
def _GetRollbackRelease(release_id, pipeline_id, target_ref):
"""Gets the release that will be used by promote API to create the rollback rollout."""
ref_dict = target_ref.AsDict()
if release_id:
return resources.REGISTRY.Parse(
release_id,
collection='clouddeploy.projects.locations.deliveryPi... | a2d978093a4475df07a3dd56816c0a914daf5a58 | 51,293 |
import os
def load(data_dir=DEFAULT_DATA_DIR, delay=100, num_possible_symbols=10):
""" Load Copy Problem data.
Args:
data_dir: A string. The data directory.
delay: An integer.
num_possible_symbols: An integer.
Returns:
A tuple with 6 elements: train inputs, train targets, val inputs, val
t... | 6722ace34fc98c01308da858337c78b7ea119e76 | 51,294 |
def find_spaces(string_to_check):
"""Returns a list of string indexes for each string this finds.
Args:
string_to_check; string: The string to scan.
Returns:
A list of string indexes.
"""
spaces = list()
for index, character in enumerate(string_to_check):
if character == ' ':
spaces.ap... | 8bcd1d9911efab3c65e08524293b11afd449efa0 | 51,295 |
def calculate_activation_statistics(images, batch_size):
"""Calculates the statistics used by FID
Args:
images: torch.tensor, shape: (N, 3, H, W), dtype: torch.float32 in range 0 - 1
batch_size: batch size to use to calculate inception scores
Returns:
mu: mean over all activation... | 9d1760c3aba636004bf158d2efaf021a035484a6 | 51,296 |
def _should_recurse(start, config_lines, initial_indent):
"""Sometimes object are not expected to document every parameter and contain all the description at the top.
This is valid, therefore we should not recurse and analyze what's next after the whole object. Returns whether or
not to recurse as long a po... | a89c5a641f13cba8b487a1e41b707450a5998e00 | 51,297 |
def unwrap_eth():
"""
Withdraw ETH by depositing wETH
"""
account = get_account()
# Need to get the ABI and the Address of the contract
weth = interface.IWeth(config["networks"][network.show_active()]["weth_token"])
# Deposit
amount = 0.1
tx = weth.withdraw(
Web3.toWei(amo... | 277bbf8a23e5d0d14f27e53b5d7787e9b6f991b2 | 51,298 |
def client() -> User:
"""Construct the User (client) class"""
return User(username=USERNAME, auth=AUTH) | 8c217f2ed6cd4a5e60948bdfcac1594b28e2197f | 51,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.