content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def tnaming_Displace(*args):
"""
* Application de la Location sur les shapes du label et de ses sous labels.
:param label:
:type label: TDF_Label &
:param aLocation:
:type aLocation: TopLoc_Location &
:param WithOld: default value is Standard_True
:type WithOld: bool
:rtype: void
... | 91d2550b5ecb108a2ddcceb6a3a227e48ab16f24 | 3,636,693 |
def get_capital_np(markets,signals,size,commiRate,climit = 4, wlimit = 2, op=True):
"""使用numpy回测,标签的盈亏, op 表示是否延迟一个tick以后撮合"""
postions = np.zeros(len(signals))
actions = np.zeros(len(signals))
costs = np.zeros(len(signals))
pnls = np.zeros(len(signals))
lastsignal = 0
l... | 4604bb16c298e4ea32d2fca5f8332e5d21e4aada | 3,636,694 |
def slicename_to_hostname(vs_name):
"""Converts a vserver slice name into a canonical FQDN.
Slice names use a pattern like: <some site>_<some name>.
Example:
If vs_name is 'mlab_utility' and the system hostname is
'mlab4.nuq01.measurement-lab.org', then slicename_to_hostname will return
'utility.m... | 7f8b6ff17ab402cfa89ee732f1e4c61ddffee7c2 | 3,636,695 |
from typing import Dict
def swim_for_a_day(life_counts: Dict[int, int]):
"""Process the shoal, decrement the life_counts:
any that get to -1 have procreated in the last day, their offspring are
created with 8 day life_counts, whilst they get reset to 6 days… and are
added to the count of any fish that... | 3d5d3f48942a5a1f4eba3100e903df592d933e23 | 3,636,696 |
def page_not_found (error):
"""
Generic Error Message
"""
return "Unable to find Distill." | ed764c2c2814487c33f9945b17b85a234ae45645 | 3,636,697 |
def dict_to_obj(our_dict):
"""
Function that takes in a dict and returns a custom object associated with
the dict. This function makes use of the "__module__" and "__class__"
metadata in the dictionary to know which object type to create.
"""
if "__class__" in our_dict:
# Pop ensures we... | 4ad11ff943d2055d37643b6d7058175f504f8271 | 3,636,698 |
def display_fips( collection_of_fips, fig, **kwargs ):
"""
Method that is very similar to :py:meth:`display_fips_geom <covid19_stats.engine.viz.display_fips_geom>`, except this *also* displays the FIPS code of each county. For example, for `Rhode Island`_, this is.
.. _viz_display_fips_rhodeisland:
... | ea609e19f4f42032a0533c12ea8ebc9ded6412aa | 3,636,699 |
import itertools
import re
def _apply_constraints(password_hash, size, is_non_alphanumeric):
"""
Fiddle with the password a bit after hashing it so that it will
get through most website filters. We require one upper and lower
case, one digit, and we look at the user's password to determine
if ther... | 8757c3197052fb1606a95dfa417a13ba833cdb43 | 3,636,700 |
def SplitLineRecursive(linepts,i,j,THRESHOLD=5.0,ds_min=50.0):
"""
Choose best point at which to split a line to minimize total reprojection error
"""
max_err = np.max(ProjectionError(np.stack((linepts[:,i],linepts[:,j])).T, linepts[:,i:j]))
if max_err < THRESHOLD:
ds = np.cumsum(np.sqrt(np.... | fe17a756d588468b04db999f72274d459fec0d65 | 3,636,701 |
def create_report() -> FlaskResponse:
"""Creates a new report.
Note: This is the existing implementation, currently used for the v1 endpoint.
Returns:
FlaskResponse: details of the report just created or a list of errors with the corresponding HTTP status code.
"""
logger.info("Creating a ... | dbe64f79e05dc67932beac0aa06b6cd6c4f998c5 | 3,636,702 |
def sample_exercise():
"""Create a sample exercise"""
return ExerciseModel.objects.create(
name='exercise name',
duration=10,
calories=10
) | c4c9424aa987a8cb2d0fa493c63920b438ae5b73 | 3,636,704 |
def der_kinetic_integral(a,bfi,bfj):
"""
The kinetic energy operator does not depend on the atomic position so we only
have to consider differentiating the Gaussian functions. There are 4 possible
cases we have to evaluate
Case 1: Neither of the basis functions depends on the position of atom ... | 5c84eea3fcd1f44bd41a9c14d0c104d9b3af0390 | 3,636,705 |
import torch
import datasets
def get_celeba():
"""Get and preprocess the CelebA dataset.
"""
transform = transforms.Compose([
transforms.Resize((64, 64)),
transforms.ToTensor()])
# Use only 18/40 labels as described in Appendix C.1
mask = torch.tensor(
[False, True, False, ... | 05789f37a9fa0c360ae4d5a2cdcfe5f9a2a4c440 | 3,636,706 |
def waa_adjust_baseline(rsl, baseline, wet, waa_max, delta_t, tau):
"""Calculate baseline adjustion due to wet antenna
Parameters
----------
rsl : iterable of float
Time series of received signal level
baseline : iterable of float
Time series of ... | 80bdec1a9cdd5dcf22008a6efdc08c5a7ae9ec1f | 3,636,707 |
def linear_warmup_decay(learning_rate, warmup_steps, num_train_steps):
""" Applies linear warmup of learning rate from 0 and decay to 0."""
with fluid.default_main_program()._lr_schedule_guard():
lr = fluid.layers.tensor.create_global_var(
shape=[1],
value=0.0,
dtype=... | 727d303adf144407e45a013ca36b0bac592bc522 | 3,636,708 |
def space2():
"""Create a Space with two real dimensions."""
space = Space()
space.register(Real("lr", "uniform", 0, 1))
space.register(Real("weight_decay", "uniform", 0, 1))
return space | acc6bc1529fdc26c6e3c8140c89c0db3d7703ea7 | 3,636,709 |
def calculate_thresh(twindow, pctile, skipna):
"""Calculate threshold for one cell grid at the time
Parameters
----------
twindow: xarray DataArray
Stacked array timeseries with new 'z' dimension representing
a window of width 2*w+1
pctile: int
Threshold percentile used to d... | 37228003d1c564205067e6d71a78ab83ffdeaf2f | 3,636,710 |
def edit_car(item_id):
"""
Edit item
:param item_id:
:return mix:
"""
# get user
user = get_user_by_id(session['uid'])
# Get car
car = get_item_by_id(item_id)
# Check the user is the owner
if int(session['uid']) != int(car.author):
flash('You don\'t have permissio... | 498b9b07292cf2de3ac8a929f624d0e93ee793b7 | 3,636,711 |
def replace_ensembl_ids(expression_df, gene_id_mapping):
"""
Replaces ensembl gene ids with hgnc symbols
Arguments
---------
expression_df: df
gene expression data matrix (sample x gene)
gene_id_mapping: df
Dataframe mapping ensembl ids (used in DE_stats_file) to hgnc symbols,
... | db21341c337481f897da47e482a6667b3e4b9c8e | 3,636,712 |
async def get_latency(ctx: Context) -> dict[str, str]:
"""
Get the bot's latency and database latency.
Parameters
----------
ctx : Context
The context.
"""
now = perf_counter()
collection = ctx.bot.db['test']['TESTS']
if await collection.find_one({'_id': PAYLOAD['_id']}) ... | f42e8d3456a72b9b9b6520a2c60b777d74924cd3 | 3,636,713 |
def ssl_allowed(fn):
"""
Decorator - marks a route as allowing ssl, but not requiring it. It can be served over http and https.
NOTE: This must go BEFORE the route!
"""
fn.ssl_allowed = True
return fn | d8a22ed69a356189bca69a08516fd0a1187e4866 | 3,636,714 |
def fold_with_enum_index(xtypes, x):
"""
see MixedIntegerContext.fold_with_enum_index
"""
x = np.atleast_2d(x)
xfold = np.zeros((x.shape[0], len(xtypes)))
unfold_index = 0
for i, xtyp in enumerate(xtypes):
if xtyp == FLOAT or xtyp == INT:
xfold[:, i] = x[:, unfold_index]
... | 42a2385f591ac3349d9a7c25870adb23eb0a8fe8 | 3,636,717 |
import redis
def unlock(arguments):
"""Unlock the database."""
u = coil.utils.ask("Redis URL", "redis://localhost:6379/0")
db = redis.StrictRedis.from_url(u)
db.set('site:lock', 0)
print("Database unlocked.")
return 0 | 859ec2ec159529ab5cb5e05c32703a3164666e68 | 3,636,718 |
from typing import cast
def filter_atom_tokens(entity: SerializableEntity) -> bool:
"""
When locating tokens for equations, only detect atom tokens (i.e., skipping affix tokens like
arrows and hats), because affixes be colorized by wrapping them in colorization commands.
"""
token = cast(Serializa... | 42c60615a7e7c87dee40d2326d5e41518644ac88 | 3,636,719 |
def xmp_extract(fns, type_map):
"""xmp_extract
:param fns:
:param type_map:
"""
logger.info("Extracting raw XMP data.")
func = partial(xmp_to_vec, type_map=type_map)
xmp_to_vec(fns[0], type_map=type_map)
xmp_data = imap_unordered_bar(func, fns, n_proc=2)
xmp_data = pd.DataFrame(xmp_... | 413d179dd5dd8579e12ffb648f05802e1ff7501e | 3,636,721 |
import textwrap
def fisbUnavailable(db):
"""Create string containing any FIS-B Unavailable messages.
Args:
db (object): Handle to database connection.
Returns:
str: Containing any FIS-B Unavailable information.
"""
if SHOW_UNAVAILABLE == False:
return ''
fisbStr ... | 319a1477c0873741d7c67550b9c27d64f2707c73 | 3,636,722 |
def rotate_file(filename, copy=False):
"""
Rotate file like logrotate.
If given filename already exists, rename it to "filename".n, n=1...
Filename with larger n is older one.
"""
# If not exist,
if not os.path.isfile(filename):
return
# make list [ [filename, number], ... ]
... | 1d2ddbc5153b8b79e4f8130c82fdf34437f4a4d6 | 3,636,724 |
def change_master(host, confirm=False):
"""
Change to different master host.
Arguments:
- host (str): Hostname of the new master to change to.
Optional arguments:
- confirm (bool): Acknowledge the execution of this command. Default is 'False'.
"""
if not confirm:
raise sal... | e24da255ef2c85b18266e3143e31d19d8d4c3136 | 3,636,725 |
import six
def decode_text(s):
"""
Decodes a PDFDocEncoding string to Unicode.
Adds py3 compatability to pdfminer's version.
"""
if type(s) == bytes and s.startswith(b'\xfe\xff'):
return six.text_type(s[2:], 'utf-16be', 'ignore')
else:
ords = (ord(c) if type(c) == str else c fo... | 9a98160acff455bb77dca6223454a57a0058a418 | 3,636,726 |
def normalize_bound(sig, lb=0, ub=1):
"""
Normalize a signal between the lower and upper bound.
Parameters
----------
sig : ndarray
Original signal to be normalized.
lb : int, float, optional
Lower bound.
ub : int, float, optional
Upper bound.
Returns
------... | a9f609da88d05f76ce4c244eb516405956d79acb | 3,636,727 |
import itertools
def get_chisqr3d(res3d):
"""Extract fit3d result chisqr attribute into a 3d volume
Args:
res3d -- 3d numpy array of model.ModelResult; output of fit3d
Return:
attr3d -- numpy arrays of chi-square statistics of fit
"""
# create empty array
data_type = type(re... | e0f0571237a4b79694e14abe1b0376d864b656fd | 3,636,728 |
def detect_Telephony_SMS_abuse(x) :
"""
@param x : a VMAnalysis instance
@rtype : a list of formatted strings
"""
formatted_str = []
structural_analysis_results = x.tainted_packages.search_methods("Landroid/telephony/SmsManager","sendTextMessage", ".")
#structural_analysis_results = x.tainted_packa... | 1d337cc66ea8d536832b2582beabd1985c88a2f2 | 3,636,729 |
import torch
from typing import Optional
from typing import Tuple
def depth_map_to_point_cloud(
depth_map: torch.Tensor,
valid_map: Optional[torch.Tensor],
focal_x: float,
focal_y: float,
center_x: float,
center_y: float,
trunc_depth_min: Optional[float],
trunc_depth_max: Optional[float],
flip_h: bo... | 555dc106e8e9075d6f05ba5b221bba3cb8dccb34 | 3,636,730 |
import logging
def symbol_definitions(goto, wkdir, srcdir=None):
"""Symbol definitions appearing in symbol table.
Source file path names in symbol table are absolute or relative to
wkdir. If srcdir is given, return only symbols defined in files
under srcdir.
"""
wkdir = srcloct.abspath(wkdi... | 4030fa44407146f3339088fb6a34ff2822410b83 | 3,636,731 |
import re
def get_my_ip() -> None:
"""
Funtion to get current ip in Network
"""
url = "http://checkip.dyndns.com/"
return re.compile(r"Address: (\d+.\d+.\d+.\d+)").search(get(url).text).group(1) | 0c52ad85ec29a1dfb65f2699b13e66b038fc31a8 | 3,636,733 |
def param_squared_mean(ns_run, logw=None, simulate=False, param_ind=0):
"""Mean of the square of single parameter (second moment of its
posterior distribution).
Parameters
----------
ns_run: dict
Nested sampling run dict (see the data_processing module
docstring for more details).
... | bcb7677eb648ad559e56b853de4f9246da638ff2 | 3,636,734 |
def match_login_url_with(username, default="https://foo.bar/login"):
"""
Match a given username with the corresponding
login URL
:param username: username of user. type str
:returns URL: login URL for user. type str
"""
return matches(
{
"yelluw": "https://yelluw.com/log... | f6351e978b2010818092bfb3340fde1b84635d32 | 3,636,736 |
def odict_1to1(from_sp, to_sp):
"""
Filtered flat odict with only 1to1 orthologs.
"""
od = odict(from_sp, to_sp)
od_rev = odict(to_sp, from_sp)
return dict([(k,list(v)[0]) for k,v in od.items() if len(v)==1 and
len(od_rev[list(v)[0]])==1]) | 1ad1deca32d883f2bd8637d93b8b1a3578a05a75 | 3,636,737 |
import fnmatch
def find_devices(vendor=None, product=None, serial_number=None, custom_match=None, **kwargs):
"""Find connected USB devices matching certain keywords.
Wildcards can be used for vendor, product and serial_number.
:param vendor: name or id of the vendor (manufacturer)
:param product: na... | 7067b27d9d3c27eabe28150e460661682f02045d | 3,636,738 |
def get_static_graph(app_name=None, app_dict=None, *args, **kwargs):
""" Explicityl avoid request and user. """
return get_graph(app_name=app_name, app_dict=app_dict, request=None) | 8628f88e88080b18ead39871f3e3f69ba07c09a6 | 3,636,739 |
def downsample_spectrum(ar_wavelength, ar_flux, ar_ivar, scale):
"""
:type ar_wavelength: np.ndarray
:type ar_flux: np.ndarray
:type ar_ivar: np.ndarray
:type scale: int
:return: (np.ndarray, np.ndarray, np.ndarray)
"""
new_length = ar_wavelength.size // scale
old_length_clipped = ne... | 443a917c02eab7bdfc2c544c9bec431dbe1691ac | 3,636,740 |
def format_date(date):
"""
Format date for creation of Twitter URL and Facebook API.
Format a datetime object to a string in the form of '%Y-%m-%d', e.g. '2018-01-21'
Parameters
----------
date : datetime
date to be formated
Returns
-------
str
date in string repre... | d76e81613d2c3b06623cadb30d706c537555ad51 | 3,636,741 |
import base64
def basic_token(username, password):
"""Generate the Authorization token for Resource Orchestrator (SO-ub container).
Args:
username (str): the SO-ub username
password (str): the SO-ub password
Returns:
str: the Basic token
"""
if not isinstance(username, st... | 054fccad28d1c18a34d630a664742f77e15ee4fe | 3,636,742 |
import csv
def read_alias(alias_csv_path):
"""Reads alias.csv at the specified path.
Then returns a dict mapping from alias to monster id.
"""
with open(alias_csv_path) as alias_csv:
return {
alias: int(monster_id)
for alias, monster_id in csv.reader(alias_csv)} | 3a3818b81a916b4dd18ca7cab5fbcbe1b4050d03 | 3,636,743 |
async def get_pipeline_run_node_steps(request: web.Request, organization, pipeline, run, node) -> web.Response:
"""get_pipeline_run_node_steps
Retrieve run node steps details for an organization pipeline
:param organization: Name of the organization
:type organization: str
:param pipeline: Name of... | 8ad3b987500366d562a5f6f59cc106fe374f50aa | 3,636,744 |
def query_available_collections(opts: Options) -> pd.DataFrame:
"""Search for the available collections."""
# Graphql query to get the collections
query = create_collections_query()
# Call the server
reply = query_server(opts.web, query)
collections = json_properties_to_dataframe(reply["collecti... | f1ce5738739956a4a9a4258f35cdfadd1a75dffc | 3,636,745 |
from typing import List
from typing import Dict
from typing import Any
from typing import Tuple
def _create_agent_object_list(
trial_list: List[List[Dict[str, Any]]],
agent_object_config_list: List[ObjectConfigWithMaterial],
unit_size: Tuple[float, float]
) -> List[Dict[str, Any]]:
"""Create and retur... | e30b172a7c2dc2c35e180955a65cd5de98a43ec1 | 3,636,746 |
async def send_data_controller_details_message_handler(request: web.BaseRequest):
"""Send data controller details message to remote agent hosted by Data Controller."""
context = request.app["request_context"]
connection_id = request.match_info["connection_id"]
# Initialise MyData DID Manager.
myda... | 65437e2f3ea79c9d09d04bfabe1fce6ef02294a4 | 3,636,747 |
def test_llhelper(monkeypatch):
"""Show how to get function pointers used in type slots"""
FT = lltype.FuncType([], lltype.Signed)
FTPTR = lltype.Ptr(FT)
def make_wrapper(self, space):
def wrapper():
return self.callable(space)
return wrapper
monkeypatch.setattr(pypy.mod... | 323ddd524e24eeb70284bf2229e77fe66e557f51 | 3,636,748 |
def get_chronicle_http_client(account_info):
"""
Return an http client that is authorized with the given credentials
using oauth2client or google-auth.
"""
try:
credentials = service_account.Credentials.from_service_account_info(
account_info, scopes=current_app.config['AUTH_SCO... | df75a33c41891ccdab36ac933c81a09be8ebf4f8 | 3,636,749 |
def svn_auth_save_credentials(*args):
"""svn_auth_save_credentials(svn_auth_iterstate_t state, apr_pool_t pool) -> svn_error_t"""
return apply(_core.svn_auth_save_credentials, args) | 429958f965bea9b5f4838cf471c91dd6e1d26e77 | 3,636,750 |
def get_nodes_str (name, nodes):
"""
helper function to dump nodes as a list of names
"""
nodes_str = " %s nodes = %d\n" % (name, len(nodes))
nodes_str += " " + ", ".join(map(lambda x: x._name, nodes)) + "\n"
return nodes_str | cafb9fd0aa202c2172aede97eabbf829dc9a1b53 | 3,636,751 |
import requests
def clean_df(df, selected_columns=default_columns):
"""Take a dataframe with GDELT2.0 data and only retain the useful columns for us and also add the country where the news was written
Keyword arguments:
df -- The dataframe complying to GDELT2.0 columns format
selected_col... | 6ef2b2537c5190541691c4230e6f3164c5c9ae32 | 3,636,753 |
from functools import reduce
def mse(y_true, y_pred, reduce_mode="mean"):
"""mean squared error。"""
return reduce(tf.math.square(y_pred - y_true), reduce_mode) | a74f04405d1cbc5d4ff3715286f4b76fa3355a42 | 3,636,754 |
def calculate_assignment_probabilites(assignments, num_clusters):
"""
Just counts the occurence of each assignment to get an empirical pdf estimate
"""
temp = np.arange(num_clusters)
hist_b_edges = np.hstack([-np.inf, (temp[:-1] + temp[1:]) / 2, np.inf])
assignment_counts, _ = np.histogram(assignments, hist... | fe2d99b108d9baac9876a7cb9af54cb69a04525a | 3,636,755 |
def getStudiesOptions(request, id):
""" Get a list of studies for an investigation id.
Input:
id, investigation id.
"""
seekdb = SeekDB(None, None, None)
user_seek = seekdb.getSeekLogin(request, False)
investigation_id = id
studies = seekdb.getStudiesFromID(investigation_id)... | b864a9aae99851f8f904cbc55b896ec6d22300c1 | 3,636,757 |
def fibonacci_thrid(n):
"""计算斐波那契数列3"""
return n if n < 2 else fibonacci_thrid(n - 2) + fibonacci_thrid(n - 1) | b98251e9bd4ec507933338738c2b65faea8700b2 | 3,636,758 |
import socket
def site_url(url):
"""
Determine the server URL.
"""
base_url = 'http://%s' % socket.gethostname()
if server.port is not 80:
base_url += ':%d' % server.port
return urlparse.urljoin(base_url, url) | cb759e7e7d0273397106be79c20072eb3d7d1898 | 3,636,759 |
from typing import Tuple
from typing import List
def get_coordinates(
mask: np.ndarray, ths: int = 5, kernel_len: int = 10
) -> Tuple[List, np.ndarray, np.ndarray]:
"""This function extract the coordinate of table, horizontal and vertical lines.
Args:
mask (np.darray): A binary table image
... | 3c0bbc395df07cb240d82cf0cf78b3623591bd98 | 3,636,760 |
def get_pixels(extrinsic, intrinsic, X):
"""
Returns the x, y pixels for the given X vector
:param extrinsic: extrinsic (4*4) matrix obtained from the headset
:param intrinsic: intrinsic (3*3) matrix obtained from the headset
:param X: the position vector
:return: image pixels for the vector
... | 700bbbd721e4a1547c593163a41e13a8c20bee0d | 3,636,761 |
def delete_question(media_package, level=0):
"""
Ask user the question whether they want to delete the distribution artefacts for the next media package or for all
remaining media packages.
:param media_package: The media package to ask the question for
:type: str
:param level: The level to ind... | b11ea47f01f41c4211b32d1f61fa5255f5a0fb92 | 3,636,762 |
import importlib
import pkgutil
def import_submodules(package, recursive=True):
""" Import all submodules of a package, recursively, including subpackages
Arguments:
1. package = (string) name of the package
(module) loader of the package
2. recrusive = (bool) True = load pack... | e299334de43ee9bd9544589698472db978fcae8d | 3,636,763 |
def is_collision_ray_cell(map_obj, cell):
"""
cell : cell r, c index from left bottom.
"""
idx = cell[0] + map_obj.mapdim[0] * cell[1]
if (cell[0] < 0) or (cell[1] < 0) or (cell[0] >= map_obj.mapdim[0]) or (cell[1] >= map_obj.mapdim[1]):
return True
#elif (map_obj.map is not None) and map_obj.map[cell[0... | 6eaf38710843c4c4e82e8411db9f1e1d97fb1710 | 3,636,764 |
from datetime import datetime
def time_of_trip(datum, city):
"""
Takes as input a dictionary containing info about a single trip (datum) and
its origin city (city) and returns the month, hour, and day of the week in
which the trip was made.
Remember that NYC includes seconds, while Washington and... | 37824a6f2fe3816ec09fc3f86bb00400cfd43b38 | 3,636,765 |
def transform_resource_name(ctx, param, value):
"""Callback to transform resource_name into title case."""
if value is not None:
return value.title()
return value | b708c3318b731d652a7acad216093c96bc18fe2e | 3,636,766 |
def extrema (im):
"""
Return the minimum and maximum of an image.
Arguments:
im image whose extrema are to be found
"""
return [im.min(), im.max()] | 303d9c50cca91c3e73341d7b40195aceb02aef7a | 3,636,767 |
def _create_statement(name, colnames):
"""Create table if not exists foo (...).
Note:
Every type is numeric.
Table name and column names are all lowercased
"""
# every col is numeric, this may not be so elegant but simple to handle.
# If you want to change this, Think again
sche... | 53c7fc9486274645c5dc7dea2257fda3cf496f9e | 3,636,768 |
def createBundle():
"""create bundled type of OSC messages"""
b = OSC.OSCMessage()
b.address = ""
b.append("#bundle")
b.append(0)
b.append(0)
return b | fee80abd7aa2d71b2e03dbebd65aaca07be7037a | 3,636,769 |
def binary_or(a: int, b: int):
"""
Take in 2 integers, convert them to binary, and return a binary number that is the
result of a binary or operation on the integers provided.
>>> binary_or(25, 32)
'0b111001'
>>> binary_or(37, 50)
'0b110111'
>>> binary_or(21, 30)
'0b11111'
>>> b... | 514fa4a02b778dfa91c4097bb8916522339cda33 | 3,636,770 |
def tukey(N, alpha):
"""
generate a tukey window
The Tukey window, also known as the tapered cosine window, can be regarded as a cosine lobe of width \alpha * N / 2
that is convolved with a rectangle window of width (1 - \alpha / 2). At \alpha = 1 it becomes rectangular, and
... | 507b86f0cc98c832d0405f560b1018531d32c172 | 3,636,771 |
def psi(X, Y, c_i, A, config, pkg='numpy'):
"""Computes the value of magnetic flux at point (X, Y)
according to coefficients ci.
Args:
X (float or numpy.array): x coordinate
Y (float or numpy.array): y coordinate
c_i (list): list of floats, the ci coefficients
A (float): pla... | af110abfe37a82a0fcf89a31d1c8eae87bf280b8 | 3,636,773 |
def tempConvert(temp, unit):
""" Convert Fahrenheit to Celsius """
if unit == 'F':
celsius = (temp-32) * 5/9
return celsius
else:
return temp | 224c7b5bd72ff5d209bfaf2b10d94cc24ac8681d | 3,636,775 |
def _find_best_twitter_key(type, reset, remaining, limit, proxies, auth):
"""
This function switches to another pair of Twitter API keys, if they are available, to avoid pausing.
* WANT TO SWAP KEYS HERE B/C PAUSE IS MORE THAN 3 MINUTES
:param type: Type of API call: "timeline", "friends", "followers"... | 777cd7bed54f635c06ad3cef1bb65a6a6075dcc9 | 3,636,776 |
import fnmatch
def allowed_file(filename, allowed_exts):
"""
The validator for blueimp that limits which file extensions are allowed.
Args:
filename (str): a filepath
allowed_exts (str): set of allowed file extensions
Returns:
bool: True if extension is an allowed file type, ... | af23f6017ffa76e5402800a77cf794a2c1bce330 | 3,636,777 |
import string
def tokenize(document):
"""
Given a document (represented as a string), return a list of all of the
words in that document, in order.
Process document by coverting all words to lowercase, and removing any
punctuation or English stopwords.
"""
words = document.lower()
... | 76e2eedc08ccc8bec28830ab6b0d8a70d4a67b14 | 3,636,778 |
def check_auth(username, password):
"""This function is called to check if a username /
password combination is valid.
"""
database = db_connect()
cursor = database.cursor()
cursor.execute("SELECT password, active FROM users WHERE api_user=%s;", (username,))
results = cursor.fetchone()
c... | d621ecefba65793b8f8230eb9e211e3d23d2c270 | 3,636,780 |
from typing import Union
def _handle_axis(axis: Union[str, int]) -> int:
"""Handles axis arguments including "columns" and "index" strings."""
if axis not in {0, 1, 'columns', 'index'}:
raise ValueError(
"axis value error: not in {0, 1, 'columns', 'index'}"
)
# Map to int if s... | 4ebc4fe2ccf9124e326d21b14a7dc4d9aae52f12 | 3,636,781 |
def is_icmp_dest_unreach(icmp_data):
"""is ICMP_DEST_UNREACH?"""
return icmp_data["TYPE"] == ICMP_DEST_UNREACH | 07213bed90a9e17c0236883b2739f54b8d5ccf09 | 3,636,785 |
def exists_user_notifications(session, user_id):
"""Helper method to check if notifications for user exists."""
res = session.execute(text("""SELECT EXISTS(
SELECT 1 FROM public.notification WHERE user_id='{0}') AS user"""
.format(user_id))).fet... | a22c171359a95fc3723edbb967df865046692969 | 3,636,786 |
import torch
def export_onnx(model, config, device, onnx_model_path, verbose):
""" Export GPT-2 model with past state to ONNX model
"""
num_layer = config.n_layer
dummy_inputs = get_dummy_inputs(batch_size=1,
past_sequence_length=1,
... | 13b4152750efecef5275a154768d8a891fe95829 | 3,636,787 |
def set_peak_elo(df: DataFrame, playersElo) -> DataFrame:
"""Add 2 columns PeakElo and PeakEloSince to a dataframe containing Date, P1Id and P2Id fields
Args:
df (DataFrame): the dataframe from where we read row by row (match by match)
playersElo ([type]): dict <id>:[eloratings_history]
Re... | a55c4d098686a1b75b03eac0c46345bc7c248593 | 3,636,788 |
def calc_plane_vector(atom_pos):
"""
Method to calculate best-fitted (unit) plane vector given a set of points using SVD
ARGS:
atom_pos (ndarray) :: ndarray storing atomic positions
returns:
ndarray
"""
# Zero-centering centroid of atoms before SVD
atom_pos_0 = atom_pos.T - np... | 5576152adcd1406a94e79eb29d3030214424c2b7 | 3,636,789 |
import requests
def search_reddit(search, subreddit='', t='week', limit='100',
sort='new', restrict_sr='1'):
"""
search - string object, representing your search query
subreddit - string object, representing the subreddit
t - string object, one of (hour, day, week, month, year, all)... | d26383f464b16bf8cefa5e089b975c6ad2c5f19f | 3,636,790 |
def _expected_type_expression(typedef: Typedef) -> str:
"""
Determine the type expression supplied to ``from_obj`` function corresponding to the type definition.
:param typedef: type definition in Python representation
:return: Python code representing the type definition
"""
# pylint: disable=... | 98ce70280c5054083b9234f1ef47b759b852720a | 3,636,791 |
def adjoint(m):
"""Compute the Hermitian adjoint."""
return np.transpose(np.conj(m)) | f7dea92a990473f88547574846aa1be8dc4bfee1 | 3,636,792 |
def get_graphic_template_variables(path, graphic_number):
"""
Generates the template variables for each graphic
"""
slug, abspath = utils.parse_path(path)
graphic_path = '%s/%s' % (abspath, slug)
## Get Spreadsheet Path
try:
graphic_config = load_graphic_config(graphic_path)
exc... | e755ec96cdcf0f9bddeb2d5134db97cdc9777dfd | 3,636,793 |
def svc(self, model):
""" Obtain the model and the search space of the SVC
classifier. """
svc_sp = {}
if model == "linear":
svc = LinearSVC(dual=False, class_weight='balanced')
else:
svc = SVC(cache_size=1000, class_weight='balanced')
svc_sp['kernel'] = ['linear', 'poly', '... | a58bafa7bdf3ff71120afd528b479893dada14e4 | 3,636,794 |
import re
def _FormatDataTransferIdentifiers(client, transfer_identifier):
"""Formats a transfer config or run identifier.
Transfer configuration/run commands should be able to support different
formats of how the user could input the project information. This function
will take the user input and create a u... | 951a3576a1a53f9dd141e718c31c8b0314a550d7 | 3,636,795 |
def getReactionUrl(reaction, family=None, estimator=None, resonance=True):
"""
Get the URL (for kinetics data) of a reaction.
Returns '' if the reaction contains functional Groups or LogicNodes instead
of real Species or Molecules.
"""
kwargs = dict()
for index, reactant in enumerate(reacti... | 6ce5ca833bf4871d98314f8bf64a1ce024d4f41d | 3,636,796 |
def hexLat2W(nrows=5, ncols=5):
"""
Create a W object for a hexagonal lattice.
Parameters
----------
nrows : int
number of rows
ncols : int
number of columns
Returns
-------
w : W
instance of spatial weights class W
Notes
-----
... | 7e33f66d40d87b71d0b06d73cf83a33752aecfdd | 3,636,797 |
import numpy as np
def Modelo(Mags, Phi, Me, alpha):
""" Modelo para ajustar
Parameters
----------
Mags, ERR : list
Magnitudes observadas
Phi, Me, alpha : .float, .float, .float
Parámetros del modelo
Returns
--------
F : list
Valores de la función... | 0e547058032bc682c6d0c5bffa5f00aaa1318989 | 3,636,798 |
import fractions
def totient(n):
"""
Calculates Euler's totient
"""
count = 0
for i in range(1, n):
if (fractions.gcd(n, i) == 1):
count = count + 1
return count | 11107816582285e712d9b2f5e98649ad345f9bf0 | 3,636,799 |
import pickle
def read_img_pkl(path):
"""Real image from a pkl file.
:param path: the file path
:type path: str
:return: the image
:rtype: tuple
"""
with open(path, "rb") as file:
return pickle.load(file) | 8c7045d460e0583b02b565b818888c6b7991bc6b | 3,636,800 |
from datetime import datetime
def create_new_session(connection_handler, session_tablename="session"):
"""
Creates a new session record into the session datatable
:param connection_handler: the connection handler
:param session_tablename: the session tablename (default: session)
... | f955ed02b7292aab6d71b96a0412aa56c1212999 | 3,636,801 |
def splitData(y, tx, ratios=[0.4, 0.1]):
""" Split the dataset into train, test and validation sets """
indices = np.arange(len(y))
np.random.shuffle(indices)
splits = (np.array(ratios) * len(y)).astype(int).cumsum()
training_indices, validation_indices, test_indices = np.split(indices, splits)
... | 6cbf2907f32906779f8cf4193336cb867e66bf14 | 3,636,802 |
def conv_compare(node1, node2):
"""Compares two conv_general_dialted nodes."""
assert node1["op"] == node2["op"] == "conv_general_dilated"
params1, params2 = node1["eqn"].params, node2["eqn"].params
for k in ("window_strides", "padding", "lhs_dilation", "rhs_dilation",
"lhs_shape", "rhs_shape"):
... | cd7bad7d298e5f3faa971a9c968b3cd3a6a27812 | 3,636,803 |
import json
def render_zones(zones: dict):
"""Render the zones based on accept header"""
requested_types = bottle.request.headers.get("Accept")
if "application/json" in requested_types:
output = json.dumps(zones)
content_type = "application/json"
elif "text/html" in requested_types:
... | c4bbbef191fc6507d13bddcb4ffe1d51124a3e18 | 3,636,804 |
from typing import Union
import numbers
def less(left: Tensor, right: Union[Tensor, np.ndarray,numbers.Number],dtype=Dtype.float32,name='less'):
"""Elementwise 'less' comparison of two tensors. Result is 1 if left < right else 0.
Args:
left: left side tensor
right: right side tensor
d... | 4848bbbadf5ff789c1b406b1b53f0de4b436b155 | 3,636,805 |
def load_sample_image(image_name):
"""Load the numpy array of a single sample image
Read more in the :ref:`User Guide <sample_images>`.
Parameters
----------
image_name : {`china.jpg`, `flower.jpg`}
The name of the sample image loaded
Returns
-------
img : 3D array
The... | 7a1131f49a04343a4d8c0dbfed1099420ee906fb | 3,636,806 |
from datetime import datetime
def read_date_from_GPM(infile, radar_lat, radar_lon):
"""
Extract datetime from TRMM HDF files.
Parameters:
===========
infile: str
Satellite data filename.
radar_lat: float
Latitude of ground radar
radar_lon: float
Longitude of ground... | 1366ad4da74b5c31f88435257bbf2c6bc4662b92 | 3,636,807 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.