content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def is_valid_combination( row ):
"""
Should return True if combination is valid and False otherwise.
Test row that is passed here can be incomplete.
To prevent search for unnecessary items filtering function
is executed with found subset of data to validate it.
"""
n = len(row)
if ... | c0758c3d30debbd3fc3d5f07d6728c23bfb71145 | 3,632,647 |
def PinkFilter(c):
"""Returns True if color can be classified as a shade of pink"""
if (c[0] > c[1]) and (c[2] > c[1]) and (c[2] == c[0]): return True
else: return False | 0514954e95a409901f3b7053a1c67315b556f517 | 3,632,649 |
def greedy_search(problem, h=None):
"""f(n) = h(n)"""
h = memoize(h or problem.h, 'h')
return best_first_graph_search(problem, h) | eaa1aac7e8b10f95effb32f61c765224ebe1f01e | 3,632,650 |
def get_callback(request, spider):
"""Get request.callback of a scrapy.Request, as a callable."""
if request.callback is None:
return getattr(spider, 'parse')
return request.callback | a1f62822d812bebdeabafa14edda4462949657d8 | 3,632,651 |
import requests
def veryrandom(msg, min=1, max=6, base=10, num=1):
"""Los datos generados por veryrandom provienen de random.org, lo cual
es una garantía adicional de la aleatoriedad de los resultados. Se
obtendrá un número aleatorio entre los 2 definidos, ambos inclusive.
"""
url = 'http://www.ra... | 75320750423e060ba117ed8ce6bfb84a02d16411 | 3,632,652 |
from typing import Union
from typing import List
from typing import Dict
from typing import Sequence
def clean_documents(documents: Union[List[str], Dict[str, str]], **kwargs) -> Union[Sequence[str], Dict[str, str]]:
"""Seaches for `Filth` in `documents` and replaces it with placeholders.
`documents` can be ... | 2c789e3fa5db952db452341a4e838230c01decf5 | 3,632,654 |
from math import log
def calcShannonEnt(dataSet):
"""
计算香农熵,用于判断划分
Parameters
----------
dataSet:数据集(可能是原始数据集,有可能是划分子集)
Returns:数据集的信息熵,根据分类标签信息确定
-------
"""
numEntries = len(dataSet) # 数据总量
labelCounts = {} # 创建一个数据字典,用来计数各个类别
for featVec in dataSet.values: # 每次取一行
... | bdade097a799feff0cb41eb15b3438ca1e088983 | 3,632,655 |
def Disc(
pos=(0, 0, 0),
r1=0.5,
r2=1,
c="coral",
alpha=1,
res=12,
resphi=None,
):
"""
Build a 2D disc of internal radius `r1` and outer radius `r2`.
|Disk|
"""
ps = vtk.vtkDiskSource()
ps.SetInnerRadius(r1)
ps.SetOuterRadius(r2)
ps.SetRadialResolution(res)
... | b7f79bfa2a1b8e06a028c741c590d71a93c2faf0 | 3,632,656 |
def identity_block(x, n_filters):
""" Construct a Bottleneck Residual Block with Identity Link
x : input into the block
n_filters: number of filters
"""
# Save input vector (feature maps) for the identity link
shortcut = x
## Construct the 1x1, 3x3, 1x1 residual block (fi... | 7de4980119577a5b37bf34a9394dfc779094b015 | 3,632,657 |
def makeDarker(color: colors.Color) -> colors.Color:
"""
Takes a color and returns a slightly darker version of the
original color.
:param Color color: the color you want to darken
:return: the new, darker color
:rtype: Color
:raises TypeError: if ``color`` is not a :py:class:`~.colors.Colo... | 79d89502019b66cb413a6e231b54832cd0690a54 | 3,632,658 |
import itertools
def multi_indices(n):
"""Return the list of all multi-indices within the specified bounds.
Return the list of multi-indices ``[b[0], ..., b[dim - 1]]`` such that
``0 <= b[i] < n[i]`` for all i.
"""
iterables = [range(ni) for ni in n]
return [np.asarray(b, dtype=np.intc)
... | f469e90253f4d762416b7757cc1b8de427589915 | 3,632,659 |
def removeProject(info, project):
"""
Removing an docker stack for the current project
if the checkIfComposerExistsBool == TRUE
else perform `docker rm`
:param info:
:param project:
:return:
"""
print(project)
if checkIfComposerExistsBool(project):
return "docker stack rm... | c8f3556aa67882c7241d93482d2371c9f8263793 | 3,632,660 |
def columnize_as_rows(lis, columns, horizontal=False, fill=None):
"""Like 'zip' but fill any missing elements."""
data = distribute(lis, columns, horizontal, fill)
rowcount = len(data)
length = max(len(x) for x in data)
for c, lis in enumerate(data):
n = length - len(lis)
if n > 0:
... | cce7251db42e7d17ee1e01a97eb5a0bcce7e9b60 | 3,632,661 |
from pathlib import Path
def single_extra_atom_line_v3000_sdf(tmp_path: Path) -> Path:
"""Write a single molecule to a v3000 sdf with an extra atom line.
Args:
tmp_path: pytest fixture for writing files to a temp directory
Returns:
Path to the sdf
"""
sdf_text = """
0 0 0 ... | e4fff4a730362fc2f75cb322b773853d9a6ec364 | 3,632,662 |
def add_metaclass(metaclass): # pragma: no cover
""" Class decorator for creating a class with a metaclass.
Copied from six
"""
def wrapper(cls):
orig_vars = cls.__dict__.copy()
orig_vars.pop('__dict__', None)
orig_vars.pop('__weakref__', None)
for slots_var in orig_... | dc101f414207e7e3c73bb7427d1bc1142c2e6a1a | 3,632,663 |
def vzerog(v):
"""vzerog(ConstSpiceDouble * v) -> SpiceBoolean"""
return _cspyce0.vzerog(v) | 7496c628dda05a01d77637fb5f8b05dbc414afcf | 3,632,664 |
from pathlib import Path
import csv
def read_barcodes(barcodes_file: Path) -> dict:
"""
Read in barcodes from file
:param barcodes_file: path to csv file with barcodes and gene name
:return barcode_dict:
barcode_dict = {
barcode_1 : {"gene": Gene_1, "count": 0}
barcode_2 : {"gene... | ee68f0172134e22b37432af9f0de2f0884b4354c | 3,632,665 |
def is_localized(node):
"""Check message wrapped by _()"""
if isinstance(node.parent, compiler.ast.CallFunc):
if isinstance(node.parent.node, compiler.ast.Name):
if node.parent.node.name == '_':
return True
return False | 09c7a0693c5aba9a984bc94a85a3476aeb15528c | 3,632,666 |
from typing import Callable
from typing import Iterable
def skip(count: int) -> Callable[[Iterable[_TSource]], Iterable[_TSource]]:
"""Returns a sequence that skips N elements of the underlying
sequence and then yields the remaining elements of the sequence.
Args:
count: The number of items to sk... | bae4c2e92940a1d2ade01f1defc7242e35a59e7a | 3,632,667 |
from threading import Thread
from pathlib import Path
import click
import json
from typing import List
def upload_to_nomad(nomad_configfile, num, mongo_configfile):
"""
upload n launchers to NOMAD using the following procedure
1. Find n launchers and split them into 10 threads
2. upload those n launch... | fc4ed41ac042ebdec429fb3c30b8c020ed7c9e15 | 3,632,668 |
def init_db(uri, echo=True):
"""Initialize the database and reflect the tables"""
global meta
uri = make_url(uri)
uri.query.setdefault("charset", "utf8")
engine = create_engine(uri, echo=echo)
meta.bind = engine
Session.configure(bind=engine)
reflect_tables()
return engine | 9535a6b3f2379b65da151f1384f739ccdcf25d70 | 3,632,670 |
def get_weighted_average(We, x, w):
"""
Compute the weighted average vectors
:param We: We[i,:] is the vector for word i
:param x: x[i, :] are the indices of the words in sentence i
:param w: w[i, :] are the weights for the words in sentence i
:return: emb[i, :] are the weighted average vector f... | 6fbc2a5581a9cab4609604b771a4a27a6631b74d | 3,632,671 |
def logout_user_cleanup():
"""Logs out user."""
print("\n\nGot to logout from: {}".format(request.referrer))
logout_user()
session.clear()
flash("You were logged out!")
return redirect(request.referrer) | 60d114c94bd1409982e004840c29a3da3c3dd772 | 3,632,672 |
def read_vtk_sowfa(filename):
"""
Reads SOWFA results .vtk file and returns coordinates of cell centres and velocity field as numpy arrays.
:param filename:
:return:
"""
reader = vtk.vtkPolyDataReader()
reader.SetFileName(filename)
reader.Update()
data = reader.GetOutput()
u = v... | e78c4ee4300204af53373ca2199582b8ddacbc4a | 3,632,673 |
def compute_primary_orientations(primary_segments, angle_epsilon=0.1):
"""
Computes the primary orientations based on the given primary segments.
Parameters
----------
primary_segments : list of BoundarySegment
The primary segments.
angle_epsilon : float, optional
Angles will be... | 327a92aa493e8f6d82a760ba7087d0889ddf55e4 | 3,632,674 |
def plot_contribution_map(contribution_map, ax=None, vrange=None, vmin=None, vmax=None, hide_ticks=True, cmap="bwr",
percentile=100):
"""
Visualises a contribution map, i.e., a matrix assigning individual weights to each spatial location.
As default, this shows a contribution map w... | 2715424895926652539d8775e0629ba47dfc76c2 | 3,632,676 |
def pac_mvl(z):
""" Calculate PAC using the mean vector length.
Parameters
----------
ang: array_like
Phase of the low frequency signal.
amp: array_like
Amplitude envelop of the high frequency signal.
Returns
-------
out: float
The pac strength using the mean v... | 5412f9f4596b105e939a586fd570e1c1299b4194 | 3,632,677 |
def merge_values(list1, list2):
"""Merge two selection value lists and dedup.
All selection values should be simple value types.
"""
tmp = list1[:]
if not tmp:
return list2
else:
tmp.extend(list2)
return list(set(tmp)) | 9412dd28c6110bc6df70ac7d563cb19d1211beb8 | 3,632,678 |
def load_data(database_filepath):
"""
Load data from sqlite database
Arguments:
database_filepath: path to database file
"""
engine = create_engine(f'sqlite:///{database_filepath}')
sql = 'SELECT * FROM DisasterPipeline'
df = pd.read_sql(sql, engine)
x = df.message
... | 99371afba33d7527cc5a6a3c4f0d98b1b76ba5c0 | 3,632,679 |
import numpy as np
from .._tier0 import empty_image_like
from .._tier0 import execute
from .._tier1 import copy
from .._tier0 import create
from .._tier1 import copy_slice
from .._tier0 import _warn_of_interpolation_not_available
from typing import Union
def affine_transform(source : Image, destination : Image = None... | 78fe7ff1ea9c9afc9284a2a9248765f7ff57ba3d | 3,632,680 |
def create_host(values):
"""Create a host from the values."""
return IMPL.create_host(values) | bb49c51dfd6ef7be988da89dd12ec441948dbb2b | 3,632,681 |
import math
def get_distance(lat_a, long_a, lat_b, long_b):
"""
Returns the distance, in meters, between two points
Uses the haversine formula, i.e.:
a = sin²(Δφ/2) + cos φ1 ⋅ cos φ2 ⋅ sin²(Δλ/2)
c = 2 ⋅ atan2( √a, √(1−a) )
d = R ⋅ c
Keep in mind this is an "as the crow flies" type of estimation
... | 57b64ad307c28d87caf7015f8a16c9a5fb8562dd | 3,632,683 |
def format_heading(level, text):
"""Create a heading of <level> [1, 2 or 3 supported]."""
underlining = ['=', '-', '~', ][level-1] * len(text)
return '%s\n%s\n\n' % (text, underlining) | 6b8caaa134ddc32666a4d7ce62a775d6ffda7425 | 3,632,684 |
def get_list_of_temps(temp_string):
"""
A function to process an argument string line to an array of temperatures
"""
success = True
error = ""
temps = None
arr_string = temp_string.split(",")
arr_string_len = len(arr_string)
temps = np.zeros(arr_string_len)
for i in range(arr_string_len... | 0ad6ffd2ecf25ae3158b25b592f89824e4370633 | 3,632,685 |
def test():
"""Test
:param:
:return:
"""
print('!! Begin Test!..')
return encrypt("vigenere","hello","lemon") | d698bba18d8dba0465c5bb2bd8ac0311b9b9f64d | 3,632,686 |
def get_new_size_zoom(current_size, target_size):
"""
Returns size (width, height) to scale image so
smallest dimension fits target size.
"""
scale_w = target_size[0] / current_size[0]
scale_h = target_size[1] / current_size[1]
scale_by = max(scale_w, scale_h)
return (int(current_size[0]... | e0b42eab3d35ba5c662282cab1ffa798327ad92a | 3,632,687 |
def get_name_component(x509_name, component):
"""Gets single name component from X509 name."""
value = ""
for c in x509_name.get_components():
if c[0] == component:
value = c[1]
return value | 6a473a96b99daa6f69fd6aac45f2594af933d4bd | 3,632,688 |
def hurst(ts):
""" the implewmentation on the blog http://www.quantstart.com
http://www.quantstart.com/articles/Basics-of-Statistical-Mean-Reversion-Testing
Returns the Hurst Exponent of the time series vector ts"""
# Create the range of lag values
lags = range(2, 100)
# Calculate the array of t... | 59708d86d9f0022cf991fd60e32e9d8c59c630c7 | 3,632,689 |
def _bunchify(b):
"""Ensure all dict elements are Bunch."""
assert isinstance(b, dict)
b = Bunch(b)
for k in b:
if isinstance(b[k], dict):
b[k] = Bunch(b[k])
return b | c76bb7ba86d1958f498775ab68f944b0fcb1dd0c | 3,632,690 |
import random
def generate_random_username():
"""Generate function
Generates a random username for anonymous users.
:returns: String with the anonymous username
"""
random.seed()
return 'anon-' + str(random.randint(0, MAX_INT_ANONYMOUS)) | ef7d7897d3eeb518808547afd8e1717c7db1d5d6 | 3,632,691 |
import math
def GetRadar(dt):
""" Simulate radar range to object at 1K altidue and moving at 100m/s.
Adds about 5% measurement noise. Returns slant range to the object.
Call once for each new measurement at dt time from last call.
"""
if not hasattr (GetRadar, "posp"):
GetRadar.posp = 0
... | 0f61b507d57efa68825b22b0ba2d97154f97547c | 3,632,694 |
def get_gin_feature(inputs, neigh_idx, k):
"""
Aggregate neighbor features for each point with GIN
GIN conv layer:
Xu, Keyulu, Weihua Hu, Jure Leskovec, and Stefanie Jegelka.
"How Powerful are Graph Neural Networks?."
arXiv:1810.00826 (2018).
Args:
inputs: (batch_size, num_vertices... | 12fd947cd9e18e3a8755cf32b4e72a0aa0befa5f | 3,632,695 |
def five_crops(image, crop_size):
""" Returns the central and four corner crops of `crop_size` from `image`. """
image_size = tf.shape(image)[:2]
crop_margin = tf.subtract(image_size, crop_size)
assert_size = tf.assert_non_negative(
crop_margin, message='Crop size must be smaller or equal to the... | 16f699f8569ca8271c180027db4df199543a62b1 | 3,632,697 |
from typing import Dict
from re import A
def get_tfms(conf: DictConfig) -> Dict[str, A.Compose]:
"""
Loads in albumentation augmentations for train, valid, test
from given config as a dictionary.
"""
trn_tfms = [
load_obj(i["class_name"])(**i["params"]) for i in conf.augmentation.train
... | e4d47d19a52027fd413f501aa05d1e659e232ace | 3,632,698 |
def song_line(line):
"""Parse one line
Parameters
----------
line: str
One line in the musixmatch dataset
Returns
-------
dict
track_id: Million song dataset track id, track_id_musixmatch:
Musixmatch track id and bag_of_words: Bag of words dict in
{word: cou... | 2108dfa037aa6293a0b3111a97c354e62c0dd2a5 | 3,632,699 |
def _select_command_reply(replies: list, command: int, seq: int=None):
"""
Find a valid command reply
returns dict
"""
filtered_replies = list(filter(lambda x: x["cmd"] == command, replies))
if seq is not None:
filtered_replies = list(filter(lambda x: x["seq"] == seq, filtered_replies))... | 4ee65e604918a9c1fe4e639c524f6f4e4371f775 | 3,632,700 |
def remove_st_less_than(dataframe, column='ST', less_than=0.001):
"""
Remove any entry with an ST less than specified
Args:
dataframe (pandas.Dataframe): dataframe containing sensitivity analysis output
column (str): Column name, default is 'ST'
less_than (float): Remove anything le... | 2ba052004c436f8d527ab9b5bc3e76c90aa5dce9 | 3,632,701 |
def count_positives_sum_negatives2(arr):
"""
More space efficient, but not as concise as above
"""
if not arr:
return arr
count = 0
total = 0
for num in arr:
if num > 0:
count += 1
else:
total += num
return [count, total] | f1f8de28dcf6669d49044a43e6a8603f0da01577 | 3,632,702 |
import json
def read_json(url, cached=True):
"""Read JSON content from url."""
content = read(url, cached)
return json.loads(content) if content else None | 9a256e2ec5842c6e77da175cf11e953e2a1c03a0 | 3,632,703 |
def spherical_Lloyd(radius,
num_cells,
dimension=3,
fixed='center',
approximation='monte-carlo',
approx_n=5000,
max_iter=500,
momentum=0.9,
verbose=0):
"""C... | cd3f202945be887a0835ce271bc38c3dc192aa33 | 3,632,704 |
def first_primes(n: Integral) -> list:
"""
Generates a list of the first n primes. A cast will be used if the input is not an integer
"""
n = int(n) - 1
bank = []
track = 2
while len(bank) < n + 1:
if all(track % y for y in range(2, min(track, 11))):
bank.append(track)
... | 04927ce0be9f9ed2fc3e65a346599625e9919a95 | 3,632,707 |
def is_ne_atom(phi: Formula):
""" Return whether the given formula is an inequality """
return isinstance(phi, Atom) and phi.predicate.symbol == BuiltinPredicateSymbol.NE | 30cdee64bf622b803efe041bd1feaa7d7a2fb2fe | 3,632,708 |
def fact(n):
"""Return the factorial of the given number."""
r = 1
while n > 0:
r = r * n
n = n - 1
return r | 7bdcdc759b49a9cd72f7bf3f12a18fc03ce50668 | 3,632,709 |
def getCoatThickCorr(f, materials, wavelength, dOpt, dTE, dTR):
"""Finite coating thickness correction
:f: frequency array in Hz
:materials: gwinc optic materials structure
:wavelength: laser wavelength
:wBeam: beam radius (at 1 / e**2 power)
:dOpt: coating layer thickness array (Nlayer x 1)
... | 92734aced5c17e44b97e73f57850409fcddc3102 | 3,632,710 |
import itertools
def create_purchase(row):
"""Creates Purchase object based on BeautifulSoup table row object"""
name = next(itertools.islice(row.stripped_strings, 0, 1))
id = row.a['data-character-id']
price = "".join(next(itertools.islice(row.stripped_strings, 3, 4)).split())
level = len(row.fin... | 3676d8e382bd9cc7441118cdd19a6e12fe955821 | 3,632,712 |
def load_tough_corners(fname):
"""
Load the mesh of the domain; discared by default. Use VTK_output = .TRUE. to obtain from MeshMaker_V2
fname shoud be the CORNERS file
"""
ndim = 3
verts = {}
cells = []
elemnames = []
f = open(fname,"r")
enum = -1
elem = []
for l in f:
... | a7219c39344b79fa33459e64ed7eaffe124b941b | 3,632,715 |
import io
def dumps(obj, bytes=False):
"""WARNING: can mutate obj"""
if bytes:
out = io.BytesIO()
else:
out = io.StringIO()
dump(obj, out)
return out.getvalue() | 063ad30f8bd4b1b5905da5c924e3dcd6a577a244 | 3,632,716 |
def evaluate_results(model, contexts, layer_dimension, all_tasks_test_data, superposition, task_index, first_average, use_MLP, batch_size, use_PSP=False):
"""
Evaluate the results on test data with or without using superposition. Return accuracy, AUROC and AUPRC.
:param model: torch model instance
:par... | 3d8bdaae78d53df9edfd767af85229c73a96b12e | 3,632,717 |
def list_column(column, original_name):
"""Get all non nan values from column."""
if original_name == 'original_formatted':
list_filled = [[x for x in row if str(x) != 'nan'] for row in column]
else:
list_filled = [[_] for _ in column]
return list_filled | ae8b900cdcf3e59ff4ede3b3dc0321d93ea07253 | 3,632,718 |
def query_audioobject(identifier: str = None, title: str = None, contributor: str = None,
creator: str = None, source: str = None, format_: str = None, name: str = None,
date: str = None, encodingformat: str = None,
embedurl: str = None, url: str = None,... | 63ee4c20acef392dad4fa6b4d2039bd6609659f0 | 3,632,719 |
import copy
def test_create_new_grant_alt2(cbcsdk_mock):
"""Test creation of a grant and the profile inside it with more options."""
def respond_to_profile_grant(url, body, **kwargs):
ret = copy.deepcopy(POST_PROFILE_IN_GRANT_RESP_2)
ret['profile_uuid'] = body['profile_uuid']
return re... | 75ddaa6d488409e04b4045aed34813804659c0ee | 3,632,720 |
from models.user import User
def stats() -> str:
""" GET /api/v1/stats
Return:
- the number of each objects
"""
stats = {}
stats['users'] = User.count()
return jsonify(stats) | 18ff101234c1df23460417ecac13663e60e6ae26 | 3,632,721 |
from optparse import OptionParser
def main(args=None):
"""The main function; parses options and plots"""
# ---------- build and read options ----------
optParser = OptionParser()
optParser.add_option("-n", "--net", dest="net", metavar="FILE",
help="Defines the network to read"... | f387756ac777f624f5ccdc2e0b70d72ded646b68 | 3,632,722 |
def create_split(
dataset_builder: tfds.core.DatasetBuilder,
batch_size: int,
train: bool,
dtype: tf.DType = tf.float32,
image_size: int = IMAGE_SIZE,
cache: bool = False,
) -> tf.data.Dataset:
"""Creates a split from the ImageNet dataset using TensorFlow Datasets.
Args:
dataset_builder... | bfb9da0d16f6ef21e0f26a7bcec9b196c1358139 | 3,632,723 |
import random
def randomString(stringLength=16):
"""Generate a random hex-string of fixed length """
# """Generate a random string of fixed length """
# letters = string.ascii_lowercase + string.ascii_uppercase + string.digits
# return ''.join(random.choice(letters) for i in range(stringLength))
r... | d92985a92e9bb24ed4c405c7dc45dce9d12ff135 | 3,632,724 |
def get_uri():
"""
POST body:
{
domain: string representing the domain name
term: string or number referring to be used on composing the URI for the element
}
:return:
{
uri: string with the URI for the resource
}
"""
payload = request.json
uri = DomainUR... | c410eff64e01312a12792c8f9bdd36ef44a1e765 | 3,632,725 |
def split_in_groups(key_func, l, continuous=True, max_group_size=None):
"""
Split the list `l` into groups according to the `key_func`.
Go over the list and group the elements with the same key value together.
If ``continuous==False``, groups all elements with the same key together regardless of wh... | fc5b6d381b3111a00382f16bea15c32b495fbefd | 3,632,726 |
def delete_orderitem(request, id=None):
"""
Deleting orderitems in current order CART
"""
if request.method == "POST":
order_to_delete = OrderItem.objects.get(id=id)
order_to_delete.delete()
return redirect('create-order') | adbc9a12358bab86c44759136865a2f8a2508c26 | 3,632,727 |
import warnings
def moments_dbs(data, xi_n, t_bootstrap=0.5, r_bootstrap=500, eps_stop=1.0,
verbose=False, diagn_plots=False, sort=True):
"""Double-bootstrap procedure for moments estimator.
Parameters
----------
data : (N, ) array_like
_Numpy_ array for which double-bootstrap... | 1d812561daf3ced06d68ef069dd61ace5ce4ca5a | 3,632,728 |
def http_headers(headers=None):
"""Construct common HTTP headers from the jomiel options.
Args:
headers (dict): additional headers to use
Returns:
A headers dictionary ready to be used with `requests`
"""
result = {"user-agent": opts.http_user_agent}
if headers:
result... | 5dc0cf25778c5950d0c70966606385d95f8c3a85 | 3,632,729 |
import requests
from bs4 import BeautifulSoup
def stock_classify_board() -> dict:
"""
http://vip.stock.finance.sina.com.cn/mkt/
:return: 股票分类字典
:rtype: dict
"""
url = "http://vip.stock.finance.sina.com.cn/quotes_service/api/json_v2.php/Market_Center.getHQNodes"
r = requests.get(url)
da... | 258b9315f5d8d854aaf891ff6d35ba55d5a06b31 | 3,632,730 |
def compute_rgroup_dataframe(pdb_df: pd.DataFrame) -> pd.DataFrame:
"""Return the atoms that are in R-groups and not the backbone chain.
:param pdb_df: DataFrame to compute R group dataframe from
:type pdb_df: pd.DataFrame
:returns: Dataframe containing R-groups only (backbone atoms removed)
:rtype... | fe6bef0821e5c3230c961485144ab77c2cede770 | 3,632,731 |
from typing import Dict
def find_requests(spec: Dict) -> Dict:
"""
Returns a Dict like:
{
'pets': {
'create_a_pet': {'method': 'POST', 'url': 'http://petstore.swagger.io/v1/pets'},
'info_for_a_pet': {'method': 'GET', 'url': 'http://petstore.swagger.io/v1/pets/:petId'},
... | 1efd26b8819b90e5371a409c56d11a46ee887e93 | 3,632,732 |
import collections
from typing import OrderedDict
import six
def flatten_ordered(dd, separator='_', prefix='', is_list_fn=lambda x: isinstance(x, list)):
"""Flatten a nested dictionary/list
Args:
separator: how to separate different hirearchical levels
prefix: what to pre-append to the function
... | 4475f613d8b482c31a2fe557355506a5479a9ff3 | 3,632,733 |
def error_internal_server(error):
""" Return default JSON error message for unhandled Internal Server error """
return APIError.default_handler(APIInternalError) | 9e9b543ccbb186121b79c60189deb35e192a7beb | 3,632,734 |
def apply_functions(lst, functions):
"""
:param lst: list of values
:param functions: list of functions to apply to each value.
Each function has 2 inputs: index of value and value
:return: [func(x) for x in lst], i.e apply the respective function to each
of the values
"""
assert len(ls... | 679a2219008e438249e1227d5aab6529019c497c | 3,632,735 |
import torch
def plot_graph(
codepath,
filename="graph",
directory="./",
code2in = [0,1,0,1,2,1,2,3,2,3],
code2out = [0,0,1,1,1,2,2,2,3,3],
):
""" Plot the final searched model
Args:
codepath: path to the saved .pth file, generated from the searching script.
arch_code_a: ar... | 45290fa6254855157b023a172beae242240046ad | 3,632,736 |
def rotate_image(image, rotation):
"""
Rotate the image givent eh cv2 rotation code
"""
return cv2.rotate(image, rotation) | 4d341e5e2efc4d15e9b14bf557928ad4c6bcbb4a | 3,632,737 |
def location_normalize(location):
"""
Normalize location name `location`
"""
#translation_table = dict.fromkeys(map(ord, '!@#$*;'), None)
def _remove_chars(chars, string):
return ''.join(x for x in string if x not in chars)
location = location.lower().replace('_', ' ').replace('+', ' ')... | 4b8aaec23ef9763bc02fd4d3635ba930f8c3dcea | 3,632,738 |
def remove_car(garage_id, car_id): # noqa: E501
"""remove car from garage
# noqa: E501
:param garage_id: id of garage
:type garage_id: int
:param car_id: id of car
:type car_id: int
:rtype: None
"""
with get_db() as con:
cur = con.execute('''
delete from... | ab8a09f9edb027a50cd43b9f380596bc8ff56e89 | 3,632,739 |
def review(items, config):
"""Reviews the incoming item and returns a Review for it
:param items: a list of items that must be `Sentence` instances.
:param config: a configuration map
:returns: one or more Review objects for the input items
:rtype: list of dict
"""
# We require a list: much... | c33e363ec66f9afa88f27db255533e22e349b5c0 | 3,632,741 |
def create(words, vector_length, window_size):
"""Create new word2vec model."""
w2vmodel = {}
for col in words.columns:
if col in words:
w2vmodel[col] = gs.models.Word2Vec([list(words[col])], min_count=1, size=vector_length,
window=window_size, seed=... | ba93628ba337cc40caa24bdc0a062c2c61933e14 | 3,632,742 |
def rotate(location, direction=CLOCKWISE):
"""
Find a stronghold 120 degrees clockwise or counter-clockwise from location.
location is an tuple of x and z. direction can either be CLOCKWISE or
COUNTERCLOCKWISE.
"""
location = Point(*location)
x = simplify(cos(direction) * location.x + -sin(d... | 34f98ce6171ea1cb4b488ebcc0e8686973346ae5 | 3,632,744 |
def checkWin():
"""Analyze the scores of the players and check win, return player1 or player2 as a string"""
if player1.score < player2.score:
return "player 2"
else:
return "player 1" | bf6d6ad5aca0713f63658516ce8df422a9bcc0ea | 3,632,745 |
def credits(request):
"""A view that outputs the result of a credit query."""
md = request.matchdict
model = model_from_matchdict(md)
items = items_from_matchdict(md, model)
date = date_from_matchdict(md)
return model.bulk_credits(
items,
*(s for s in md['types'].split('+') if s)... | 34c61e5ef8a29932f296e3678df8ba51b4111fb3 | 3,632,746 |
def dict_is_test(data):
"""helper function to check whether passed argument is a proper :class:`dict` object describing a test.
:param dict data: value to check
:rtype: bool
"""
return (
isinstance(data, dict)
and "type" in data
and data["type"] == "test"
and "id" in... | 320b47f8f41f42f6a6554741c9b2de38b370605a | 3,632,747 |
import string
def _replace_vars(text, param_dict):
"""
Given a block of text, replace any instances of '{key}' with 'value'
if param_dict contains 'key':'value' pair.
This is done safely so that brackets in a file don't cause an error if
they don't contain a variable we want to replace.
See ht... | 4f218a9f9df46c2535c2d3060084430b74d0cd72 | 3,632,748 |
from typing import Union
from pathlib import Path
from typing import Optional
def import_key(filepath: Union[str, PathLike[str], Path], passphrase: Optional[str] = None) -> RsaKey:
"""
Import a secret key from file.
Parameters
----------
filepath : str | os.PathLike[str] | pathlib.Path
Fi... | 40a0b12ea17ec391cb71883aa6aecb9f73fdeb0d | 3,632,749 |
from typing import Set
def GetZonesInRegion(region: str) -> Set[str]:
"""Returns a set of zones in the region."""
# As of 2021 all Azure AZs are numbered 1-3 for eligible regions.
return set([f'{region}-{i}' for i in range(1, 4)]) | e539662604eb5da2583630844dd54d11d266c827 | 3,632,750 |
def compare_3PC_keys(key1, key2) -> int:
"""
Return >0 if key2 is greater than key1, <0 if lesser, 0 otherwise
"""
if key1[0] == key2[0]:
return key2[1] - key1[1]
else:
return key2[0] - key1[0] | d134eaaa4ef8f218164be4e5bc6fced01c3de7eb | 3,632,751 |
import heapq
def merge_two_lists_heap(l1: ListNode, l2: ListNode) -> ListNode:
"""Returns a single sorted, in-place merged linked list of two sorted input linked lists
The linked list is made by splicing together the nodes of l1 and l2
Args:
l1:
l2:
Examples:
>>> l1 = linked... | 19c7507a53d6d365259f2226b008b3ad065e5f21 | 3,632,752 |
import requests
def demo():
""" Step 1 of the authentication workflow, obtain a temporary
resource owner key and use it to redirect the user. The user
will authorize the client (our flask app) to access its resources
and perform actions in its name (aka get feed and post updates)."""
# In this st... | 547114a93f44f152d6e8545c311b07ad86101441 | 3,632,753 |
def get_blast(pdb_id, chain_id='A'):
"""
Return BLAST search results for a given PDB ID
The key of the output dict())that outputs the full search results is
'BlastOutput_iterations'
To get a list of just the results without the metadata of the search use:
hits = full_results['BlastOutput_iterat... | 92a1ed6e53914e5468b491782263082a6c35b4de | 3,632,754 |
from datetime import datetime
import time
def getDayBoundaryTimeStampFromUtcTimeStamp(timeStamp, timeZoneId):
"""
get to the day boundary given a local time in the UTC timeZone.
ts is the local timestamp in the UTC timeZone i.e. what you would
get from time.time() on your computer + the offset betwen ... | e8c24c0a3ec47546cb30eaebe172bdcfd627c7c9 | 3,632,755 |
def generate_cylinder_square_array(size, porosity, segmented=True):
""" Generate a 2D periodic array of circles
:param size: length of one side of the output domain
:type size: int
:param porosity: porosity of the output domain
:type porosity: float
:param segmented: return ... | 0c8c35d6549c6335156bc475eeeef235a442a213 | 3,632,756 |
import csv
def ephemerides(file_path,
P_orb=2.644,
T_e=2455959.0039936211,
e=0.152,
P_rot=None,
phase_start=None,
Rot_phase=False,
print_stat=True,
save_results=False,
save_... | 0651616848c9fa0f20862ab00826751672a86156 | 3,632,757 |
def _GetMSBuildToolSettings(msbuild_settings, tool):
"""Returns an MSBuild tool dictionary. Creates it if needed."""
return msbuild_settings.setdefault(tool.msbuild_name, {}) | 3a2cb3e9c8910a6901be0937be18aac00d532e2b | 3,632,758 |
def _apply_color(color: str, message: str) -> str:
"""Dye message with color, fall back to default if it fails."""
color_code = AvailableColors["DEFAULT"].value
try:
color_code = AvailableColors[color.upper()].value
except KeyError:
pass
return f"\033[1;{color_code}m{message}\033[0m" | 752557dc4416c5d141169f8155f41b6847eef318 | 3,632,759 |
import scipy
def get_mel_spectrogram(audio, pextract=None):
"""Mel-band energies
Parameters
----------
audio : numpy.ndarray
Audio data.
params : dict
Parameters.
Returns
-------
feature_matrix : numpy.ndarray
(log-scaled) mel spectrogram energies per audio ch... | 71e685ee0cf0f1359329aaf15df2a02db0f879b2 | 3,632,761 |
from pathlib import Path
def getName(value):
"""
Finds the name of a :model:`browseNet.path` or :model:`browseNet.Share`.
"""
if isinstance(value,Path):
return value.shortname
elif isinstance(value, Share):
return value.sharename
else:
return "??" | 006114fc40b75d1630ce18f55694e582711c5ee8 | 3,632,762 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.