content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def run_MLKWayPartMgr(H: Netlist, K: int):
"""[summary]
Args:
H (Netlist): [description]
K (int): [description]
Returns:
[type]: [description]
"""
partMgr = MLKWayPartMgr(0.4, K)
# partMgr.limitsize = 2000
randseq = [randint(0, K - 1) for _ in H]
if isinstance(... | 30c09c7889960ff83da1f1f37f5cf1ca3b22a506 | 3,609,000 |
import math
def compute_difference(bbox, x, y, w, h):
"""
Helper function for calculating shortest distance between two bounding boxes, using the center coordinates
"""
boxX, boxY = getBboxMidPoint(bbox)
inX, inY = getMidpoint(x, y, w, h)
difX = abs(boxX - inX)
difY = abs(boxY - inY)
d... | c61c0019773ae8d274358f13e779f3183db85597 | 3,609,001 |
def ODP_methods(CASRN):
"""Return all methods available to obtain ODP for the desired chemical.
Parameters
----------
CASRN : str
CASRN, [-]
Returns
-------
methods : list[str]
Methods which can be used to obtain ODP with the given inputs.
See Also
--------
ODP... | 186ee39db26923c4fc94a80bbe751ef910265062 | 3,609,002 |
def PySet_Pop(space, w_set):
"""Return a new reference to an arbitrary object in the set, and removes the
object from the set. Return NULL on failure. Raise KeyError if the
set is empty. Raise a SystemError if set is an not an instance of
set or its subtype."""
return space.call_method(space.w_set... | 5303f9b7afd4d4cfdb6ee065e860720af5b88b8e | 3,609,003 |
def pad_portraits_to_same_size(B1, B2):
"""
Make sure that two matrices are padded with zeros and/or trimmed of
zeros to be the same dimensions.
Parameters
----------
B1, B2 (np.ndarray):
Portrait matrices of a graph (k x N)
Returns
-------
BigB1, BigB2 (np.ndarray):
... | d4fbee5187066c440e03922961a143fb610c9aa0 | 3,609,004 |
def rss_func(mean, ground_truth):
"""
Compute the Residual Sum of Squares between the GP predictions and the ground truth values of the simulated
lightcurves.
:param mean: GP predictive mean
:param ground_truth: ground truth values of the simulated lightcurve
:return: residual sum of squares
... | 7ad2dcf372baf3b2ca5455e175fa6adcf13a8aad | 3,609,005 |
import json
def adminUsersEdit():
"""
Admin - edit user
"""
if current_user.is_admin:
body = json.loads(request.data)
id = body["id"]
user = User.query.filter_by(id=id).first()
if user is None:
user = User.query.filter_by(username=body["username"]).first()
... | 93a18439d41ff47d69d6a514a4cb0f822bb04293 | 3,609,006 |
def get_hwmi_(kde, inv, ax_t, c_hwmi, c_wsdi, minL):
"""
... get hwmi/cwmi and wsdi/csdi over nD cube ...
Parsed arguments:
kde: dictionary keys: 'cdf', 'x'
- cdf: cdf values of KernelDistributionEstimate object
- x: support values of KernelDistributionEstimate ... | 1fd03168cf00fc23a1ee7f77b97c61ef22b9f723 | 3,609,007 |
import random
def random_mac_address(local=True):
"""
Generate random MAC address
"""
vendor = random.SystemRandom().choice(
(
(0x00, 0x05, 0x69), # VMware MACs
(0x00, 0x50, 0x56), # VMware MACs
(0x00, 0x0C, 0x29), # VMware MACs
(0x00, 0x16, 0... | eb89ab223d0e8ae9f011277d92f3cd01d27627e8 | 3,609,008 |
def logpolar(src, r0, r1, center=None):
"""Log-Polar transform
The area radii [r0:r1] of radius N/2 mapsto the same size of src image
cf. cv2.logPolar(src, (nx,ny), M, cv2.INTER_CUBIC)
"""
h, w = src.shape
if center is None:
xc, yc = w//2, h//2
else:
xc, yc = center
... | 762df3fb22d9f0734334b69c9b160bb6663bcab8 | 3,609,009 |
def check_win(game, players):
"""
-1: ongoing
0: tie
> 0: id of winner
"""
# print(status)
# print(status)
for player in players:
if len(player.destination_cards) == 0:
return player.id, 1
if game.card_index >= len(game.cards) or player.trains == 0:
... | 0127de10c9b6b9b08dbf07b3747d92a2a9b4115c | 3,609,010 |
from datetime import datetime
def now():
""" Return the current UTC time as a datetime object unless the test suites
have overriden this value. """
# If the value of now has been frozen, use that, otherwise use the wallclock.
if _now_override:
n = _now_override
else:
n = datetime.u... | 90d2d1caf2830349136864ef1cc6dbf73d752255 | 3,609,011 |
def extract_gs1_data(filepath):
"""Filepath is absolute filepath to the file "GPC Schema 2018-12 EN.xml"
It can be downloaded from https://www.gs1.org/sites/default/files/docs/gpc/en_2018-12.zip.
"""
root = objectify.parse(open(filepath, encoding="utf-8")).getroot()
schema = root["{urn:ean.ucc:2}m... | 8b6cd1e5dde6abfeee56b29e2e82aacae00bb65b | 3,609,012 |
import requests
import os
def download_url(url, file_name=None, verify=True, timeout=10):
"""
Fetch `url` and return the temporary location where the fetched content was
saved. Use `file_name` if provided or create a new `file_name` base on the last
url segment. If `verify` is True, SSL certification ... | b02d8870890821507b679290c21e75b6bc5daa4e | 3,609,013 |
def message_has_label(message, label):
"""Tests whether a message has a label
Args: message: message to consider.
label: label to check.
Returns: True/False.
"""
return label['id'] in message.get('labelIds', []) | 634808b2533469daa42779a3563f127d06ce1b14 | 3,609,014 |
def indent_func_def(func_def):
"""Ensures max columns in a function signature follows style guide"""
if len(func_def) < 80:
return func_def
parts = func_def.split(',')
idx = func_def.index('(')
params = parts[0]
for x in parts[1:]:
params += ',\n{}{}'.format(idx * ' ', x)
ret... | 371bde9c8580982894759d6716a9be6d4f8521a5 | 3,609,015 |
import sys
def good_default_options():
"""
Probably very subjective. But just to have some reasonable defaults,
which might be used.
This is dependent on the OS.
Usage in your config might be like::
import common
globals().update(common.good_default_options())
"""
if sys.platform == "darwin":... | 29a739081f70bdce5fda4070036823854a22f53f | 3,609,016 |
def load_img(path):
"""Returns the numpy array after loading image
Input
----------
path: str
Output
----------
image: numpy.ndarray
"""
img = Image.open(path)
image = np.array(img)
return image | 8f8a1e1e9b5c0c2783a423cdfbe7aa111846d568 | 3,609,017 |
from typing import Tuple
def project_lidarpcs_to_camera(pc: LidarPointCloud,
transform: npt.NDArray[np.float64],
camera_intrinsic: npt.NDArray[np.float64],
width: int,
height: int) -> Tuple[npt.... | 9348adc47ab41179991a0bb01229b7f3e3ac8433 | 3,609,018 |
import unicodedata
import re
def slugify(value):
"""
Normalizes string, converts to lowercase, removes non-alpha characters,
and converts spaces to hyphens. Borrowed from
https://stackoverflow.com/questions/295135/turn-a-string-into-a-valid-filename
"""
value = str(unicodedata.normalize('NFKD'... | 88683c3e4c91f909c584f946ac887f1431df1f83 | 3,609,019 |
def buildValue(value):
"""Builds a positioning value record.
Value records are used to specify coordinates and adjustments for
positioning and attaching glyphs. Many of the positioning functions
in this library take ``otTables.ValueRecord`` objects as arguments.
This function builds value records f... | 8d8d05079a9b4e92fcbfed5a477898b39520d847 | 3,609,020 |
def line_colors(streamlines, cmap='rgb_standard'):
""" Create colors for streamlines to be used in fvtk.line
Parameters
----------
streamlines : sequence of ndarrays
cmap : ('rgb_standard', 'boys_standard')
Returns
-------
colors : ndarray
"""
if cmap=='rgb_standard':
... | a89fa0384e632f3faa2eac709d722c727b37a3dc | 3,609,021 |
def transform_case(input_string):
"""
Lowercase string fields
"""
return input_string.lower() | 4d15f33781c1b58d3a04a52fcc8e5f5042e33bdf | 3,609,022 |
from re import S
def linear_expand(expr):
"""
If a sympy 'Expr' is of the form:
expr = expr_0 + expr_1*a_1 + ... + expr_n*a_n
where all the a_j are noncommuting symbols in basis then
(expr_0, ..., expr_n) and (1, a_1, ..., a_n) are returned. Note that
expr_j*a_j does not have to be of that... | bbbf7329f14ddadf14fc26d65f0358f71b923a18 | 3,609,023 |
from typing import Union
def format_numbers_consistently(number: Union[int, float]) -> Union[int, float]:
"""
Formats numeric values in a consistent way.
Prevents inconsistencies with how numbers are formatted (e.g. '12.0' as '12')
:type number: float or int
:param number: numeric value to forma... | ebf7acdca53ac331ac7a5e1e8ba2ee416cc7112b | 3,609,024 |
import re
def extract_date_from_date_time(date_time: str) -> str:
"""
Given a date in format YYYY-MM-DDTHH:MM:SS, extract the date
part (i.e. YYYY-MM-DD)
:param date_time : str (DATETIME_FORMAT)
:return str
a date in DATE_FORMAT
"""
assert type(date_time) == str, "date_time must ... | 4727273615fa38a48eace841c4ff8760ab10d08e | 3,609,025 |
def _join_tokens_to_string(tokens):
"""Join a list of string tokens into a single string."""
token_is_alnum = [t[0] in _ALPHANUMERIC_CHAR_SET for t in tokens]
ret = []
for i, token in enumerate(tokens):
if i > 0 and token_is_alnum[i - 1] and token_is_alnum[i]:
ret.append(u" ")
ret.append(token)
... | ea5ba745650ba7f9f6cca205152387aa4b95f500 | 3,609,026 |
def make_divisible(value, divisor, min_value=None, min_ratio=0.9):
"""Make divisible function.
This function rounds the channel number down to the nearest value that can
be divisible by the divisor.
Args:
value (int): The original channel number.
divisor (int): The divisor to fully div... | 950aeb4d48ca8749b8da55c9359798c8127f318e | 3,609,027 |
def cli(ctx, role_name, description, user_ids="", group_ids=""):
"""Create a new role.
Output:
Details of the newly created role.
For example::
{'description': 'desc',
'url': '/api/roles/ebfb8f50c6abde6d',
'model_class': 'Role',
'type': 'admin',
... | 7b9b9f0d72dd2312448eee96dc9743b2b9657271 | 3,609,028 |
def train(features, labels, type='cnn', num_classes=None, print_summary=True,
save_model=True, lr=0.01, loss_type=None, epochs=100, optimizer='Adam', verbose=True):
"""Trains model based on provided feature & target data
Options:
- epochs: The number of iterations. Default is 50.
- lr: Learning rate... | c9f96787f384cbb281bfb661d3268da30acf1936 | 3,609,029 |
def get_train_test(folder_path, train_size):
"""返回训练集和测试集的 pcap 的路径, 这里返回的数据格式如下,
{
'Chat': ['./data/preprocess_data\\Chat\\AIMchat1\\AIMchat1.pcap.UDP_131-202-240-87_137_131-202-243-255_137.pcap', ...],
'Email': [...],
...
}
Args:
folder_path (str): 包含 pcap 文件的根目录
... | b67381ba3414236f4128c6aaf1ab45642402578d | 3,609,030 |
from argparse import ArgumentParser
def parse_args(argv=None):
"""
Argument parsing routine.
:param argv: A list of argument strings.
:rtype argv: list
:return: A parsed and verified arguments namespace.
:rtype: :py:class:`argparse.Namespace`
"""
parser = ArgumentParser(
desc... | 89be357415a339323c644184b315bb238433b417 | 3,609,031 |
def plot_inter_train_results(results, figure_title, pretrain_res=None, key='val_accuracy'):
"""Plot training progress of pretraining models.
:param results: list of subjects inter training results
:type results: list of lists of dicts
:param figure_title: saving location for created plot
:type ... | 9bb679aec3daa1ea6accb428110c2e48525f9f5c | 3,609,032 |
def user_point_timestamps(date_start, date_end, outfile=None):
"""display the timestamps for user points."""
output = _output('=== point timestamps from %s to %s ===\n' % (
date_start, date_end), outfile)
if not date_start:
output += _output("must specify date_start parameter.", outfile)
... | f7020ae3192e5a1482d8f4bb0b2597b6b01fe157 | 3,609,033 |
def haversine(lon1, lat1, lon2, lat2):
"""
Calculate the great circle distance between two points ... | d93dcb63911f361bd294a11ce2423e90cd4cc131 | 3,609,034 |
def eq_entropy(drva,drvt,drvd,airf,temp,dhum,chkbnd=False):
"""Calculate humid air entropy with derivatives.
Calculate the specific entropy of humid air or its derivatives with
respect to dry air mass fraction, temperature, and humid air
density.
:arg int drva: Number of dry fraction deriv... | f5ef09936df64d4db66740921a69fb55063c74f1 | 3,609,035 |
import aiohttp
import asyncio
async def async_check_can_reach_url(
hass: HomeAssistant, url: str, more_info: str | None = None
) -> str:
"""Test if the url can be reached."""
session = aiohttp_client.async_get_clientsession(hass)
try:
await session.get(url, timeout=5)
return "ok"
... | 967cc2aa722f35b172138d95dbfad8345c73c69a | 3,609,036 |
import sys
def prioritize_match_list(dataframe, row_mz, row_rt):
"""Prioritize matched peaks for peak_list_annotate. Used in cases where matching by various criteria gives
more thank one possible match in order to select the closest match based on mz and/or rt matching.
"""
annotation = ""
blank_... | 0ad3c279e4e905c8f5fbe581d4908b578bf566f3 | 3,609,037 |
def is_licence_accepted(licence_expression: str) -> bool:
"""Determines whether the licence expressed is valid with regards to project's accepted licences."""
authorised_licences = [licence.identifier for licence in get_allowed_opensource_licences()]
is_or = _is_expression_or(licence_expression)
if bool... | 0cf230a5350a50cb1849945e2d3608d0ece7f589 | 3,609,038 |
def offer_str(rq_offer):
""" this function converts the offer_dict of travelers to a string for debugging """
return ", ".join(["{}:{}".format(k, str(v)) for k, v in rq_offer.items()]) | 67c29c85b9bf7aa705ff604caceb31a290fec011 | 3,609,039 |
import numpy
def sentence_to_weight_matrix(sentence):
"""
Converts the dependency graph of a sentence of tokens into a weight matrix.
weight[u, v] = 0 iff u == v
weight[u, v] = 1 iff u != v and are_bidirectionaly_directly_connected(u, v) == True
weight[u, v] = 0 else
"""
V = len(sentence)... | e413de859ce825b8fc0c00b4241d74746d26b0b0 | 3,609,040 |
import csv
def find_by_column(filename, column, value):
""" This method discovers interactions registered in the DLT looking at one specific value"""
list = []
with open(filename) as f:
reader = csv.DictReader(f)
for item in reader:
if item[column] == value:
lis... | 928f53e72c7b5e3e63316748545a530c20559f8b | 3,609,041 |
def restore(context, backup_info, restore_location):
"""
Main entry point for restoring a backup based on the given backup id. This
will transfer backup data to this instance an will carry out the
appropriate restore procedure (eg. mysqldump)
:param context: the context token which contains th... | 907eba4fa280ca00c911d8f9602f1b950af3ee61 | 3,609,042 |
def end_match(s, t, k, direction='sp'):
"""
Compares the first or last k-1 bases of strings s,t for a match.
The direction argument is a two character string whose characters are 'p'
or 's', where the first character indicates whether to use the prefix or
suffix of s for comparison and the second ch... | d5b912cbcbc33d21c5cba60dd85897fcf73feee4 | 3,609,043 |
def hilbert_space_kron(op, indx, dims):
"""
Extend an operator op to the full product hilbert space
given by dimensions in dims.
Parameters
----------
op : np.array
Operator to be extended.
indx : int
Position of which subspace to extend.
dims : list
New dimensio... | 2ce100ddfecd1acb6088ebabed00d7578f7aab9a | 3,609,044 |
def genSpecSines_p(ipfreq, ipmag, ipphase, N, fs):
"""
Generate a spectrum from a series of sine values
iploc, ipmag, ipphase: sine peaks locations, magnitudes and phases
N: size of the complex spectrum to generate; fs: sampling rate
returns Y: generated complex spectrum of sines
"""
Y = np.zeros(N, dtype = com... | bc3f2a195f190d02513bf14b98816c6a4d8e74fc | 3,609,045 |
from datetime import datetime
def dt_to_dec(dt):
"""Convert a datetime to decimal year."""
year_start = datetime(dt.year, 1, 1)
year_end = year_start.replace(year=dt.year+1)
return dt.year + ((dt - year_start).total_seconds() / # seconds so far
float((year_end - year_start).total_seconds())) | 0841f21c245b0f3a2a1404c7c8c5bff9a26aae21 | 3,609,046 |
def check_pypi_update(dist_name):
"""Just check for updates and return a json
with the attribute "has_update".
:param dist_name: distribution name
:rtype: json
:return: json with the attribute "has_update"
"""
pkg_res = get_pkg_res()
try:
pkg_dist_version = pkg_res.get_distribut... | cc8e3600ebf1d0a07ab8960337249170e2899490 | 3,609,047 |
import os
def multifig_bleach(
record_name, kwargs_xdata=None, kwargs_ydata=None, kwargs_yerr=None,
fig_axis=0, kwargs_plot=None,
sfile='bleach.pdf', ylim=None, titles=None
):
"""Function to make a multi figure plot from y data selection.
`fig_axis` defines the axis of kwargs_ydata se... | 32a5c6b0dfe0f21c3fdc964291f41acd5f27978d | 3,609,048 |
import os
import shutil
def fetch_repo(url, branch, commit=None, bootstrap=None, lock=True):
"""
Make sure we have a given project's repo checked out and up-to-date with
the current branch requested
:param url: The URL to the repo
:param bootstrap: An optional callback function to execute... | b7db4dc067137baeaba16bb28b581316b104775f | 3,609,049 |
import requests
import json
def city_coordinate(ip):
"""
将ip地址定位:返回城市左下和右上两个点经纬度
:param ip: ip地址
:return: dot_ls 左下,右上经纬度坐标,[(lng1,lat1),(lng2,lat2)]
"""
url = "https://restapi.amap.com/v3/ip?parameters"
parameters = {
"ip": ip,
"key": user_config.LBS_WEB_KEY
}
res... | 10020d1636f6f055c37aacbce7ba4d2208d7d3c4 | 3,609,050 |
def get_fit1():
"""
Returns fit file for unit tests, uses data with larger uncertainties.
"""
info_path = InfoPath(
path='temp_data',
dir_name="a02_gaussian_mixture1",
sub_dir_name=InfoPath.DO_NOT_CREATE
)
return run(info_... | e5c0cc9165fbe876553ef033ee06bfd4540daca2 | 3,609,051 |
def get_brain_file(file_id):
"""
:param file_id:
:return:
"""
try:
response = get(file_id)
except ValueError:
response = None
return response | 915b2ce819cf27b6512ba947d520699c630a92b4 | 3,609,052 |
from typing import Optional
from typing import Union
def normalize_ip_address(
v: Optional[Union[str, IPv4Address, IPv6Address]]
) -> Optional[str]:
"""Pydantic validator for IP address fields.
Convert the PostgreSQL INET type to `str` to support reading entries from
a PostgreSQL database.
Param... | 3decda34f8c1265d5a374b0571cc3c1982357be5 | 3,609,053 |
def elements_to_stress_array(element_list, timestep=0) -> np.array:
"""Extract a numpy array containing element stress from a
list of nodes at a given timestep"""
points = []
for element in element_list:
points.append(element.get_stress())
return np.array(points)[:, timestep, :] | 20317c23cce42470a64aabbce1c01c6f18d5a075 | 3,609,054 |
def enhanceEntries(entriesList, feedId, feedName):
"""
Add Id of feed to each entry so that we only need the item, which then
contains all information that we need
Parameters
----------
entriesList : list
A List of RSSEntries (FeedParserDicts)
feedId : string
The URL of th... | db4bf6a82ca4fe41ee0797d361b962126836a7b8 | 3,609,055 |
def get_topic_attributes(TopicArn, region=None, key=None, keyid=None, profile=None):
"""
Returns all of the properties of a topic. Topic properties returned might differ based on the
authorization of the user.
CLI example::
salt myminion boto3_sns.get_topic_attributes someTopic region=us-west... | 18dba2cdd4b55070c6f37d64073fc9ab85fd7f6b | 3,609,056 |
def check_type(val, predicate, k, name):
"""Returns VAL. Raises a SchemeError if not PREDICATE(VAL)
using "argument K of NAME" to describe the offending value."""
if not predicate(val):
bad_type(val, k, name)
return val | d0944a6d384ebfe8161cebffe6da001b8e3b49ae | 3,609,057 |
def CalculateMediationPEEffect(PointEstimate2, PointEstimate3, ia = 0, ib = 1):
"""Calculate derived effects from simple mediation model.
Given parameter estimates from a simple mediation model,
calculate the indirect effect, the total effect and the indirect effects
Parameters
----------... | d2a80db944715a02dd267147087076b14db939a2 | 3,609,058 |
def filterColorBias( bmp, bias, savefile = '' ):
"""
"""
for h in range(bmp.height):
for w in range(bmp.width):
if( abs(bmp.pixels[h][w][0]-bmp.pixels[h][w][1]) > bias or
abs(bmp.pixels[h][w][0]-bmp.pixels[h][w][2]) > bias or
abs(bmp.pixels[h][w][1]-bmp... | 1813c85a638fc0bd7523430eb54b9ceb88d379dc | 3,609,059 |
async def delete_page_route(
current_user: UserIn = Depends(get_validated_user),
page_id: str = Form(None, title="page_id")):
"""Remove a page for a given user, provided they own it"""
if (page := await page_verify(current_user, page_id)):
# Delete metadata
return await page_dele... | 099c9f8f024a5dfca1154071d0904e754f41a057 | 3,609,060 |
def get_keywords(search_term):
"""
get the scored keywords for the search term's page,
then just return the top words without their scores
"""
keywords_and_scores = keywords_with_scores(search_term)
return [keyword for keyword, score in keywords_and_scores] | e968b5ff594e201f946be17b164cac927db53cb2 | 3,609,061 |
import json
def get_employees_by_current_project(term):
"""
Method to return an array of employees by project as json response.
"""
print("-" * 50)
print("Term: " + term + "\n")
results = es.search(
index="projects",
body={
"query": {
"match_phrase... | 42d9cdc3a7850d06ce5e6444b37c73c4704803ba | 3,609,062 |
def tf_out():
"""Static equilibrium results from threebar funicular."""
output = {}
output["xyz"] = {0: [0.29289321881345254, -0.7071067811865475, 0.0],
1: [1.0, 0.0, 0.0],
2: [2.5, 0.0, 0.0],
3: [3.207106, -0.7071067, 0.0]}
output["force"]... | 1f60894de3cb14b147baa552e4485aed0544a2b0 | 3,609,063 |
from bs4 import BeautifulSoup
def get_text_from_XML_without_saving(path):
"""
:param path: path to the XML file
:return: Text extracted from the path
"""
tree = open(path, 'r', encoding='utf8')
soup = BeautifulSoup(tree)
for script in soup(["script", "style"]):
script.extract()
... | f6fd435ae75ca6cc7743e8d0b7da6afca24b0719 | 3,609,064 |
def makeOutputTweak(outMod, job):
"""
_makeOutputTweak_
Make a PSetTweak for the output module and job instance provided
"""
result = PSetTweak()
# output filenames
modName = str(getattr(outMod, "_internal_name"))
fileName = "%s.root" % modName
result.addParameter("process.%s.file... | 8e595ce7f274b5e29dc1c61343081f656481ae47 | 3,609,065 |
def _parse_color_input(number_of_elements, color_spec,
cmap=None, vmin=None, vmax=None, alpha=1.):
"""
Handle the mess that is matplotlib color specifications.
Return an RGBA array with specified number of elements.
Arguments
---------
number_of_elements: int
Numb... | 5752f06475786d02f7f897c52191f02be4e646cb | 3,609,066 |
def Histogram(dfs, measurement, configs, analysisType, bins=50, iqr=None, **addConfigs):
"""Generates a Points Plot with a corresponding Histogram"""
newConfigs = addConfigs
log.info("Generating histograms for measurement {}...".format(measurement))
finalplots = None
try:
for key in dfs["key... | d205966633505270ff60a08348ee8536527c9f21 | 3,609,067 |
import json
def user_profile(username):
"""Renders the user profile page given their username."""
user = User.query(User.username_lower == username.lower()).get()
if not user:
user = User.query(User.username == username).get()
if not user:
return render_template("blank_profile.html", username=username... | 199456fb57c23cb7cd795864d14c4e141d050f7d | 3,609,068 |
import hashlib
def _insert_object_resp(bucket=None, name=None, data=None):
"""Fake GCS object metadata"""
assert type(data) is bytes
hasher = hashlib.md5()
hasher.update(data)
md5_hex_hash = hasher.hexdigest()
return {
u'bucket': bucket,
u'name': name,
u'md5Hash': _he... | 7bad1a7ecab042e60cb7a34d2e92679581226a18 | 3,609,069 |
def graph_mutation_diff(source_graph, dest_graph):
"""
Generates the set of operations (ADD, DEL) needed to go from `source_graph` to
`dest_graph`.
"""
source_graph_edges = break_knowledge_graph(source_graph)
dest_graph_edges = break_knowledge_graph(dest_graph)
diff_edges = source_graph_edge... | f2d8caff213f91c5af64bfcf2f2679f16fce6b4e | 3,609,070 |
def load_dataset(dataset='mnist', flatten=False):
"""Keras, derin öğrenme ve makine öğrenmesi çalışmalarında sıkça kullanılan bazı verisetlerini kendi içinde barındırmaktadır.
Bu verisetlerini ilk yüklemeye çalıştığınızda keras internetten otomatik olarak indirecek ve önbelleğe alaaktır.
Bu yüzden kodun çal... | 91303ece070da6569594ea6021bfe3cca7855557 | 3,609,071 |
def non_stratified_matching(control, treatment):
"""Find index of KNN-neighbor of control sample for treatment group.
:returns nn_index: knn index, M1 X M2 matrix. M1 is number of treatment, M2
is number of control.
Conponent function of :func:`psm`.
"""
exam_input(control, treatment)
t... | 4365a2fa12720914f8e4a668f0ccac16bf0e2306 | 3,609,072 |
def normal_upper_bound(probability, mu=0.0, sigma=1.0):
"""returns the z for which P(Z <= z) = probability"""
return inverse_normal_cdf(probability, mu, sigma) | 1814536206554e4f9a547ef43ffff7f8b98e197b | 3,609,073 |
def PropertyLookup(
desired,
unit_system=None,
verbose=False,
**kwargs,
):
"""
Each of the follow properties/parameters is expected to be a quantity with units
:param desired: Dependent from two of the following independent properties
:param T: dry-bulb Temperature (Default value = None... | 81139a23d2a60facd977deb711b7fec7a108eea8 | 3,609,074 |
import unicodedata
import re
def slugify(value):
"""
Normalizes string, removes non-alpha characters,
and converts spaces to hyphens.
"""
# assume that strings are ascii
if isinstance(value, str):
value = value.decode('ascii')
value = unicodedata.normalize('NFKD', value).encode('as... | 37ed557de0ab93d8bbdb356b2e5ec66895083c4e | 3,609,075 |
import os
def find(dir_name :str) -> list:
"""
List regular files in a stored in given directory or one of its subdirectories.
Args:
dir_name: A String corresponding to an existing directory.
Returns:
A list of String, each of them corresponding to a file.
"""
filenames = list(... | 369b9997bdf36949972140a5c7a54fac72c3d25d | 3,609,076 |
def common_to_alphabetical_key(common_key):
"""Convert a common key to an alphabetical key.
Convert a key ordered by most common letter to a key ordered by most common
letter at indices determined by the English alphabet, i.e. the most common letter
will be at index 4, second most common at index 18, a... | a22795797031e2b88827fd07f5da5f1f8e429c65 | 3,609,077 |
def vfunc(probability, prediction, threshold):
"""Simple function for thresholding predictions.
Args:
probability: The probability of the minority class
prediction: The class prediction of the classifier
threshold: Probability threshold above which the minor... | 3ae085dabee7432a543f68b35a274bd613b7f07f | 3,609,078 |
def dijkstra(mazeMap, start):
""" ͏ ͏ ͏ ͏ ͏ ͏ ͏͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏͏ ͏ ͏ ͏ ͏͏ ͏ ͏ ͏͏ ͏ ͏ ͏͏ ͏ ͏ ͏͏ ͏ ͏͏ ͏ ͏ ͏ ͏͏͏͏ ͏͏ ͏͏͏͏ ͏ ͏ ͏͏ ͏ ͏ ͏͏ ͏ ͏͏ ͏ ͏ ͏͏͏͏ ͏͏ ͏͏͏͏ ͏ ͏
Return t... | b6c2634dc2b115a244e1601ccf58258d8189f017 | 3,609,079 |
import os
def _pkgmap(d):
"""Return a dictionary mapping package to recipe name."""
target_os = d.getVar("TARGET_OS", True)
target_vendor = d.getVar("TARGET_VENDOR", True)
basedir = os.path.dirname(d.getVar("PKGDATA_DIR", True))
dirs = ("%s%s-%s" % (arch, target_vendor, target_os)
fo... | a65b559957c8a4ee3afa7686fd54abec627175c2 | 3,609,080 |
def check_custom_parameters_against_defaults(assay_type, custom_config_parameters, json=False):
"""
Converts and evaluates set of custom parameters against default config. If json, maps parameters and
populates background (default) parameters for non-specified parameters.
NB: requires that default conf... | 7ae2ee3ac79f78b49377a4875f1f9ca2a4a9cc44 | 3,609,081 |
def broadcast_ts(ts, params_len, new_columns):
"""Broadcast time series `ts` to match the length of `new_columns` through tiling."""
if checks.is_series(ts) or len(new_columns) > ts.shape[1]:
return ts.vbt.wrap(reshape_fns.tile(ts.values, params_len, axis=1), columns=new_columns)
else:
retur... | 7a6635eb7ec9992221397d0050b2b529b5683dc8 | 3,609,082 |
import requests
def get_room_id(room_name):
"""
This function will find the Webex Teams room id based on the {room_name}
Call to Webex - /rooms
:param room_name: The Webex Teams room name
:return: the Webex Teams room Id
"""
room_id = None
url = WEBEX_URL + '/rooms' + '?max=1000'
h... | 2e33edf94313fdef63c7d92021ee48b73492b7bc | 3,609,083 |
def pysiphash(uint64):
"""Convert SipHash24 output to Py_hash_t
"""
assert 0 <= uint64 < (1 << 64)
# simple unsigned to signed int64
if uint64 > (1 << 63) - 1:
int64 = uint64 - (1 << 64)
else:
int64 = uint64
# mangle uint64 to uint32
uint32 = (uint64 ^ uint64 >> 32) & 0xf... | a0a4bb7703aef9a95146c519aa1ace751bcf532e | 3,609,084 |
from typing import List
def _parse_lammps_log(file_in) -> List[float]:
"""Parse a LAMMPS log file for energy components."""
tag = False
with open(file_in) as fi:
for line in fi.readlines():
if tag:
data = [float(val) for val in line.split()]
tag = False
... | a5bb037a4482053d12b84ea6570ee80ec314f516 | 3,609,085 |
def get_authenticator():
"""Get authenticator instance."""
return current_authenticator | a131faaac547b35eb2f488c226a7290a99aaee3e | 3,609,086 |
import select
from operator import and_
async def gen_invitation(request: AthenianWebRequest, id: int) -> web.Response:
"""Generate a new regular member invitation URL."""
async with request.sdb.connection() as sdb_conn:
await get_user_account_status(request.uid, id, sdb_conn, request.cache)
e... | b66ef01723e23d2080645349e6fbc1decdc62b76 | 3,609,087 |
def histc(x: np.ndarray, bins: np.ndarray) -> np.ndarray:
"""
MATLAB `histc` equivalent function.
Args:
x: Input array
bins: Array of bins. It has to be 1-dimensional and monotonic
Rrturns
Counts the number of values in x that are within each specified bin range
"""
... | 7ec584c3dc62220008aaf7603ee9256feda7370a | 3,609,088 |
import random
import string
def get_unique_key(str_len: int) -> str:
"""Returns a random string of length str_len.
Args:
str_len (int): Length of string.
Returns:
str: Random string
"""
return "".join([random.choice(string.ascii_lowercase) for _ in range(str_len)]) | de8a7743ac5b802e3fe5687e4305ec14e26987a8 | 3,609,089 |
import tqdm
def load_word_vector(vector_path, word2id, dim=300):
"""
Read pretrained vectors
Make lookup table with vocabulary
Load vector at lookup table
"""
vocab_size = len(word2id)
lookup_table = np.random.normal(size=[vocab_size, dim])
if 'glove' in str(vector_path):
n_to... | 49cf4e437ea2a5354399b27454d0281b44fc702f | 3,609,090 |
def get_rr_cholesky(N, Fmat, psd):
"""
Use the Smola and Vishwanathan method to obtain the lower-triangular
Cholesky decomposition L of a matrix C = N + FF^{T} = LL^{T}.
This is a fast version of lowRankUpdate_slow, assuming that N is diagonal.
@param N: Vector with the elements of the diagon... | 0c5b506d5c47d202a5bd3f2bc87a7ffa885c71bd | 3,609,091 |
def greet_user():
"""Greets users and asks for their name"""
font= Figlet(font='standard',justify='center')
print(font.renderText("Welcome to Flat_Me !"))
name_prompt= {
'type':'input',
'name':'user_name',
'message':'Before we begin, let\'s start with something easy: What is your... | 13c4e24b507e4ab59005610b1eb0a20dc330bb34 | 3,609,092 |
import string
import random
def randomStringDigits(stringLength=11):
"""Generate a random string of letters and digits """
lettersAndDigits = string.ascii_letters + string.digits
return ''.join(random.choice(lettersAndDigits) for i in range(stringLength)) | e41bc2879d1ab75a61df25139df90b7ef5ee756b | 3,609,093 |
from typing import List
import sys
def main(argv: List[str] = None) -> object:
"""
Apply R5 edits to FHIR JSON files
:param argv: Argument list. If None, use sys.argv
:return: 0 if all RDF files that had valid FHIR in them were successful, 1 otherwise
"""
def gen_dlp(args: List[str]) -> dirl... | 498c720207664e7aad867cdeaa5b9c5ec6c8054a | 3,609,094 |
def get_quota_message(user):
"""
get quota warning, grace period, or enforcement message to email users and display
when the user logins in and display on user profile page
:param user: The User instance
:return: quota message string
"""
if not QuotaMessage.objects.exists():
QuotaMes... | 3ee6c7384777e4f1696e937bb38bbecb74f19b95 | 3,609,095 |
def find_augmenting_path(path, adjacency, n_rooms):
"""
Find an angmenting path if possible by a breadth-first serach, update the
residual capacity matrix,and return the flow increment.
If there is no augmenting path, return and IndexError Exception.
"""
parents = [-1] * n_rooms
parents[0]... | a4d3b1d9d222f43a9560de2a2a3d10e9c1b80058 | 3,609,096 |
def roll_2d6_plus6(count=6):
"""
Roll 2d6+6 and assign as required
"""
stats = list()
for _ in repeat(None, count):
stat = best_rolls(num_rolls=2, top=2, discard_ones=False, base=6) + 6
stats.append(stat)
stats.sort(reverse=True)
return stats | 305ce25b741a61062027c1d328e42838e85b3f3d | 3,609,097 |
import copy
def mk_gnfa(Nin):
"""Input : Nin, an NFA.
Output: G, a GNFA, with at-most one transition from any
state p to a state q.??true any more?? Note that we have created
an NFA (G+NFA), and so one state can have a transition
to A SET OF STATES !!
Met... | 0f978570d66fda16dd056a99b2b72b876b84448a | 3,609,098 |
from typing import OrderedDict
def sort_by_key(value, reverse=False):
"""
sorts a dictionary by its keys.
:param dict value: dict to be sorted.
:param bool reverse: sort by descending order.
defaults to False if not provided.
:rtype: OrderedDict
"""
result = so... | df200eaf2810e04281e8f8379ded09f21ed6df74 | 3,609,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.