content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def get_exact_match(user_input, groups):
"""Return an exact match from the groups
"""
lower_groups = [group.lower() for group in groups]
if user_input.lower() in lower_groups:
return groups[lower_groups.index(user_input.lower())] | 55,800 |
def compute_perc_id(aln):
""" Compute percent identity of aligned region on read """
length = len(aln.query_alignment_sequence)
edit = dict(aln.tags)['NM']
return 100 * (length - edit)/float(length) | 55,801 |
def getXRDExpiration(xrd_element, default=None):
"""Return the expiration date of this XRD element, or None if no
expiration was specified.
@type xrd_element: ElementTree node
@param default: The value to use as the expiration if no
expiration was specified in the XRD.
@rtype: datetime.da... | 55,802 |
def main():
"""main routine for iphotoexport."""
parser = OptionParser(usage=USAGE)
parser.add_option(
"-a", "--albums",
help="""Export matching regular albums. The argument
is a regular expression. Use -a . to export all regular albums.""")
parser.add_option(
"-d", "--delete", acti... | 55,803 |
def test_no_api_key():
"""Test ChemSpider cannot be initialized with no API key."""
with pytest.raises(TypeError):
ChemSpider() | 55,804 |
def patient_is_account_owner_with_email(method):
"""
Verify if patient is a owner of request with email
"""
def wrap(request, email, *args, **kwargs):
is_patient = hasattr(request.user, 'patient')
is_owner = email == request.user.email
if is_owner and is_patient:
retu... | 55,805 |
def test_sn_ejected_metals(sn_ii_kobayashi, m, z, m_final, m_cut, m_h, m_he):
"""Get items right from the table."""
metal_ejecta = m_final - (m_cut + m_h + m_he)
my_answer = sn_ii_kobayashi.elemental_ejecta_mass(m, z, "total_metals")
assert my_answer == approx(metal_ejecta, rel=1E-2) | 55,806 |
def convert_to_tfrecord(dataset, output_file, subset):
"""Converts a file to TFRecords."""
with tf.python_io.TFRecordWriter(output_file) as record_writer:
data = dataset.features
labels = dataset.labels
num_entries_in_batch = len(labels)
for i in tqdm(range(num_entries_in_batch)):
example = t... | 55,807 |
def get_byte_to_char_offset_mapping(text):
"""Get mapping from bytes positions to unicode code point positions."""
if not text:
return {}, {}
bytes_per_char = [len(c.encode('utf-8')) for c in text]
bytes_per_char_cumsum = np.cumsum(bytes_per_char)
char_begin_offset = np.roll(bytes_per_char_cumsum, 1)
ch... | 55,808 |
def test_has_docstrings_does_not_trigger_alias_resolution():
"""Assert the `.has_docstrings` method does not trigger alias resolution."""
with temporary_pypackage("package", ["mod_a.py", "mod_b.py"]) as tmp_package:
mod_a = tmp_package.path / "mod_a.py"
mod_b = tmp_package.path / "mod_b.py"
... | 55,809 |
def get_total_time(locations: [str]) -> int:
"""
Gets the total time required on a trip to all of the given locations
:param locations: The locations to get the total trip time for
:return: An integer that is the number of minutes required to travel to all the given locations
"""
response = _get... | 55,810 |
def sscf(ao_int, scf_params, e_nuc, mode = "minvar", logger_level = "normal"):
"""
Solve the sigma-SCF problem given AO integrals (ao_int [dict]):
- T: ao_kinetic
- V: ao_potential
- g: ao_eri
- S: ao_overlap
- A: S^(-1/2)
and parameters for SCF (scf_params [dict]):
... | 55,811 |
def fetch_entities(project, namespace, query, datastore):
"""A helper method to fetch entities from Cloud Datastore.
Args:
project: Project ID
namespace: Cloud Datastore namespace
query: Query to be read from
datastore: Cloud Datastore Client
Returns:
An iterator of entities.
"""
return ... | 55,812 |
def _add_composite_operator(A: np.ndarray, B: np.ndarray) -> np.ndarray:
"""Add composite operator.
For more information about the add composite operator, see
`Cairo Compositing Operators <https://www.cairographics.org/operators/>`_.
Args:
A (np.ndarray): Source image represented as 4-channel ... | 55,813 |
def select_user(allow_root=False):
"""
Have the user select from a list of users with home directories.
Args:
allow_root - (optional) Include the root user in the list (True or False)
"""
user_list = get_user_list(allow_root)
questions = [
inquirer.List('u',
... | 55,814 |
def test_prepare():
"""
test of the variable preparation enstools.cluster.prepare
"""
# input with different shapes
with numpy.testing.assert_raises(ValueError):
x = prepare(numpy.zeros((ens_members, 10, 11)), *variables)
# test with valid input
x = prepare(*variables)
numpy.tes... | 55,815 |
def delete_project(data, workspace):
"""删除project和与project相关的task
Args:
data为dict,key包括
'pid'项目id
"""
proj_id = data['pid']
assert proj_id in workspace.projects, "项目ID'{}'不存在.".format(proj_id)
tids = list()
for key in workspace.tasks:
tids.append(key)
for tid in... | 55,816 |
def roundTime(dt=None, roundTo=60):
"""Round a datetime object to any time lapse in seconds
dt : datetime.datetime object, default now.
roundTo : Closest number of seconds to round to, default 1 minute.
Author: Thierry Husson 2012 - Use it as you want but don't blame me.
"""
if dt is None:
... | 55,817 |
def neighborhood_tally(df_pop, pwmat, x_cols, df_centroids=None, count_col='count', knn_neighbors=50, knn_radius=None):
"""Forms a cluster around each row of df and tallies the number of instances with/without traits
in x_cols. The contingency table for each cluster/row of df can be used to test for enrichments... | 55,818 |
def prox_soft_plus(X, step, thresh=0):
"""Soft thresholding with projection onto non-negative numbers
"""
return prox_plus(prox_soft(X, step, thresh=thresh), step) | 55,819 |
def debug_logging() -> None:
"""Enables logging on all ``elastic_transport.*`` loggers and attaches a
:class:`logging.StreamHandler` instance to each. This is an easy way to
visualize the network activity occurring on the client or debug a client issue.
"""
handler = logging.StreamHandler()
form... | 55,820 |
def axisym_u(Rcp, Zcp, r, z, omega_t, epsilon=0):
"""
Velocity field from distribution of tangential vorticity
INPUTS:
- Rcp, Zcp: array or control points coordinates, where velocity will be computed
- r, z : 1d-array or points where vorticity is defined
- omega_t : 2d-array consistent wi... | 55,821 |
def p_matrix_body(p):
"""matrix_body : vector
| matrix_body ',' vector""" | 55,822 |
def Expression(tokenizer, staticContext):
"""
Top-down expression parser for stylestyles.
"""
node = AssignExpression(tokenizer, staticContext)
if tokenizer.match("comma"):
childNode = Node.Node(tokenizer, "comma")
childNode.append(node)
node = childNode
while True... | 55,823 |
def generate_guid(entry):
"""Generate missing guid for post entry."""
return md5sum("|".join(safe_encode(entry.get(key) or "")
for key in GUID_FIELDS)) | 55,824 |
def _validate_defn(value, path, val_type, val_opts):
"""
Validate a compound type definition.
We want to validate a value against a definition like:
::
cred_key:
one_of:
- str: str()
- EnvironmentVar: str()
- KeyVault: str(required=Fal... | 55,825 |
def now(timeformat='date'):
"""
Returns the current time in the specified timeformat.
:param timeformat: the target format for the time conversion. May be:
'*date*' (default - outputs a ``datetime.datetime`` object), '*unix*'
(outputs a long UNIXtime) or '*iso*' (outputs an ISO8601-formatte... | 55,826 |
def check_pfam_db(path):
"""Check if Pfam-A db exists else download
Args:
path: String, path where to check
"""
path = Path(path)
if path.exists() and not path.is_dir():
raise FileExistsError("Expected directory")
if not path.exists():
path.mkdir()
h... | 55,827 |
def geo_dist(point1, point2, units='deg'):
"""Function returns geographic distance between two points"""
return np.linalg.norm(geog2ecef(point1, units) - geog2ecef(point2, units)) | 55,828 |
def prepare_models(encoder_config, transformer_config, replica_batch_size, verbose=0):
"""This function is used to initiate the Encoder and the Transformer with appropriate
configs set by the user. After initiating the models this function returns the Encoder,Transformer
and the optimizer.
Args:
... | 55,829 |
def part2():
"""
>>> part2()
17202899
"""
max_value = 50000000
buffer_size = 1
position = 0
current = None
step = INPUT
for value in range(1, max_value + 1):
position = (position + step) % buffer_size + 1
buffer_size += 1
if position == 1:
cu... | 55,830 |
def test_default():
"""
Example using the default settings
"""
logger = logging.getLogger(__name__)
log_all_levels(logger)
log_all_levels_decorated(logger)
log_all_levels_loop(logger)
return logger | 55,831 |
def newsgroups_dictl(
data_home="~/scikit_learn_data",
to_remove=("headers", "footers", "quotes"),
text_key="text",
label_key="label",
label_mapping=None,
):
"""
Load the 20 Newsgroups dataset into a list of dicts, deterministically.
"""
label_mapping = label_mapping or dict()
da... | 55,832 |
def _prepare_ldpreload(container_dir, app):
"""Add mandatory ldpreloads to the container environment.
"""
etc_dir = os.path.join(container_dir, 'overlay', 'etc')
fs.mkdir_safe(etc_dir)
new_ldpreload = os.path.join(etc_dir, 'ld.so.preload')
try:
shutil.copyfile('/etc/ld.so.preload', new_... | 55,833 |
def list_calendars(service):
"""
Given a google 'service' object, return a list of
calendars. Each calendar is represented by a dict.
The returned list is sorted to have
the primary calendar first, and selected (that is, displayed in
Google Calendars web app) calendars before unselected calenda... | 55,834 |
def minimise_master_output(summary_yaml, mode):
""" Converts the master output to include issues and bugs. """
log.debug("Minimising output (mode=%s).", mode)
if not summary_yaml:
return summary_yaml
filtered = {}
if mode == 'short':
filtered = _get_short_format(summary_yaml)
e... | 55,835 |
def async_unload_screenlogic_services(hass: HomeAssistantType):
"""Unload services for the ScreenLogic integration."""
if hass.data[DOMAIN]:
# There is still another config entry for this domain, don't remove services.
return
if not hass.services.has_service(DOMAIN, SERVICE_SET_COLOR_MODE):... | 55,836 |
def deg2rad(angle: float):
"""Convert degree unit to radian unit
Args:
angle (float): input angle.
Returns:
float: output angle.
Usage:
rad_angle = deg2rad(deg_angle)
"""
return angle * ONE_DIV_180 * PI | 55,837 |
def main():
"""主入口函数"""
qapp = create_qapp()
event_engine = EventEngine()
main_engine = MainEngine(event_engine)
main_engine.add_gateway(HuobiSpotGateway)
main_engine.add_gateway(HuobiFuturesGateway)
main_engine.add_gateway(HuobiUsdtGateway)
main_engine.add_gateway(HuobiInverseGateway)
... | 55,838 |
def init_gns_from_files(path):
"""
Run GNS3 from a given set of router configs, builds GNS3 topology as well as adjacency information and
starts all routers in the GNS3 project
:param path: path to the configuration files, router configs are located at path/configs/
:return: GNS3 project descriptor ... | 55,839 |
def from_hdf(symbol: str, interval: str) -> Optional[pd.DataFrame]:
"""Try to load a DataFrame from .h5 store for a given symbol and interval
:param symbol: Binance symbol pair, e.g. `ETHBTC` for the klines to retrieve
:param interval: Binance kline interval to retrieve
:return: Pandas.DataFrame with r... | 55,840 |
async def uptime(ctx: commands.Context):
"""
Gets the Uptime info of the bot.
"""
if ctx.interaction is not None:
await ctx.interaction.response.defer()
embed = (
discord.Embed(color=bot.color, timestamp=ctx.message.created_at)
.set_author(name="Uptime Info:", icon_url=... | 55,841 |
def parse_evergreen_datetime(evg_date: Optional[Any]) -> Optional[datetime]:
"""
Convert an evergreen datetime string into a datetime object.
:param evg_date: String to convert to a datetime.
:return: datetime version of date.
"""
if not evg_date:
return None
if type(evg_date) in [... | 55,842 |
def dateToQuarter(string):
"""takes a string of the type YYYY-MM and converts it to YYY-QN
basically from month to quarter"""
y,m = string.split('-')
return y + '-' + QUARTER_MAP[int(m)] | 55,843 |
def get_main_container_network() -> Optional[str]:
"""
Gets the main network of the LocalStack container (if we run in one, bridge otherwise)
If there are multiple networks connected to the LocalStack container, we choose the first as "main" network
:return: Network name
"""
main_container_netw... | 55,844 |
def tri3_Bmat(zi_px, zi_py):
"""
Computing the B-matrix for a 3-node beam element
:param list zi_px: partial derivative of zeta with respect to x
:param list zi_py: partial derivative of zeta with respect to y
:return: B-matrix for a 3-node element
"""
B = np.matrix([
[zi_px[0],... | 55,845 |
def _validate_compute_resources(compute_resources):
"""
Performs check of Batch Compute Environment compute resources.
:param compute_resources: compute resources definition
:raises AssertionError in case of invalidity.
:return: None
"""
compute_resource_type = compute_resources.get('type'... | 55,846 |
def test_endofweek_offset():
"""endofweek works correctly for a column arg."""
db = FakeDatabase("help", "Samples")
tbl = TableExpr("tbl", database=db, columns={"foo": datetime})
query = tbl.project(weekend=F.endofweek(tbl.foo, 1))
assert "weekend" in query.columns
assert "foo" not in query.colu... | 55,847 |
def fixedcase_prefix(ws, truelist=None, phrase_truelist=None):
"""Returns a list of 1 or more bools: True if some prefix of the tuple 'ws' should be fixed-case,
False if not, None if unsure."""
# phrase_truelist is sorted in descending order by phrase length
if phrase_truelist is not None:
for n... | 55,848 |
def all_urls(tab_widget):
"""
Prints all the urls held on a tab widget
"""
for i in range(tab_widget.count()):
print(tab_widget.widget(i).webkit.url().toString()) | 55,849 |
def pipeline_dict() -> dict:
"""Pipeline config dict. Updating the labels is needed"""
pipeline_dict = {
"name": "german_business_names",
"features": {
"word": {
"embedding_dim": 16,
},
},
"head": {
"type": "TextClassification"... | 55,850 |
def read_links(input_dir,
links,
nodes,
id_to_no_dict,
agent_type_size,
demand_period_size):
""" step 2: read input_link """
with open(input_dir+'/link.csv', 'r', encoding='utf-8') as fp:
print('read link.csv')
reader = csv.... | 55,851 |
def test_change_ui_theme_and_color_scheme(config_dialog, mocker, qtbot):
"""Test that changing color scheme or UI theme works as expected."""
# Patch methods whose calls we want to check
mocker.patch.object(SpyderConfigPage, "prompt_restart_required")
# Get reference to Preferences dialog and widget pa... | 55,852 |
def _read_chip(path, selection):
"""Reads content of a single classification chip."""
d = {'filename': os.path.basename(path)}
for filename in tf.io.gfile.glob(path + '/*'):
if filename.endswith('_labels_metadata.json'):
with tf.io.gfile.GFile(filename, 'r') as fid:
d['metadata'] = json.loads(fi... | 55,853 |
def status(all):
"""Summarise the status of alpenhorn storage nodes."""
import tabulate
# Data to fetch from the database (node name, total files, total size)
query_info = (
di.StorageNode.name,
pw.fn.Count(di.ArchiveFileCopy.id).alias("count"),
pw.fn.Sum(di.ArchiveFile.size_b)... | 55,854 |
def isadmin(ctx):
"""Checks if the author is an admin"""
if str(ctx.author.id) not in config['admins']:
admin = False
else:
admin = True
return admin | 55,855 |
def get_name_from_filename(filename):
"""Gets the partition and name from a filename"""
partition = filename.split('_', 1)[0]
name = filename.split('_', 1)[1][:-4]
return partition, name | 55,856 |
def threshold(threshold, utilization):
""" Static threshold-based underload detection algorithm.
The algorithm returns True, if the last value of the host's
CPU utilization is lower than the specified threshold.
:param threshold: The static underload CPU utilization threshold.
:type threshold: fl... | 55,857 |
def test_main_entry_point_exit(mocker, workspace_without_git):
"""main function should exit if ran in not valid git project"""
python_githooks.__main__.__BASE_DIR__ = workspace_without_git
python_githooks.__main__.__GITHOOKS_BASE_DIR__ = os.path.join(workspace_without_git, '.git/hooks')
mocked_sys_exit ... | 55,858 |
def process_html(html_page, this_parser):
""" extract links from an html page """
this_parser.feed(html_page)
return {
"int_links": this_parser.int_links,
"ext_links": this_parser.ext_links,
"static_links": this_parser.static_links
} | 55,859 |
def sync_execute_run_grpc(api_client, instance_ref, pipeline_origin, pipeline_run):
"""Synchronous version of execute_run_grpc."""
return [
event
for event in execute_run_grpc(
api_client=api_client,
instance_ref=instance_ref,
pipeline_origin=pipeline_origin,
... | 55,860 |
def random_cutout_color(imgs, min_cut=10,max_cut=30):
"""
args:
imgs: shape (B,C,H,W)
out: output size (e.g. 84)
"""
n, c, h, w = imgs.shape
w1 = np.random.randint(min_cut, max_cut, n)
h1 = np.random.randint(min_cut, max_cut, n)
cutouts = np.empty((n, c, h, w), ... | 55,861 |
def handle_ws(message, ws):
"""
fall through opcodes do do work
"""
global current_message
if "," in message:
op, message = message.split(",", 1)
op = int(op)
elif message.strip().isdigit():
op = int(message)
message = ""
else:
print("WTF is '%s'" % s... | 55,862 |
def get_day():
"""Function for retrieving the wanted day"""
day = datetime.datetime.today().weekday()
if len(sys.argv) == 3:
if sys.argv[2] == "mon":
day = 0
elif sys.argv[2] == "tue":
day = 1
elif sys.argv[2] == "wed":
day = 2
elif sys.arg... | 55,863 |
def main():
"""Count lines, words and bytes of the text from the file"""
args = get_args()
sum_bytes, sum_lines, sum_words = 0, 0, 0
for file in args.file:
text_bytes, text_words = 0, 0
text = file.readlines()
text_lines = len(text)
for line in text:
text_by... | 55,864 |
def _unknown_variants_in_dependencies(pkgs, error_cls):
"""Report unknown dependencies and wrong variants for dependencies"""
import spack.repo
import spack.spec
errors = []
for pkg_name in pkgs:
pkg = spack.repo.get(pkg_name)
filename = spack.repo.path.filename_for_package_name(pkg... | 55,865 |
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the PCF8574 devices."""
i2c_address = config.get(CONF_I2C_ADDRESS)
i2c_port_num = config.get(CONF_I2C_PORT_NUM)
pcf = PCF8574(i2c_port_num, i2c_address)
switches = []
pins = config.get(CONF_PINS)
for pin_num, pi... | 55,866 |
def _copyForwardTroveMetadata(repos, troveList, recipeObj):
"""
Copies forward metadata from a previous build of this package
if possible. Searches on the current label then one level up
(to make sure shadowed sources get metadata from their parent).
Tries to match the flavor if po... | 55,867 |
def bbox_transform(boxes, deltas, weights=(1.0, 1.0, 1.0, 1.0)):
"""Forward transform that maps proposal boxes to predicted ground-truth
boxes using bounding-box regression deltas. See bbox_transform_inv for a
description of the weights argument.
"""
if boxes.shape[0] == 0:
return np.zeros((0, deltas.shape[1]), ... | 55,868 |
def _get_crop(cytomine, image_inst, geometry):
"""
Download the crop corresponding to bounds on the given image instance
from cytomine
Parameters
----------
cytomine : :class:`Cytomine`
The cilent holding the communication
image_inst : :class:`ImageInstance` or image instance id (in... | 55,869 |
def authorship_below_random_chance(X, classifier, numAuthors):
"""See if the user's document features fool the classifier
"""
randomChance = 1 / numAuthors
authorProb = classifier.predict_proba(X)
print("User probability: ", authorProb[0][0])
print("numAuthors: ", numAuthors)
print("Highest ... | 55,870 |
def create_executables(*args, **kwargs) -> None:
"""
Allows each enabled plugin to create a special executable if needed
:param args: arguments to pass to plugins
:param kwargs: keyword arguments to pass to plugins
"""
for plugin in get_subclasses(MainPlugin):
plugin().create_executable(... | 55,871 |
def test_command_line_interface():
"""Test the CLI."""
runner = CliRunner()
result = runner.invoke(cli.main)
assert result.exit_code == 0
assert "investment_tracker.cli.main" in result.output
help_result = runner.invoke(cli.main, ["--help"])
assert help_result.exit_code == 0
assert "--he... | 55,872 |
def fnr_func_multi(threshold, preds, labels):
"""False rejection rate or False negative rate."""
return tf.reduce_sum(
tf.multiply(tf.cast(tf.less_equal(preds, threshold), tf.float32), labels),
axis=0) / tf.reduce_sum(
labels, axis=0) | 55,873 |
def queue() -> RedisQueue:
"""An empty queue"""
q = RedisQueue('localhost', topics=['priority'])
q.connect()
q.flush()
return q | 55,874 |
def test_is_not_mutually_orthogonal():
"""Return False for non-orthogonal vectors."""
states = [np.array([1, 0]), np.array([1, 1])]
np.testing.assert_equal(is_mutually_orthogonal(states), False) | 55,875 |
async def determine_building_main(dct_lst: list):
"""Async cadastre units' building main
:param dct_lst: dictionary to be used
:return: cadastre units w/ buildings and without
"""
connector = aiohttp.TCPConnector(limit=c.MAX_CONNECTIONS)
async with aiohttp.ClientSession(connector=connector) as ... | 55,876 |
def pre_tax(sale):
"""
Args:
sale: 持股平台减持价格(元/股)
Returns:
需交纳税金
"""
return income_tax(income(pre_price, options)) + cap_tax(all_option(options) * (sale - pre_price)) | 55,877 |
def _offset_to_boxes(F, center, pred, stride, transform="minmax", **kwargs):
""" Change from point offset to bbox.
:param center: the initial points center
:param pred: the predicted point offsets
:param stride: the stride of the offsets
:param transform: the transform from points to bbox: "minmax",... | 55,878 |
def poll_lldp_neighbors(dut, iteration_count=180, delay=1, interface=None):
"""
Poll for LLDP Neighbours Info
Author: Prudvi Mangadu (prudvi.mangadu@broadcom.com)
:param dut:
:param iteration_count:
:param delay:
:param interface:
:return:
"""
i = 1
while True:
rv = g... | 55,879 |
def GetForegroundControl():
"""return Foreground Window"""
return ControlFromHandle(Win32API.GetForegroundWindow())
#another implement
#focusedControl = GetFocusedControl()
#parentControl = focusedControl
#controlList = []
#while parentControl:
#controlList.insert(0, parentControl)
... | 55,880 |
def _set_device(disable_cuda=False):
"""Set device to CPU or GPU.
Parameters
----------
disable_cuda : bool (default=False)
Whether to use CPU instead of GPU.
Returns
-------
device : torch.device object
Device to use (CPU or GPU).
"""
# XXX we might also want to us... | 55,881 |
def adaptive_thres(img, FIL1=10, R1=100):
"""adaptive thresholding for picking objects with different brightness.
"""
bw = adaptive_thresh(img, R=R1, FILTERINGSIZE=FIL1)
return label(bw) | 55,882 |
def two_way_skar_bounds(dist, rvs, crvs, rv_mode=None):
"""
Iteratively compute tighter bounds on the two way secret key agreement rate.
Parameters
-----------
dist : Distribution
The distribution of interest.
rvs : iterable
The indices to consider as X (Alice) and Y (Bob).
... | 55,883 |
def print_results_from_evaluation_dirs(work_dir_path: Path, run_numbers: list,
print_results_only: bool = False) -> None:
"""Print the aggregated results from multiple evaluation runs."""
def float_representer(dumper, value):
text = '{0:.4f}'.format(value)
... | 55,884 |
def clear_crontab(owner: Owner) -> Result[Unset]:
"""
Clear the owning user's crontab, if one exists on the current server.
"""
if not get_crontab(owner):
return Result(State.unchanged)
command(["/usr/bin/crontab", "-u", owner_name(owner), "-r"])
return Result(State.success) | 55,885 |
def test_unicode_handling(username, password):
"""
With a unicode string for the password, set and verify the
Authorization header.
"""
authorizer = BasicAuthorizer(username, password)
header_val = authorizer.get_authorization_header()
assert header_val[:6] == "Basic "
decoded = base64.... | 55,886 |
def get_stats_by_month(session, datetime_column, months, autofill=True):
"""获取月统计数据
:param session: db.sessoin
:param datetime_column: ORM Column
:param months: int, 用负数表示过去的月数
:param autofill: bool, 是否自动填充没有的数据
"""
first_day, last_day = get_first_day_and_last_day_by_month(months)
stats... | 55,887 |
def message():
"""Manage a job's message queue via Pub/Sub."""
pass | 55,888 |
async def start_game(game_params: GameParams):
"""
Method used to create game instance with given parameters
:param game_params: GameParams object with integer how_many_cards and list of strings with players_names
:return: integer value of game_id
"""
game_state = game.GameState()
gp = game_... | 55,889 |
def test_get_breakfast_recipes(test_client):
"""
GIVEN a Flask application configured for testing
WHEN the '/breakfast/' page is requested (GET)
THEN check the response is valid
"""
recipes = [b'Pancakes', b'Honey Bran Muffins', b'Acai Bowl',
b'Breakfast Scramble', b'Pumpkin Donut... | 55,890 |
def _run_efibootmgr(valid_efi_bootloaders, device, efi_partition):
"""Executes efibootmgr and removes duplicate entries.
:param valid_efi_bootloaders: the list of valid efi bootloaders
:param device: the device to be used
:param efi_partition: the efi partition on the device
"""
# Before updat... | 55,891 |
def infer_Tmap_from_clonal_info_alone(
adata_orig,
method="naive",
clonal_time_points=None,
later_time_point=None,
selected_fates=None,
):
"""
Compute transition map using only the lineage information.
As in :func:`.infer_Tmap_from_multitime_clones`, we provide two modes of inference:
... | 55,892 |
def safe_quote_string(text):
"""
safe_quote_string(text)
returns the text in quotes, with escapes for any quotes in the text itself
text - input text to quote
returns: text in quotes with escapes
"""
if os.sep != '\\':
text2 = text.replace('\\', '\\\\')
text3 = text2.replace('"', '\\"')
else:
text3 ... | 55,893 |
def evaluate(input_data, predicted_output):
"""The function computes the accuracy for each of the datapoints
that are part of the information extraction problem.
Args:
input_data (list): The input is a list of dictionary values from the isda json file
predicted_output (list): This is a list... | 55,894 |
def blockInhalfSpace(conds):
""" Returns a block in a halfspace model based on the inputs"""
M, freqs, rx_loc, elev = getInputs()
# Model
ccM = M.gridCC
# conds = [1e-2]
groundInd = ccM[:, 2] < elev
sig = simpeg.Utils.ModelBuilder.defineBlock(
M.gridCC, np.array([-1000, -1000, -1500... | 55,895 |
def build_generator(input_shape=(256, 256, 3), ngf=64, kernel_size=4,
strides=2):
"""U-Net Generator"""
image_input = Input(shape=input_shape)
n_channels = input_shape[-1]
# encoding blocks
e1 = Conv2D(ngf, kernel_size=kernel_size, strides=2, padding='same')(
image_inpu... | 55,896 |
def randomize(img, noise_level=.03):
""" given an array, randomizes the values in that array
noise_level [0,1] controls the overall likelihood of a bit being
flipped. This overall level is then multiplied by the levels variable,
which modifies the noise level for the various significant bit... | 55,897 |
def test_fail_to_remove_no_existing_connection_record(requester: Client):
"""Test to fail the remove DIDComm Connection record."""
resp = unset_resolver_connection.sync_detailed(client=requester, conn_id="DNE")
assert resp.status_code == 404 | 55,898 |
def write_data(worksheet, data):
"""Writes data into worksheet.
Args:
worksheet: worksheet to write into
data: data to be written
"""
if not data:
return
if isinstance(data, list):
rows = data
else:
rows = [data]
if isinstance(rows[0], dict):
... | 55,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.