content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def list_project_milestones(request):
"""
list project specific milestones
"""
project_id = request.GET.get('project_id')
project = Project.objects.get(id=project_id)
template = loader.get_template('project_management/list_project_milestones.html')
open_status = Status.objects.get(nam... | 5,327,600 |
def build_update_fn(loss_fn, *, scan_mode: bool = False):
"""Build a simple update function.
*Note*: The output of ``loss_fn`` must be ``(loss, (aux, model))``.
Arguments:
loss_fn: The loss function.
scan_mode: If true, use `(model, optimizer)` as a single argument.
Example:
>>> ... | 5,327,601 |
def plot_model_fits(fit_ds, plot_models='all', plot_total=True, background_models=[],
overlay_data=True, pts_per_plot=200, show_legend=True,
selections=None, omissions=None, ranges=None, **kwargs):
"""
Plots individual models
Parameters
----------
plot_m... | 5,327,602 |
def _get_perf_hint(hint, index: int, _default=None):
"""
Extracts a "performance hint" value -- specified as either a scalar or 2-tuple -- for
either the left or right Dataset in a merge.
Parameters
----------
hint : scalar or 2-tuple of scalars, optional
index : int
Indica... | 5,327,603 |
def synchronized_limit(lock):
"""
Synchronization decorator; provide thread-safe locking on a function
http://code.activestate.com/recipes/465057/
"""
def wrap(f):
def synchronize(*args, **kw):
if lock[1] < 10:
lock[1] += 1
lock[0].acquire()
... | 5,327,604 |
def fast_warp(img, tf, output_shape=(50, 50), mode='constant', order=1):
"""
This wrapper function is faster than skimage.transform.warp
"""
m = tf._matrix
res = np.zeros(shape=(output_shape[0], output_shape[1], 3), dtype=floatX)
from scipy.ndimage import affine_transform
trans, offset = m[:... | 5,327,605 |
def _get_detections(generator, model, score_threshold=0.05, max_detections=400, save_path=None):
""" Get the detections from the model using the generator.
The result is a list of lists such that the size is:
all_detections[num_images][num_classes] = detections[num_detections, 4 + num_classes]
# A... | 5,327,606 |
def LikeArticle(browser):
"""
Like the article that has already been navigated to.
browser: selenium driver used to interact with the page.
"""
likeButtonXPath = '//div[@data-source="post_actions_footer"]/button'
numLikes = 0
try:
numLikesElement = browser.find_element_by_xpath(lik... | 5,327,607 |
def BF (mu, s2, noise_var=None, pps=None):
"""
Buzzi-Ferraris et al.'s design criterion.
- Buzzi-Ferraris and Forzatti (1983)
Sequential experimental design for model discrimination
in the case of multiple responses.
Chem. Eng. Sci. 39(1):81-85
- Buzzi-Ferraris et al. (1984)
Sequential experimental design... | 5,327,608 |
def do_cg_delete(cs, args):
"""Remove one or more consistency groups."""
failure_count = 0
kwargs = {}
if args.force is not None:
kwargs['force'] = args.force
for consistency_group in args.consistency_group:
try:
cg_ref = _find_consistency_group(cs, consistency_group)
... | 5,327,609 |
def deploy(usr, pwd, path=getcwd(), venv=None):
"""release on `pypi.org`"""
log(INFO, ICONS["deploy"] + 'deploy release on `pypi.org`')
# check dist
module('twine', 'check --strict dist/*', path=path, venv=venv)
# push to pypi.org
return module("twine", "upload -u %s -p %s dist/*" % (usr, pwd),
... | 5,327,610 |
def process_files(userglob):
"""Accepts a string that is used as a file glob. Each file is opened
and processed through extract_data(). Implemented as a generator
and each output is a tuple with the frame number prepending the output
from extract_data().
"""
# get the specified file list
... | 5,327,611 |
def most_interval_scheduling(interval_list):
"""
最多区间调度:优先选择'end'值小的区间
Args:
interval_list(list): 区间列表
Returns:
scheduling_list(list): 去重实体列表
"""
scheduling_list = list()
sorted_interval_list = sorted(interval_list,
key=lambda x: x['end'])
... | 5,327,612 |
def kernel_program(inputfile, dimData, Materials, dict_nset_data, \
dict_elset_matID={}, dict_elset_dload={}):
"""The kernel_program should be called by the job script (e.g., Job-1.py)
where the user defines:
- inputfile: the name of the input file
- dimData: the dimensional data (s... | 5,327,613 |
def filter_fasta(infa, outfa, regex=".*", v=False, force=False):
"""Filter fasta file based on regex.
Parameters
----------
infa : str
Filename of input fasta file.
outfa : str
Filename of output fasta file. Cannot be the same as infa.
regex : str, optional
Regular... | 5,327,614 |
def test_list_byte_enumeration_1_nistxml_sv_iv_list_byte_enumeration_2_3(mode, save_output, output_format):
"""
Type list/byte is restricted by facet enumeration.
"""
assert_bindings(
schema="nistData/list/byte/Schema+Instance/NISTSchema-SV-IV-list-byte-enumeration-2.xsd",
instance="nist... | 5,327,615 |
def rmse_metric(predicted: Collection,
actual: Collection) -> float:
"""
Root-mean-square error metric.
Args:
predicted (list): prediction values.
actual (list): reference values.
Returns:
root-mean-square-error metric.
"""
return np.sqrt(np.mean(np.subt... | 5,327,616 |
def set_user_data(session_id, user_data):
"""
this function temporarily stores data transmitted by user, when POSTed
by the user device; the data is then picked up by the page ajax
polling mechanism
"""
return session_id if red.set(K_USER_DATA.format(session_id), json.dumps(user_data), ex... | 5,327,617 |
def find_keys(info: dict) -> dict:
"""Determines all the keys and their parent keys.
"""
avail_keys = {}
def if_dict(dct: dict, prev_key: str):
for key in dct.keys():
if key not in avail_keys:
avail_keys[key] = prev_key
if type(dct[key]) == d... | 5,327,618 |
def valid(exc, cur1, cur2=None, exclude=None, exclude_cur=None):
"""
Find if the given exc satisfies currency 1
(currency 2) (and is not exclude) (and currency is not exclude)
"""
if exclude is not None and exc == exclude:
return False
curs = [exc.to_currency, exc.from_currency]
if e... | 5,327,619 |
def custom(value):
"""Parse custom parameters
value: string containing custom parameters"""
files = []
if os.path.isfile(value):
files.append(value)
else:
files += value.split(",")
for filename in files:
customs = {}
if os.path.isfile(filename):
ex... | 5,327,620 |
def arc(
x: float, y: float, radius: float, start: float, stop: float, quantization: float = 0.1,
) -> np.ndarray:
"""Build a circular arc path. Zero angles refer to east of unit circle and positive values
extend counter-clockwise.
Args:
x: center X coordinate
y: center Y coordinate
... | 5,327,621 |
def prepare_watermark(path_mark, inver_style):
"""
reads the image in greyscale, create an alpha mask according to the scale
invert_style determines whether the key info letters/shapes are darker or lighter than the rest
""" | 5,327,622 |
def build_feature_columns(schema):
"""Build feature columns as input to the model."""
# non-numeric columns
exclude = ['customer_id', 'brand', 'promo_sensitive', 'weight', 'label']
# numeric feature columns
numeric_column_names = [col for col in schema.names if col not in exclude]
numeric_colu... | 5,327,623 |
def registerSampleData():
"""
Add data sets to Sample Data module.
"""
# It is always recommended to provide sample data for users to make it easy to try the module,
# but if no sample data is available then this method (and associated startupCompeted signal connection) can be removed.
import SampleData
... | 5,327,624 |
def get_mol_func(smiles_type):
"""
Returns a function pointer that converts a given SMILES type to a mol object.
:param smiles_type: The SMILES type to convert VALUES=(deepsmiles.*, smiles, scaffold).
:return : A function pointer.
"""
if smiles_type.startswith("deepsmiles"):
_, deepsmil... | 5,327,625 |
def index():
"""Return to the homepage."""
return render_template("index.html") | 5,327,626 |
def species_thermo_value(spc_dct):
""" species enthalpy at 298
"""
return spc_dct['H298'] | 5,327,627 |
def save_solution_1d(iMax, dX, U, OutFile):
"""Save the 1d solution to a specified file."""
print(f"IMAX= {iMax}", file=OutFile)
print(f"Grid Step= {dX:>6.4f}", file=OutFile)
print(f'{"X":^14} {"U":^14}', file=OutFile)
for i in range(0, iMax):
print(f"{dX*i:>12.8e} {U[i]:>12.8e}", file... | 5,327,628 |
def invest_validator(validate_func):
"""Decorator to enforce characteristics of validation inputs and outputs.
Attributes of inputs and outputs that are enforced are:
* ``args`` parameter to ``validate`` must be a ``dict``
* ``limit_to`` parameter to ``validate`` must be either ``None`` or a
... | 5,327,629 |
async def async_setup(hass: HomeAssistant, config: dict):
"""Set up the Flood integration."""
hass.data.setdefault(DOMAIN, {})
return True | 5,327,630 |
def typehint(x, typedict):
"""Replace the dtypes in `x` keyed by `typedict` with the dtypes in
`typedict`.
"""
dtype = x.dtype
lhs = dict(zip(dtype.fields.keys(), map(first, dtype.fields.values())))
dtype_list = list(merge(lhs, typedict).items())
return x.astype(np.dtype(sort_dtype_items(dty... | 5,327,631 |
def balance(samples, labels, balance_factor, adjust_func):
"""create a balanced dataset by subsampling classes or generating new
samples"""
grouped = group_by_label(samples, labels)
if balance_factor <= 1.0:
largest_group_size = max([len(x[1]) for x in grouped])
target_group_size = int... | 5,327,632 |
def make_util_private_h(cfile):
""" Create util_private.h """
import urllib, posixpath
hfile = posixpath.join(posixpath.dirname(cfile), 'util_private.h')
fp = file(hfile, 'w')
try:
print >> fp, """/*
* XXX This file is autogenerated by setup.py, don't edit XXX
*/
#ifndef WTF_UTIL_PRIVATE_H... | 5,327,633 |
def generate_sha1(string, salt=None):
"""
Generates a sha1 hash for supplied string. Doesn't need to be very secure
because it's not used for password checking. We got Django for that.
:param string:
The string that needs to be encrypted.
:param salt:
Optionally define your own sal... | 5,327,634 |
def sentences_from_doc(ttree_doc, language, selector):
"""Given a Treex document, return a list of sentences in the given language and selector."""
return [bundle.get_zone(language, selector).sentence for bundle in ttree_doc.bundles] | 5,327,635 |
def managed_session(
factory: sessionmaker, **kwargs,
) -> t.ContextManager[Session]:
"""Wraps a session in a context manager to manage session lifetime.
Makes sure to commit if the code in the context runs successfully,
otherwise it rolls back. Also ensures that the session is closed.
Parameters
... | 5,327,636 |
def train_test_split(data_dir):
"""Function thats splits a folder with brat files into train/test based on csv file"""
csv_split = 'train-test-split.csv'
with open(data_dir+csv_split, newline='') as f:
reader = csv.reader(f, delimiter=';')
for row in reader:
if row[1] == 'TRAI... | 5,327,637 |
def demo_func(par):
"""Test function to optimize."""
x = par['x']
y = par['y']
z = par['z']
p = par['p']
s = par['str']
funcs = {
'sin': math.sin,
'cos': math.cos,
}
return (x + (-y) * z) / ((funcs[s](p) ** 2) + 1) | 5,327,638 |
def file_to_list(filename):
"""
Read in a one-column txt file to a list
:param filename:
:return: A list where each line is an element
"""
with open(filename, 'r') as fin:
alist = [line.strip() for line in fin]
return alist | 5,327,639 |
def regular_ticket_price(distance_in_km: int) -> float:
""" calculate the regular ticket price based on the given distance
:int distance_in_km:
"""
# source --> Tarife 601 Chapter 10.1.3 on https://www.allianceswisspass.ch/de/Themen/TarifeVorschriften
price_ticket_per_km = {range(1, 5): 44.51,
... | 5,327,640 |
def find_cal_indices(datetimes):
"""
Cal events are any time a standard is injected and being quantified by the system. Here, they're separated as though
any calibration data that's more than 60s away from the previous cal data is a new event.
:param epoch_time: array of epoch times for all of the supp... | 5,327,641 |
def rename(isamAppliance, id, new_name, check_mode=False, force=False):
"""
Rename a Password Strength
"""
if force is True or _check(isamAppliance, id) is True:
if check_mode is True:
return isamAppliance.create_return_object(changed=True)
else:
return isamApplia... | 5,327,642 |
def reinvoke_on_edit(ctx, *additional_messages: discord.Message, timeout: float = 600) -> None:
# noinspection PyUnresolvedReferences
"""
Watches a given context for a given period of time. If the message that
invoked the context is edited within the time period, then the invoking message
plus any a... | 5,327,643 |
def compile_test_programs():
"""Invokes CMake and make to create the test binaries.
Calls a debug build as I don't want optimizations to get in the way."""
subprocess.call(["cmake", "-DCMAKE_BUILD_TYPE=Debug", ts.TEST_PROGRAMS_FOLDER], cwd=ts.TEST_PROGRAMS_FOLDER)
subprocess.call(["make"], cwd=ts... | 5,327,644 |
def gen_model_forms(form, model):
"""Creates a dict of forms. model_forms[0] is a blank form used for adding
new model objects. model_forms[m.pk] is an editing form pre-populated
the fields of m"""
model_forms = {0: form()}
for m in model.objects.all():
model_forms[m.pk] = form(instanc... | 5,327,645 |
def _state_size_with_prefix(state_size, prefix=None):
"""Helper function that enables int or TensorShape shape specification.
This function takes a size specification, which can be an integer or a
TensorShape, and converts it into a list of integers. One may specify any
additional dimensions that precede the f... | 5,327,646 |
def as_pandas(cursor, coerce_float=False):
"""Return a pandas `DataFrame` out of an impyla cursor.
This will pull the entire result set into memory. For richer pandas-like
functionality on distributed data sets, see the Ibis project.
Parameters
----------
cursor : `HiveServer2Cursor`
... | 5,327,647 |
def test_values():
""" Test LDAPEntry's values method. """
entry = LDAPEntry("cn=test")
entry["cn"] = "test"
entry["sn"] = "Test"
assert len(entry.values()) == 3
assert entry.dn in entry.values()
assert entry["cn"] in entry.values()
assert entry["sn"] in entry.values()
assert len(lis... | 5,327,648 |
def check_ip(ip, network_range):
"""
Test if the IP is in range
Range is expected to be in CIDR notation format. If no MASK is
given /32 is used. It return True if the IP is in the range.
"""
netItem = str(network_range).split('/')
rangeIP = netItem[0]
if len(netItem) == 2:
ran... | 5,327,649 |
async def index(_request: HttpRequest) -> HttpResponse:
"""A request handler which provides an index of the compression methods"""
html = """
<!DOCTYPE html>
<html>
<body>
<ul>
<li><a href='/gzip'>gzip</a></li>
<li><a href='/deflate'>deflate</a></li>
<li><a href='/compress'>compress</a><... | 5,327,650 |
def ifft_function(G,Fs,axis=0):
"""
This function gives the IDFT
Arguments
---------------------------
G : double
DFT (complex Fourier coefficients)
Fs : double
sample rate, maximum frequency of G times 2 (=F_nyquist*2)
axis : double
the axis on which the IDFT... | 5,327,651 |
def test_atomic_duration_min_inclusive_nistxml_sv_iv_atomic_duration_min_inclusive_1_2(mode, save_output, output_format):
"""
Type atomic/duration is restricted by facet minInclusive with value
P1970Y01M01DT00H00M00S.
"""
assert_bindings(
schema="nistData/atomic/duration/Schema+Instance/NIST... | 5,327,652 |
def configure(**config):
"""Configure the module using a set of configuration options.
:param **config: Dict of configuration options.
"""
global _ROOTWRAPPER
# Don't break existing deploys...
rw_conf_file = config.get('rootwrap_config', '/etc/nova/rootwrap.conf')
if config.get('use_rootwra... | 5,327,653 |
def user_tweets_stats_grouped_new(_, group_type):
"""
Args:
_: Http Request (ignored in this function)
group_type: Keyword defining group label (day,month,year)
Returns: Activities grouped by (day or month or year) wrapped on response's object
"""
error_messages = []
success_messages = []
status = HTTP_2... | 5,327,654 |
def test_setext_headings_extra_23():
"""
Test case extra 23: SetExt heading ends with 2+ spaces as in a hard line break, but not since end of paragraph
"""
# Arrange
source_markdown = """what? no line break?\a\a\a
---""".replace(
"\a", " "
)
expected_tokens = [
"[setext(2,1... | 5,327,655 |
def analyse_editing_percent(pileup_file, out_file, summary_file=None, add_headers=False, summary_only=False, min_editing=0,
max_noise=100, min_reads=1, edit_tag='' ):
"""
analyses pileup file editing sites and summarises it
@param pileup_file: input pileup file name
@param ou... | 5,327,656 |
def login_required(func, *args, **kwargs):
"""
This is a decorator that can be applied to a Controller method that needs a logged in user.
The inner method receives the Controller instance and checks if the user is logged in
using the `request.is_authenticated` Boolean on the Controller instance
:p... | 5,327,657 |
def preProcessImage(rgbImage):
""" Preprocess the input RGB image
@rgbImage: Input RGB Image
"""
# Color space conversion
img_gray = cv2.cvtColor(rgbImage, cv2.COLOR_BGR2GRAY)
img_hsv = cv2. cvtColor(rgbImage, cv2.COLOR_BGR2HLS)
ysize, xsize = getShape(img_gray)
#Detecting yellow and w... | 5,327,658 |
def distribute():
"""Run all cpu experiments on a single process. Distribute gpu experiments over all available gpus.
Args:
device_count (int, optional): If device count is 0, uses only cpu else spawn processes according
to number of gpus available on the machine. Defaults to 0.
"""
swe... | 5,327,659 |
def consume_messages(consumer: Consumer, num_expected: int, serialize: bool = True) -> List[Dict[str, Any]]:
"""helper function for polling 'everything' off a topic"""
start = time.time()
consumed_messages = []
while (time.time() - start) < POLL_TIMEOUT:
message = consumer.poll(1)
if mes... | 5,327,660 |
def get_compressed_size(data, compression, block_size=DEFAULT_BLOCK_SIZE):
"""
Returns the number of bytes required when the given data is
compressed.
Parameters
----------
data : buffer
compression : str
The type of compression to use.
block_size : int, optional
Input... | 5,327,661 |
def flat_command(bias=False,
flat_map=False,
return_shortname=False,
dm_num=1):
"""
Creates a DmCommand object for a flat command.
:param bias: Boolean flag for whether to apply a bias.
:param flat_map: Boolean flag for whether to apply a flat_map.
... | 5,327,662 |
def plot_graph_routes(
G,
routes,
bbox=None,
fig_height=6,
fig_width=None,
margin=0.02,
bgcolor="w",
axis_off=True,
show=True,
save=False,
close=True,
file_format="png",
filename="temp",
dpi=300,
annotate=False,
node_color="#999999",
node_size=15,
... | 5,327,663 |
def _parse_book_info(html):
"""解析豆瓣图书信息(作者,出版社,出版年,定价)
:param html(string): 图书信息部分的原始html
"""
end_flag = 'END_FLAG'
html = html.replace('<br>', end_flag)
html = html.replace('<br/>', end_flag)
doc = lxml.html.fromstring(html)
text = doc.text_content()
pattern = r'{}[::](.*?){}'
... | 5,327,664 |
def offers(request, region_slug, language_code=None):
"""
Function to iterate through all offers related to a region and adds them to a JSON.
Returns:
[String]: [description]
"""
region = Region.objects.get(slug=region_slug)
result = []
for offer in region.offers.all():
resu... | 5,327,665 |
def scan_to_scan(vol_names, bidir=False, batch_size=1, prob_same=0, no_warp=False, **kwargs):
"""
Generator for scan-to-scan registration.
Parameters:
vol_names: List of volume files to load, or list of preloaded volumes.
bidir: Yield input image as output for bidirectional models. Default ... | 5,327,666 |
def provision_new_database_for_variant_warehouse(db_name):
"""Create a variant warehouse database of the specified name and shared the collections"""
# Passing the secrets_file override the password already in the uri
db_handle = MongoDatabase(
uri=cfg['mongodb']['mongo_admin_uri'],
secrets_... | 5,327,667 |
def get_ellipse(mu: np.ndarray, cov: np.ndarray, draw_legend: bool = True):
"""
Draw an ellipse centered at given location and according to specified covariance matrix
Parameters
----------
mu : ndarray of shape (2,)
Center of ellipse
cov: ndarray of shape (2,2)
Covariance of G... | 5,327,668 |
def load_hashes(
filename: str, hash_algorithm_names: Sequence[str]
) -> HashResult:
"""
Load the size and hash hex digests for the given file.
"""
# See https://github.com/python/typeshed/issues/2928
hashes: List['hashlib._hashlib._HASH'] = [] # type: ignore
for name in hash_algorithm... | 5,327,669 |
def ucs(st: Pixel, end: Pixel, data: np.ndarray):
"""
Iterative method to find a Dijkstra path, if one exists from current to end vertex
:param startKey: start pixel point key
:param endKey: end pixel point key
:return: path
"""
q = PriorityQueue()
startPri... | 5,327,670 |
def tvdb_refresh_token(token: str) -> str:
"""
Refreshes JWT token.
Online docs: api.thetvdb.com/swagger#!/Authentication/get_refresh_token.
"""
url = "https://api.thetvdb.com/refresh_token"
headers = {"Authorization": f"Bearer {token}"}
status, content = request_json(url, headers=headers, ... | 5,327,671 |
def cli():
"""
A utility for creating, updating, listing and deleting AWS CloudFormation stacks.
"""
logger.debug('cli() called') | 5,327,672 |
def seek_and_destroy():
"""
You will be provided with an initial array (the first argument in the destroyer function),
followed by one or more arguments. Remove all elements from the initial array that are of the
same value as these arguments.
"""
return | 5,327,673 |
def get_data():
""" _ _ _ """
df_hospital = download_hospital_admissions()
#sliding_r_df = walkingR(df_hospital, "Hospital_admission")
df_lcps = download_lcps()
df_mob_r = download_mob_r()
df_gemeente_per_dag = download_gemeente_per_dag()
df_reprogetal = download_reproductiegetal()
df_... | 5,327,674 |
def load_bin_file(bin_file, dtype="float32"):
"""Load data from bin file"""
data = np.fromfile(bin_file, dtype=dtype)
return data | 5,327,675 |
def add_user(id: int):
"""
Add user
---
description: Add new user
summary: New user
tags:
- user
responses:
'200':
description: Created successfull
'403':
description: Data not corrent
parameters:
... | 5,327,676 |
def nearest_value(array, value):
"""
Searches array for the closest value to a given target.
Arguments:
array {NumPy Array} -- A NumPy array of numbers.
value {float/int} -- The target value.
Returns:
float/int -- The closest value to the target value found in the array.
""... | 5,327,677 |
def task(pid):
"""Synchronous non-deterministic task.
"""
sleep(0.2) # random.randint(0, 2) *
print('Task %s done' % pid) | 5,327,678 |
def write_manifest(data, manifest_name):
"""
Write the game metadata to a YAML manifest file
"""
path = data.get('path')
if not path:
raise GamePathError('No path found in game data.\nData=' +\
'\n'.join(['%s:\t%s' % (k, v) for k, v in data.iteritems()]))
path... | 5,327,679 |
def interpret_go_point(s, size):
"""Convert a raw SGF Go Point, Move, or Stone value to coordinates.
s -- 8-bit string
size -- board size (int)
Returns a pair (row, col), or None for a pass.
Raises ValueError if the string is malformed or the coordinates are out of
range.
Only support... | 5,327,680 |
def get_domain_name_for(host_string):
"""
Replaces namespace:serviceName syntax with serviceName.namespace one,
appending default as namespace if None exists
"""
return ".".join(
reversed(
("%s%s" % (("" if ":" in host_string else "default:"), host_string)).split(
... | 5,327,681 |
def bbox_classify(bboxes, possible_k):
"""bbox: x, y, w, h
return: best kmeans score anchor classes [(w1, h1), (w2, h2), ...]
"""
anchors = [bbox[2:4] for bbox in bboxes]
return anchors_classify(anchors, possible_k) | 5,327,682 |
def cleanFAAText(origText):
"""Take FAA text message and trim whitespace from end.
FAA text messages have all sorts of trailing whitespace
issues. We split the message into lines and remove all
right trailing whitespace. We then recombine them into
a uniform version with no trailing whitespace.
... | 5,327,683 |
def LoadModel(gd_file, ckpt_file):
"""Load the model from GraphDef and Checkpoint.
Args: gd_file: GraphDef proto text file. ckpt_file: TensorFlow Checkpoint file.
Returns: TensorFlow session and tensors dict."""
with tf.Graph().as_default():
#class FastGFile: File I/O wrappers without thread loc... | 5,327,684 |
def get_additional_rent(offer_markup):
""" Searches for additional rental costs
:param offer_markup:
:type offer_markup: str
:return: Additional rent
:rtype: int
"""
html_parser = BeautifulSoup(offer_markup, "html.parser")
table = html_parser.find_all(class_="item")
for element in t... | 5,327,685 |
def make_known_disease_variants_filter(sample_ids_list=None):
""" Function for retrieving known disease variants by presence in Clinvar and Cosmic."""
result = {
"$or":
[
{
"$and":
[
... | 5,327,686 |
def main():
"""
in_file = '/Users/pereza1/Projects/Jo/data/gecko_proper_excel/mouse_library_A_gecko.xlsx'
header = True
sequence_field = 0
"""
# user inputs
in_file,outdir,kmer_counts_file,trie_file,mismatch_score,pam_score,header,sequence_field,cpf1 = arg_parser()
# data read in
data = sequence_file_read_... | 5,327,687 |
def sharedArray(dtype, dims):
"""Create a shared numpy array."""
mpArray = multiprocessing.Array(dtype, int(np.prod(dims)), lock=False)
return np.frombuffer(mpArray, dtype=dtype).reshape(dims) | 5,327,688 |
def _read_hyperparameters(idx, hist):
"""Read hyperparameters as a dictionary from the specified history dataset."""
return hist.iloc[idx, 2:].to_dict() | 5,327,689 |
def test_register_short_password(client, post_data, cleanup_dummy_user):
"""Register a user with too short a password"""
with fml_testing.mock_sends(
UserCreateV1({"msg": {"agent": "dummy", "user": "dummy"}})
):
post_data["register-password"] = post_data["register-password_confirm"] = "42"
... | 5,327,690 |
def row_annotation(name=None, fn_require=None):
"""
Function decorator for methods in a subclass of BaseMTSchema.
Allows the function to be treated like an row_annotation with annotation name and value.
@row_annotation()
def a(self):
return 'a_val'
@row_annotation(name=... | 5,327,691 |
def _alert(sound=None, player=None):
"""Play an alert sound for the OS."""
if sound is None and Options.sound is not None:
sound = Options.sound
if player is None and Options.player is not None:
player = Options.player
if player is not None and sound is not None:
try:
... | 5,327,692 |
def test_parse_correctness(
format: str,
quoted: str,
unquoted: str,
) -> None:
"""
Quoted strings parse correctly
"""
if format in QUAD_FORMATS:
data = f'<example:Subject> <example:Predicate> "{quoted}" <example:Graph>.'
else:
data = f'<example:Subject> <example:Predicat... | 5,327,693 |
def create_user_table():
"""Creates user table"""
User.metadata.create_all(engine) | 5,327,694 |
async def test_turn_away_mode_on_cooling(hass, setup_comp_3):
"""Test the setting away mode when cooling."""
_setup_switch(hass, True)
_setup_sensor(hass, 25)
await hass.async_block_till_done()
await common.async_set_temperature(hass, 19)
await common.async_set_preset_mode(hass, PRESET_AWAY)
... | 5,327,695 |
def path_exists_case_insensitive(path, root="/"):
"""
Checks if a `path` exists in given `root` directory, similar to
`os.path.exists` but case-insensitive. If there are multiple
case-insensitive matches, the first one is returned. If there is no match,
an empty string is returned.
:param str p... | 5,327,696 |
def parse_time(date_time, time_zone):
"""Returns the seconds between now and the scheduled time."""
now = pendulum.now(time_zone)
update = pendulum.parse(date_time, tz=time_zone)
# If a time zone is not specified, it will be set to local.
# When passing only time information the date will default t... | 5,327,697 |
def ls(request):
"""
List a directory on the server.
"""
dir = request.GET.get("dir", "")
root = os.path.relpath(os.path.join(
settings.MEDIA_ROOT,
settings.USER_FILES_PATH
))
fulldir = os.path.join(root, dir)
response = HttpResponse(mimetype="application/json")
simp... | 5,327,698 |
def test_ping():
"""
Builds the topology described on the following schema and ping h2 from h1.
::
+------+ +------+
| | +------+ +------+ | |
| h1 <-----> s1 <-----> s2 <-----> h2 |
| | +------+ +------+ ... | 5,327,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.