content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def validate_sample_for_sampleSet(
queryDict, samplesetitem_label=_SampleSetItem.verbose_name
):
"""
basic validation of sample attributes for sample set item creation/update
return a boolean isValid and a list of text error messages
"""
errors = []
if not queryDict:
return (
... | 15f2a9f6a67cfbc10f488d8837bf39d313b9a74f | 56,627 |
from typing import Type
from typing import Callable
from typing import Sequence
from typing import Any
def polars_type_to_constructor(
dtype: Type[DataType],
) -> Callable[[str, Sequence[Any], bool], "PySeries"]:
"""
Get the right PySeries constructor for the given Polars dtype.
"""
try:
r... | 13a5128acd666c9e89b88c527986aaa57b91763a | 56,628 |
def cresci_genuine_accounts_users():
"""Load genuine_accounts/users.csv from cresci-2017"""
return CresciUserDataset(GENUINE_ACCOUNT_USER_PATH) | 86062d35f9af57f20ba1457dd164c67f24f82a98 | 56,629 |
def safe_iteritems(items):
"""Safely iterate over a dict or a list."""
# For dictionaries, iterate over key, value and for lists iterate over
# index, item
if hasattr(items, 'items'):
return _compat.iteritems(items)
else:
return enumerate(items) | 7e6ee430412c9b5b067bc28f3b5b6f6a9b36dbec | 56,632 |
import types
def appendStr(obj, st):
"""adds a string onto the __str__ output of an instance"""
def appendedStr(oldStr, st, self):
return oldStr() + st
oldStr = getattr(obj, '__str__', None)
if oldStr is None:
def stringer(s):
return s
oldStr = Functor(stringer, str... | f61994a6f37af3fe51caba1be526ec7a4b63c9fb | 56,633 |
def get_umls_ticket(apikey=None, AuthClient=AuthClient, tgt=tgt):
"""
Get a single use ticket for the UMLS REST services.
It is supposed that an Author Client and a Ticket
Granting Service have already been set-up in case
the apikey = None. If an api-key is given, create the
above needed instanc... | 626ad36efed98bec4069b5d442aebaddfdd2ec23 | 56,635 |
def init_float64_multiarray(rows,columns):
"""!
Function that initializes a Float64MultiArray of size rows x columns.
@param rows: Number of rows of the returned multiarray.
@param columns: Number of columns of the returned multiarray.
@return empty Float64MultiArray instance.
"""
a = Float6... | 0480b8d3b86daea2f0d6b31e08f953c751d2598d | 56,637 |
def partition(pred, iterable):
"""Use a predicate to partition entries into false entries and true entries.
:param pred: the predicate that divides the values
:param iterable: source of values
"""
# partition(lambda x: x % 2, range(10)) --> 0 2 4 6 8 and 1 3 5 7 9
t1, t2 = it.tee(iterable)
... | 697173c169e5a8f42e3c7c361e01ea6f73b4ee3a | 56,639 |
def reset():
"""
Inserts the escape sequence of display reeet.
Returns
-------
seq : str
Escape sequence of display reeet.
"""
return display_reset() | 23094814ece1c551052179be1a837de761060444 | 56,640 |
def steffen_3d(
v_in,
z_in,
z_out,
z_min_surface,
z_max_surface,
lower_extrapolation_with_gradient=False,
upper_extrapolation_with_gradient=False,
):
"""
Performs Steffen interpolation on each individual column.
Steffen, M. (1990). A simple method for monotonic interpolation
... | 84733cbbf1075632cbeaa09a4e5f9872f53288c2 | 56,641 |
def _compute_attention(attention_mechanism, cell_output, attention_state,
attention_layer):
"""Computes the attention and alignments for a given attention_mechanism."""
alignments, next_attention_state = attention_mechanism(
cell_output, state=attention_state)
# Context is the inner ... | 37782abd6eb7d66eaa545e63f3203ee0440b1a2a | 56,642 |
import re
def clean_scenarios(row) -> pd.Series:
"""Helper function to extract select scenario details for final comparison plots."""
row = str(row)
sel_col = re.search(pattern="^s.*([13])", string=row).group(1) if re.match(pattern="^s.*([13])", string=row) else nan
pos_col = re.search(pattern="^s.*[1... | e346423b1bbec5d7f0db730a5f80fc62189b79b8 | 56,643 |
def GetNumRedisServers(redis_vm: _LinuxVirtualMachine) -> int:
"""Get the number of redis servers to install/use for this test."""
if FLAGS.num_cpus_override:
return FLAGS.num_cpus_override * _NUM_PROCESSES.value
return redis_vm.NumCpusForBenchmark() * _NUM_PROCESSES.value | 44b5561d9ab0ca4456fcdde2179d2e08589aeb06 | 56,644 |
def plot_evlossdistr(lossSamples, meanloss):
"""Plot historgram of the loss summary"""
ax = lossSamples.hist(cumulative=True, bins=len(lossSamples))
ax.vlines(lossSamples.median(), ymin=0, ymax=100, label="Sample Median")
ax.vlines(lossSamples.mean(), linestyles='dashed', ymin=0, ymax=100,
... | 6a665aa0a5d35422cb6e19ba66cca6667e76b620 | 56,646 |
import json
def main(vk_file, proof_file):
"""Verifies the proof.json using the vk.json"""
with open(vk_file, 'r') as vk_handle:
vk = VerifyingKey.from_dict(json.load(vk_handle))
with open(proof_file, 'r') as proof_handle:
proof = Proof.from_dict(json.load(proof_handle))
if not vk.veri... | 37ce16aec16698d4b37cffcbaf6f0e21429999f1 | 56,647 |
def reduce_opacity(im, opacity):
"""Returns an image with reduced opacity."""
assert opacity >= 0 and opacity <= 1
if im.mode != 'RGBA':
im = im.convert('RGBA')
else:
im = im.copy()
alpha = im.split()[3]
alpha = ImageEnhance.Brightness(alpha).enhance(opacity)
im.putalpha(alph... | 662bcc4b6d68a87af07634ca464ed605a6c29846 | 56,649 |
import re
def crawllogs_to_df(logs_file_path):
"""Convert a crawl logs file to a DataFrame.
An interesting option while using the ``crawl`` function, is to specify a
destination file to save the logs of the crawl process itself. This contains
additional information about each crawled, scraped, blocke... | 53771cf36a0b9a47a95fafb0e1ef8bd4791c141a | 56,650 |
def centerImageFile(infile, outfile=None, targetRadius=None):
"""
Center the given image file on a target and save it to outfile, if given.
Returns x,y,foundRadius
"""
im = cv2.imread(infile, cv2.IMREAD_GRAYSCALE)
# find the bounding box of biggest object
# either a blob or a circle
bo... | fc3a3cbd407a4a0f67225c71a4c078f08c883055 | 56,651 |
def get_data(data):
"""Gets the section data payload from the given section data
Parses the given array of section data bytes and returns the section data. This is an array of data bytes.
It can be further parsed based on the type of section.
"""
offset = 3
sl = get_section_length(data)
data_len = sl
if get_... | 710edd4d2fb1f4295bc69fb751a42bc765749111 | 56,652 |
def uniq_count(data):
"""
Count number of unique elements in the data.
Args:
data (list): values.
Returns the number of unique elements in the data.
"""
uniq_atom_list = list(set(data))
return len(uniq_atom_list) | d61eff27aed7d788fa6cc80eb25661f0ebae7dfd | 56,653 |
def parse_output_minimap2(output, id):
"""
:param output: minimap2 stdout
:type output: io.TextIOBase or io.StringIO
:rtype: list[Alignment]
"""
alignments = []
for line in output:
split_line = line.rstrip().split("\t")
query_name = split_line[0]
query_len = int(spl... | 7450a3bd33f3d36e320115bf9339f690f8e22317 | 56,654 |
def try_float(x):
"""
Convert to float
:param x:
:return:
"""
if x is None:
return None
try:
return try_float(x)
except:
pass | 905b1cdedc086a2f6f6572bb720b9d04ef1aa2b6 | 56,655 |
def isBGS_colors(rfiberflux=None, gflux=None, rflux=None, zflux=None, w1flux=None, rfibertotflux=None,
maskbits=None, south=True, targtype=None, primary=None):
"""Standard set of color-based cuts used by all BGS target selection classes
(see, e.g., :func:`~desitarget.cuts.isBGS` for parameters)... | 0fc72308f9f9fd1383c5279beca1c7dac7c2bf3d | 56,656 |
def SubPhase( Fin, Phi):
"""
*Substitutes a given phase distribution in the field with.*
:param Phi: N x N square array of real numbers or scalar
:type Phi: numpy.ndarray, int, float
:return: output field (N x N square array of complex numbers).
:rtype: `LightPipes.field.Field`
:Exampl... | a341f27bb828a4eb8215c0028f8278e83188ab53 | 56,657 |
def void_ptrptr_generator(*args):
"""void_ptrptr_generator() -> void"""
return _cv.void_ptrptr_generator(*args) | b306bd1cd636ab205bec6cf1fa6903ec2258fe72 | 56,658 |
def get_e_b2(Theta_ex_Ave, L_BB_DHW_b2, f_hs):
"""浴槽自動湯はり時における日平均給湯機効率 (3e)
Args:
Theta_ex_Ave(ndarray): 日平均外気温度 (℃)
L_BB_DHW_b2(ndarray): 1日当たりの浴槽水栓湯はり時におけるバックアップボイラーが分担する給湯熱負荷
f_hs(float): 当該給湯機に対する効率の補正係数
Returns:
ndarray: 浴槽自動湯はり時における日平均給湯機効率
"""
# 日平均給湯機効率を計算するための回帰係数... | cbef9b2c5437083decb33db9bafb853fd42afb22 | 56,659 |
import pickle
def load_dt(filename):
"""
加载保存好的决策树
:param filename: 文件名
:return: python dict
"""
# 'b' 表示二进制模式
fr = open(filename, 'rb')
return pickle.load(fr) | c61772d6c8606e45ef323bd8dd30cb0c9e6ebf35 | 56,660 |
def compute_graham_scan( planars ):
"""
Attempt to clean the data,
and simplify it to an approximate shape
by returning the list of corners
corresponding to the convex hull of the
given points.
It attempts this using the Graham Scan
"""
return graham_scan.convex_hull( planars ) | 5c1ea0311be6baa9f76143ace1e71148a5dd5a4f | 56,661 |
def hartmann3_by_2_1_01(x):
""" Summing two Hartmann3 functions to get a 6D function. """
return hartmann3_01([x[0], x[4], x[2]]) + hartmann3_01([x[3], x[1], x[5]]) | 3bac0289a7c18cb82cde87b79befdf70318df427 | 56,663 |
def bbox_to_segmentation(image, bbox, matter=None, seg_type='rle', mask_type='gaussian'):
"""
:param image: ndarry, (img_h, img_w, 3)
:param bbox: [int], x, y, w ,h
:param seg_type: 'rle', 'poly'
:param mask_type: 'gaussian', 'bbox', 'butterfly'
:param matting: bool, whether to mat the mask or ... | ee17d6eeedcc9219a3b69de9339ed6955c1754e5 | 56,664 |
def _get_feature_by_index(x, p_h, p_w):
"""gather feature by specified index"""
# x (n, c, h_in, w_in)
# p_h (n, h, w, k*k)
# p_w (n, h, w, k*k)
n, c, h_in, w_in = x.shape
_, h, w, k2 = p_h.shape
# (n, c, h_in, w_in) -> (n, h_in, w_in, c)
x = x.transpose(0, 2, 3, 1)
# the following... | 4c1b52935c88a5f7531c1ee00c469db10bca8b3a | 56,665 |
def parse_params(param_str, case_sensitive = False):
"""
parse_params(param_str, case_sensitive = False) -> a map of parameters
Parse parameter from given string. The string follows a format like
below:
param1=value1,param2=value2,...
We support escape token '\\' to escape "," and "=".
... | e43cf824fb232cba9ea3be53d50394d6a1cac08d | 56,668 |
def extract_top_level_dict(current_dict):
"""
Builds a graph dictionary from the passed depth_keys, value pair. Useful for dynamically passing external params
:param depth_keys: A list of strings making up the name of a variable. Used to make a graph for that params tree.
:param value: Param value
:... | 52fd9592b514a925279e1a0ae64ebc6b62ab5d20 | 56,670 |
from pathlib import Path
import re
def extract_dependence():
"""
get all dockerfile dependence
"""
dockerfiles = Path("../").walkfiles("Dockerfile*")
dep_graph = {}
for i in dockerfiles:
with open(i, "r") as f:
match = re.search(r"FROM (.*):", f.readline().rstrip())
... | 666d9c0ae107f9b68b51ed03a81ed5c3d776a83f | 56,671 |
def getCoordonneesJoueur(plateau,numJoueur):
"""
retourne les coordonnées sous la forme (lig,col) du joueur passé en paramètre
paramètres: plateau: le plateau considéré
numJoueur: le numéro du joueur à trouver
resultat: un couple d'entier donnant les coordonnées du joueur ou None si
... | d3a4b88609df803850266097235fbdd852329c60 | 56,672 |
def wrap(tensor, is_stacked=True, is_sparse_stacked=False):
"""Helper to create a WrappedTensor object."""
assert isinstance(is_stacked, bool)
assert isinstance(is_sparse_stacked, bool)
assert isinstance(tensor, ops.Tensor)
assert not is_sparse_stacked or is_stacked, ("If the wrapped tensor is "
... | 4438fd9fa6ea7f3ede2b928d800597061b35acf6 | 56,674 |
def v_ext(x):
"""Ground-state external potential
"""
return 0.5*(0.25**2)*(x**2) | ea4f5f835ed99451a518c19e0e5accb84c576693 | 56,675 |
def _rrv_rdiv_ ( s , o ) :
"""(right) Division of RooRealVar and ``number''
>>> var = ...
>>> num = ...
>>> res = num / var
"""
if isinstance ( o , _RRV_ ) and not o.isConstant() : o = o.ve ()
elif hasattr ( o , 'getVal' ) : o = o.getVal ()
#... | a21101e430b00a1d634a1c0ebc0fb0bc8bf7cc1a | 56,676 |
from typing import MutableSequence
from typing import Any
def swap(seq: MutableSequence[Any], frst_idx: int, snd_idx: int) -> MutableSequence[Any]:
"""Swaps two elements in the `seq`."""
if seq[frst_idx] == seq[snd_idx]:
return seq
seq[frst_idx], seq[snd_idx] = seq[snd_idx], seq[frst_idx]
retu... | 1d4c3260e57f827293d849b490bd35c2ae9f9698 | 56,677 |
def app_factory(global_config, **local_conf):
""" This function is defined as a `paste.app_factory` entry point in
`./setup.py` and is called with configuration settings by::
paster serve config.ini
"""
# merge the global and local config
config = global_config
con... | 6cfa012160543c522a168dde2a0f48c861be147c | 56,679 |
def get_call_tree(profile_file):
"""
Typical use case, gets all the information regarding the calltree
Parameters
==========
profile_file : str
Name of the ``.cubex`` file
Returns
=======
calltree : CubeTreeNode
A recursive representation of the call tree.
"""
#... | 4c7e8adea238f4e03c26082dc061781237ab512e | 56,680 |
def parse_problems(lines):
""" Given a list of lines, parses them and returns a list of problems. """
problems = []
i = 0
while i < len(lines):
h, w = map(int, lines[i].split(" "))
problems.append((w, h, lines[i + 1:i + h + 1]))
i += h + 1
return problems | 883a6a7cfaa8104c171a6e166fcbb8f4403f4c01 | 56,681 |
def home(request):
"""Search page for Organisation Unit / Default page."""
try:
orgs = get_list_types()
if request.method == 'POST':
form = FormRegistry(data=request.POST)
search_string = request.POST.get('org_unit_name')
org_type = request.POST.get('org_type'... | d6db7bf59e0f11480981c906bc2eb5aab0b1a919 | 56,683 |
import json
def _InternalRequest(connection_policy, request_options, request_body):
"""Makes one http request.
:Parameters:
- `connection_policy`: documents.ConnectionPolicy
- `request_options`: dict
- `request_body`: str, unicode or Non
:Returns:
tuple of (result, header... | bb914f6c293c08585c80f22b178b413618f84c74 | 56,684 |
def create_c2_arena(target_path, arena_name, max_reward=5, time=250,
max_num_good_goals=1, is_train=False):
"""
Create .yaml file for C2-type arena.
- Only goals.
- Different random size for all goals.
- At least one green and one red ball.
Parameters:
... | 7619ccd931a721c57cfa022bd2aeaa5719a29e7a | 56,685 |
def read_input(fpath):
"""
Read a specified file, and return a list of the file's contents
separated by new lines.
Args:
fpath (str): Path of the file to read.
Returns:
list
"""
with open(fpath, 'r') as f:
return f.read().splitlines() | ac10f24d7b5769ee85b3f13f3fde278d56ef1741 | 56,686 |
def move_ferry_with_new(instructions: list) -> np.ndarray:
"""Navigate ferry according to new navigation instructions."""
waypoint = np.array([10, 1]) # W/E and N/S directions
position = np.zeros(2, int)
for action, value in instructions:
if action == "F":
position += value * waypoi... | 35bd396e2fbf1856a12ee7cb239505e865efe1b9 | 56,687 |
def ndim(X):
"""Return the number of array dimensions."""
return X.ndim if issparse(X) else np.ndim(X) | 946a52b38534651bf2577174ebe679bf28592247 | 56,689 |
def safe_get(dictionary, key, default_value, can_return_none=True):
"""
Safely perform a dictionary get,
returning the default value if the key is not found.
:param dict dictionary: the dictionary
:param string key: the key
:param variant default_value: the default value to be returned
:par... | eb53ad7a17db3f2c66c8b16b20ae2aac9b1e34e3 | 56,690 |
def sizeof(C_type): # real signature unknown; restored from __doc__
"""
sizeof(C type) -> integer
sizeof(C instance) -> integer
Return the size in bytes of a C instance
"""
return 0 | 8eba27c0e08247dea9188806dcc2eee6b81e2afc | 56,691 |
def computeCostMulti(X, y, theta):
"""
computes the cost of using theta as the parameter for linear
regression to fit the data points in X and y
"""
m = y.size
J = 0.
# ====================== YOUR CODE HERE ======================
# Instructions: Compute the cost of a particular ch... | 99b50b935266001c44b6b0645f73468888c0ba80 | 56,692 |
def process_video(video):
"""Process a video and extract the ball position during each frame
and the corresponding timestamp
Args:
video(cv2.VideoCapture): the video to be processed
Returns:
positions(pandas.DataFrame): a dataframe containing frame timestamp, ball x positio... | 22bb67621cfdc288521dc683589a93ff0dd1145a | 56,693 |
def load_star_file(fil, dic):
"""
Load star counts file into a dictionary.
:param fil: path to STAR counts file to load
:param dic: ``OrderedDict`` to load file to
:returns: updated ``OrderedDict``
"""
reader = get_open_function(fil)
with reader(fil, "rt") as fh:
for line in fh:
... | cf9d697d3012ccda0360ae2c1863cf92aa9f417b | 56,694 |
def parse_grid(grid):
"""
converts a grid like
K F A
L G B
M H C
N I D
O J E
to
ABCDEFGHIJKLMNO
"""
rows = [row.strip().split(" ") for row in grid]
return "".join(rows[row][col] for col in range(2, -1, -1) for row in range(0, 5)) | f1cb825e3d20edd2db92fee4104204e9bcb1f54a | 56,695 |
def DecodeFltZero(x) -> int:
"""Returns the integer representation of 32 bit float zero"""
assert x == 0
return 0 | 69dc1e10dca39b2720d457f049260109a10bd48f | 56,696 |
def check_capthca(param: Param, request: Request):
"""
post 方法示例
- **type**: 类型
- **app_id**: 应用id
"""
type = param.type
app_id = param.app_id
return_dict = ResponseMessage(code=SUCCESS, message=ERR_MSG[SUCCESS], data={'check_status': '1'})
# 日志
log.info('xxx result : {}'.for... | 2b6b292e674a3a218bd68bd7b209a1eb52a1fa5d | 56,697 |
def user_custom_site(request):
"""
用户自定义源名称
"""
site_id = request.POST.get('site_id', '').strip()[:32]
site_name = request.POST.get('site_name', '').strip()[:20]
site_author = request.POST.get('site_author', '').strip()[:20]
user = get_login_user(request)
if user and site_id:
l... | 060c50ff8c353a368228cbaed786699e39294b24 | 56,698 |
def _find_clubs(search_terms):
""" Generate list of clubs matching all search terms.
:param List[str] search_terms: a list of search terms
:return: a list of organizations
:rtype: List[Organization]
"""
clubs = []
for club in get_organizations():
if all([(a in club.name) for a in s... | 26b73ba914fb05a3d269a11b034a640499eea22f | 56,699 |
def update_yt_to_mlab_vector(field, ds, xkey, ykey, zkey,
cube_slice=np.s_[:,:,:]):
"""
Update a mayavi field based on a yt dataset.
Parameters
----------
field : mayavi vector field
The field to update.
ds : yt dataset
The dataset to get the data f... | a83326339f3aa13259a3102d1eac570de6399190 | 56,700 |
def get_colour_map_list():
"""Return the list of the available colormaps."""
return sorted(plt.cm.datad) | a70d1e8af694c7df8dbed8e1087f2096fe42b572 | 56,701 |
def forgot_password():
"""
If NOTIFICO_PASSWORD_RESET is enabled and Flask-Mail is configured,
this view allows you to request a password reset email. It also
handles accepting those tokens.
"""
# Because this functionality depends on Flask-Mail and
# celery being properly configured, we def... | cb00ffed8b7cdaa36dc433dfdc0a0c5d4fa7d42b | 56,702 |
def get_bound_mask(y_bound_mask):
"""
this method gets a bound_mask matrix
and returns the masks for each keypoint
:type y_bound_mask: int
: param y_bound_mask: a matrix of shape (#batch, #kpts)
where for each keypoint one
values is given:
0: no... | dcd363874c9a48ce9c3811a6c3b4f066eeab5d69 | 56,703 |
import torch
import tqdm
def runBestNet(train_dl, test_dl, best_test, outputPath , nfold , class_len , net, feature_name , test_len ):
""" Load the best net and test it on your test set
Attributes:
train_dl, test_dl: train(test) sets
best_test: the testing accuracy of best model
outp... | b217f80240044fcb3c0d05d92a41cc23e348cc09 | 56,705 |
from typing import Optional
import torch
def fit_circle_in_3d(
points,
*,
n_points: int = 0,
angles: Optional[torch.Tensor] = None,
offset: Optional[torch.Tensor] = None,
up: Optional[torch.Tensor] = None,
) -> Circle3D:
"""
Simple best fit circle to 3D points. Uses circle_2d in the
... | 305d4d76602c03037fe12832d62ccd32ea3ae1bd | 56,706 |
def predicate_contains_hello(x):
"""Predicate True when 'hello' is in value."""
return 'hello' in x | 884ef0a9a925865d5bd9093d52f1c248e498aa80 | 56,707 |
def index(request):
"""
index home page
:param request:
:return:
"""
# PC 版、手机版适配
user_agent = parse(request.META.get('HTTP_USER_AGENT', ''))
pc = user_agent.is_pc
# 判断是否登录用户
user = get_login_user(request)
# 默认的渲染列表,区分是否登录用户
if user is None:
sub_feeds = get_visi... | 42ff2de48bb7bc7e1de1413cd7c1590b5510fda4 | 56,708 |
def operation_name_check(operation_name, check_info, conditions, message_list):
"""
[概要]
OPERATION_NAMEのバリデーションチェックを行う
[引数]
operation_name : OPERATION_NAME
check_info : チェック情報
conditions : 条件名
message_list : メッセージリスト
[戻り値]
message_list : メッセージリスト
"""
if opera... | 13b0776dee4804bf80b6497a80f4fe3572bdddd6 | 56,709 |
import random
def get_message(response_type):
"""
Return a random string message from a given type
"""
if response_type in chat_responses:
return random.choice(chat_responses[response_type])
return random.choice(chat_responses['no_answer']) | 1472a3cb8bad09e050ad663a28f33f0833fada7e | 56,710 |
from typing import Union
def BM1(x: Union[float, np.ndarray]) -> Union[float, np.ndarray]:
"""
J. Wojdyła, Z. Szkutnik, "Nonparamteric confidence bands in Wicksell's problem", Statistica Sinica28(2018), 93-113
"""
return 0.55 * 252 * (1 - x) ** 6 * x ** 2 + 0.45 * 252 * (1 - x) ** 2 * x ** 6 | 0acc6a80ec9f77c32cb6a4ac89d2cd244943cf61 | 56,711 |
def get_recent_trading_stocks():
"""获取最近一期处于交易状态的股票清单"""
df = fetch_minutely_prices()
return sorted(df.query('成交量>0').index.str.slice(2, 8).values) | 60649320b562fcc1e8db2d2c3557449e38c6068b | 56,712 |
def get_tile_url(xtile, ytile, zoom):
"""
Return a URL for a tile given some OSM tile co-ordinates
"""
return "http://tile.openstreetmap.org/%d/%d/%d.png" % (zoom, xtile, ytile) | 20af9f5b4065d96c285e6c4e5c64123f0343b659 | 56,713 |
def split_into_words_by_char_count(s, chunk_size, max_from_end=None):
"""
Split a string into an array of strings each of length at most chunk_size.
Try to split on whitespace if possible (possibly resulting in chunks of size
less than chunk_size), except if it would make the last word longer
than m... | ae3391536bd6e92f0c8ae9ce5cce76865485f689 | 56,714 |
import torch
import random
def train(input_variable, lengths, target_variable, mask, max_target_len, encoder, decoder, SOS,
encoder_optimizer, decoder_optimizer, batch_size, teacher_forcing_ratio, clip, device):
"""
Training function for one iteration
"""
# Zero gradients
encoder_optimiz... | 0919450361631d198e640d61f44795ae1a5f7e8d | 56,715 |
def set_arguments(self, _id):
"""
Set arguments
"""
args = list()
cwl_wf_url = {
"name": self.cwl_static_keys[0],
"description": self.cwl_static_keys[1],
"help": self.cwl_static_keys[1] + " for " + _id,
"type": self.cwl_static_keys[2],
"value": self.cwl_wf,
... | 7965d86438a43a44f40784805a09c4320233b2be | 56,716 |
import json
import torch
def invocations():
"""Do an inference on a single batch of data. In this sample server, we take data as CSV, convert
it to a pandas data frame for internal use and then convert the predictions back to CSV (which really
just means one prediction per line, since there's a single col... | 2523cc39b2b973069df643efaeaba2c07d779971 | 56,717 |
def get_implementation(plugin_identifier):
"""
Get a plugin implementation instance for the given plugin identifier.
The map of identifier to plugin class lives in `settings.DEMOCRACY_PLUGINS`.
:param plugin_identifier: Plugin identifier string
:return: An object instance deriving from `Plugin`.
... | d7dde285325a028fe69cd67ecf5f395e5eb81330 | 56,718 |
import json
def json_to_dict(json_file_path):
"""
Convert a .json file to a Python dictionary.
Parameters
----------
json_file_path: str
Path of the JSON file
Returns
-------
dictionary: dict
The original JSON file as a Python dictionary
"""
with open(json_fi... | d8ef47ab43c3477212795e795690bad4081e0321 | 56,720 |
def remove_outliers(df_raw):
"""
Removes outliers
:param df_raw:
:return:
"""
diff_secs_col = f.col("dropoff_datetime").cast("long") - f.col("pickup_datetime").cast("long")
df_raw = df_raw.withColumn("trip_duration_m", diff_secs_col / 60.0)
df_raw = df_raw.filter((f.col("tip_amount") >= ... | 4633c2ea512cd1fe92ad17a41d60775576604244 | 56,721 |
def get_audits():
"""Get OS hardening security limits audits.
:returns: dictionary of audits
"""
audits = []
settings = utils.get_settings('os')
# Ensure that the /etc/security/limits.d directory is only writable
# by the root user, but others can execute and read.
audits.append(Direc... | f60d5b974b00ae3558dc0684a43f751930441472 | 56,722 |
def save_input(filename, values):
"""
# Save the input/printing parameters of the EFI measurement.
#
# Input
# =====
# `filename`: File name of the input parameters to save to.
# `values`: The input parameters to save, expect shape (`n_input`,).
"""
return np.savetxt(filename, values... | b8ad858cc97399d47d2ec111989453ced1cedcc7 | 56,723 |
from typing import Tuple
def send_initial_inference_request(
predict_service: prediction_service_pb2_grpc.PredictionServiceStub,
inputs: Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]
) -> core.NetworkOutput:
"""Initial inference for the agent, used at the beginning of MCTS."""
input_ids, input_typ... | f49bd289c81cd4bc4adda3a32e5a649530a29031 | 56,724 |
def create_app() -> Flask:
"""Create a new API application."""
app = Flask('preview')
app.json_encoder = PreviewEncoder
app.config.from_pyfile('config.py')
Base(app)
auth.Auth(app)
# Set up the API.
app.register_blueprint(routes.api)
register_error_handlers(app)
# Add WSGI mid... | 09a38736f716c953b4a0500e862c0c44d32d38cb | 56,725 |
def list_all_usecase():
"""
Lists down all the Use cases that are supported in Feature Recommender module.
Returns
-------
DataFrame of all the supported usecases as part of feature exploration/recommendation
"""
odf_uni = df_input_fer.iloc[:, 3].unique()
odf = pd.DataFrame(odf_uni, col... | 3f2922bd759b75882014c375c01d68fb2ae60d30 | 56,726 |
def format_bases(bases):
"""
Generate HTML that colours the bases in a string.
Args:
bases: A string containing a genetic sequence.
Returns:
An HTML string.
"""
formatted = ''
for b in bases:
formatted += '<span class="base-{}">{}</span>'.format(b,b)
return forma... | a94f34a53178ceb5dd1640eaa8897a128c7c4d67 | 56,727 |
def zscores(a):
"""Converts a to zscores in each col, i.e. subtract mean and div by stdev."""
return (a - mean(a,axis=0)) / std(a, axis=0) | 2750b5575eb24d16cf5d65b27d23f123078968a4 | 56,728 |
import math
import random
def grid_template_list():
"""
List of lengths. Values can be a length, percentage, factor, etc
Examples:
grid-template-columns: 1093px 255px 1825px 12px 400px;
grid-template-columns: 1093px 10% 3fr;
"""
value_types = [_p_length_px, _percent, _p_length_fr]... | 4915ad3ce2ff3502c246b107787a0f1a6b6a7682 | 56,729 |
def Get_K_to_q(porb, asini):
"""
Returns the K_to_q conversion factor given an
orbital period and an observed asini.
The K is for the "primary" whereas asini is that
of the "secondary" star.
porb: Orbital period in seconds.
asini: Projected semi-major axis in lt-s.
>>> K_to_q = Get_K_t... | 47ca141173e07f02a417cf653c07abf22705572d | 56,730 |
def calculate_ECE(bin_means, proportion_correct, all_hist):
"""
Calculates Expected Calibration Error (Naeini et al. 2015). This is simply
the sum of the weighted average of each bin's accuracy / confidence difference.
Input:
bin_means - list means for the 10 bins
proportion_correct - l... | a51080be40c532c052a51c51132fc64193fc13a7 | 56,731 |
def compute_elipticities(xx, yy, xy):
"""Compute star elipticities from second momments."""
denom = xx + 2. * N.sqrt(xx * yy - N.square(xy))
e1 = (xx - yy) / denom
e2 = 2.0 * xy / denom
return e1, e2 | aa1b3d324d4b2fc20236ddb2f5a88d976f2e2d4f | 56,732 |
def solow_steady_state(g, n, s, alpha, delta):
"""
Steady-state level of capital stock (per unit effective labor).
Parameters
----------
g : float
Growth rate of technology.
n : float
Growth rate of the labor force.
s : float
Savings rate. Must satisfy `0 < s < 1`.
... | 51f34393761430388b91f9ff43a4eb0453d5d22d | 56,733 |
def daily_return(close, fillna=False):
"""Daily Return (DR)
Args:
close(pandas.Series): dataset 'Close' column.
fillna(bool): if True, fill nan values.
Returns:
pandas.Series: New feature generated.
"""
dr = (close / close.shift(1, fill_value=close.mean())) - 1
dr *= 10... | 98dc664d8f7aa2184637e02db1a8103a03af753d | 56,734 |
def get_vm_macs(vm_name, conn=LIBVIRT_CONNECTION):
"""Get VM mac addresses along with source network names"""
if not vm_exists(vm_name, conn):
return {}
vm_xml = _virsh_dumpxml(vm_name, conn)
return _get_vm_macs(vm_xml) | d81289894e26c082f77e7b587efe1b510ef55480 | 56,735 |
from typing import Callable
from typing import Union
from typing import Literal
from typing import Tuple
from typing import List
import itertools
import uuid
from pathlib import Path
import re
def __make_daybyday_interactive_timeline(
df: pd.DataFrame,
*,
geo_df: geopandas.GeoDataFrame,
value_col: str... | 73ef2901f44cd791f320a2167315e7d7a0481556 | 56,736 |
def pgettext(context, message, **variables):
"""Translates `message` given the `context`"""
return _translate('pgettext', context, message, **variables) | 8d159d6d1f0a9231f4d7b14c46c99bc02db5982b | 56,737 |
def create_credentials(account, username, password):
"""
Function to create new user credentials
Args:
account: Account type
username: New username
password: New password
"""
new_credential = Credential(account, username, password)
return new_credential | a237dea82d7a92d2e0306be9fb8c6d5f50577162 | 56,738 |
def match_dtypes(training_df,testing_df,target_name='TARGET'):
"""
This function converts dataframe to match columns in accordance with the
training dataframe.
"""
for column_name in training_df.drop([target_name],axis=1).columns:
testing_df[column_name]= testing_df[column_name].astype(tra... | c8fc3c6beb1a50c2d02c357355a12055543f4f87 | 56,739 |
import time
def get_page_by_random() -> Article:
"""Gets the contents and metadata of a random Wikipedia article.
:returns: the Article object representing the Wikipedia article.
"""
article_id, title = None, None
page_html = None
url = None
while page_html is None:
article_id... | 46710d7ad6f76f41d59bcfb060eb3cbde855bbce | 56,741 |
def _get_fixture_from_dict_fixtures(fixture):
"""Get value of fixture by key (fixture name) from dictionary of
executed fixtures."""
global dict_executed_fixtures
# extend executed fixtures using exist fixture in snapshot representation
if fixture.endswith("_snapshot"):
origin_obj = _get_fixture_from_dict... | 1bdd1b97b99f90cb84c7fa7c33cba82cfee92537 | 56,742 |
def variance_contrib(var_comp_lc, var_comp_qc, var_comp_cp, vz):
"""
Convert actual variance components to percent contributions (best if used
in conjunction with ``variance_components`` function).
Parameters
----------
var_comp_lc : array
The actual variance components from the 1st... | 490dc46afc1547b2f8c5e59bf506600451f80f2f | 56,743 |
def get_fitted_model(X_train, y_train) -> RandomForestClassifier:
""" Returns model trained on the provided data
:param X_train: training dataset for the model
:param y_train: labels for the training dataset
:return: Fitted Random Forest classifier model
"""
model = RandomForestClassifier(
... | 300432a11fc1cfe3eadc62dbf43f144020e231b8 | 56,744 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.