content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import requests
def make_new_paste(devkey, paste_text, user_key=None, paste_title=None, paste_format=None, paste_type=None, paste_expiry: int=None):
"""This function creates a new paste
on pastebin with the given arguments."""
data = {'api_dev_key': devkey, 'api_option': 'paste', 'api_paste_code': paste_... | 59b5be916c007e778ac0cf7a22b49b094f68dfaa | 18,000 |
def not_none(value):
"""
This function ensures that passed value is not None:
>>> schema = Schema(not_none)
>>> assert 1 == schema(1)
>>> try:
... schema(None)
... assert False, "an exception should've been raised"
... except MultipleInvalid:
... pass
"""
if val... | d3381c51d2d25edfbd56f6e1008d39056b0a0bda | 18,001 |
def j1c_dblprime(amplitudes):
"""Calculate j''1c angular observable"""
[_, _, _, _, a_0_l, a_0_r, a_00_l, a_00_r] = amplitudes
return (2 / tf.sqrt(3.0)) * (
tf.math.real(a_00_l * tf.math.conj(a_0_l) * bw_k700_k892) +
tf.math.real(a_00_r * tf.math.conj(a_0_r) * bw_k700_k892)
) | eead7c64e7033262aa98ccb966fd83a51419a065 | 18,002 |
def preprocess(img):
"""Changes RGB [0,1] valued image to BGR [0,255] with mean subtracted."""
mean_bgr = load_mean_bgr()
print 'mean blue', np.mean(mean_bgr[:, :, 0])
print 'mean green', np.mean(mean_bgr[:, :, 1])
print 'mean red', np.mean(mean_bgr[:, :, 2])
out = np.copy(img) * 255.0
out =... | 759110f2004315ab45aed1b18dbe5a1132366dd5 | 18,003 |
def profile_detail(request, username, template_name='userena/profile_detail.html', extra_context=None, **kwargs):
"""
Detailed view of an user.
:param username:
String of the username of which the profile should be viewed.
:param template_name:
String representing the template name tha... | c81d3cb2910e6358760c742c7b4081df4ed95a45 | 18,004 |
def prepare_ternary(figsize, scale):
"""Help function to ternary plot"""
fig, ax = plt.subplots(figsize=figsize)
tax = ternary.TernaryAxesSubplot(ax=ax, scale=scale)
ax.axis('off')
gm = 0.1 * scale
blw = 1
tlw = 1
# Draw Boundary and Gridlines
tax.boundary(linewidth=blw)
tax.grid... | 67b40d55d2296957cbe152bce69a5afcd22c2624 | 18,005 |
from typing import Dict
def parse_spreadsheet(hca_spreadsheet: Workbook, entity_dictionary: Dict):
"""
Parse the spreadsheet and fill the metadata with accessions.
:param hca_spreadsheet: Workbook object of the spreadsheet
:param entity_dictionary: Dictionary mapping by entity UUID to the proper arch... | 83607766eda5b0f9d5a6fc09035a12d29fb8b44c | 18,006 |
def decode(data):
"""Decode JSON serialized string, with possible embedded Python objects.
"""
return _decoder.decode(data) | b82d55eb7e704f9396aab3642314f172c2205a04 | 18,007 |
def p_correction(p_values):
"""
Corrects p_values for multiple testing.
:param p_values: Dictionary storing p_values with corresponding feature names as keys.
:return: DataFrame which shows the results of the analysis; p-value, corrected p-value and boolean indicating \
significance.
"""
p... | f1e7faa35176cdf41aca273413d7eb9d784dfdb1 | 18,008 |
def GetFlippedPoints3(paths, array):
"""same as first version, but doesnt flip locations: just sets to -1
used for random walks with self intersections - err type 6"""
# this may not work for double ups?
for i in paths:
for j in i: # for the rest of the steps...
array[j[0]][j[1]][j[... | ad0bc7a03e293beb2542ee555a341bdfc8706408 | 18,009 |
from typing import Callable
async def _silent_except(f: Callable, *args, **kwargs):
"""
Helper Function that calls a function or coroutine and returns its result excepting all errors
"""
try:
called = f(*args, **kwargs)
except:
return
if isawaitable(called):
try:
... | adaaf3e4a35dfed86d8fa83f8254396e0fa5245b | 18,010 |
def get_concat_h(im1, im2):
"""Concatenate two images horizontally."""
dst = Image.new("RGB", (im1.width + im2.width, im1.height))
dst.paste(im1, (0, 0))
dst.paste(im2, (im1.width, 0))
return dst | 60c67011c25ace5e0491bc365256364a9b677798 | 18,011 |
def get_taxname(taxid):
"""Return scientific name for NCBI Taxonomy ID."""
if get_taxname.id_name_map is None:
get_taxname.id_name_map = load_taxid_name_map('data/taxnames.tsv')
if get_taxname.id_name_map is None: # assume fail, fallback
get_taxname.id_name_map = TAXID_NAME_MAP
... | 8a42b542fef9a003e7f40542513d8d4a9d5d8e88 | 18,012 |
import os
def _get_movies(dir):
"""Gets the movies from the specified directory"""
movieList = []
directories = os.listdir(dir)
for d in directories:
# We need to skip past directories without instruction sets
if '__' not in d:
continue
files = os.listdir("{root}/{... | b3624580b364b357999288f8d9ddffa43cfebb3a | 18,013 |
def lrfn(epoch):
"""
lrfn(epoch)
This function creates a custom piecewise linear-exponential learning rate function for a custom learning rate scheduler. It is linear to a max, then exponentially decays
* INPUTS: current `epoch` number
* OPTIONAL INPUTS: None
* GLOBAL INPUTS:`START_LR`, `MIN_LR... | f71e776e07ac9f4be5802127e8c9ca84e864de58 | 18,014 |
import numbers
def get_balances():
"""
Get the balances of the configured validator (if possible)
"""
balances = account.get_balance_on_all_shards(validator_config['validator-addr'], endpoint=node_config['endpoint'])
for bal in balances:
bal['balance'] = float(numbers.convert_atto_to_one(b... | ed79137e7eb8482f86246174b1bf107229c59b90 | 18,015 |
import collections
def _make_ordered_node_map(
pipeline: pipeline_pb2.Pipeline
) -> 'collections.OrderedDict[str, pipeline_pb2.PipelineNode]':
"""Prepares the Pipeline proto for DAG traversal.
Args:
pipeline: The input Pipeline proto, which must already be topologically
sorted.
Returns:
An O... | 04d766081bffe000509a70a43208b6998b764a49 | 18,016 |
def energy(_x, _params):
"""Kinetic and Potential Energy of point mass pendulum.
_x is an array/list in the following order:
q1: Angle of first pendulum link relative to vertical (0 downwards)
u1: A[1] measure number of the inertial angular velocity of the first link.
_params is an array... | 0796149bab5a5a36717a67477661633eaf3a29c2 | 18,017 |
import math
def gelu(input_tensor):
"""Gaussian Error Linear Unit.
This is a smoother version of the RELU.
Original paper: https://arxiv.org/abs/1606.08415
Args:
input_tensor: float Tensor to perform activation.
Returns:
`input_tensor` with the GELU activation applied.
"""
#... | fd6de5888839521118c42d2e046b526f7025c70d | 18,018 |
import torch
def KPConv_ops(query_points,
support_points,
neighbors_indices,
features,
K_points,
K_values,
KP_extent,
KP_influence,
aggregation_mode):
"""
This function creates a graph of op... | 29fbb193fef31cdd3bdfcf4df212c56eae32cb3e | 18,019 |
def kerneleval(X_test, X_train, kernel):
"""
This function computes the pariwise distances between
each row in X_test and X_train using the kernel
specified in 'kernel'
X_test, X_train: 2d np.arrays
kernel: kernel parameters
"""
if kernel is None:
return X_train
fn = kernel... | 7cdba3af72dab288c9efac757905c51ed5f9a5f6 | 18,020 |
def aks_show_snapshot_table_format(result):
"""Format a snapshot as summary results for display with "-o table"."""
return [_aks_snapshot_table_format(result)] | 174deb4bdbe1da27826c89b4bd187e5aa8a00216 | 18,021 |
from typing import List
from typing import Dict
from typing import Any
import subprocess
def get_all_monitors() -> List[Dict[str, Any]]:
"""
:return: all monitors array list sorted from left to right.
i.e: [
{'hr': 1366, 'vr': 768, 'ho': 0, 'vo': 914, 'name': 'eDP-1-1'},
{'hr': 2560, 'vr':... | 29e6dc676bf52f8a4c15fd94a6bed8422fef594f | 18,022 |
def poly_prem(f, g, *symbols):
"""Returns polynomial pseudo-remainder. """
return poly_pdiv(f, g, *symbols)[1] | 4360e2bb4afc7d49f12b411aa18d2d5a1786306b | 18,023 |
def gen_input_code(question, id):
"""
Returns the html code for rendering the appropriate input
field for the given question.
Each question is identified by name=id
"""
qtype = question['type']
if qtype == 'text':
return """<input type="text" class="ui text" name="{0}"
... | b76bea45c0ce847d664a38694732ef0b75c2a53c | 18,024 |
def orbit_position(data, body='sun'):
"""calculate orbit position of sun or moon for instrument position at each time in 'data' using :class:`ephem`
Args:
data: :class:`xarray.Dataset`, commonly Measurement.data
body (optional): name of astronomical body to calculate orbit from ('sun' or 'moon'... | 98ab63c20026d83010b10db7ef141d6f1c9bf55f | 18,025 |
def list_inventory (inventory):
"""
:param inventory: dict - an inventory dictionary.
:return: list of tuples - list of key, value pairs from the inventory dictionary.
"""
result = []
for element, quantity in inventory.items():
if quantity > 0:
result.append ((element, qua... | 264f8cde11879be8ace938c777f546974383122c | 18,026 |
def wsd_is_duplicated_msg(msg_id):
"""
Check for a duplicated message.
Implements SOAP-over-UDP Appendix II Item 2
"""
if msg_id in wsd_known_messages:
return True
wsd_known_messages.append(msg_id)
if len(wsd_known_messages) > WSD_MAX_KNOWN_MESSAGES:
wsd_known_messages.popl... | acd0c1b7de00e6e5ef2a04ff15c1906a5c543089 | 18,027 |
import matplotlib.pyplot as plt
def match_diagnostic_plot(V1, V2, pair_ix, tf=None, new_figure=False):
"""
Show the results of the pair matching from `match_catalog_quads`.
"""
if new_figure:
fig = plt.figure(figsize=[4,4])
ax = fig.add_subplot(111)
else:
ax = plt.gca(... | 7af49a4b7ced3c0d310a6e5b4f623ef93698fa12 | 18,028 |
import json
def sliding_tile_state():
"""
Return the current state of the puzzle
:return: JSON object representing the state of the maze puzzle
"""
json_state = {'sliding_tile': sliding_tile.array(), 'solver': sliding_tile_str_solver, 'steps': sliding_tile_steps,
'search_steps': ... | 8438ab4066e4a70b33873fee39667251da0823fc | 18,029 |
import json
def _json_to_numpy(string_like, dtype=None): # type: (str) -> np.array
"""Convert a JSON object to a numpy array.
Args:
string_like (str): JSON string.
dtype (dtype, optional): Data type of the resulting array. If None, the dtypes will be determined by the
... | accdb28572ed13e6e977d569a69e4dfe27e22e21 | 18,030 |
import json
import time
def connect(**kwargs):
"""
A strategy to connect a bot.
:param kwargs: strategy, listener, and orders_queue
:return: the input strategy with a report
"""
strategy = kwargs['strategy']
listener = kwargs['listener']
orders_queue = kwargs['orders_queue']
asset... | fd2c2637e9eb02356e441994d214d86ec77f56f1 | 18,031 |
def create_env(env, render=False, shared=False, maddpg=False, evaluate=False):
"""Return, and potentially create, the environment.
Parameters
----------
env : str or gym.Env
the environment, or the name of a registered environment.
render : bool
whether to render the environment
... | 8c43a177418b7b9317d2ebcd4155edf5a58b5afe | 18,032 |
def measure_approximate_cost(structure):
""" Various bits estimate the size of the structures they return. This makes that consistent. """
if isinstance(structure, (list, tuple)): return 1 + sum(map(measure_approximate_cost, structure))
elif isinstance(structure, dict): return len(structure) + sum(map(measure_approx... | 8adbd962e789be6549745fbb71c71918d3cc8d0c | 18,033 |
def make3DArray(dim1, dim2, dim3, initValue):
"""
Return a list of lists of lists representing a 3D array with dimensions
dim1, dim2, and dim3 filled with initialValue
"""
result = []
for i in range(dim1):
result = result + [make2DArray(dim2, dim3, initValue)]
return result | c4972ff72fe751d131e4d840b12905d2383299c2 | 18,034 |
import math
def generate_boxes(bounds=(-1, -1, 1, 1), method='size', size=math.inf):
"""
Generate a stream of random bounding boxes
Has two methods for generating random boxes:
- *size* - generates a random central point (x0, y0)
within the bounding box, and then draws widths and heig... | 4cb4ae7fd179b466054c21d7512a1861652476c0 | 18,035 |
def create_assets(asset_ids, asset_type, mk_parents):
"""Creates the specified assets if they do not exist.
This is a fork of the original function in 'ee.data' module with the
difference that
- If the asset already exists but the type is different that the one we
want, raise an error
- Start... | 7be92642b6863f19039ed92d6652027ccd43d4ba | 18,036 |
def decoration(markdown: str, separate: int = 0) -> str:
"""見出しが使われているマークダウンをDiscordで有効なものに変換します。
ただたんに`# ...`を`**#** ...`に変換して渡された数だけ後ろに改行を付け足すだけです。
Parameters
----------
markdown : str
変換するマークダウンです。
separate : int, default 1
見出しを`**`で囲んだ際に後ろに何個改行を含めるかです。"""
new = ""
... | f76a21b093a00d04d1e95fc733a0956722737d51 | 18,037 |
import hashlib
def get_fingerprint(file_path: str) -> str:
"""
Calculate a fingerprint for a given file.
:param file_path: path to the file that should be fingerprinted
:return: the file fingerprint, or an empty string
"""
try:
block_size = 65536
hash_method = hashlib.md5()
... | b0ee4d592b890194241aaafb43ccba927d13662a | 18,038 |
def set_publish_cluster_args(args):
"""Set args to publish cluster
"""
public_cluster = {}
if args.public_cluster:
public_cluster = {"private": False}
if args.model_price:
public_cluster.update(price=args.model_price)
if args.cpp:
public_cluster.update(cr... | a1a5842093daf4d6de9bc9cdfae0cf7f9f5a0f5c | 18,039 |
import os
def create_session():
"""creates database session"""
db_engine = sa.create_engine(os.environ.get('DATABASE_URL'), echo=True)
return sessionmaker(bind=db_engine) | 312486556abc977f1187ba8a2ada70f2b681f3d0 | 18,040 |
def _get_iforest_anomaly_score_per_node(children_left, children_right, n_node_samples):
"""
Get anomaly score per node in isolation forest, which is node depth + _average_path_length(n_node_samples). Will
be used to replace "value" in each tree.
Args:
children_left: left children
childr... | d567d083d8e1914e4aee809092fd81e08e74f98d | 18,041 |
def get_invalid_value_message(value_name: str, value: str, line_no: int, uid: str, expected_vals: "list[str]") -> str:
"""
Returns the formatted message template for invalid value while parsing students data!
"""
msg = f"Invalid {value_name} <span class=\"font-weight-bold\">{value}</span>\
o... | cb7dc84b566bb117fe53ce5956919978558ccbbf | 18,042 |
def compute_score_for_coagulation(platelets_count: int) -> int:
"""
Computes score based on platelets count (unit is number per microliter).
"""
if platelets_count < 20_000:
return 4
if platelets_count < 50_000:
return 3
if platelets_count < 100_000:
return 2
if plate... | dc6e9935555fbb0e34868ce58a8ad8bc77be8b0c | 18,043 |
def check_horizontal_visibility(board: list):
"""
Check row-wise visibility (left-right and vice versa)
Return True if all horizontal hints are satisfiable,
i.e., for line 412453* , hint is 4, and 1245 are the four buildings
that could be observed from the hint looking to the right.
>>> che... | b84ff29fde689069ba5e92b10d54c8f0528aa321 | 18,044 |
import requests
def _get_soup(header, url):
"""This functions simply gets the header and url, creates a session and
generates the "soup" to pass to the other functions.
Args:
header (dict): The header parameters to be used in the session.
url (string): The url address to create the ses... | 22ad8876bdd19d405398272cfe0d4429f4b6ac9a | 18,045 |
import sys
def test_model(model, name_model, X_train, y_train, X_test, y_test, details=False,
normalize=False, weights=None, return_model=False, lib='scikit-learn', fit_params=None):
"""
Function that does a detailed investigation of a given model. Confusion matrices are generated
and vario... | d0fd0f528b14dcb0502c62b97c883d6469ef81ed | 18,046 |
import json
def get_text_block(dunning_type, language, doc):
"""
This allows the rendering of parsed fields in the jinja template
"""
if isinstance(doc, string_types):
doc = json.loads(doc)
text_block = frappe.db.get_value('Dunning Type Text Block',
{'parent': dunning_type, 'language': language},
['... | 31775b402a943e0c735d65a3c388503a6e03b37e | 18,047 |
import os
def load(test=False, cols=None):
"""Loads data from FTEST if *test* is True, otherwise from FTRAIN.
Pass a list of *cols* if you're only interested in a subset of the
target columns.
"""
fname = FTEST if test else FTRAIN
df = pd.read_csv(os.path.expanduser(fname)) # load pandas data... | 7de65b700ee077b496cd7ca4e678bc133d0532d7 | 18,048 |
import os
def flow_read(src_file):
"""Read optical flow stored in a .flo, .pfm, or .png file
Args:
src_file: Path to flow file
Returns:
flow: optical flow in [h, w, 2] format
Refs:
- Interpret bytes as packed binary data
Per https://docs.python.org/3/library/struct.html... | 855e0a6a65bbf6d3658843da4f4d9d0c4e3ea597 | 18,049 |
def group_create_factory(context, request):
"""Return a GroupCreateService instance for the passed context and request."""
user_service = request.find_service(name="user")
return GroupCreateService(
session=request.db,
user_fetcher=user_service.fetch,
publish=partial(_publish, reques... | 3928a35a74d1f62e4a6f5e38087fce72e7ebbc95 | 18,050 |
def verify(params, vk, m, sig):
""" verify a signature on a clear message """
(G, o, g1, hs, g2, e) = params
(g2, X, Y) = vk
sig1 , sig2 = sig
return not sig1.isinf() and e(sig1, X + m * Y) == e(sig2, g2) | 7413d9172d383c3602cbc2b8348c4ace61c40302 | 18,051 |
import os
def prepend_items():
"""
Return a function than prepend any item from "paths" list with "prefix"
"""
def prepend_func(prefix, paths):
return [os.path.join(prefix, item) for item in paths]
return prepend_func | b7c4fd8e1c53c82ba7dd1e826feb084e6543691b | 18,052 |
def generate_data(n):
"""
生成训练数据
"""
X, y = make_classification(n_samples=n, n_features=4)
data = pd.DataFrame(X, columns=["x1", "x2", "x3", "x4"])
data["y"] = y
return data | 0bf9cac1cf94c6bf8c12cb605f3bfcd6cde10a0d | 18,053 |
def blsimpv(p, s, k, rf, t, div=0, cp=1):
"""
Computes implied Black vol from given price, forward, strike and time.
"""
f = lambda x: blsprice(s, k, rf, t, x, div, cp) - p
result = brentq(f, 1e-9, 1e+9)
return result | 30ad8274aa40f50460cc7f52095ead8ef5021c9a | 18,054 |
def container_describe(object_id, input_params={}, always_retry=True, **kwargs):
"""
Invokes the /container-xxxx/describe API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Containers-for-Execution#API-method%3A-%2Fcontainer-xxxx%2Fdescribe
"""
return DXHTTPRequest('... | e56126b67880a316a84ab81cbcd208844282f0f5 | 18,055 |
from typing import Union
from typing import Dict
def nested(fields: Union[Dict[str, Dict], DataSpec], **config) -> dict:
"""
Constructs a nested Field Spec
Args:
fields: sub field specifications
config: in kwargs format
Returns:
the nested spec
"""
spec = {
"... | 3cba172e642b968aabbeb7ee1f2c21d217f443e2 | 18,056 |
from matplotlib.colors import ListedColormap
def make_cluster_cmap(labels, grey_pos='start'):
"""
Creates an appropriate colormap for a vector of cluster labels.
Parameters
----------
labels : array_like
The labels of multiple clustered points
grey_pos: str
Where to put th... | 3766f2db561705660bb572f8757ae8b0cc225a10 | 18,057 |
from typing import List
def objects_from_array(
objects_arr: np.ndarray, default_keys=constants.DEFAULT_OBJECT_KEYS
) -> List[btypes.PyTrackObject]:
"""Construct PyTrackObjects from a numpy array."""
assert objects_arr.ndim == 2
n_features = objects_arr.shape[1]
assert n_features >= 3
n_obje... | eeabc05132fa04f826c65d204f2d97ded625189a | 18,058 |
def run_policy(env, policy, scaler, logger, episodes):
""" Run policy and collect data for a minimum of min_steps and min_episodes
Args:
env: ai gym environment
policy: policy object with sample() method
scaler: scaler object, used to scale/offset each observation dimension
... | 8d723d13d10b15fda3a2da3591b663ec3c1b81b8 | 18,059 |
def load_data():
"""Load database"""
db = TinyDB(DATABASE_PATH)
data = db.all()
return pd.DataFrame(data) | 5fba31fb66f1ccb86125902e8a39fe2c0247f741 | 18,060 |
def plotcmaponaxis(ax, surf, title, point_sets=None):
"""Plot a Surface as 2D heatmap on a given matplotlib Axis"""
surface = ax.pcolormesh(surf.X, surf.Y, surf.Z, cmap=cm.viridis)
if point_sets:
for x_y, z, style in point_sets:
ax.scatter(x_y[:, 0], x_y[:, 1], **style)
ax.set_xlabe... | 9d462c745cc3a5f2142c29d69ddba1b4f96f6cab | 18,061 |
def get_log_storage() -> TaskLogStorage:
"""Get current TaskLogStorage instance associated with the current application."""
return current_app.config.get("LOG_STORAGE") | 30e4e8d6c61196ee94d519cff020d54d47b2ddbf | 18,062 |
def test_optional_posonly_args1(a, b=10, /, c=100):
"""
>>> test_optional_posonly_args1(1, 2, 3)
6
>>> test_optional_posonly_args1(1, 2, c=3)
6
>>> test_optional_posonly_args1(1, b=2, c=3) # doctest: +ELLIPSIS
Traceback (most recent call last):
TypeError: test_optional_posonly_args1() g... | 8986d0718e65988f109b31bf5f7ce8fdcd65c833 | 18,063 |
def _build_schema_resource(fields):
"""Generate a resource fragment for a schema.
Args:
fields (Sequence[google.cloud.bigquery.schema.SchemaField): schema to be dumped.
Returns:
Sequence[Dict]: Mappings describing the schema of the supplied fields.
"""
return [field.to_api_repr() f... | 34a32c9b1707062d202a1fd9f98cdd4dc0cb11ae | 18,064 |
def flatten_swtn(x):
""" Flatten list an array.
Parameters
----------
x: list of dict or ndarray
the input data
Returns
-------
y: ndarray 1D
the flatten input list of array.
shape: list of dict
the input list of array structure.
"""
# Check input
if... | 2f8e0b17c462dd97eaa3cd69104164cdcf533cdc | 18,065 |
from sys import path
def checkpoint(cache, **csv_args):
"""
Return a decorator which automatically caches the result of a function
which returns a pandas.DataFrame.
Parameters
----------
cache : str or path object
The path to the file which contains the results of `func`.
**csv_ar... | 5f43a48e6635b6bfa012daaf84780457f98037aa | 18,066 |
def crossing(series, value, **options):
"""Find where a function crosses a value.
series: Series
value: number
options: passed to interp1d (default is linear interp)
returns: number
"""
interp = interp1d(series.values, series.index, **options)
return interp(value) | 5318975ad28280e6aff4c0dbd944daf0dd2a24d1 | 18,067 |
import math
def equilSoundSpeeds(gas, rtol=1.0e-6, maxiter=5000):
"""
Returns a tuple containing the equilibrium and frozen sound speeds for a
gas with an equilibrium composition. The gas is first set to an
equilibrium state at the temperature and pressure of the gas, since
otherwise the equilibr... | c2b10fe05cc2f19e50b5ed8934c463768ec16c8e | 18,068 |
import time
import click
def benchmark(partitioner_list: list, item_list: list, bucket_list: list, iterations: int = 1,
begin_range: int = 1, end_range: int = 10, specified_items_sizes: list = None, verbose: bool = False)\
-> pd.DataFrame:
"""
Args:
Returns:
Raises:
"""
... | 08e4d00fa57bada7297c509ead2a2e45f1fb5cc7 | 18,069 |
def adj_by_strand(genes):
"""
liste: list of hmm gene with homogenous strand
Check if the gene is in tandem with another and if so store the gene inside a set obj.TA_gene.linked
In parallel it clean up the list obj.TA_gene.genes
by removing the genes that forme a tandem. Then TA_gene.genes has only ... | 2836375fadf46b445098ddecf3aaf1884dad8efc | 18,070 |
def register_user():
""" register a user and take to profile page """
form = RegisterForm()
if form.validate_on_submit():
username = form.username.data
password = form.password.data
email = form.email.data
first_name = form.first_name.data
last_name = form.last... | 2f1f875d3c35589d8efc1e069a8d050b931a5f51 | 18,071 |
def stack_init_image(init_image, num_images):
"""Create a list from a single image.
Args:
init_image: a single image to be copied and stacked
num_images: number of copies to be included
Returns:
A list of copies of the original image (numpy ndarrays)
"""
init_images = []
... | 2cf26723bdbf53921ff053308e408bd84ec03edb | 18,072 |
import os
def process_problem(_path, _lang=EN):
""" Обработка задачи """
path = os.path.join(_path, 'problem.xml')
with open(path, 'r', encoding='utf-8') as file:
root = ET.parse(file).getroot()
titles = root.find('names').findall('name')
title = titles[0].attrib['value']
for t in titl... | f5a3a987212c6b0c7d688a0bc59783a7554b04a2 | 18,073 |
import sys
def input_to_text(s):
"""Convert the given byte string or text type to text using the
file system encoding of the current system.
:param basestring s: String or text type to convert
:return: The string as text
:rtype: unicode
"""
return avalon.compat.to_text(s, sys.getfilesyste... | 7147c91984ea4e7e3099b37297009ac37e7218fb | 18,074 |
def f5(x, eps=0.0):
"""The function f(x)=tanh(4x)+noise"""
return np.tanh(4*x) + eps * np.random.normal(size=x.shape) | 02025ed30032b1e8de9ecbca4238170e5adff4b1 | 18,075 |
def get_next_event(game, players):
"""
return None if a player has to move before the next event
otherwise return the corresponding Event enum entry
"""
active_player = get_active_player(players, game.finish_time)
if active_player is None:
return None
planet_rotation_event = (
... | 955082da6a3c0ec8b0ee50e149e7251651584352 | 18,076 |
import six
import json
def _convert_requirements(requirements):
"""Convert the requirements to an array of strings.
["key op value", "key op value", ...]
"""
# TODO(frossigneux) Support the "or" operator
# Convert text to json
if isinstance(requirements, six.string_types):
try:
... | 6b221a303af41ea81dd172fc0a3bd2f4069ffd0c | 18,077 |
def max_width(string, cols, separator='\n'):
"""Returns a freshly formatted
:param string: string to be formatted
:type string: basestring or clint.textui.colorred.ColoredString
:param cols: max width the text to be formatted
:type cols: int
:param separator: separator to break rows
:type se... | 49521ec4521b639e71b3fc5212738cc6e4d93129 | 18,078 |
import base64
def aes_encrypt(text, sec_key):
"""
AES encrypt method.
:param text:
:param sec_key:
:return:
"""
pad = 16 - len(text) % 16
if isinstance(text, bytes):
text = text.decode('utf-8')
text += pad * chr(pad)
encryptor = AES.new(sec_key, 2, '0102030405060708')
... | 55340a7f1fcf37c58daaf3a72db70344159fbf30 | 18,079 |
def get_value_at_coords(matrix, x, y):
"""Returns the value of the matrix at given integer coordinates.
Arguments:
matrix {ndarray} -- Square matrix.
x {int} -- x-coordinate.
y {int} -- y-coordinate.
Returns:
int -- Value of the matrix.
"""
offset = matrix_offset(m... | 92e96f276025e21bc8643eb96ce03fd191285c93 | 18,080 |
def rms(vector):
"""
Parameters
----------
vector
Returns
-------
"""
return np.sqrt(np.mean(np.square(vector))) | 9d4888050e7f048a8d2ca5b92fa638d5c8d24eb7 | 18,081 |
def parse(text):
"""Parse a tag-expression as text and return the expression tree.
.. code-block:: python
tags = ["foo", "bar"]
tag_expression = parse("foo and bar or not baz")
assert tag_expression.evaluate(tags) == True
:param text: Tag expression as text to parse.
:param... | 202951a1023557e3405b8f5d4d06084e798ae12c | 18,082 |
import itertools
def average_distance(points, distance_func):
"""
Given a set of points and their pairwise distances, it calculates the average distances
between a pair of points, averaged over all C(num_points, 2) pairs.
"""
for p0, p1 in itertools.combinations(points, 2): # assert symmetry... | 236735da94e902dd7fbe062de8abb9a02208156f | 18,083 |
def get_bin_alignment(begin, end, freq):
"""Generate a few values needed for checking and filling a series if
need be."""
start_bin = get_expected_first_bin(begin,freq)
end_bin = (end/freq)*freq
expected_bins = expected_bin_count(start_bin, end_bin, freq)
return start_bin, end_bin, expecte... | 0ff46d4d8df2d7fd177377621c69bac95f23eb9f | 18,084 |
def TagAndFilterWrapper(target, dontRemoveTag=False):
"""\
Returns a component that wraps a target component, tagging all traffic
coming from its outbox; and filtering outany traffic coming into its inbox
with the same unique id.
"""
if dontRemoveTag:
Filter = FilterButKeepTag
else:
... | 83329d0c3f6bbf872ba65d31f7b2111c60a768e7 | 18,085 |
import requests
import json
def tweets(url):
"""tweets count"""
try:
twitter_url = 'http://urls.api.twitter.com/1/urls/count.json?url=' + url
r = requests.get(twitter_url, headers=headers)
json_data = json.loads(r.text)
return json_data['count']
except:
return 0 | 07e10d4b1ddad8cf74d79dc21fbc8dbfe1c38428 | 18,086 |
def CLJPc(S):
"""Compute a C/F splitting using the parallel CLJP-c algorithm.
CLJP-c, or CLJP in color, improves CLJP by perturbing the initial
random weights with weights determined by a vertex coloring.
Parameters
----------
S : csr_matrix
Strength of connection matrix indicating the... | 3ef11327120a71123e51b702c5452e8036f581d5 | 18,087 |
def displayTwoDimMapPOST():
"""Run displayTwoDimMap"""
executionStartTime = int(time.time())
# status and message
success = True
message = "ok"
plotUrl = ''
dataUrl = ''
# get model, var, start time, end time, lon1, lon2, lat1, lat2, months, scale
jsonData = request.json
model... | 7b0402b66538b7b5d987c1385d9ac12df82fac66 | 18,088 |
def encrypt(msg, hexPubkey):
"""Encrypts message with hex public key"""
return pyelliptic.ECC(curve='secp256k1').encrypt(
msg, hexToPubkey(hexPubkey)) | 30befcf48d0417f13a93ad6d4e9f8ccf0fdbeae5 | 18,089 |
def indexing(zDatagridLeft,zDatagridRight,zModelgridLeft,zModelgridRight):
"""
Searches for closest distances between actual and theorectical points.
zDatagridLeft = float - tiled matrix (same values column-wise) of z coordintates
of droplet on left side, size = [len(z... | d14b0037a4898fc12524aba0a29231a545dfed8a | 18,090 |
def torch2np(tensor):
"""
Convert from torch tensor to numpy convention.
If 4D -> [b, c, h, w] to [b, h, w, c]
If 3D -> [c, h, w] to [h, w, c]
:param tensor: Torch tensor
:return: Numpy array
"""
array, d = tensor.detach().cpu().numpy(), tensor.dim()
perm = [0, 2, 3, 1] if d == 4 el... | 23acaa7b4e58d7891e77c22f29b7cbdc7a9a80d0 | 18,091 |
import glob
import os
import random
def get_filenames(feature_folder, glob_pattern, sample_size=None):
"""
Finds the all the files in the given feature folder which matches the glob pattern.
:param feature_folder: The folder to search for files.
:param glob_pattern: The glob pattern to use for finding... | 19b97b9e981b8fe0b978d5af2240dc22c02d7e93 | 18,092 |
from typing import Any
import array
import numpy
def message_to_csv(msg: Any, truncate_length: int = None,
no_arr: bool = False, no_str: bool = False) -> str:
"""
Convert a ROS message to string of comma-separated values.
:param msg: The ROS message to convert.
:param truncate_leng... | 10ab4c7482c2fbf6e4335daaf0359390ed215152 | 18,093 |
def create_message(username, message):
""" Creates a standard message from a given user with the message
Replaces newline with html break """
message = message.replace('\n', '<br/>')
return '{{"service":1, "data":{{"message":"{mes}", "username":"{user}"}} }}'.format(mes=message, user=username) | d12807789d5e30d1a4a39c0368ebe4cf8fbde99e | 18,094 |
def overlaps(sdf, other):
"""
Indicates if the intersection of the two geometries has the same shape
type as one of the input geometries and is not equivalent to either of
the input geometries.
========================= =========================================================
**Argument** ... | 14cad072b3b11efe4c4f14d7fc14e053a262f904 | 18,095 |
from django.contrib.auth.views import redirect_to_login
def render_page(request, page):
"""Рендер страницы"""
if page.registration_required and not request.user.is_authenticated:
return redirect_to_login(request.path)
# if page.template:
# template = loader.get_template(page.template)
... | 6e11ea24ee9dc9cf7e1cf8df3bfc192715202044 | 18,096 |
def _whctrs(anchor):
"""
Return width, height, x center, and y center for an anchor (window).
"""
w = anchor[2] - anchor[0] + 1
h = anchor[3] - anchor[1] + 1
x_ctr = anchor[0] + 0.5 * (w - 1)
y_ctr = anchor[1] + 0.5 * (h - 1)
# 16,16, 7.5, 7.5
return w, h, x_ctr, y_ctr | ae3f3d7c486b1698f31ecce301f0e2c2f8af5e84 | 18,097 |
def obtener_atletas_pais(atletas: list, pais_interes: str) -> list:
"""
Función que genera una lista con la información de los atletas del país dado,
sin importar el año en que participaron los atletas.
Parámetros:
atletas: list de diccionarios con la información de cada atleta.
pais_in... | 4b03364a76af4e7818f977731b259fdfee6817ee | 18,098 |
def kl_div_mixture_app(m1, v1, m2, v2,
return_approximations=False,
return_upper_bound=False):
"""Approximate KL divergence between Gaussian and mixture of Gaussians
See Durrieu et al, 2012: "Lower and upper bounds for approximation of the
Kullback-Leibler dive... | e90fbf8596a06513d68c1eca17a35857d75eea70 | 18,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.