content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import requests
def get_auth():
"""
POST request to users/login, returns auth token
"""
try:
url_user_login = f"https://{url_core_data}/users/login"
json = {
"username": creds_name,
"password": creds_pw
}
headers = {
... | 86aa225a8c856dd46ece14d982a24b32a52a87ef | 14,890 |
def vector_between_points(P, Q):
""" vector between initial point P and terminal point Q """
return vector_subtract(Q, P); | de86c29dfe8c75b31040942d7195b8b92d731106 | 14,891 |
import time
def before_train(loaded_train_model, train_model, train_sess, global_step, hparams, log_f):
"""Misc tasks to do before training."""
stats = init_stats()
info = {"train_ppl": 0.0, "speed": 0.0, "avg_step_time": 0.0,
"avg_grad_norm": 0.0, "avg_train_sel": 0.0,
"learning_r... | d333808bec0771e74d709f859b7423b9e561703f | 14,892 |
def methodInDB(method_name, dict_link, interface_db_cursor): #checks the database to see if the method exists already
"""
Method used to check the database to see if a method exists in the database
returns a list [Boolean True/False of if the method exists in the db, dictionary link/ID]
"""
crsr = ... | 8dc3ecc256b696a06906e63a461c241ff429e8ae | 14,894 |
def dict_to_image(screen):
""" Takes a dict of room locations and their block type output by RunGame.
Renders the current state of the game screen.
"""
picture = np.zeros((51, 51))
# Color tiles according to what they represent on screen:.
for tile in screen:
pos_x, ... | 5657d3984a035d11854ef2b1f6dff642a00032a1 | 14,895 |
def can_fuse_to(wallet):
"""We can only fuse to wallets that are p2pkh with HD generation. We do
*not* need the private keys."""
return isinstance(wallet, Standard_Wallet) | 1ee8693d7457591a64057a4913d9739f96319e7a | 14,897 |
def _build_context(hps, encoder_outputs):
"""Compute feature representations for attention/copy.
Args:
hps: hyperparameters.
encoder_outputs: outputs by the encoder RNN.
Returns:
Feature representation of [batch_size, seq_len, decoder_dim]
"""
with tf.variable_scope("memory_context"):
contex... | 6ce8a9a7845376f1804610d371d23b32fa9991f7 | 14,898 |
from typing import Union
def rf_local_divide(left_tile_col: Column_type, rhs: Union[float, int, Column_type]) -> Column:
"""Divide two Tiles cell-wise, or divide a Tile's cell values by a scalar"""
if isinstance(rhs, (float, int)):
rhs = lit(rhs)
return _apply_column_function('rf_local_divide', le... | 76740879461e6dea302568d3bebc4dd6d7eb9363 | 14,899 |
def check_dependencies_ready(dependencies, start_date, dependencies_to_ignore):
"""Checks if every dependent pipeline has completed
Args:
dependencies(dict): dict from id to name of pipelines it depends on
start_date(str): string representing the start date of the pipeline
dependencies_... | 8ff01e54e3dae4110e7bd06accbc01b73148f4c3 | 14,900 |
def factor_returns(factor_data, demeaned=True, group_adjust=False):
"""
计算按因子值加权的投资组合的收益
权重为去均值的因子除以其绝对值之和 (实现总杠杆率为1).
参数
----------
factor_data : pd.DataFrame - MultiIndex
一个 DataFrame, index 为日期 (level 0) 和资产(level 1) 的 MultiIndex,
values 包括因子的值, 各期因子远期收益, 因子分位数,
因子分组(... | 127f26e20ca14cae5d9fc2e444ab93d98cc6b8c4 | 14,901 |
def create_input_lambda(i):
"""Extracts off an object tensor from an input tensor"""
return Lambda(lambda x: x[:, i]) | b574e5659723f5394590cedcc4305f9fade5021e | 14,902 |
def create_model_talos(params, time_steps, num_features, input_loss='mae', input_optimizer='adam',
patience=3, monitor='val_loss', mode='min', epochs=100, validation_split=0.1):
"""Uses sequential model class from keras. Adds LSTM layer. Input samples, timesteps, features.
Hyperparameters inclu... | e17becc7b95b07fb15059e8ef76a70fbfbd68b88 | 14,903 |
def ortho_init(scale=1.0):
"""
Orthogonal initialization for the policy weights
:param scale: (float) Scaling factor for the weights.
:return: (function) an initialization function for the weights
"""
# _ortho_init(shape, dtype, partition_info=None)
def _ortho_init(shape, *_, **_kwargs):
... | d82af86b0650c4588b1f4a22fea809cda1e72959 | 14,905 |
def get_rde_model(rde_version):
"""Get the model class of the specified rde_version.
Factory method to return the model class based on the specified RDE version
:param rde_version (str)
:rtype model: NativeEntity
"""
rde_version: semantic_version.Version = semantic_version.Version(rde_version)... | 0ce32c2649ebdac84f6a000e40df8e85715733e1 | 14,906 |
import math
def pnorm(x, mu, sd):
"""
Normal distribution PDF
Args:
* scalar: variable
* scalar: mean
* scalar: standard deviation
Return type: scalar (probability density)
"""
return math.exp(- ((x - mu) / sd) ** 2 / 2) / (sd * 2.5) | 08896264db17493bc299a3e69b781c28429ef08f | 14,907 |
import numpy as np
import math
def getTransformToPlane(planePosition, planeNormal, xDirection=None):
"""Returns transform matrix from World to Plane coordinate systems.
Plane is defined in the World coordinate system by planePosition and planeNormal.
Plane coordinate system: origin is planePosition, z axis is p... | 19073b3fefdb75a92ccc812538078e1d5ad72d75 | 14,908 |
def jp_runtime_dir(tmp_path):
"""Provides a temporary Jupyter runtime dir directory value."""
return mkdir(tmp_path, "runtime") | 17794c4b702d97d4040d89909452df5e4dd1344e | 14,909 |
def _softmax(X, n_samples, n_classes):
"""Derive the softmax of a 2D-array."""
maximum = np.empty((n_samples, 1))
for i in prange(n_samples):
maximum[i, 0] = np.max(X[i])
exp = np.exp(X - maximum)
sum_ = np.empty((n_samples, 1))
for i in prange(n_samples):
sum_[i, 0] = np.sum(exp... | 8544a79dc52601e882383164ae34dd05d893ed2a | 14,910 |
from typing import OrderedDict
from typing import MutableMapping
def merge_dicts(dict1, dict2, dict_class=OrderedDict):
"""Merge dictionary ``dict2`` into ``dict1``"""
def _merge_inner(dict1, dict2):
for k in set(dict1.keys()).union(dict2.keys()):
if k in dict1 and k in dict2:
... | b2013f888dfc3a1713153c7aa8a00ce4044fba07 | 14,911 |
import numpy
def jaccard_overlap_numpy(box_a: numpy.ndarray, box_b: numpy.ndarray) -> numpy.ndarray:
"""Compute the jaccard overlap of two sets of boxes. The jaccard overlap
is simply the intersection over union of two boxes.
E.g.:
A ∩ B / A ∪ B = A ∩ B / (area(A) + area(B) - A ∩ B)
Args:
box... | 4fc79406724815a9d5982ac94344ca2e45993980 | 14,912 |
import glob
def find_pkg(pkg):
""" Find the package file in the repository """
candidates = glob.glob('/repo/' + pkg + '*.rpm')
if len(candidates) == 0:
print("No candidates for: '{0}'".format(pkg))
assert len(candidates) == 1
return candidates[0] | ac91f34ed7accd2c81e1c68e143319998de9cdf3 | 14,913 |
import random
def random_choice(lhs, ctx):
"""Element ℅
(lst) -> random element of a
(num) -> Random integer from 0 to a
"""
if vy_type(lhs) == NUMBER_TYPE:
return random.randint(0, lhs)
return random.choice(iterable(lhs, ctx=ctx)) | 9b4251a9b1d590742cab847035a2ef78c565af70 | 14,914 |
def ask(choices,
message="Choose one from [{choices}]{default}{cancelmessage}: ",
errormessage="Invalid input", default=None,
cancel=False, cancelkey='c',
cancelmessage='press {cancelkey} to cancel'):
"""
ask is a shorcut instantiate PickOne and use .ask method
"""
return PickOne(ch... | 09f1951a72800bb710167bbf0b2695b94a6370ec | 14,915 |
def _check_eq(value):
"""Returns a function that checks whether the value equals a
particular integer.
"""
return lambda x: int(x) == int(value) | 4d2a02727afd90dbc012d252b01ed72f745dc564 | 14,918 |
def query_data(session, agency_code, start, end, page_start, page_stop):
""" Request D2 file data
Args:
session - DB session
agency_code - FREC or CGAC code for generation
start - Beginning of period for D file
end - End of period for D file
page_... | f555685ae4072aec14db29ee3b3425f1b0de5adb | 14,919 |
def ProfitBefTax(t):
"""Profit before Tax"""
return (PremIncome(t)
+ InvstIncome(t)
- BenefitTotal(t)
- ExpsTotal(t)
- ChangeRsrv(t)) | 4787d1c34698beb1e493968e5302defdf1416516 | 14,920 |
def myCommand():
"""
listens to commands spoken through microphone (audio)
:returns text extracted from the speech which is our command
"""
r = sr.Recognizer()
with sr.Microphone() as source:
print('Say something...')
r.pause_threshold = 1
r.adjust_for_ambient_noise(sourc... | ce0b3c01efa1fe0aa704183e6293d4ed7e5170e9 | 14,921 |
def hammer(ohlc_df):
"""returns dataframe with hammer candle column"""
df = ohlc_df.copy()
df["hammer"] = (((df["high"] - df["low"])>3*(df["open"] - df["close"])) & \
((df["close"] - df["low"])/(.001 + df["high"] - df["low"]) > 0.6) & \
((df["open"] - df["low"])/(.0... | 7445d20e27ad2e34702868eaad028c86e71ac3a7 | 14,922 |
def calcPhase(star,time):
"""
Calculate the phase of an orbit, very simple calculation but used quite a lot
"""
period = star.period
phase = time/period
return phase | 4b282d9e4fdb76a4358d895ba30b902328ce030c | 14,923 |
def advanced_search():
"""
Get a json dictionary of search filter values suitable for use with the javascript queryBuilder plugin
"""
filters = [
dict(
id='name',
label='Name',
type='string',
operators=['equal', 'not_equal', 'be... | 73453941eff4aa03def530691b52b109b1fe0a76 | 14,924 |
def rdp_rec(M, epsilon, dist=pldist):
"""
Simplifies a given array of points.
Recursive version.
:param M: an array
:type M: numpy array
:param epsilon: epsilon in the rdp algorithm
:type epsilon: float
:param dist: distance function
:type dist: function with signature ``f(point, sta... | 2518ef902bb9d7e696145e86746804a6fca115f8 | 14,925 |
from datetime import datetime
def secBetweenDates(dateTime0, dateTime1):
"""
:param dateTime0:
:param dateTime1:
:return: The number of seconds between two dates.
"""
dt0 = datetime.strptime(dateTime0, '%Y/%m/%d %H:%M:%S')
dt1 = datetime.strptime(dateTime1, '%Y/%m/%d %H:%M:%S')
timeDi... | d9e2f839d8a7c10fbde8009ea1f69db56a222426 | 14,926 |
def iframe_home(request):
""" Página inicial no iframe """
# Info sobre pedidos de fabricação
pedidosFabricacao = models.Pedidofabricacao.objects.filter(
hide=False
).exclude(
fkid_statusfabricacao__order=3
).order_by(
'-fkid_statusfabricacao', 'dt_fim_maturacao'
)
... | b8db02d3b8a019bdc23fd369ab4ccc96e9b77437 | 14,927 |
def inv(n: int, n_bits: int) -> int:
"""Compute the bitwise inverse.
Args:
n: An integer.
n_bits: The bit-width of the integers used.
Returns:
The binary inverse of the input.
"""
# We should only invert the bits that are within the bit-width of the
# integers we use. W... | 5be1eaf13490091096b8cd13fdbcdbbbe43760da | 14,929 |
def _render_flight_addition_page(error):
"""
Helper to render the flight addition page
:param error: Error message to display on the page or None
:return: The rendered flight addition template
"""
return render_template("flights/add.html",
airlines=list_airlines(),
... | 916b14fa3b829b4fa6e0720d64bcdd74aab476ce | 14,930 |
def get_node_index(glTF, name):
"""
Return the node index in the glTF array.
"""
if glTF.get('nodes') is None:
return -1
index = 0
for node in glTF['nodes']:
if node['name'] == name:
return index
index += 1
return -1 | cb0c6a727e9786467861d0ea622462264269814a | 14,931 |
def online_user_count(filter_user=None):
"""
Returns the number of users online
"""
return len(_online_users()) | 5ab03f1ca6738925847b338e956a0c8afbbc4d7d | 14,932 |
def get_latest_version_url(start=29, template="http://unicode.org/Public/cldr/{}/core.zip"):
"""Discover the most recent version of the CLDR dataset.
Effort has been made to make this function reusable for other URL numeric URL schemes, just override `start` and
`template` to iteratively search for the latest vers... | a93ff3081e6e0a5a507d79a5340b69b2be670f88 | 14,933 |
def import_module(name, package=None):
"""Import a module.
The 'package' argument is required when performing a relative import. It
specifies the package to use as the anchor point from which to resolve the
relative import to an absolute import.
"""
level = 0
if name.startswith('.'):
... | aeed1a00ec9149923c9be73a2346de4664ff98e3 | 14,935 |
import requests
from bs4 import BeautifulSoup
def get_image_links_from_imgur(imgur_url):
"""
Given an imgur URL, return a list of image URLs from it.
"""
if 'imgur.com' not in imgur_url:
raise ValueError('given URL does not appear to be an imgur URL')
urls = []
response = requests.get(... | 19d8f994cd1730c23fdf5d6105e8db916da67d15 | 14,937 |
def filter_ignored_images(y_true, y_pred, classification=False):
""" Filter those images which are not meaningful.
Args:
y_true: Target tensor from the dataset generator.
y_pred: Predicted tensor from the network.
classification: To filter for classification or
regression.
... | a3f5e10c2f2961eafe734bc27c53e23294ee9eea | 14,938 |
def context_data_from_metadata(metadata):
""" Utility function transforming `metadata` into a context data dictionary.
Metadata may have been encoded at the client by `metadata_from_context_data`, or
it may be "normal" GRPC metadata. In this case, duplicate values are allowed;
they become a list in the... | 7b801b5835f7146a2ab163b83741113a039cb6bd | 14,939 |
def plot_results_fit(
xs,
ys,
covs,
line_ax,
lh_ax=None,
outliers=None,
auto_outliers=False,
fit_includes_outliers=False,
report_rho=False,
):
"""Do the fit and plot the result.
Parameters
----------
sc_ax : axes to plot the best fit line
lh_ax : axes to plot th... | 695d7f47fa8319f9fd085b51e4bb031acee0079a | 14,941 |
def check_for_features(cmph5_file, feature_list):
"""Check that all required features present in the cmph5_file. Return
a list of features that are missing.
"""
aln_group_path = cmph5_file['AlnGroup/Path'][0]
missing_features = []
for feature in feature_list:
if feature not in cmph5_fil... | 2d51e1389e6519607001ad2b0006581e6a876ddd | 14,942 |
def inverse(a: int, b: int) -> int:
"""
Calculates the modular inverse of a in b
:param a:
:param b:
:return:
"""
_, inv, _ = gcd_extended(a, b)
return inv % b | 5bde17e2526d5d8f940c8c384c2962dee8cb7188 | 14,943 |
def build_md2po_events(mkdocs_build_config):
"""Build dinamically those mdpo events executed at certain moments of the
Markdown file parsing extrating messages from pages, different depending on
active extensions and plugins.
"""
_md_extensions = mkdocs_build_config['markdown_extensions']
md_ex... | 5dd4cf7afe9168d4b110c197454b237f9267ce0e | 14,944 |
def is_three(x):
"""Return whether x is three.
>>> search(is_three)
3
"""
return x == 3 | a57266892eebf684945d0d841ede67965c751f1a | 14,945 |
def get_task_id(prefix, path):
"""Generate unique tasks id based on the path.
:parma prefix: prefix string
:type prefix: str
:param path: file path.
:type path: str
"""
task_id = "{}_{}".format(prefix, path.rsplit("/", 1)[-1].replace(".", "_"))
return get_unique_task_id(task_id) | 965b5df1d1cc80d489d4a003f453e53a96d4c38e | 14,946 |
def rot_permutated_geoms(geo, saddle=False, frm_bnd_key=[], brk_bnd_key=[], form_coords=[]):
""" convert an input geometry to a list of geometries
corresponding to the rotational permuations of all the terminal groups
"""
gra = graph(geo, remove_stereo=True)
term_atms = {}
all_hyds = []
... | 347e358b311725801587a2174f62084b066b414e | 14,947 |
def wasserstein_loss(y_true, y_pred):
""" for more detail: https://github.com/keras-team/keras-contrib/blob/master/examples/improved_wgan.py"""
return K.mean(y_true * y_pred) | bc99572e298a565e68fe41d38e1becb72b4c304d | 14,948 |
from typing import Optional
def call_and_transact(
contract_function: ContractFunction, transaction_params: Optional[TxParams] = None,
) -> HexBytes:
""" Executes contract_function.{call, transaction}(transaction_params) and returns txhash """
# First 'call' might raise an exception
contract_function.... | 851904f85d757faa548f8988ffcdfe97188de288 | 14,949 |
import re
def compress_sparql(text: str, prefix: str, uri: str) -> str:
"""
Compress given SPARQL query by replacing all instances of the given uri with the given prefix.
:param text: SPARQL query to be compressed.
:param prefix: prefix to use as replace.
:param uri: uri instance to be replaced.
... | b86ceebadb262730fb4dec90b43e04a09d9c9541 | 14,951 |
from operator import mod
def easter(g_year):
"""Return fixed date of Easter in Gregorian year g_year."""
century = quotient(g_year, 100) + 1
shifted_epact = mod(14 +
11 * mod(g_year, 19) -
quotient(3 * century, 4) +
quotient(5 + (8 * ... | e084e9a0ae755065bf7704da6aa1506894ad958e | 14,952 |
def _with_generator_error_translation(code_to_exception_class_func, func):
"""Same wrapping as above, but for a generator"""
@funcy.wraps(func)
def decorated(*args, **kwargs):
"""Execute a function, if an exception is raised, change its type if necessary"""
try:
for x in func(*a... | fbd0491b2f7d68ecfaa5405a02203c3c8294bdc2 | 14,953 |
import requests
def openei_api_request(
data,
):
"""Query the OpenEI.org API.
Args:
data (dict or OrderedDict): key-value pairs of parameters to post to the
API.
Returns:
dict: the json response
"""
# define the Overpass API URL, then construct a GET-style URL as ... | c02ef34fd3fc8327a0debc954eb1a211dc161978 | 14,954 |
def generate_content(vocab, length):
"""Generate a random passage.
Pass in a dictionary of words from a text document and a specified
length (number of words) to return a randomized string.
"""
new_content = []
pair = find_trigram(vocab)
while len(new_content) < length:
third = find... | 5897c507281ffccddfb28880a0c5678b0fab7363 | 14,955 |
def transform_generic(inp: dict, out, met: ConfigurationMeta) -> list:
""" handle_generic is derived from P -> S, where P and S are logic expressions.
This function will use a generic method to transform the logic expression P -> S
into multiple mathematical constraints. This is done by first conv... | 0b87c001a94fb9ad3198651d0948bddf7d477b1b | 14,956 |
def generate_mprocess_from_name(
c_sys: CompositeSystem, mprocess_name: str, is_physicality_required: bool = True
) -> MProcess:
"""returns MProcess object specified by name.
Parameters
----------
c_sys : CompositeSystem
CompositeSystem of MProcess.
mprocess_name : str
name of t... | 8be8f79610e424342fae3c6ddbccf2177d0941b1 | 14,957 |
from vtk.util.numpy_support import vtk_to_numpy, numpy_to_vtk
def convert_polydata_to_image_data(poly, ref_im, reverse=True):
"""
Convert the vtk polydata to imagedata
Args:
poly: vtkPolyData
ref_im: reference vtkImage to match the polydata with
Returns:
output: resulted vtkI... | 75a8780d287b5c2f5b2cc81d735859d56a5f9641 | 14,958 |
def matplot(x, y, f, vmin=None, vmax=None, ticks=None, output='output.pdf', xlabel='X', \
ylabel='Y', diverge=False, cmap='viridis', **kwargs):
"""
Parameters
----------
f : 2D array
array to be plotted.
extent: list [xmin, xmax, ymin, ymax]
Returns
-------
Save a ... | f50d7f7d8ebcb87a993001042f48afcc69616393 | 14,959 |
def createNewClasses(df, sc, colLabel):
"""
Divide the data into classes
Parameters
----------
df: Dataframe
Spark Dataframe
sc: SparkContext object
SparkContext object
colLabel: List
Items that considered Label
logs_dir: string
Directory for... | e28e5240bca65bd602234b6560b58d934012f530 | 14,960 |
def scan_usb(device_name=None):
""" Scan for available USB devices
:param device_name: The device name (MX6DQP, MX6SDL, ...) or USB device VID:PID value
:rtype list
"""
if device_name is None:
objs = []
devs = RawHid.enumerate()
for cls in SDP_CLS:
for dev in dev... | 0178537f65d46b5e1333ef4ee8d590c68d619019 | 14,961 |
def _boolrelextrema(
data, comparator, axis=0, order: tsutils.IntGreaterEqualToOne = 1, mode="clip"
):
"""Calculate the relative extrema of `data`.
Relative extrema are calculated by finding locations where
comparator(data[n],data[n+1:n+order+1]) = True.
Parameters
----------
data: ndarray... | b9315675845b27d77b39e1b0a8facd8cdda955c1 | 14,962 |
from bs4 import BeautifulSoup
def parse_description(offer_markup):
""" Searches for description if offer markup
:param offer_markup: Body from offer page markup
:type offer_markup: str
:return: Description of offer
:rtype: str
"""
html_parser = BeautifulSoup(offer_markup, "html.parser")
... | 30464ca8ac313f4998fb067b46c3ec17e567da50 | 14,963 |
def return_args():
"""Return a parser object."""
_parser = ArgumentParser(add_help=True, description=(
"Translate msgid's from a POT file with Google Translate API"))
_parser.add_argument('-f', '--file', action='store', required=True,
help="Get the POT file name.")
_pars... | 45b608f25cbf9823dcd2dcaa070eaf97daf52895 | 14,964 |
def get_df_tau(plot_dict, gen_err):
"""
Return a dataframe of the kendall tau's coefficient for different methods
"""
# tau, p_value = compute_tau(result_dict[err], plot_dict['avg_clusters'], inverse=True)
# taus, pvalues, names, inverses = [tau], [p_value], ['cc'], ['True']
taus, pvalues, names... | 642af1f675aa1b323f8221cebb81aa98e4a9d188 | 14,965 |
def traverse(graph, priorities):
"""Return a sequence of all the nodes in the graph by greedily choosing high 'priority' nodes
before low 'priority' nodes."""
reachable = PriorityContainer()
visited = {}
# start by greedily choosing the highest-priority node
current_node = max(priorities.items... | 255c14348a1fb7ba33e85ad36537529434ce2865 | 14,966 |
def build_dataset(dataset_name, set_name, root_path, transforms=None):
"""
:param dataset_name: the name of dataset
:param root_path: data is usually located under the root path
:param set_name: "train", "valid", "test"
:param transforms:
:return:
"""
if "cameo_half_year" in dataset_name... | eb7a3090e03c95031f04d6f13f165c02eef8850c | 14,967 |
def remove_characters(text, characters_to_remove=None):
"""
Remove various auxiliary characters from a string.
This function uses a hard-coded string of 'undesirable'
characters (if no such string is provided),
and removes them from the text provided.
Parameters:
--... | d2864983bfa3d58c631ff91a8719d45392f4bf42 | 14,968 |
def changePrev ( v, pos, findPat, changePat, bodyFlag = 1 ):
"""
changePrev: use string.rfind() to change text in a Leo outline.
v the vnode to start the search.
pos the position within the body text of v to start the search.
findPat the search string.
changePat the replacement string.
bodyFlag true: cha... | 5c45b08b6aba5f7e699e1864e9a44af457b46d17 | 14,969 |
def trait_colors(rows):
"""Make tags for HTML colorizing text."""
backgrounds = defaultdict(lambda: next(BACKGROUNDS))
for row in rows:
for trait in row['traits']:
key = trait['trait']
if key not in ('heading',):
_ = backgrounds[key]
return backgrounds | 851783d8fa5acca3b9c7f1f3ea1e59466f056ad0 | 14,971 |
import json
def webhook():
""" CI with GitHub & PythonAnywhere
Author : Aadi Bajpai
https://medium.com/@aadibajpai/deploying-to-pythonanywhere-via-github-6f967956e664 """
try:
event = request.headers.get('X-GitHub-Event')
# Get payload from GitHub webhook request
payloa... | 998a82897b2aa36dfef6e8125b34964b47218621 | 14,972 |
def pension_drawdown(months, rate, monthly_drawdown, pension_pot):
""" Returns the balance left in the pension pot after drawing an income for the given nr of months """
return monthly_growth(months, rate, -monthly_drawdown, pension_pot) | 2b2d811bbe134eca71d2965de4b06a62a71ccf85 | 14,974 |
def bytesToUInt(bytestring):
"""Unpack 4 byte string to unsigned integer, assuming big-endian byte order"""
return _doConv(bytestring, ">", "I") | f3d645d71b3503b8e5b4b052fe33e839a82c3782 | 14,975 |
def use(*authenticator_classes):
""" A decorator to attach one or more :class:`Authenticator`'s to the decorated class.
Usage:
from thorium import auth
@auth.use(BasicAuth, CustomAuth)
class MyEngine(Endpoint):
...
OR
@auth.use(BasicAuth)
@auth.use... | 27aeb7711c842540a1ed77a76cebeb61e0342f1e | 14,976 |
def list_standard_models():
"""Return a list of all the StandardCellType classes available for this simulator."""
standard_cell_types = [obj for obj in globals().values() if isinstance(obj, type) and issubclass(obj, standardmodels.StandardCellType)]
for cell_class in standard_cell_types:
try:
... | 7c7d36c5931340ddca5dcad91b34b9e9deb6ef1b | 14,977 |
def AchievableTarget(segments,target,Speed):
"""
The function checks if the car can make the required curvature to reach the target, taking into account its speed
Return [id, radius, direction}
id = 1 -> achievable else id =0
direction = 1 -> right ... | 1608847c224b5315cd668d650b52b9a6184c84ac | 14,978 |
import math
def mutual_information(co_oc, oi, oj, n):
"""
:param co_oc: Number of co occurrences of the terms oi and oj in the corpus
:param oi: Number of occurrences of the term oi in the corpus
:param oj: Number of occurrences of the term oi in the corpus
:param n: Total number of words in the c... | 76c27295c7e757282573eab71f2bb7cfd3df74cb | 14,980 |
def is_dark(color: str) -> bool:
"""
Whether the given color is dark of bright
Taken from https://github.com/ozh/github-colors
"""
l = 0.2126 * int(color[0:2], 16) + 0.7152 * int(color[2:4], 16) + 0.0722 * int(color[4:6], 16)
return False if l / 255 > 0.65 else True | 80fe2c4bd42b20fedff11ef200ae5ca246d4489d | 14,983 |
from datetime import datetime
def get_date_input_examples(FieldClass) -> list:
"""
Generate examples for a valid input value.
:param FieldClass: InputField
:return: List of input examples.
"""
r = []
for f in FieldClass.input_formats:
now = datetime.now()
r.append(now.strft... | e0b73aac49ac2bbd6423faa3e5e5ebfb81c2d7b7 | 14,984 |
def sve_logistic():
"""SVE of the logistic kernel for Lambda = 42"""
print("Precomputing SVEs for logistic kernel ...")
return {
10: sparse_ir.compute_sve(sparse_ir.LogisticKernel(10)),
42: sparse_ir.compute_sve(sparse_ir.LogisticKernel(42)),
10_000: sparse_ir.compute_sve(spa... | 774365aa9f17c66ea8a3296a08fe1d0972c82ad6 | 14,985 |
def post_team_iteration(id, team, organization=None, project=None, detect=None): # pylint: disable=redefined-builtin
"""Add iteration to a team.
:param id: Identifier of the iteration.
:type: str
:param team: Name or ID of the team.
:type: str
"""
organization, project = resolve_instance_an... | 78648eba53e50be7023ac88f9a4ffe2635c74d5b | 14,986 |
import collections
def JoinTypes(types):
"""Combine a list of types into a union type, if needed.
Leaves singular return values alone, or wraps a UnionType around them if there
are multiple ones, or if there are no elements in the list (or only
NothingType) return NothingType.
Arguments:
types: A list... | 0d43551a2882fa75a1827302811670fefe19433c | 14,987 |
def calc_nominal_strike(traces: np.ndarray):
"""
Gets the start and ending trace of the fault and ensures order for largest lon value first
Parameters
----------
traces: np.ndarray
Array of traces of points across a fault with the format [[lon, lat, depth],...]
"""
# Extract just la... | 21c5c2de8c136ac44cbea401dce79c84007fc4ac | 14,988 |
def merge_options(custom_options, **default_options):
"""
Utility function to merge some default options with a dictionary of custom_options.
Example: custom_options = dict(a=5, b=3)
merge_options(custom_options, a=1, c=4)
--> results in {a: 5, b: 3, c: 4}
"""
merged_option... | a1676c9304f3c231aefaeb107c8fb6f5a8251b26 | 14,989 |
def build_wall(game: Board, player: Player) -> float:
"""
Encourage the player to go the middle row and column of the board
to increase the chances of a partition in the later game
"""
position = game.get_player_location(player)
blanks = game.get_blank_spaces()
blank_vertical = [loc for loc... | 9309e152b704317442e646d2283c0b20041c55b9 | 14,990 |
from bs4 import BeautifulSoup
def get_menu_from_hzu_navigation():
"""
获取惠州学院官网的导航栏的 HTML 文本。
:return: 一个 ul 标签文本
"""
try:
html = urlopen("https://www.hzu.edu.cn/")
except HTTPError as e:
print(e)
print('The page is not exist or have a error in getting page.')
... | 1e0fab3402aeaca8bce3a93787f98a9360ffe49f | 14,991 |
def calc_user_withdraw_fee(user_id, amount):
"""手续费策略"""
withdraw_logs = dba.query_user_withdraw_logs(user_id, api_x.utils.times.utctoday())
if len(withdraw_logs) > 0:
return Decimal('2.00')
return Decimal('0.00') | a9d28ad6c3cb2cf801ac8fdcf67e3f9d2c804a67 | 14,992 |
def get_last_row(dbconn, tablename, n=1, uuid=None):
"""
Returns the last `n` rows in the table
"""
return fetch(dbconn, tablename, n, uuid, end=True) | 0c70b6fca976b4f97fb816279653e0c2bbd67d5c | 14,993 |
from typing import Optional
def get_start(period, reference_date: Optional[FlexDate] = None, strfdate="%Y-%m-%d") -> FlexDate:
"""
Returns the first day of the given period for the reference_date.
Period can be one of the following: {'year', 'quarter', 'month', 'week'}
If reference_date is instance of... | 53016712c6949291fe2e4e81de0ae993da4311c1 | 14,994 |
def prepare_lc_df(star_index, frame_info, magmatch, magx):
"""Prepare cleaned light curve data
Add mag, mag_err, magx, and magx_err to info
Remove nan values or too bright values in magx
Args:
star_index (int): index of the star
frame_info (DataFrame): info data
magmatch (array... | b99123fb5bd0b84a84576791d578b5ae91f05575 | 14,995 |
def _filter_nones(centers_list):
"""
Filters out `None` from input list
Parameters
----------
centers_list : list
List potentially containing `None` elements
Returns
-------
new_list : list
List without any `None` elements
"""
return [c for c in centers_list if... | 031e878ebc8028deea238f5ac902ca55dba72a6d | 14,996 |
import multiprocessing
import time
def exec_in_subprocess(func, *args, poll_interval=0.01, timeout=None, **kwargs):
""" Execute a function in a fork
Args:
func (:obj:`types.FunctionType`): function
* args (:obj:`list`): list of positional arguments for the function
poll_interval (:obj... | b04b506ced8f5e90489dd789ebd9f77fd4487d8a | 14,998 |
def get_cv_score_table(clf):
"""
Get a table (DataFrame) of CV parameters and scores for each combination.
:param clf: Cross-validation object (GridSearchCV)
:return:
"""
# Create data frame
df = pd.DataFrame(list(clf.cv_results_['params']))
# Add test scores
df['rank'] = clf.cv_r... | e1912b6545b0a6649fa66673d2fdd5dfd2b91cd5 | 14,999 |
def model_handle_check(model_type):
"""
Checks for the model_type and model_handle on the api function,
model_type is a argument to this decorator, it steals model_handle and checks if it is
present in the MODEL_REGISTER
the api must have model_handle in it
Args:
model_type: the "type"... | 1c2bab3399dff743fd1ca1a37971a4e71f5d5b8f | 15,000 |
def train_model_mixed_data(type_tweet, split_index, custom_tweet_data = pd.Series([]), stop_words = "english"):
"""
Fits the data on a Bayes model. Modified train_model() with custom splitting of data.
:param type_tweet:
:param split_index:
:param custom_tweet_data: if provided, this is used instea... | 4c7d4e29562b63ea53f1832af0841fb112c6596a | 15,001 |
import scipy
def _fit_curves(ns, ts):
"""Fit different functional forms of curves to the times.
Parameters:
ns: the value of n for each invocation
ts: the measured run time, as a (len(ns), reps) shape array
Returns:
scores: normalised scores for each function
coef... | 9a480869d930e27d9aa988455228e6197f87417a | 15,002 |
def isolate_integers(string):
"""Isolate positive integers from a string, returns as a list of integers."""
return [int(s) for s in string.split() if s.isdigit()] | cc95f7a37e3ae258ffaa54ec59f4630c600e84e1 | 15,003 |
def extractAFlappyTeddyBird(item):
"""
# A Flappy Teddy Bird
"""
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or 'preview' in item['title'].lower():
return None
if 'The Black Knight who was stronger than even the Hero' in item['title']:
return buildReleaseMess... | ca382caa9d1d9244424a39d1bc43c141b003691d | 15,004 |
def get_trainable_vars(name):
"""
returns the trainable variables
:param name: (str) the scope
:return: ([TensorFlow Variable])
"""
return tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope=name) | c45b075c739e8c86d6f1dadc0b1f4eacfb1d1505 | 15,005 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.