content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def _get_blobs(im, rois):
"""Convert an image and RoIs within that image into network inputs."""
blobs = {'data' : None, 'rois' : None}
blobs['data'], im_scale_factors = _get_image_blob(im)
if not cfg.TEST.HAS_RPN:
blobs['rois'] = _get_rois_blob(rois, im_scale_factors)
#print ('lll: ', blobs['r... | d4adb2e049a86fe1a42aab6dea52b55aabeeb0d2 | 3,648,500 |
def string_limiter(text, limit):
"""
Reduces the number of words in the string to length provided.
Arguments:
text -- The string to reduce the length of
limit -- The number of characters that are allowed in the string
"""
for i in range(len(text)):
if i >= limit an... | 1ae70d2115be72ec628f38b2c623064607f534ef | 3,648,501 |
def in_ellipse(xy_list,width,height,angle=0,xy=[0,0]):
"""
Find data points inside an ellipse and return index list
Parameters:
xy_list: Points needs to be deteced.
width: Width of the ellipse
height: Height of the ellipse
angle: anti-clockwise rotation angle in degrees
... | 6540520caa6eef12871847f80d3ed42279b0c1a0 | 3,648,502 |
import logging
def get_real_images(dataset,
num_examples,
split=None,
failure_on_insufficient_examples=True):
"""Get num_examples images from the given dataset/split.
Args:
dataset: `ImageDataset` object.
num_examples: Number of images to read.
... | 0f9be93076b8d94b3285a1f5badb8952788e2a82 | 3,648,503 |
from typing import Callable
from typing import Any
import websockets
async def call(fn: Callable, *args, **kwargs) -> Any:
"""
Submit function `fn` for remote execution with arguments `args` and `kwargs`
"""
async with websockets.connect(WS_SERVER_URI) as websocket:
task = serialize((fn, args... | 073090186e4a325eb32b44fb44c1628c6842c398 | 3,648,504 |
import numpy
def wrap_array_func(func):
"""
Returns a version of the function func() that works even when
func() is given a NumPy array that contains numbers with
uncertainties.
func() is supposed to return a NumPy array.
This wrapper is similar to uncertainties.wrap(), except that it
ha... | 7cbd33599b62df096db3ce84968cc13f24512fc0 | 3,648,505 |
def checkCrash(player, upperPipes, lowerPipes):
"""returns True if player collides with base or pipes."""
pi = player['index']
player['w'] = fImages['player'][0].get_width()
player['h'] = fImages['player'][0].get_height()
# if player crashes into ground
if player['y'] + player['h'] >= nBaseY -... | e638f0ae40610fc0c4097998e8fa3df0dc6a5d56 | 3,648,506 |
import os
def alter_subprocess_kwargs_by_platform(**kwargs):
"""
Given a dict, populate kwargs to create a generally
useful default setup for running subprocess processes
on different platforms. For example, `close_fds` is
set on posix and creation of a new console window is
disabled on Window... | 93ada5c681c535b45fc5c321ab4b27b49587a106 | 3,648,507 |
def convert_gwp(context, qty, to):
"""Helper for :meth:`convert_unit` to perform GWP conversions."""
# Remove a leading 'gwp_' to produce the metric name
metric = context.split('gwp_')[1] if context else context
# Extract the species from *qty* and *to*, allowing supported aliases
species_from, uni... | 23d47e3b93f1ed694fbb5187433af5c8caa72dc8 | 3,648,508 |
from AppKit import NSSearchPathForDirectoriesInDomains
import sys
import os
def appdataPath(appname):
"""
Returns the generic location for storing application data in a cross
platform way.
:return <str>
"""
# determine Mac OS appdata location
if sys.platform == 'darwin':
#... | d4d26890ca1fa607cbb09bd4838e3513d19c6af9 | 3,648,509 |
import random
def getAction(board, policy, action_set):
"""
return action for policy, chooses max from classifier output
"""
# if policy doesn't exist yet, choose action randomly, else get from policy model
if policy == None:
valid_actions = [i for i in action_set if i[0] > -1]
if ... | fddb9160f0571dfaf50f945c05d5dbb176465180 | 3,648,510 |
def f_assert_must_between(value_list, args):
"""
检测列表中的元素是否为数字或浮点数且在args的范围内
:param value_list: 待检测列表
:param args: 范围列表
:return: 异常或原值
example:
:value_list [2, 2, 3]
:args [1,3]
:value_list ['-2', '-3', 3]
:a... | 6e082f3df39509f0823862497249a06080bd7649 | 3,648,511 |
from scipy.stats import zscore
from scipy.ndimage import label
def annotate_muscle_zscore(raw, threshold=4, ch_type=None, min_length_good=0.1,
filter_freq=(110, 140), n_jobs=1, verbose=None):
"""Create annotations for segments that likely contain muscle artifacts.
Detects data segm... | a09b2b9098c7dfc48b29548691e3c6c524a6b6bf | 3,648,512 |
def circ_dist2(a, b):
"""Angle between two angles
"""
phi = np.e**(1j*a) / np.e**(1j*b)
ang_dist = np.arctan2(phi.imag, phi.real)
return ang_dist | db60caace70f23c656c4e97b94145a246c6b2995 | 3,648,513 |
def hinge_loss(positive_scores, negative_scores, margin=1.0):
"""
Pairwise hinge loss [1]:
loss(p, n) = \sum_i [\gamma - p_i + n_i]_+
[1] http://yann.lecun.com/exdb/publis/pdf/lecun-06.pdf
:param positive_scores: (N,) Tensor containing scores of positive examples.
:param negative_scores: (... | daa698f012c30c8f99ba1ce08cbb73226251e3c1 | 3,648,514 |
def build(req):
"""Builder for this format.
Args:
req: flask request
Returns:
Json containing the creative data
"""
errors = []
v = {}
tdir = "/tmp/" + f.get_tmp_file_name()
index = get_html()
ext = f.get_ext(req.files["videofile"].filename)
if ext != "mp4":
return {"errors": ["Only ... | 33ad1e003533407626cd3ccdd52e7f6c414e6470 | 3,648,515 |
def search(query, data, metric='euclidean', verbose=True):
"""
do search, return ranked list according to distance
metric: hamming/euclidean
query: one query per row
dat: one data point per row
"""
#calc dist of query and each data point
if metric not in ['euclidean', 'hamming']:
... | 576471dfbe1dc0a2ae80235faf36d42d4b3a7f8a | 3,648,516 |
def create_circle_widget(canvas: Canvas, x: int, y: int, color: str, circle_size: int):
"""create a centered circle on cell (x, y)"""
# in the canvas the 1st axis is horizontal and the 2nd is vertical
# we want the opposite so we flip x and y for the canvas
# to create an ellipsis, we give (x0, y0) and ... | b048b7d9c262c40a93cfef489468ad709a1e3883 | 3,648,517 |
def _format_program_counter_relative(state):
"""Program Counter Relative"""
program_counter = state.program_counter
operand = state.current_operand
if operand & 0x80 == 0x00:
near_addr = (program_counter + operand) & 0xFFFF
else:
near_addr = (program_counter - (0x100 - operand)) & ... | 74f13e9230a6c116413b373b92e36bd884a906e7 | 3,648,518 |
def compile_program(
program: PyTEAL, mode: Mode = Mode.Application, version: int = 5
) -> bytes:
"""Compiles a PyTEAL smart contract program to the TEAL binary code.
Parameters
----------
program
A function which generates a PyTEAL expression, representing an Algorand program.
mode
... | 50e9b4263a0622dfbe427c741ddfba2ff4007089 | 3,648,519 |
def fetch_url(url):
""" Fetches a URL and returns contents - use opener to support HTTPS. """
# Fetch and parse
logger.debug(u'Fetching %s', url)
# Use urllib2 directly for enabled SSL support (LXML doesn't by default)
timeout = 30
try:
opener = urllib2.urlopen(url, None, timeout)
... | d6603fda5917423cb99c619810c8161a7c2885a1 | 3,648,520 |
def predict(yolo_outputs, image_shape, anchors, class_names, obj_threshold, nms_threshold, max_boxes = 1000):
"""
Process the results of the Yolo inference to retrieve the detected bounding boxes,
the corresponding class label, and the confidence score associated.
The threshold value 'obj_threshold' serves to disca... | df90a5baed671e316e03c0a621ce1740efc7a833 | 3,648,521 |
import json
def get_event_details(entry, workday_user, demisto_user, days_before_hire_to_sync, days_before_hire_to_enable_ad,
deactivation_date_field, display_name_to_user_profile, email_to_user_profile,
employee_id_to_user_profile, source_priority):
"""
This functi... | dd8095f81a0df7db9196accbcdef2f72ef92a39f | 3,648,522 |
def ae_model(inputs, train=True, norm=True, **kwargs):
"""
AlexNet model definition as defined in the paper:
https://papers.nips.cc/paper/4824-imagenet-classification-with-deep-convolutional-neural-networks.pdf
You will need to EDIT this function. Please put your AlexNet implementation here.
N... | 659908f6fbfb401941984668634382c6d30a8124 | 3,648,523 |
def filter_by_country(data, country=DEFAULT_COUNTRY):
"""
Filter provided data by country (defaults to Czechia).
data: pandas.DataFrame
country: str
"""
# Filter data by COUNTRY
return data[data[COLUMN_FILTER] == country] | bbf9eacd74a6032f1298cd7313d5c8233ec4a8ec | 3,648,524 |
import requests
import os
def get_instance_id() -> str:
"""Returns the AWS instance id where this is running or "local"."""
global INSTANCE_ID
if INSTANCE_ID is None:
if get_env_variable("RUNNING_IN_CLOUD") == "True":
@retry(stop_max_attempt_number=3)
def retrieve_instance_... | a73c49e114dac360151a8b571eadea13c8cb35a6 | 3,648,525 |
def scans_from_csvs(*inps, names=None):
"""
Read from csvs.
:param inps: file names of the csvs
:param names: names of the Scans
:return: list of Scans
"""
ns, temp_vals, heat_flow_vals = read_csvs(inps)
names = ns if names is None else names
return [Scan(*vals) for vals in zip(temp... | 6acddf330e10793dab6b76ec6a1edb1d2fd0660d | 3,648,526 |
def part_b(puzzle_input):
"""
Calculate the answer for part_b.
Args:
puzzle_input (list): Formatted as the provided input from the website.
Returns:
string: The answer for part_b.
"""
return str(collect_letters(puzzle_input)[1]) | b82597c610e8a7d03ea68ddad392385636b0e2f3 | 3,648,527 |
def data_encoder(data):
"""
Encode all categorical values in the dataframe into numeric values.
@param data: the original dataframe
@return data: the same dataframe with all categorical variables encoded
"""
le = preprocessing.LabelEncoder()
cols = data.columns
numcols = data._get_n... | 2a2177891e1930311661f6549dbd33f329704fec | 3,648,528 |
def _search_settings(method_settings_keys, settings):
"""
We maintain a dictionary of dimensionality reduction methods
in dim_settings_keys where each key (method) stores another
dictionary (md) holding that method's settings (parameters).
The keys of md are component ids and the values are paramete... | 20a8a0e24df1dc572dfbe541f1439bc6245f6170 | 3,648,529 |
def svn_opt_resolve_revisions(*args):
"""
svn_opt_resolve_revisions(svn_opt_revision_t peg_rev, svn_opt_revision_t op_rev,
svn_boolean_t is_url, svn_boolean_t notice_local_mods,
apr_pool_t pool) -> svn_error_t
"""
return _core.svn_opt_resolve_revisions(*args) | 5f011401c4afc044f0fa877407f7c7a3da56f576 | 3,648,530 |
from typing import Union
from pathlib import Path
from typing import Any
def write_midi(
path: Union[str, Path],
music: "Music",
backend: str = "mido",
**kwargs: Any
):
"""Write a Music object to a MIDI file.
Parameters
----------
path : str or Path
Path to write the MIDI file... | 963e5aafffbc348df17861b615c2e839c170adce | 3,648,531 |
import string
from re import VERBOSE
def find_star_column(file, column_type, header_length) :
""" For an input .STAR file, search through the header and find the column numbers assigned to a given column_type (e.g. 'rlnMicrographName', ...)
"""
with open(file, 'r') as f :
line_num = 0
for ... | 832a63d2084b6f007c0b58fbafbe037d0a81ab38 | 3,648,532 |
def recalculate_bb(df, customization_dict, image_dir):
"""After resizing images, bb coordinates are recalculated.
Args:
df (Dataframe): A df for image info.
customization_dict (dict): Resize dict.
image_dir (list): Image path list
Returns:
Dataframe: Updated dataframe.
... | 412149195898e492405fe58aef2d8c8ce360cef7 | 3,648,533 |
def free_port():
"""Returns a free port on this host
"""
return get_free_port() | 94765cdb1a6e502c9ad650956754b3eda7f1b060 | 3,648,534 |
def justify_to_box(
boxstart: float,
boxsize: float,
itemsize: float,
just: float = 0.0) -> float:
"""
Justifies, similarly, but within a box.
"""
return boxstart + (boxsize - itemsize) * just | a644d5a7a6ff88009e66ffa35498d9720b24222c | 3,648,535 |
import time
def newton(oracle, x_0, tolerance=1e-5, max_iter=100,
line_search_options=None, trace=False, display=False):
"""
Newton's optimization method.
Parameters
----------
oracle : BaseSmoothOracle-descendant object
Oracle with .func(), .grad() and .hess() methods implemen... | 5ecf60c7e26e4bf4c965203ea9dddc5f22104225 | 3,648,536 |
import time
def generate_hostname(domain, hostname):
"""If hostname defined, returns FQDN.
If not, returns FQDN with base32 timestamp.
"""
# Take time.time() - float, then:
# - remove period
# - truncate to 17 digits
# - if it happen that last digits are 0 (and will not be displayed, s... | 54d85cea2b2aa69cc2864b0974852530453d63ca | 3,648,537 |
def symmetrize(M):
"""Return symmetrized version of square upper/lower triangular matrix."""
return M + M.T - np.diag(M.diagonal()) | a2f1311aa96d91d5c4992ad21018b07ac5954d1c | 3,648,538 |
import sys
def process_checksums_get(storage_share, hash_type, url):
"""Run StorageShare get_object_checksum() method to get checksum of file/object.
Run StorageShare get_object_checksum() method to get the requested type of
checksum for file/object whose URL is given.
The client also needs to sp
... | addd04d54348958b5c06b377a796fa12a30bd3cd | 3,648,539 |
def prep_public_water_supply_fraction() -> pd.DataFrame:
"""calculates public water supply deliveries for the commercial and industrial sectors individually
as a ratio to the sum of public water supply deliveries to residential end users and thermoelectric cooling.
Used in calculation of public water supp... | bb759cfa25add08b0faf0d9232448698d0ae8d53 | 3,648,540 |
def set_matchq_in_constraint(a, cons_index):
"""
Takes care of the case, when a pattern matching has to be done inside a constraint.
"""
lst = []
res = ''
if isinstance(a, list):
if a[0] == 'MatchQ':
s = a
optional = get_default_values(s, {})
r = gener... | c40f15f500736102f4abf17169715387c2f1b91b | 3,648,541 |
def istype(klass, object):
"""Return whether an object is a member of a given class."""
try: raise object
except klass: return 1
except: return 0 | bceb83914a9a346c59d90984730dddb808bf0e78 | 3,648,542 |
from typing import Mapping
from typing import Any
def _embed_from_mapping(mapping: Mapping[str, Any], ref: str) -> mapry.Embed:
"""
Parse the embed from the mapping.
All the fields are parsed except the properties, which are parsed
in a separate step.
:param mapping: to be parsed
:param ref:... | 10d3894aa33d41efd47f03335c6e90547ee26e6c | 3,648,543 |
import pdb
def generate_csv_from_pnl(pnl_file_name):
"""在.pnl文件的源路径下新生成一个.csv文件. 拷贝自export_to_csv函数. pnl_file_name需包含路径. """
pnlc = alib.read_pnl_from_file(pnl_file_name)
pnl = pnlc[1]
if pnl is None:
print('pnl文件{}不存在!'.format(pnl_file_name))
pdb.set_trace()
csv_file_name = pnl_fi... | ceed6ce7d31fe6cb738252b7458c2f404c01135c | 3,648,544 |
def parse_number(text, allow_to_fail):
"""
Convert to integer, throw if fails
:param text: Number as text (decimal, hex or binary)
:return: Integer value
"""
try:
if text in defines:
return parse_number(defines.get(text), allow_to_fail)
return to_number(text)
exce... | 90906b56e8a88fcde9f66defeed48cf12371d375 | 3,648,545 |
import importlib
def pick_vis_func(options: EasyDict):
"""Pick the function to visualize one batch.
:param options:
:return:
"""
importlib.invalidate_caches()
vis_func = getattr(
import_module("utils.vis.{}".format(options.vis.name[0])),
"{}".format(options.vis.name[1])
)
... | 4d65f00075c984e5407af09d3680f2195be640bb | 3,648,546 |
import numpy
def scale_quadrature(quad_func, order, lower, upper, **kwargs):
"""
Scale quadrature rule designed for unit interval to an arbitrary interval.
Args:
quad_func (Callable):
Function that creates quadrature abscissas and weights on the unit
interval.
orde... | f3854cee12a482bc9c92fe2809a0388dddb422e0 | 3,648,547 |
def ask_for_region(self):
"""ask user for region to select (2-step process)"""
selection = ["BACK"]
choices = []
while "BACK" in selection:
response = questionary.select(
"Select area by (you can go back and combine these choices):",
choices=["continents", "regions", "co... | dd7ea9ca33ca8348fba0d36c5661b6fd30c96090 | 3,648,548 |
import array
def peakAlign(refw,w):
""" Difference between the maximum peak positions of the signals.
This function returns the difference, in samples, between the peaks position
of the signals. If the reference signal has various peaks, the one
chosen is the peak which is closer to the middle ... | a7497e828008281318dff25b5547e0ab4f8e9a35 | 3,648,549 |
def get_games(by_category, n_games):
"""
This function imports the dataframe of most popular games and returns a list of game names
with the length of 'n_games' selected by 'by_category'. Valid options for 'by_category': rank, num_user_ratings
"""
df = pd.read_csv('../data/popular_games_with_image_u... | 2702d6b072ba9ac49565c9ee768d65c431441724 | 3,648,550 |
def diurnalPDF( t, amplitude=0.5, phase=pi8 ):
"""
"t" must be specified in gps seconds
we convert the time in gps seconds into the number of seconds after the most recent 00:00:00 UTC
return (1 + amplitude*sin(2*pi*t/day - phase))/day
"""
if amplitude > 1:
raise ValueError("amplitude ca... | 6bf755851d2bf2582ca98c1bcbe67aa7dc4e0a2f | 3,648,551 |
def imap_workers(workers, size=2, exception_handler=None):
"""Concurrently converts a generator object of Workers to
a generator of Responses.
:param workers: a generator of worker objects.
:param size: Specifies the number of workers to make at a time. default is 2
:param exception_handler: Callbac... | c4ab81770b40238025055394bf43ca0dc99dd506 | 3,648,552 |
import time
def output_time(time_this:float=None,end:str=" | ")->float:
"""输入unix时间戳,按格式输出时间。默认为当前时间"""
if not time_this:
time_this=time.time()-TIMEZONE
print(time.strftime('%Y-%m-%d %H:%M:%S',time.gmtime(time_this)),end=end)
#
return time_this | ba17400306af7142a91bd5b62941c52fc59dbf1a | 3,648,553 |
def blend_color(color1, color2, blend_ratio):
"""
Blend two colors together given the blend_ration
:param color1: pygame.Color
:param color2: pygame.Color
:param blend_ratio: float between 0.0 and 1.0
:return: pygame.Color
"""
r = color1.r + (color2.r - color1.r) * blend_ratio
g = c... | 0bb7fa1570472e60bd93a98f6da3a515ca9dd500 | 3,648,554 |
import os
def load_flickr25k_dataset(tag='sky', path="data", n_threads=50, printable=False):
"""Returns a list of images by a given tag from Flick25k dataset,
it will download Flickr25k from `the official website <http://press.liacs.nl/mirflickr/mirdownload.html>`_
at the first time you use it.
Param... | b2d449a9d234aeb3d0d80bd1508ebcb55d57e6cd | 3,648,555 |
def solve_a_star(start_id: str, end_id: str, nodes, edges):
"""
Get the shortest distance between two nodes using Dijkstra's algorithm.
:param start_id: ID of the start node
:param end_id: ID of the end node
:return: Shortest distance between start and end node
"""
solution_t_start = perf_c... | 467257c15c7a99d217d75b69876b2f64ecd0b58e | 3,648,556 |
def get_dhcp_relay_statistics(dut, interface="", family="ipv4", cli_type="", skip_error_check=True):
"""
API to get DHCP relay statistics
Author Chaitanya Vella ([email protected])
:param dut:
:type dut:
:param interface:
:type interface:
"""
cli_type = st.get_ui_typ... | 0784cd367d638124458d9e0fb808b45bcc239a84 | 3,648,557 |
def _runcmd(cmd, proc):
"""Run a command"""
cmdstr = proc.template(cmd,
**proc.envs).render(dict(proc=proc, args=proc.args))
logger.info('Running command from pyppl_runcmd ...', proc=proc.id)
logger.debug(' ' + cmdstr, proc=proc.id)
cmd = cmdy.bash(c=cmdstr, _raise=False)... | f7271954e94b45ba46cb7d32535b29f7946cbde0 | 3,648,558 |
def check_rule_for_Azure_ML(rule):
"""Check if the ports required for Azure Machine Learning are open"""
required_ports = ['29876', '29877']
if check_source_address_prefix(rule.source_address_prefix) is False:
return False
if check_protocol(rule.protocol) is False:
return False
i... | fb6067d484a3698b2d10d297e3419510d1d8c4e9 | 3,648,559 |
import re
def text_cleanup(text: str) -> str:
"""
A simple text cleanup function that strips all new line characters and
substitutes consecutive white space characters by a single one.
:param text: Input text to be cleaned.
:return: The cleaned version of the text
"""
text.replace('\n', ''... | 84b9752f261f94164e2e83b944a2c12cee2ae5d8 | 3,648,560 |
from re import T
def geocode():
"""
Call a Geocoder service
"""
if "location" in request.vars:
location = request.vars.location
else:
session.error = T("Need to specify a location to search for.")
redirect(URL(r=request, f="index"))
if "service" in request.vars:
... | 0ddc7380b3ff3ccfba5f9cf3fbcc489a92dd1ba0 | 3,648,561 |
def create_overide_pandas_func(
cls, func, verbose, silent, full_signature, copy_ok, calculate_memory
):
""" Create overridden pandas method dynamically with
additional logging using DataFrameLogger
Note: if we extracting _overide_pandas_method outside we need to implement decorator like here
... | db2bf7cb5d5395aeb700ca14211690750f056a91 | 3,648,562 |
def orthogonalize(U, eps=1e-15):
"""
Orthogonalizes the matrix U (d x n) using Gram-Schmidt Orthogonalization.
If the columns of U are linearly dependent with rank(U) = r, the last n-r columns
will be 0.
Args:
U (numpy.array): A d x n matrix with columns that need to be orthogonalized.... | 5807c0e5c7ee663391123076c8784cfb7e445760 | 3,648,563 |
import os
def get_files_under_dir(directory, ext='', case_sensitive=False):
"""
Perform recursive search in directory to match files with one of the
extensions provided
:param directory: path to directory you want to perform search in.
:param ext: list of extensions of simple extension for files t... | 3ba3428d88c164fce850a29419b6eab46aa8b646 | 3,648,564 |
def boolean(func):
"""
Sets 'boolean' attribute (this attribute is used by list_display).
"""
func.boolean=True
return func | 9bbf731d72e53aa9814caacaa30446207af036bd | 3,648,565 |
def load_output_template_configs(items):
"""Return list of output template configs from *items*."""
templates = []
for item in items:
template = OutputTemplateConfig(
id=item["id"],
pattern_path=item.get("pattern-path", ""),
pattern_base=item.get("pattern-base", ... | 028502662906230bf2619fa105caa1d525ff8e75 | 3,648,566 |
def read_keyword_arguments_section(docstring: Docstring, start_index: int) -> tuple[DocstringSection | None, int]:
"""
Parse a "Keyword Arguments" section.
Arguments:
docstring: The docstring to parse
start_index: The line number to start at.
Returns:
A tuple containing a `Sect... | 9c789fd4b08d2f3d9e99d4db568ab710e4765c91 | 3,648,567 |
from typing import Mapping
from typing import Iterable
def is_builtin(x, drop_callables=True):
"""Check if an object belongs to the Python standard library.
Parameters
----------
drop_callables: bool
If True, we won't consider callables (classes/functions) to be builtin.
Classes have ... | d84fbd770e048172d8c59315fbe24d58046f77b8 | 3,648,568 |
import yaml
def random_pair_selection(config_path,
data_size=100,
save_log="random_sents"):
"""
randomly choose from parallel data, and save to the save_logs
:param config_path:
:param data_size:
:param save_log:
:return: random selected pair... | 417b59bae49fe8aa0566f20f8ff371c7760e1a8a | 3,648,569 |
from sys import version
def test_deployable():
"""
Check that 1) no untracked files are hanging out, 2) no staged but
uncommitted updates are outstanding, 3) no unstaged, uncommitted changes
are outstanding, 4) the most recent git tag matches HEAD, and 5) the most
recent git tag matches the curren... | 32d8f0a49bbd212b6e0123a34d8844dd622b1ba6 | 3,648,570 |
from typing import OrderedDict
from typing import Counter
def profile_nominal(pairs, **options):
"""Return stats for the nominal field
Arguments:
:param pairs: list with pairs (row, value)
:return: dictionary with stats
"""
result = OrderedDict()
values = [r[1] for r in pairs]
c = Cou... | 00ef211e8f665a02f152e764c409668481c748cc | 3,648,571 |
from typing import List
def class_definitions(cursor: Cursor) -> List[Cursor]:
"""
extracts all class definitions in the file pointed by cursor. (typical mocks.h)
Args:
cursor: cursor of parsing result of target source code by libclang
Returns:
a list of cursor, each pointing to a class definiti... | c2831b787905b02865890aa2680c37b97ec2e0a8 | 3,648,572 |
import os
def visualize_dataset(dataset_directory=None, mesh_filename_path=None):
"""
This method loads the mesh file from dataset directory and helps us to visualize it
Parameters:
dataset_directory (str): root dataset directory
mesh_filename_path (str): mesh file name to process
Ret... | 53a91f923fd231fb467dfc970c91d7400c085035 | 3,648,573 |
def service_list_by_category_view(request, category):
"""Shows services for a chosen category.
If url doesn't link to existing category, return user to categories list"""
template_name = 'services/service-list-by-category.html'
if request.method == "POST":
contact_form = ContactForm(request.POST... | dcbed59c8b6876b7072eb82b27f6b10e829c2daa | 3,648,574 |
def check_columns(board: list):
"""
Check column-wise compliance of the board for uniqueness (buildings of unique height) and visibility (top-bottom and vice versa).
Same as for horizontal cases, but aggregated in one function for vertical case, i.e. columns.
>>> check_columns(['***21**', '412453*', '... | 26ea379a165b90eadcf89640f00857e9e95146c7 | 3,648,575 |
def get_git_tree(pkg, g, top_prd):
"""
:return:
"""
global pkg_tree
global pkg_id
global pkg_list
global pkg_matrix
pkg_tree = Tree()
pkg_id = 0
pkg_list = dict()
# pkg_list['root'] = []
if pkg == '':
return None
if pkg in Config.CACHED_GIT_REPOS:
p... | 05434882a476c8506804918cb44624c7734bf405 | 3,648,576 |
import requests
def get_requests_session():
"""Return an empty requests session, use the function to reuse HTTP connections"""
session = requests.session()
session.mount("http://", request_adapter)
session.mount("https://", request_adapter)
session.verify = bkauth_settings.REQUESTS_VERIFY
sess... | e5921b12d29718e9ef1f503f902fed02a7c7e82f | 3,648,577 |
def edit_role_description(rid, description, analyst):
"""
Edit the description of a role.
:param rid: The ObjectId of the role to alter.
:type rid: str
:param description: The new description for the Role.
:type description: str
:param analyst: The user making the change.
:type analyst:... | f857755766da1f8f5be0e3dc255ed34aa7ed3ed3 | 3,648,578 |
def have_questions(pair, config, info=None):
"""
Return True iff both images are annotated with questions.
"""
qas = info["qas"]
c1id = pair[0]
if qas[c1id]['qas'] == []:
return False
c2id = pair[1]
if qas[c2id]['qas'] == []:
return False
return True | 45a5f4babcc17ad5573008ca31773d51334144cd | 3,648,579 |
def get_dist_genomic(genomic_data,var_or_gene):
"""Get the distribution associated to genomic data for its characteristics
Parameters: genomic_data (dict): with UDN ID as key and list with dictionaries as value,
dict contaning characteristics of the considered genomic data
... | ada0b7ecd57ace9799102e97bc9173d888c23565 | 3,648,580 |
def get_gmb_dataset_train(max_sentence_len):
"""
Returns the train portion of the gmb data-set. See TRAIN_TEST_SPLIT param for split ratio.
:param max_sentence_len:
:return:
"""
tokenized_padded_tag2idx, tokenized_padded_sentences, sentences = get_gmb_dataset(max_sentence_len)
return tokeniz... | 762800a0b986c74037e79dc1db92d5b2f6cd2e50 | 3,648,581 |
def is_answer_reliable(location_id, land_usage, expansion):
"""
Before submitting to DB, we judge if an answer reliable and set the location done if:
1. The user passes the gold standard test
2. Another user passes the gold standard test, and submitted the same answer as it.
Parameters
--------... | 3aa510d68115ef519ec2a1318102d302aae81382 | 3,648,582 |
import numpy
def _polyfit_coeffs(spec,specerr,scatter,labelA,return_cov=False):
"""For a given scatter, return the best-fit coefficients"""
Y= spec/(specerr**2.+scatter**2.)
ATY= numpy.dot(labelA.T,Y)
CiA= labelA*numpy.tile(1./(specerr**2.+scatter**2.),(labelA.shape[1],1)).T
ATCiA= numpy.dot(label... | 9398fa2072625eb66ea8df2f79008577fe6aaabe | 3,648,583 |
import os
from pathlib import Path
def get_repo_dir():
"""Get repository root directory"""
root_dir = './'
if os.path.isdir(Path(__file__).parent.parent / 'src'):
root_dir = f"{str((Path(__file__).parent.parent).resolve())}/"
elif os.path.isdir('../src'):
root_dir = '../'
elif os.p... | efa688b3458ab282a427506578cbabfc2d329c1f | 3,648,584 |
def colorize(data, colors, display_ranges):
"""Example:
colors = 'white', (0, 1, 0), 'red', 'magenta', 'cyan'
display_ranges = np.array([
[100, 3000],
[700, 5000],
[600, 3000],
[600, 4000],
[600, 3000],
])
rgb = fig4.colorize(data, colors, display_ranges)
... | efb6ff9c0573da4a11cbfdbf55acaccbb69de216 | 3,648,585 |
import itertools
def multi_mdf(S, all_drGs, constraints, ratio_constraints=None, net_rxns=[],
all_directions=False, x_max=0.01, x_min=0.000001,
T=298.15, R=8.31e-3):
"""Run MDF optimization for all condition combinations
ARGUMENTS
S : pandas.DataFrame
Pandas DataFrame... | 3496105b764bc72b1c52ee28d419617798ad72cc | 3,648,586 |
def nufft_adjoint(input, coord, oshape=None, oversamp=1.25, width=4.0, n=128):
"""Adjoint non-uniform Fast Fourier Transform.
Args:
input (array): Input Fourier domain array.
coord (array): coordinate array of shape (..., ndim).
ndim determines the number of dimension to apply nuff... | d3d03ebe3d905cb647fab7d801592e148023709e | 3,648,587 |
def get_bustools_version():
"""Get the provided Bustools version.
This function parses the help text by executing the included Bustools binary.
:return: tuple of major, minor, patch versions
:rtype: tuple
"""
p = run_executable([get_bustools_binary_path()], quiet=True, returncode=1)
match ... | 7de14349b9349352c3532fbcc0be58be0f9756c7 | 3,648,588 |
import nose
import sys
def main():
"""
Args: none
Returns: exit code
Usage: python -m rununittest
"""
# Can use unittest or nose; nose here, which allows --with-coverage.
return nose.run(argv=[sys.argv[0], "-s", "--with-coverage", "rununittest"]) | 6eaaf5ebfbe9536364669f186d1c84a5fc31be05 | 3,648,589 |
def request_from_url(url):
"""Parses a gopher URL and returns the corresponding Request instance."""
pu = urlparse(url, scheme='gopher', allow_fragments=False)
t = '1'
s = ''
if len(pu.path) > 2:
t = pu.path[1]
s = pu.path[2:]
if len(pu.query) > 0:
s = s + '?' + pu.query... | aff334f8358edcae028b65fa1b4cf5727638eaad | 3,648,590 |
import os
def getJsonPath(name, moduleFile):
"""
获取JSON配置文件的路径:
1. 优先从当前工作目录查找JSON文件
2. 若无法找到则前往模块所在目录查找
"""
currentFolder = os.getcwd()
currentJsonPath = os.path.join(currentFolder, name)
if os.path.isfile(currentJsonPath):
return currentJsonPath
else:
moduleFolder... | 5f0dca485794dead91ecce70b4040809886186c3 | 3,648,591 |
def enable_pause_data_button(n, interval_disabled):
"""
Enable the play button when data has been loaded and data *is* currently streaming
"""
if n and n[0] < 1: return True
if interval_disabled:
return True
return False | 4257a2deb9b8be87fe64a54129ae869623c323e8 | 3,648,592 |
import scipy
def dProj(z, dist, input_unit='deg', unit='Mpc'):
"""
Projected distance, physical or angular, depending on the input units (if
input_unit is physical, returns angular, and vice-versa).
The units can be 'cm', 'ly' or 'Mpc' (default units='Mpc').
"""
if input_unit in ('deg', 'arcmi... | 13610816dfb94a92d6890d351312661b04e8604f | 3,648,593 |
def savgoldiff(x, dt, params=None, options={}, dxdt_truth=None, tvgamma=1e-2, padding='auto',
optimization_method='Nelder-Mead', optimization_options={'maxiter': 10}, metric='rmse'):
"""
Optimize the parameters for pynumdiff.linear_model.savgoldiff
See pynumdiff.optimize.__optimize__ and pynu... | cb6da1a5fe3810ea1f481450667e548a9f64dae2 | 3,648,594 |
import base64
def credentials(scope="module"):
"""
Note that these credentials match those mentioned in test.htpasswd
"""
h = Headers()
h.add('Authorization',
'Basic ' + base64.b64encode("username:password"))
return h | 4f0b1c17da546bfa655a96cfe5bcf74719dff55d | 3,648,595 |
import sys
def _score_match(matchinfo: bytes, form, query) -> float:
""" Score how well the matches form matches the query
0.5: half of the terms match (using normalized forms)
1: all terms match (using normalized forms)
2: all terms are identical
3: all terms are identical, including case
... | ef8c223b6c972f7b43fe46788ac894c5454e3f18 | 3,648,596 |
def _set_bias(clf, X, Y, recall, fpos, tneg):
"""Choose a bias for a classifier such that the classification
rule
clf.decision_function(X) - bias >= 0
has a recall of at least `recall`, and (if possible) a false positive rate
of at most `fpos`
Paramters
---------
clf : Classifier
... | bbc903752d9abc93f723830e5c6c51459d18d0a5 | 3,648,597 |
from typing import Type
from typing import Dict
from typing import Any
def get_additional_params(model_klass: Type['Model']) -> Dict[str, Any]:
"""
By default, we dont need additional params to FB API requests. But in some instances (i.e. fetching Comments),
adding parameters makes fetching data simpler
... | 1b4c934a06870a8ae1f2f999bab94fb286ee6126 | 3,648,598 |
def thread_loop(run):
"""decorator to make the function run in a loop if it is a thread"""
def fct(self, *args, **kwargs):
if self.use_thread:
while True:
run(*args, **kwargs)
else:
run(*args, **kwargs)
return fct | a68eee708bc0a1fe0a3da01e68ec84b6a43d9210 | 3,648,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.