content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import torch
def _demo_mm_inputs(input_shape, num_classes):
"""Create a superset of inputs needed to run test or train batches.
Args:
input_shape (tuple):
input batch dimensions
num_classes (int):
number of semantic classes
"""
(N, C, H, W) = input_shape
rn... | 9d8de5d5bd337720f386a45ad40f9e901a999b52 | 21,100 |
import socket
def get_ephemeral_port(sock_family=socket.AF_INET, sock_type=socket.SOCK_STREAM):
"""Return an ostensibly available ephemeral port number."""
# We expect that the operating system is polite enough to not hand out the
# same ephemeral port before we can explicitly bind it a second time.
s... | 37287b70e35b8aa7fbdb01ced1882fb3bbf38543 | 21,101 |
from typing import Optional
def IR_guess_model(spectrum: ConvSpectrum, peak_args: Optional[dict] = None) -> tuple[Model, dict]:
"""
Guess a fit for the IR spectrum based on its peaks.
:param spectrum: the ConvSpectrum to be fit
:param peak_args: arguments for finding peaks
:return: Model, paramet... | fa56e3c183ef08b35f177df1d727ff134c964eaf | 21,102 |
def virus_monte_carlo(initial_infected, population, k):
""" Generates a list of points to which some is infected
at a given value k starting with initial_infected infected.
There is no mechanism to stop the infection from reaching
the entire population.
:param initial_infected: The amount of people... | 856af13a8a7fdbb931ba32b97ff7bd5207e9ca49 | 21,103 |
def threadsafe_generator(f):
"""
A decorator that takes a generator function and makes it thread-safe.
"""
def g(*a, **kw):
return threadsafe_iter(f(*a, **kw))
return g | 013e0df91f70da8c8f4f501bc31d8bddcf378787 | 21,104 |
def lastmsg(self):
"""
Return last logged message if **_lastmsg** attribute is available.
Returns:
last massage or empty str
"""
return getattr(self, '_last_message', '') | ad080c05caadbb644914344145460db0164f017c | 21,105 |
def _callback_on_all_dict_keys(dt, callback_fn):
"""
Callback callback_fn on all dictionary keys recursively
"""
result = {}
for (key, val) in dt.items():
if type(val) == dict:
val = _callback_on_all_dict_keys(val, callback_fn)
result[callback_fn(key)] = val
return re... | 3cab018413a7ba8a0e5bbae8574025253a2ea885 | 21,106 |
import sys
def ovb_partial_r2_bound(model=None, treatment=None, r2dxj_x=None, r2yxj_dx=None,
benchmark_covariates=None, kd=1, ky=None):
"""
Provide a Pandas DataFrame with the bounds on the strength of the unobserved confounder.
Adjusted estimates, standard errors and t-values (a... | a94aed31bd53caf0457b3aedf339572d2a56a8a1 | 21,107 |
def top_ngrams(df, n=2, ngrams=10):
"""
* Not generalizable in this form *
* This works well, but is very inefficient and should be optimized or rewritten *
Takes a preposcessed, tokenized column and create a large list.
Returns most frequent ngrams
Arguments:
df = name of DataFrame wit... | a6c540a30a288a8d26bf6f966b44b9f080db0026 | 21,108 |
def install_openvpn(instance, arg, verbose=True):
""" """
install(instance, {"module":"openvpn"}, verbose=True)
generate_dh_key(instance, {"dh_name":"openvpn", "key_size":"2048"})
server_conf = open("simulation/workstations/"+instance.name+"/server_openvpn.conf", "w")
server_conf.write("port 1... | d95d99e7847dd08c43f54fc3dde769f69888da77 | 21,109 |
def rossoporn_parse(driver: webdriver.Firefox) -> tuple[list[str], int, str]:
"""Read the html for rossoporn.com"""
#Parses the html of the site
soup = soupify(driver)
dir_name = soup.find("div", class_="content_right").find("h1").text
dir_name = clean_dir_name(dir_name)
images = soup.find_all("... | 21aad0798bc3e13badb1076ec40c36c56f47ebf7 | 21,110 |
def pid_from_context(_, context, **kwargs):
"""Get PID from marshmallow context."""
pid = (context or {}).get('pid')
return pid.pid_value if pid else missing | 350fd4c915e186dd41575c5842e47beb7d055fb5 | 21,111 |
def score_text(text, tokenizer, preset_model, finetuned_model):
""" Uses rule-based rankings. Higher is better, but different features have different scales.
Args:
text (str/ List[str]): one story to rank.
tokenizer (Pytroch tokenizer): GPT2 Byte Tokenizer.
preset_model (Pytorch model)... | e304975b55c44e78f6ce92f4df9d1ba563389b8b | 21,112 |
import sys
import subprocess
def get_bot_list(swarming_server, dimensions, dead_only):
"""Returns a list of swarming bots."""
cmd = [
sys.executable, 'swarming.py', 'bots',
'--swarming', swarming_server,
'--bare',
]
for k, v in sorted(dimensions.iteritems()):
cmd.extend(('--dimension', k, v))
... | b34d8499ba94a0cf924b8dd446df6b797b39c35c | 21,113 |
import os
def running_on_kaggle() -> bool:
"""Detect if the current environment is running on Kaggle.
Returns:
bool:
True if the current environment is on Kaggle, False
otherwise.
"""
return os.environ.get("KAGGLE_KERNEL_RUN_TYPE") == "Interactive" | ac1432666ccc8ca8e9d1d73938c5a1212f4fc429 | 21,114 |
import subprocess
def _get_picture_from_attachments(path):
"""Get picture bytes from telegram server"""
url = 'https://api.telegram.org/file/bot' + API_TOKEN + '/' + path
pic_path = './photos/pic.jpg'
curl_command = f'curl {url} > {pic_path}'
data = subprocess.run(curl_command, shell=True)
... | d3ed1a38d8646cc506b70b4bcc4f8c597b99f5f4 | 21,115 |
def parse_cards(account_page_content):
"""
Parse card metadata and product balances from /ClipperCard/dashboard.jsf
"""
begin = account_page_content.index(b'<!--YOUR CLIPPER CARDS-->')
end = account_page_content.index(b'<!--END YOUR CLIPPER CARDS-->')
card_soup = bs4.BeautifulSoup(account_page_c... | 6ec10941aebe88af27a75c407e6805698d5cf31c | 21,116 |
def interaction_time_data_string(logs, title):
"""
times = utils.valid_values_for_enum((models.LogEntry.TIME_CHOICES))
contexts_map = dict(models.LogEntry.TIME_CHOICES)
counts = {contexts_map[k]: v
for k, v in _counts_by_getter(logs, lambda l: l.time_of_day).items()
}
pl... | fc6f6a32d39f3bd87c3b7b816e333aef462fb0f3 | 21,117 |
import math
def _label_boost(boost_form, label):
"""Returns the label boost.
Args:
boost_form: Either NDCG or PRECISION.
label: The example label.
Returns:
A list of per list weight.
"""
boost = {
'NDCG': math.pow(2.0, label) - 1.0,
'PRECISION': 1.0 if label >= 1.0 else 0.0,
}
... | 811e87949b0bbe7dc98f63814b343ffd90fe129a | 21,118 |
def has_matching_ts_templates(reactant, bond_rearr):
"""
See if there are any templates suitable to get a TS guess from a template
Arguments:
reactant (autode.complex.ReactantComplex):
bond_rearr (autode.bond_rearrangement.BondRearrangement):
Returns:
bool:
"""
mol_gra... | 10061734d2831668099f3e85d99366dda9f51157 | 21,119 |
def get_commands(xml: objectify.ObjectifiedElement):
"""
Returns an action and the room from the xml string.
:param xml:
:return:
"""
return xml.body.attrib["action"] | 3724e00c626814e792911ae094a5b200d8593f4c | 21,120 |
def compression_point(w_db, slope = 1, compression = 1,
extrapolation_point = None, axis = -1):
"""Return input referred compression point"""
interpol_line = calc_extrapolation_line(w_db, slope, extrapolation_point,
axis)
return cross(interp... | 4c8793c5796d1359aa1fc00f226ecafda98c3f61 | 21,121 |
from typing import List
import logging
def pattern_remove_incomplete_region_or_spatial_path(
perception_graph: PerceptionGraphPattern
) -> PerceptionGraphPattern:
"""
Helper function to return a `PerceptionGraphPattern` verifying
that region and spatial path perceptions contain a reference object.
... | cbcc79602bf87e1ea88f8a0027d6cd19b74fb81c | 21,122 |
def other_shifted_bottleneck_distance(A, B, fudge=default_fudge, analysis=False):
"""Compute the shifted bottleneck distance between two diagrams, A and B (multisets)"""
A = pu.SaneCounter(A)
B = pu.SaneCounter(B)
if not A and not B:
return 0
radius = fudge(upper_bound_on_radius(A, B))
e... | 51455945743bfc5f262711e826d1097122309f83 | 21,123 |
def getCountdown(c):
"""
Parse into a Friendly Readable format for Humans
"""
days = c.days
c = c.total_seconds()
hours = round(c//3600)
minutes = round(c // 60 - hours * 60)
seconds = round(c - hours * 3600 - minutes * 60)
return days, hours, minutes, seconds | f49225ae2680192340720c8958aa19b9e9369f5f | 21,124 |
def fromPSK(valstr):
"""A special version of fromStr that assumes the user is trying to set a PSK.
In that case we also allow "none", "default" or "random" (to have python generate one), or simpleN
"""
if valstr == "random":
return genPSK256()
elif valstr == "none":
return bytes([0])... | 73fa661458601ec33d2b839aeea060f7a26b530f | 21,125 |
import os
def get_subpackages(name):
"""Return subpackages of package *name*"""
splist = []
for dirpath, _dirnames, _filenames in os.walk(name):
if osp.isfile(osp.join(dirpath, "__init__.py")):
splist.append(".".join(dirpath.split(os.sep)))
return splist | e18de0b0e76841f89b95bef30d2ba473422902ec | 21,126 |
def list_hierarchy(class_name, bases):
"""
Creates a list of the class hierarchy
Args:
-----
class_name: name of the current class
bases: list/tuple of bases for the current class
"""
class_list = [Uri(class_name)]
for base in bases:
if base.__name__ not in IGNORE_C... | 1b82dfe6576a472c04bb7cb53f8eed94a83a1ac1 | 21,127 |
def move_mouse_to_specific_location(x_coordinate, y_coordinate):
"""Moves the mouse to a specific point"""
LOGGER.debug("Moving mouse to (%d,%d)", x_coordinate, y_coordinate)
pyautogui.moveTo(x_coordinate, y_coordinate)
return Promise.resolve((x_coordinate, y_coordinate)) | eae5f50486bd1f2d127a2d94f87be586e697abcd | 21,128 |
def rss():
"""Return ps -o rss (resident) memory in kB."""
return float(mem("rss")) / 1024 | 92580a4873f2afca3f419a7f661e5cd39ec28b96 | 21,129 |
def compare_words(
word1_features,
word2_features,
count=10,
exclude=set(),
similarity_degree=0.5,
separate=False,
min_feature_value=0.3
):
"""
Сравнение двух слов на основе списка похожих (или вообще каких-либо фич слова).
Возвращает 3 списка: характерные для первог... | 4a04292e48911e6a4152cb03c19cda8de51802fb | 21,130 |
def dispatch_for_binary_elementwise_apis(x_type, y_type):
"""Decorator to override default implementation for binary elementwise APIs.
The decorated function (known as the "elementwise api handler") overrides
the default implementation for any binary elementwise API whenever the value
for the first two argumen... | 743d6f85b843f6200cf8b6c6361fc81154c37936 | 21,131 |
def grid(mat, i, j, k):
"""Returns true if the specified grid contains k"""
return lookup(k, [ mat[i + p][j + q] for p in range(3) for q in range(3) ]) | b2df3a905ada922011fc344f555a908aa03d5f64 | 21,132 |
def get_list_channels(sc):
"""Get list of channels."""
# https://api.slack.com/methods/channels.list
response = sc.api_call(
"channels.list",
)
return response['channels'] | d31271bcc065b4a212e298c6283c4d658e5547da | 21,133 |
def error_handler(error):
"""エラーメッセージを生成するハンドラ"""
response = jsonify({ 'cause': error.description['cause'] })
return response, error.code | 282b1a11d8e7326be1fa2d0b1b2457dc5d5d5ca1 | 21,134 |
def search_records(
name: str,
search: TextClassificationSearchRequest = None,
common_params: CommonTaskQueryParams = Depends(),
include_metrics: bool = Query(
False, description="If enabled, return related record metrics"
),
pagination: PaginationParams = Depends(),
service: TextCla... | 7dd932131f5fda1680fd419697df9c0a04d19fa5 | 21,135 |
def guess_udic(dic,data):
"""
Guess parameters of universal dictionary from dic, data pair.
Parameters
----------
dic : dict
Dictionary of JCAMP-DX, acqu, proc and spectrum parameters.
data : ndarray
Array of NMR data.
Returns
-------
udic : dict
Univers... | a8d79255b34f407ea54766ec2e4aedaf2ae42df9 | 21,136 |
def matchPosAny (msg, pos, rules, subrules):
"""Indicates whether or not `msg` matches any (i.e. a single) `subrule`
in `rules`, starting at position `pos`.
Returns the position in `msg` just after a successful match, or -1
if no match was found.
"""
index = -1
for rule in subrules:
... | 6ad053cdb61d7cc917e3acb896ea5d23cc042de9 | 21,137 |
def compute_accuracy(model, loader):
"""
:param model: a model which returns classifier_output and segmentator_output
:param loader: data loader
"""
model.eval() # enter evaluation mode
score_accum = 0
count = 0
for x, y, _, _ in loader:
classifier_output, _ = model(x)
... | ecc86c3c9c2429843bdd25023b3c6f0393c83db9 | 21,138 |
from operator import and_
def create_base_query_grouped_fifo(rse_id, filter_by_rse='destination', session=None):
"""
Build the sqlalchemy queries to filter relevant requests and to group them in datasets.
Group requests either by same destination RSE or source RSE.
:param rse_id: The RSE id... | e4399a447e767610c7451f61ad543553168de1d6 | 21,139 |
def then(state1, state2):
"""
Like ``bind``, but instead of a function that returns a statetful action,
just bind a new stateful action.
Equivalent to bind(state1, lambda _: state2)
"""
return bind(state1, lambda _: state2) | ef6200f8776b84a5a9893b894b3d7cd406598f7d | 21,140 |
from typing import Optional
from typing import Dict
from typing import Any
def get_skyregions_collection(run_id: Optional[int]=None) -> Dict[str, Any]:
"""
Produce Sky region geometry shapes JSON object for d3-celestial.
Args:
run_id (int, optional): Run ID to filter on if not None.
Returns:... | 8d8fe2e46a9d37e774dbdab506f012a0560796e1 | 21,141 |
def construct_sru_query(keyword, keyword_type=None, mat_type=None, cat_source=None):
"""
Creates readable SRU/CQL query, does not encode white spaces or parenthesis -
this is handled by the session obj.
"""
query_elems = []
if keyword is None:
raise TypeError("query argument cannot be N... | fbe28156beca73339fa88d200777e25172796864 | 21,142 |
def sitemap_xml():
"""Default Sitemap XML"""
show_years = retrieve_show_years(reverse_order=False)
sitemap = render_template("sitemaps/sitemap.xml",
show_years=show_years)
return Response(sitemap, mimetype="text/xml") | e6be9c98d1a1cd4bbfb04e9ad9676cc4b8521d79 | 21,143 |
def remove_property(product_id, property_id):
"""
Remove the property
"""
property = db.db.session.query(TypeProperty).\
filter_by(product_id = product_id, product_property_id = property_id).first()
try:
db.db.session.delete(property)
db.db.session.commit()
except Exception as e:
db.db.session.rollback()... | cca8822d5b7de3ca8ee9b451fe21d4ddeb20e736 | 21,144 |
def format_solution_table_calc(solution, node_ids_to_nodes):
"""
:type solution: dict[int, list[int]]
:type node_ids_to_nodes: dict[int, int]
:rtype: dict[int, str]
"""
new_solution = {}
for (color, path) in solution.items():
new_path = []
for p in path:
back_p = ... | 335bc0e90860a9181d5b819a5bb9e44cd44f750d | 21,145 |
import functools
def hashable(func):
"""Decorator for functions with numpy arrays as input arguments that will benefit from caching
Example:
from midgard.math import nputil
from functools import lru_cache
@nputil.hashable
@lru_cache()
def test_func(a: np.ndarray, b: np.ndarray = None)
... | db23cc12f9a322aaae6a585068a5c30194d7be7b | 21,146 |
import argparse
def parse_args():
"""
Parse input arguments. Helps with the command line argument input.
"""
parser = argparse.ArgumentParser(description='Faster R-CNN demo')
parser.add_argument('--gpu', dest='gpu_id', help='GPU device id to use [0]',
default=0, type=int)
... | b52492a92b59b22443b0c3f0ec388d0c9f184b8f | 21,147 |
def object_hash(fd, fmt, repo=None):
""" Function to read the content of a open file, create appropiate object
and write the object to vcs directory and return the hash of the file"""
data = fd.read()
# choosing constructor on the basis of the object type found in header
if fmt == b'commit' ... | b55a4da36934843c111e4d66dc552c556c8d0ba4 | 21,148 |
import io
def read_from_pdf(pdf_file):
"""
读取PDF文件内容,并做处理
:param pdf_file: PDF 文件
:return: pdf文件内容
"""
# 二进制读取pdf文件内的内容
with open(pdf_file, 'rb') as file:
resource_manage = PDFResourceManager()
return_str = io.StringIO()
lap_params = LAParams()
# 内容转换
... | 140d4545f952983017d175303397c494457b4628 | 21,149 |
def _descending(dbus_object):
"""
Verify levels of variant values always descend by one.
:param object dbus_object: a dbus object
:returns: None if there was a failure of the property, otherwise the level
:rtype: int or NoneType
None is a better choice than False, for 0, a valid variant level,... | 55de473807c22c50d8f65597cde390a56dcb9cd6 | 21,150 |
def _is_avconv():
"""
Returns `True` if the `ffmpeg` binary is really `avconv`.
"""
out = _run_command(['ffmpeg', '-version'])
return out and isinstance(out, strtype) and 'DEPRECATED' in out | dc9003623b4497b75d37f4e759f31401ad6261e1 | 21,151 |
def countries(request):
"""
Returns all valid countries and their country codes
"""
return JsonResponse({
"countries": [{
"id": unicode(code),
"name": unicode(name)
} for code, name in list(django_countries.countries)]
}) | 20296279dea898741950715a41b4188f7f5e6724 | 21,152 |
import os
def get_reads(file, reads=None):
"""
Get the read counts from the file
"""
if not reads:
reads={}
# get the sample name from the file
sample=os.path.basename(file).split(".")[0]
reads[sample]={}
with open(file) as file_handle:
for line in file_handle:
... | 6951e5d401743c6a10e13d0d5bd0e28497a7ea5a | 21,153 |
def generate_monomer(species, monomerdict, initlen, initnames, tbobs):
"""
generate a PySB monomer based on species
:param species: a Species object
:param monomerdict: a dictionary with all monomers linked to their species id
:param initlen: number of the initial species
:param initnames: name... | 2966473ef084991d0c589c16a8479f6395702b43 | 21,154 |
import logging
import tqdm
def convert_bert_tokens(outputs):
"""
Converts BERT tokens into a readable format for the parser, i.e. using Penn Treebank tokenization scheme.
Does the heavy lifting for this script.
"""
logging.info("Adjusting BERT indices to align with Penn Treebank.")
mapped_outp... | 27cef75fc48fb87e20f77af95e265406c6b8c520 | 21,155 |
from typing import Sequence
import pathlib
import logging
def load_proto_message(
config_path: AnyPath,
overrides: Sequence[str] = tuple(),
*,
msg_class=None,
extra_include_dirs: Sequence[pathlib.Path] = tuple(),
) -> ProtoMessage:
"""Loads message from the file and applies overrides.
If ... | 253874fc5a41a51d84c4745ce61c415b13404f75 | 21,156 |
def calculate_iou(ground_truth_path, prediction_path):
""" Calculate the intersection over union of two raster images.
Args:
ground_truth_path (str): Path to the ground truth raster image.
prediction_path (str): Path to the prediction raster image.
Returns:
float: The intersection ov... | 70e49e787fe57f5c4d94a043d41b96de1b14fd39 | 21,157 |
from bokeh.models import ColumnDataSource
import warnings
def bokeh_scatter(x,
y=None,
*,
xlabel='x',
ylabel='y',
title='',
figure=None,
data=None,
saveas='scatter',
... | d2bf64efcd751f3dea0d63c1c02af14952684bd7 | 21,158 |
from utils.format import format_output
from utils.rule import get_all_rules
from utils.type import check_type
from utils.rule import get_rules
from core.exceptions import RuleArgumentsError
from utils.type import update_type, check_type
from utils.rule import add_rule
from core.exceptions import RuleArgumentsError
from... | 991873d489486b5e6ffc9676a2d9a6e5af9e944b | 21,159 |
def superposition_training_mnist(model, X_train, y_train, X_test, y_test, num_of_epochs, num_of_tasks, context_matrices, nn_cnn, batch_size=32):
"""
Train model for 'num_of_tasks' tasks, each task is a different permutation of input images.
Check how accuracy for original images is changing through tasks us... | e0e837c3a92e047ce894c166d09e2ce6a58b3035 | 21,160 |
import json
def json2dict(astr: str) -> dict:
"""将json字符串转为dict类型的数据对象
Args:
astr: json字符串转为dict类型的数据对象
Returns:
返回dict类型数据对象
"""
return json.loads(astr) | f13b698dcf7dda253fd872bb464594901280f03b | 21,161 |
from typing import Any
def any(wanted_type=None):
"""Matches against type of argument (`isinstance`).
If you want to match *any* type, use either `ANY` or `ANY()`.
Examples::
when(mock).foo(any).thenReturn(1)
verify(mock).foo(any(int))
"""
return Any(wanted_type) | 4c92d19a2168f815a88f2fa8aa56f0d656a5a534 | 21,162 |
def list_top_level_blob_folders(container_client):
"""
List all top-level folders in the ContainerClient object *container_client*
"""
top_level_folders,_ = walk_container(container_client,max_depth=1,store_blobs=False)
return top_level_folders | baf41750aae23df6d051986f24814d0f286afb6b | 21,163 |
import string
def keyword_encipher(message, keyword, wrap_alphabet=KeywordWrapAlphabet.from_a):
"""Enciphers a message with a keyword substitution cipher.
wrap_alphabet controls how the rest of the alphabet is added
after the keyword.
0 : from 'a'
1 : from the last letter in the sanitised keyword
... | 155e997e1199f4adb25e20ad2c6e0047ffc7f7fd | 21,164 |
import PIL
def plt_to_img(dummy: any = None, **kwargs) -> PIL.Image.Image:
"""
Render the current figure as a (PIL) image
- Take dummy arg to support expression usage `plt_to_img(...)` as well as statement usage `...; plt_to_img()`
"""
return PIL.Image.open(plot_to_file(**kwargs)) | d07be803a2f3c71fa62b920c0a72954578d24f59 | 21,165 |
def _escape_char(c, escape_char=ESCAPE_CHAR):
"""Escape a single character"""
buf = []
for byte in c.encode('utf8'):
buf.append(escape_char)
buf.append('%X' % _ord(byte))
return ''.join(buf) | a4f4c69eb51a338d54b685336c036d991c295666 | 21,166 |
def error_log_to_html(error_log):
"""Convert an error log into an HTML representation"""
doc = etree.Element('ul')
for l in error_log:
if l.message.startswith('<runtrace '):
continue
el = etree.Element('li')
el.attrib['class'] = 'domain_{domain_name} level_{level_name} ty... | d2df223a0be82c5f58cf57be504833061d1afd40 | 21,167 |
def get_scheduler(optimizer, opt):
"""Return a learning rate scheduler
Parameters:
optimizer -- the optimizer of the network
opt (option class) -- stores all the experiment flags; needs to be a subclass of BaseOptions.
opt.lr_policy is the name of learning... | b8996d9963533249f1b387a36bac3f209e70daff | 21,168 |
def gen_colors(count, drop_high=True):
"""Generate spread of `count` colors from matplotlib inferno colormap"""
# drop the top end of the color range by defining the norm with one
# element too many
cvals = range(0, count + drop_high)
# and dropping the last element when calculating the normed value... | 14f53d46d4b7370603624caa84b7bf4731e5e73d | 21,169 |
import subprocess
def validate_branch():
"""Checks the branch passed in against the branches available on remote.
Returns true if branch exists on remote. This may be subject to false
postivies, but that should not be an issue"""
output = subprocess.run(["/usr/bin/git", "ls-remote",
... | daf96e3f1c072890295cd796658c5d3445c5956c | 21,170 |
def train_PCA(data, num_components):
"""
Normalize the face by subtracting the mean image
Calculate the eigenValue and eigenVector of the training face, in descending order
Keep only num_components eigenvectors (corresponding to the num_components largest eigenvalues)
Each training face is represent... | 2404fca9fe053c275b187e2435b497166ed7f4d8 | 21,171 |
def count_revoked_tickets_for_party(party_id: PartyID) -> int:
"""Return the number of revoked tickets for that party."""
return db.session \
.query(DbTicket) \
.filter_by(party_id=party_id) \
.filter_by(revoked=True) \
.count() | 6ad857a4630d2add7d2d46b9e930178a18f89e29 | 21,172 |
import os
def add_service_context(_logger, _method, event_dict):
"""
Function intended as a processor for structlog. It adds information
about the service environment and reasonable defaults when not running in Lambda.
"""
event_dict['region'] = os.environ.get('REGION', os.uname().nodename)
ev... | f5ea74b09ddd7024a04bc4f42bbd339b82adc9e3 | 21,173 |
def get_player_stats():
"""
Get all the player stats
returns dict of dicts: ->
{ player_id: {
name -> str gamertag,
discord -> str discord,
rank -> int rank,
wins -> int wins,
... | 32ec1a926fb5008f596a63d68c3c19627af916fb | 21,174 |
def get_data(data_x, data_y):
"""
split data from loaded data
:param data_x:
:param data_y:
:return: Arrays
"""
print('Data X Length', len(data_x), 'Data Y Length', len(data_y))
print('Data X Example', data_x[0])
print('Data Y Example', data_y[0])
train_x, test_x, train_y, test_y... | a40406da641b36784719da3c3e375130e013e889 | 21,175 |
async def api_download_profile() -> str:
"""Downloads required files for the current profile."""
global download_status
assert core is not None
download_status = {}
def update_status(url, path, file_key, done, bytes_downloaded, bytes_expected):
bytes_percent = 100
if (bytes_expecte... | 0dd6aaf17b49f8e48eb72c8adf726f2852937f18 | 21,176 |
def cumulative_segment_wrapper(fun):
"""Wrap a cumulative function such that it can be applied to segments.
Args:
fun: The cumulative function
Returns:
Wrapped function.
"""
def wrapped_segment_op(x, segment_ids, **kwargs):
with tf.compat.v1.name_scope(
Non... | 5471e525ab73855927fe04530b8ec6e14a4436d9 | 21,177 |
from typing import Any
def read_pet_types(
skip: int = 0,
limit: int = 100,
db: Session = Depends(deps.get_db),
current_user: models.User = Depends(deps.get_current_active_superuser)
) -> Any:
"""
Read pet types
:return:
"""
if not crud.user.is_superuser(current_use... | 60de7c25b305bbb1a628db27559bcdb3abc5fb24 | 21,178 |
def get_approves_ag_request():
"""Creates the prerequisites for - and then creates and returns an instance of - ApprovesAgRequest."""
# Creates an access group request and an approver (required to create an instance of ApprovesAgRequest).
agr = AccessGroupRequest(reader=None, ag=None, justification=MAGIC_STRING)
a... | 139900d7948b4bd836410be09ba35a21954f2dc4 | 21,179 |
import requests
def currency_history(
base: str = "USD", date: str = "2020-02-03", api_key: str = ""
) -> pd.DataFrame:
"""
Latest data from currencyscoop.com
https://currencyscoop.com/api-documentation
:param base: The base currency you would like to use for your rates
:type base: str
:pa... | ed8c547e433a7f08e67863aca86b991bd746ccbb | 21,180 |
import os
def get_service_legacy(default=None):
"""Helper to get the old {DD,DATADOG}_SERVICE_NAME environment variables
and output a deprecation warning if they are defined.
Note that this helper should only be used for migrating integrations which
use the {DD,DATADOG}_SERVICE_NAME variables to the ... | 37ccd178f40af393028cc8ed88590c5d30f06855 | 21,181 |
import os
def get_met_data():
"""
Taken from Tensorflow tutorial on time series forecasting:
https://www.tensorflow.org/tutorials/structured_data/time_series
"""
zip_path = tf.keras.utils.get_file(
origin='https://storage.googleapis.com/tensorflow/tf-keras-datasets/jena_climate_2009_2... | 17558ee12c0627f242746ef6afb9f45e9541d533 | 21,182 |
import os
def get_drives():
"""A list of accessible drives"""
if os.name == "nt":
return _get_win_drives()
else:
return [] | f370697170d27600322d6b1eae1c6028e73dc5a6 | 21,183 |
from typing import Type
from typing import Dict
def _ref_tier_copy(source_eaf: Type[Eaf] = None,
target_eaf: Type[Eaf] = None,
source_tier_name: str = "",
target_tier_name: str = "",
target_parent_tier_name: str = "",
overr... | f0c2fe27446d4a1f992f33c7610bc177d0e2c896 | 21,184 |
def fibonacci(length=10):
"""Get fibonacci sequence given it length.
Parameters
----------
length : int
The length of the desired sequence.
Returns
-------
sequence : list of int
The desired Fibonacci sequence
"""
if length < 1:
raise ValueError("Sequence le... | afa3ef63a663b4e89e5c4a694315083debdbab59 | 21,185 |
def readForecast(config, stid, model, date, hour_start=6, hour_padding=6, no_hourly_ok=False):
"""
Return a Forecast object from the main theta-e database for a given model and date. This is specifically designed
to return a Forecast for a single model and a single day.
hour_start is the starting hour f... | 57260de3d8866219bcdca003b9829f9e9caf0f86 | 21,186 |
def get_direct_hit_response(request, query, snuba_params, referrer):
"""
Checks whether a query is a direct hit for an event, and if so returns
a response. Otherwise returns None
"""
event_id = normalize_event_id(query)
if event_id:
snuba_args = get_snuba_query_args(
query=u'... | 4ffc0dcd5dbac56fc60e2414c1952e629f1fc951 | 21,187 |
from typing import Any
import dotenv
import os
def get_env_var(var_name: str) -> Any:
"""Get envronment var or raise helpful exception.
:param var_name: Name of environment variable to get.
:raises: ImproperlyConfigured if environment variable not found.
"""
dotenv.load_dotenv()
try:
... | 0771f1bba146af22b695d46bb99ee2edfec13b64 | 21,188 |
from typing import List
from typing import Tuple
from typing import Set
def _canonicalize_clusters(clusters: List[List[Tuple[int, int]]]) -> List[List[Tuple[int, int]]]:
"""
The data might include 2 annotated spans which are identical,
but have different ids. This checks all clusters for spans which are
... | d8435e6859e1f9720d7a6f1ec7dd1e2d51df5502 | 21,189 |
def remove_outliers(matches, keypoints):
"""
Calculate fundamental matrix between 2 images to remove incorrect matches.
Return matches with outlier removed. Rejects matches between images if there are < 20
:param matches: List of lists of lists where matches[i][j][k] is the kth cv2.Dmatch object for im... | 53b70f98389a33ba6a28c65fab8862bc629d2f0d | 21,190 |
def err_comp(uh, snap, times_offline, times_online):
"""
Computes the absolute l2 error norm and the rms error
norm between the true solution and the nirom solution projected
on to the full dimensional space
"""
err = {}
w_rms = {}
soln_names = uh.keys()
# ky = list(uh.keys())[0]
... | d64b061ec1cb3f8d7e9247cc5a74c4b6b852bc3b | 21,191 |
from datetime import datetime
def calc_stock_state(portfolio,code:int,date:datetime,stocks,used_days:int):
"""
状態を計算
- 株価・テクニカル指標・出来高の時系列情報
- 総資産、所持株数
Args:
stocks: 単元株数と始値、終値、高値、低値、出来高を含む辞書を作成
used_days: 用いる情報の日数
"""
stock_df=stocks[code]['prices']
date=datetime(date.year,dat... | 7aec335e15d5c169bfbaf7995614c532c31bd353 | 21,192 |
def lowercase_words(words):
"""
Lowercases a list of words
Parameters
-----------
words: list of words to process
Returns
-------
Processed list of words where words are now all lowercase
"""
return [word.lower() for word in words] | b6e8658f35743f6729a9f8df229b382797b770f6 | 21,193 |
def convert_images_to_arrays_train(file_path, df):
"""
Converts each image to an array, and appends each array to a new NumPy
array, based on the image column equaling the image file name.
INPUT
file_path: Specified file path for resized test and train images.
df: Pandas DataFrame being... | bab9ccc350c891d8c8dc634a431309490533f8ad | 21,194 |
def get_projection_matrix(X_src, X_trg, orthogonal, direction='forward', out=None):
"""
X_src: ndarray
X_trg: ndarray
orthogonal: bool
direction: str
returns W_src if 'forward', W_trg otherwise
"""
xp = get_array_module(X_src, X_trg)
if orthogonal:
if direction == 'forwar... | ef7f722e6beeb652069270afd81315a951d2a925 | 21,195 |
def _standardize_df(data_frame):
"""
Helper function which divides df by std and extracts mean.
:param data_frame: (pd.DataFrame): to standardize
:return: (pd.DataFrame): standardized data frame
"""
return data_frame.sub(data_frame.mean(), axis=1).div(data_frame.std(), axis=1) | cbe0e1f5c507181a63193a4e08f4ed8139d9e129 | 21,196 |
def has_edit_metadata_permission(user, record):
"""Return boolean whether user can update record."""
return EditMetadataPermission(user, record).can() | fd2a60d27151181c02d5a0fb6548f28beaa5b2b3 | 21,197 |
def truncate_chars_middle(text, limit, sep="..."):
"""
Truncates a given string **text** in the middle, so that **text** has length **limit** if the number of characters
is exceeded, or else **len(text)** if it isn't.
Since this is a template filter, no exceptions are raised when they would normally do.... | e08e6ec0b3522104d54e6690361d6ecf297f5566 | 21,198 |
import re
def parse_block(block, site_name, site_num, year):
"""Parse a main data block from a BBC file"""
# Cleanup difficult issues manually
# Combination of difficult \n's and OCR mistakes
replacements = {'Cemus': 'Census',
'Description of plot': 'Description of Plot',
... | 0a367e9163d1136ec725560156d67c05ca1c1d38 | 21,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.