content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def make_wc2018_dataset(
matches_features: pd.DataFrame,
team_features: pd.DataFrame,
wc2018_qualified: pd.DataFrame):
"""
Simulating the Tournament
With a trained model at our disposal, we can now run tournament simulations on it.
For example, let's take the qualified teams for... | a9c0647bd3a87025cd8413170e3e7208b238822d | 3,629,100 |
from typing import OrderedDict
def calcular_indices(arr, clases_posibles):
"""
Calcula los indices positivos y negativos de un arreglo
En la primer posicion de cada elemento se espera la clase real.
En la segunda posicion de cada elemento se espera la clase calculada.
"""
dic = []
for clase in clases_... | 3607de8e7fb8b269cc2bf10f7acac50043b68119 | 3,629,101 |
def create_app():
"""Creating and configuring an instance of the Flask application"""
app = Flask(__name__)
@app.route('/')
def root():
"""Base view."""
return 'TODO - part 2 and beyond!'
return app | 8d4f5a047a1118760b409f9828bce3e9fb4bfeff | 3,629,102 |
def _box_faces(image):
""" Add borders to all detected faces """
for face in image.faces:
_box_face(image, face)
return image | 8594856f0b789d280a208e8687858f26dccb4b2b | 3,629,103 |
def get_logger(name, is_task_logger=True):
"""Return a logger with the given name.
The logger will by default be constructed as a task logger. This will
ensure it contains additional information on the current task name and task
ID, if running in a task. If executed outside of a task, the name name and... | a1a4c079603ac3c9aa288d901ab5271c00b1646a | 3,629,104 |
import warnings
def get_stratified_gene_usage_frequency(ts = None, replace = True):
"""
MODIFIES A TCRsampler instance with esitmates vj_occur_freq_stratified by subject
Parameters
----------
ts : tcrsampler.sampler.TCRsampler
replace : bool
if True, ts.v_occur_freq is set to ts... | 002367ea1e97ddbdef8692022cd312de5f27f857 | 3,629,105 |
def _calculateSvalues(xarr, yarr, sigma2=1.):
"""Calculates the intermediate S values required for basic linear regression.
See, e.g., Numerical Recipes (Press et al 1992) Section 15.2.
"""
if len(xarr) != len(yarr):
raise ValueError("Input xarr and yarr differ in length!")
if len(xarr) <= ... | 53a7a1427c232e8cf226b6d80bcd59565803a3e0 | 3,629,106 |
from typing import Tuple
from typing import Optional
def existing_deployment_openshift(
runner: Runner, deployment_arg: str, expose: PortMapping,
add_custom_nameserver: bool
) -> Tuple[str, Optional[str]]:
"""
Handle an existing deploymentconfig by doing nothing
"""
runner.show(
"Start... | 79f6cebd6854c20516315c34f4810d4b0c4e0204 | 3,629,107 |
import six
def remove_nulls_from_dict(d):
"""
remove_nulls_from_dict function recursively remove empty or null values
from dictionary and embedded lists of dictionaries
"""
if isinstance(d, dict):
return {k: remove_nulls_from_dict(v) for k, v in six.iteritems(d) if v}
if isinstance(d, ... | dd0da02eae06ceccc1347e6ac87dcb65bdc44126 | 3,629,108 |
def frame_processors(configuration, call_types, return_types):
""":type configuration: ducktest.config_reader.Configuration"""
typer = IdleProcessor()
chain(
typer,
MappingTypeProcessor(typer),
ContainerTypeProcessor(typer),
PlainTypeProcessor(),
)
call_frame_process... | ae56574ca20d91c1e50aaeb46dece0536a650940 | 3,629,109 |
import argparse
def get_args():
"""Get command-line arguments"""
parser = argparse.ArgumentParser(
description='Sum Numbers',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('item',
metavar='int',
type=int,
... | ddbd6399bb713cc2eebcf680c6e593ce55d27856 | 3,629,110 |
import os
def GetLocalPackageArchiveDir(tar_dir, archive_name):
"""Returns directory where local package archive files live.
Args:
tar_dir: The tar root directory for where package archives would be found.
archive_name: The name of the archive contained within the package.
Returns:
The standard loc... | b45c00b4806b81abef4c8ee10a325d2b3d536385 | 3,629,111 |
def StartAndRunFlow(flow_cls,
client_mock=None,
client_id=None,
check_flow_errors=True,
**kwargs):
"""Builds a test harness (client and worker), starts the flow and runs it.
Args:
flow_cls: Flow class that will be created and run.
... | fb8aee3f2ede547c7eeea293d950f0383060d925 | 3,629,112 |
from typing import Optional
def check_dk(base: str, add: Optional[str] = None) -> str:
"""Check country specific VAT-Id"""
weights = (2, 7, 6, 5, 4, 3, 2, 1)
s = sum(int(c) * w for (c, w) in zip(base, weights))
r = s % 11
if r == 0:
return '' # check ok
else:
return 'f' | 306c5fda13ce30ce0c9ddbd9302347ef0a86d393 | 3,629,113 |
import html
def generate_sidepanel(spin_system, index):
"""Generate scrollable side panel listing for spin systems"""
# title
title = html.B(f"Spin system {index}", className="")
# spin system name
name = "" if "name" not in spin_system else spin_system["name"]
name = html.Div(f"Name: {name}"... | c820638c4e9baf2983b6f20ec7fb71a5e18f417b | 3,629,114 |
import subprocess
def ensure_installed(tool):
"""
Checks if a given tool is installed and in PATH
:param tool: Tool to check if installed and in PATH
:return: Full path of the tool
"""
proc = subprocess.Popen('export PATH=$PATH:/Applications/STMicroelectronics/STM32CubeMX.app/Contents/MacOs/:/... | 6d77c686f679b693d2c29fa9750094573675a6d5 | 3,629,115 |
def clc_points(points):
"""
Args:
points (np.array|list): OpenCV cv2.boxPoints returns coordinates, order is
[right_bottom, left_bottom, left_top, right_top]
Returns:
list: reorder the coordinates, order is [left_top, right_top, right_bottom, left_bottom]
... | 201434fda90698d45126fbc99cd505e5c5096518 | 3,629,116 |
def choose_til(*args):
"""
choose_til() -> bool
Choose a type library ( 'ui_choose' , 'chtype_idatil' ).
"""
return _ida_kernwin.choose_til(*args) | 48ffd4ff9b66caf40602e4cf778dfff8240db5cc | 3,629,117 |
def _has_child_providers(context, rp_id):
"""Returns True if the supplied resource provider has any child providers,
False otherwise
"""
child_sel = sa.select([_RP_TBL.c.id])
child_sel = child_sel.where(_RP_TBL.c.parent_provider_id == rp_id)
child_res = context.session.execute(child_sel.limit(1)... | 000fad116d01e676577bc51ad3049173eb69987a | 3,629,118 |
import random
def is_zero(n, p=.5):
"""Return the sum of n random (-1, 1) variables divided by n.
n: number of numbers to sum
p: probability of 1 (probablity of -1 is 1-p)
"""
# This function should be about zero, but as n increases it gets better
numbers = random.choices((-1, 1), weights=(1-... | eae43e784d77cb50e1b0b48f6d32d5085164147d | 3,629,119 |
from typing import Union
from typing import Sequence
from typing import Tuple
from typing import List
def reduce_loss(
sim_time: Union[float, int],
n_steps: int,
scene: JaxScene,
coordinate_init: Sequence,
velocity_init: Sequence,
target_coordinate: Sequence,
attractor: Sequence,
const... | 9499b0b2b379ba27c77a8d3c2364aed4f387e10b | 3,629,120 |
def lstm_ortho_initializer(scale=1.0):
"""LSTM orthogonal initializer."""
def _initializer(shape, dtype=tf.float32,
partition_info=None): # pylint: disable=unused-argument
size_x = shape[0]
size_h = shape[1] // 4 # assumes lstm.
t = np.zeros(shape)
t[:, :size_h] = orthogonal([si... | 3eb9e743c7002878ade487d2d6a9cb0803bfea44 | 3,629,121 |
def extract_data(loss_logs, fields, max_x=-1):
"""Extract numerical logs from loss logs.
Arguments:
loss_logs: list of text files containing numerical log data generated by
autoencoders
fields: types of values to plot (each gets its own subplot, e.g.
nonzero_mae, loss, p... | ce63d683569bf49447aff32c1bb3aa23f6f164eb | 3,629,122 |
def roc_pr_curves(xaxis, tpr_list, precision_list, model_names, model_colors=None, prc_chance=None,
prc_upper_ylim=None, figname=None, legend=True, figax=None, **kwargs):
"""Make a ROC and PR curve for each model, optionally with a SD. Compute an AUC score for each curve.
Parameters
-----... | 3fa02960e628ab8ed43b8c9c53761e84efea182a | 3,629,123 |
def safe_divide(num, denom):
"""Divides the two numbers, avoiding ZeroDivisionError.
Args:
num: numerator
denom: demoninator
Returns:
the quotient, or 0 if the demoninator is 0
"""
try:
return num / denom
except ZeroDivisionError:
return 0 | 144cf6bf8b53ab43f3ab2e16e7dd2c95f5408035 | 3,629,124 |
def npSigma11( fitResult, nuisFilter="alpha_" ):
"""
Returns the block of the covariance matrix that corresponds to the main term.
"""
cov,pars = npCov( fitResult )
newPars = list( pars )
for i in reversed( range(len(pars)) ):
if nuisFilter not in pars[i]: continue
cov = np.delete( cov, i, 0 )
cov = np.del... | 751a7780b7d4a887a2b86cb9f8d0bfefda86177d | 3,629,125 |
import socket
def webpack_dev_url(request):
"""
If webpack dev server is running, add HMR context processor so template can
switch script import to HMR URL
"""
if not getattr(settings, "WEBPACK_DEV_URL", None):
return {}
data = {"host": split_domain_port(request._get_raw_host())[0]}
... | 9e5146f87d25067b43debc0a75d2f02763502c1e | 3,629,126 |
from typing import Any
from typing import AbstractSet
import sympy
def parameter_symbols(val: Any) -> AbstractSet[sympy.Symbol]:
"""Returns parameter symbols for this object.
Args:
val: Object for which to find the parameter symbols.
Returns:
A set of parameter symbols if the object is p... | d289dc941d93c34f87e6568df83b5d8e7f39f753 | 3,629,127 |
import re
def datetime(el, default_date=None):
"""Process dt-* properties
Args:
el (bs4.element.Tag): Tag containing the dt-value
Returns:
a tuple (string string): a tuple of two strings, (datetime, date)
"""
def try_normalize(dtstr, match=None):
"""Try to normalize a datetim... | 38858690a4d77f522eb8d9a6967f75b5d5d7f9cd | 3,629,128 |
def lexicallyRelated(word1, word2):
"""
Determine whether two words might be lexically related to one another.
"""
return any(map(lambda stem: stem(word1) == stem(word2), stemmers)
) or word1.startswith(word2) or word2.startswith(word1) | be6df99aee20d0275682e60f8877a3b107dc8579 | 3,629,129 |
async def playing_check(ctx: commands.Context):
"""
Checks whether we are playing audio in VC in this guild.
This doubles up as a connection check.
"""
if await connected_check(ctx) and not ctx.guild.voice_client.is_playing():
raise commands.CheckFailure("The voice client in this guild is ... | 480bd5ef0e6b6eef63af3f07307f99805adf73fb | 3,629,130 |
def create_calibrated_rtl(feature_columns, config, quantiles_dir):
"""Creates a calibrated RTL estimator."""
feature_names = [fc.name for fc in feature_columns]
hparams = tfl.CalibratedRtlHParams(
feature_names=feature_names,
num_keypoints=200,
learning_rate=0.02,
lattice_l2_laplacian_reg=... | e6a73e66049e47fd8f18272647b5b948b015a004 | 3,629,131 |
def route_distance(df, con):
"""
Given a route's dataframe determine total distance (m) using gid
"""
dist = 0
cur = con.cursor()
for edge in df.edge[0:-1]:
query = 'SELECT length_m FROM ways WHERE gid={0}'.format(edge)
cur.execute(query)
out = cur.fetchone()
dis... | ca83cca270a97b60b615f89c83541c0491abddcf | 3,629,132 |
def convert_units(P, In='cm', Out='m'):
"""
Quickly convert distance units between meters, centimeters and millimeters
"""
c = {'m':{'mm':1000.,'cm':100.,'m':1.},
'cm':{'mm':10.,'cm':1.,'m':0.01},
'mm':{'mm':1.,'cm':0.1,'m':0.001}}
return c[In][Out]*P | bc318011ffc71d575c7e7276c2dede467a84dc2c | 3,629,133 |
def _nonmonotone_line_search_cheng(f, x_k, d, f_k, C, Q, eta,
gamma=1e-4, tau_min=0.1, tau_max=0.5,
nu=0.85):
"""
Nonmonotone line search from [1]
Parameters
----------
f : callable
Function returning a tuple ``(f, F)`` w... | a8ccaf00d39848495da9d2cc66014012d57bb146 | 3,629,134 |
def course_state_editor(func):
"""
Decorator for any method that will be used to alter a Course's 'state'. It does a few useful things:
1. Clears any lingering dashboard data for a given course run to ensure that it will be in the right state
after the command.
2. Allows the user to specify a... | 891cfccd9d4a0da4c80010cd2f7827d040c82e8e | 3,629,135 |
def importDataFromCSV(dataType, filename):
"""
Import from a `.csv` file into a dataframe or python time/distance matrix dictionary.
Parameters
----------
dataType: string, Required
The type of data to be imported. Valid options are 'nodes', 'arcs', 'assignments', or 'matrix'.
filename: string, Required
The... | cc185dd59fbc0a820e6f3fe2262154325e61d915 | 3,629,136 |
def main():
"""Run the exploit and go interactive."""
args = get_parsed_args()
host = args.host
port = int(args.port)
sock = None
t = None
try:
sock = exploit(host, port)
t = Telnet()
t.sock = sock
print_info('Exploit sent, going interactive!')
t.mt_i... | ed9f340f42aadaf25157fee156d16313faf6e553 | 3,629,137 |
from typing import Optional
def xyz_to_str(xyz_dict: dict,
isotope_format: Optional[str] = None,
) -> str:
"""
Convert an ARC xyz dictionary format, e.g.::
{'symbols': ('C', 'N', 'H', 'H', 'H', 'H'),
'isotopes': (13, 14, 1, 1, 1, 1),
'coords': ((0.66165... | 589d1ac44649c9a464c051791a9044830a6aa175 | 3,629,138 |
from typing import Tuple
async def _provision_nic_with_public_ip(
network_client: NetworkManagementClient,
location: str,
vm_name: str,
) -> Tuple[str, str]:
"""
Creates a public IP address and corresponding NIC. Returns (NIC id, public address
name)
"""
subnet_id = await _ensure_virt... | 3a45d54d565f17eeebc5261fbc79c209483db321 | 3,629,139 |
from typing import Dict
from typing import Any
import json
import time
def predict(event: Dict[str, Any],
context: Any) -> Dict[str, Any]:
"""
AWS lambda function, to handle incoming GET requests asking our model for predictions.
:param event: standard AWS lambda event param - it contains the... | 33566f1477af398d253df8e89d19d241710ab4b0 | 3,629,140 |
def get_simclr_transform(size, s=1):
"""Return a set of data augmentation transformations as described in the SimCLR paper."""
color_jitter = transforms.ColorJitter(0.8 * s, 0.8 * s, 0.8 * s, 0.2 * s)
normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
... | 237de2baa38f4e0e6859c5f66d6364438026b155 | 3,629,141 |
import json
def dump(obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True,
allow_nan=True, indent=None, separators=None, sort_keys=False,
core: Core = None, **kw):
"""
Dumps an object into a Writer with support for HomeControl's data types
"""
return json.dump(obj, fp, ... | b76016041dfe99b8fa9335974eebacf3ba668dcd | 3,629,142 |
import os
def moving_slope_filter(dataframe,time,data,cutoff,time_unit=None,
log_file=os.path.join(os.getcwd(),'filter_log.txt')):
"""
Filters out datapoints based on the difference between the slope in one point
and the next (sudden changes like noise get filtered out), based on a... | a92deb31cc850214dd5ed6a29bfb2b33b78691ff | 3,629,143 |
async def get_sender_data(user_id: int) -> dict:
"""
Sender profile
:param user_id: User ID
:type user_id: int
:return: Sender profile
:rtype: dict
"""
return await get_sender_data_request(user_id) | 7ecf5290ed9d19ccd52ba5d31595adcca762eb82 | 3,629,144 |
def conditional_input_prediction_2d(x, y_pred, var_1_index, var_2_index, var_1_bins, var_2_bins, dependence_function=np.mean):
"""
For a given set of 2 input values, calculate a summary statistic based on all of the examples that fall within
each binned region of the input data space. The goal is to show ho... | 8f34450c9780bba1503d093bef19d808ee4b869e | 3,629,145 |
import re
import sys
import attr
def update_model_params(params, update):
"""Updates the default parameters using supplied user arguments."""
update_dict = {}
for p in update:
m = re.match("(.*)=(.*)", p)
if not m:
LOGGER.error("Unable to parse param update '%s'", p)
... | cb96059e91f3aa839d3646f9bdce2093a4ea4983 | 3,629,146 |
def fgt_get_pressureUnit(pressure_index, get_error = _get_error):
"""Get current unit on selected pressure device.
Args:
pressure_index: Index of pressure channel or unique ID
Returns:
current unit as a string
"""
pressure_index = int(pressure_index)
low_level_function = low... | dd5b80fbdef7b4644c944c22207b4505082c498d | 3,629,147 |
def _get_rawhide_version():
"""
Query Koji to find the rawhide version from the build target.
:return: the rawhide version (e.g. "f32")
:rtype: str
"""
koji_session = get_session(conf, login=False)
build_target = koji_session.getBuildTarget("rawhide")
if build_target:
return bui... | c8fbb63f40ca5744563f598b58b998ad4aec2d14 | 3,629,148 |
def test_mixed():
"""Test positional arguments passed via keyword.
"""
class TestView(simple.SimpleView):
args = ['id']
def __call__(self, foo):
return self.request, self.id, foo
testview = create_view(TestView)
# generally is a possibility...
assert testview('reques... | 93d9594e91d10a2aa92d7e853057dc84d638efca | 3,629,149 |
def fail_event_on_handler_exception(func):
"""
Decorator which marks the models.Event associated with handler by
BaseHandler.set_context() as FAILED in case the `func` raises an
exception.
The exception is re-raised by this decorator once its finished.
"""
@wraps(func)
def decorator(han... | 07a0b5a24b95470bee29eff545c9676b1438e801 | 3,629,150 |
def intensityAdjustment(image, template):
"""Tune image intensity based on template
----------
images : <numpy.ndarray>
image needed to be adjusted
template : <numpy.ndarray>
Typically we use the middle image from image stack. We want to match the image
in... | 4e1021c718c80c46d05c276a3c8e4e682a6fa7b5 | 3,629,151 |
def Define_core_memesa_model():
"""\nOriginal core model + inefficient branch\n"""
model_name = 'core_model_1b'
Reactions ={'R01' : {'id' : 'R01', 'reversible' : False, 'reagents' : [(-1, 'X0'), (1, 'A')], 'SUBSYSTEM' : ''},
'R02' : {'id' : 'R02', 'reversible' : True, 'reagents' : ... | 7ff51107de0de6ed9ea6a86dc759a54eff4bcfc4 | 3,629,152 |
def F16(x):
"""Rosenbrock function"""
sum = 0
for i in range(len(x)-1):
sum += 100*(x[i+1]-x[i]**2)**2+(x[i]+1)**2
return sum | 7421ad45568a8b86aff41fc5c8466ae6ce7aeb9d | 3,629,153 |
def jaccard_simple(annotation,segmentation):
""" Compute region similarity as the Jaccard Index.
Arguments:
annotation (ndarray): binary annotation map.
segmentation (ndarray): binary segmentation map.
Return:
jaccard (float): region similarity
"""
annotation = annotatio... | e1defc9cc0dedb812b0880c63c9aa218a6bc93b6 | 3,629,154 |
def shuffle_df(df):
"""
return:
pandas.DataFrame | shuffled dataframe
params:
df: pandas.DataFrame
"""
return df.reindex(np.random.permutation(df.index)) | b609158f62d271f07a8e3b5409f0b28cdc3f83d0 | 3,629,155 |
from typing import List
def transform_from_sklearn(
idx: pd.Index,
vars_: List[str],
vals: np.array,
) -> pd.DataFrame:
"""
Add index and column names to sklearn output.
:param idx: data index
:param vars_: names of feature columns
:param vals: features data
:return: dataframe wit... | 7a37752c7647143f894c13e9a90febe925adbb7f | 3,629,156 |
def from_package_str(item):
"""Display name space info when it is different, then diagram's or parent's
namespace."""
subject = item.subject
diagram = item.diagram
if not (subject and diagram):
return False
namespace = subject.namespace
parent = item.parent
# if there is a par... | ab89c199aa886bff0ec88f6df37a655bb9ee7596 | 3,629,157 |
import os
def search_by_wl(target_type: str, imaging_type: str, wl: float, base_path: str) -> str:
"""Search a folder for an image of given wavelength.
A path to the image is returned.
:param target_type:
String either 'leaf' or 'reference'. Use the ones listed in constants.py.
:param imagin... | b4c20d9b8d965d67519444597516f36570b14d1a | 3,629,158 |
def calculateAverageValue(faceBlob, binaryLabelVolume):
"""Deprecated."""
total = 0.0
for labeledPoint in faceBlob.points():
total += float(at(binaryLabelVolume, labeledPoint.loc))
return float(total) / float(len(faceBlob.points())) | 26f38c24a7b21ec4b54b5476f8af7544f701e209 | 3,629,159 |
import numpy
def calc_m_inv_m_norm_by_unit_cell_parameters(
unit_cell_parameters, flag_unit_cell_parameters: bool = False):
"""nM matrix."""
a, b = unit_cell_parameters[0], unit_cell_parameters[1]
c = unit_cell_parameters[2]
alpha, beta = unit_cell_parameters[3], unit_cell_parameters[4]
ga... | 0c4e1988ccd1ea9d055fbea58119efebac542875 | 3,629,160 |
import subprocess
def get_m():
"""获取加密参数m"""
return subprocess.check_output(['node', 'scrapy_ddiy/scripts/js/yuanrenxue/002.js']).decode().strip() | e079affe696805ba2f006e55da9a4abb90f53220 | 3,629,161 |
import os
def fetch_mirchi2018(data_dir=None, resume=True, verbose=1):
"""
Downloads (and creates) dataset for replicating Mirchi et al., 2018, SCAN
Parameters
----------
data_dir : str, optional
Directory to check for existing data files (if they exist) or to save
generated data ... | 7eb8526c8583b05d856860e97ba26c6ec7f96d07 | 3,629,162 |
def round(dt, rounding=None):
"""Round a datetime value using specified rounding method.
Args:
dt: `datetime` value to be rounded.
rounding: `DatetimeRounding` value representing rounding method.
"""
if rounding is DatetimeRounding.NEAREST_HOUR:
return round_to_hour(dt)
elif... | 3970f4ad47b73c48f134817ff9decf7363dfe906 | 3,629,163 |
def testid(prefix='',c=_default_conc,
squishy=False,squishz=False,decimate=False,substr=False,
subm=_default_subm,subr=_default_subr,subc=_default_subc,
subrho=_default_subrho,version=-1):
"""Creates a standardized string that uniquely identifies a test.
Args:
prefi... | 8383281ee2af3f0422d58f37f88e94288e5324e6 | 3,629,164 |
def calc_bearing(lat1, lon1, lat2, lon2):
"""
Calculate bearing in degrees from (lat1,lon1) towards (lat2, lon2)
"""
lat1, lon1, lat2, lon2 = map(np.radians, [lat1, lon1, lat2, lon2])
dlon = lon2 - lon1
a = np.arctan2(
np.sin(dlon) * np.cos(lat2),
np.cos(lat1) * np.sin(lat2) - np... | f2cf545de2460d1e56659d5c9a54011c46ac898c | 3,629,165 |
def Block(data, num_filter, kernel, stride=(1,1), pad=(0,0), eps=1e-3, name=None):
""" CNN block"""
conv = mx.sym.Convolution(data=data, num_filter=num_filter,
stride=stride, kernel=kernel, pad=pad, name='conv_%s' % name)
bn = mx.sym.BatchNorm(data=conv, fix_gamma=False, eps=eps,
mom... | 0ec599725324b8528c3c7dfee4e13b6f4d850764 | 3,629,166 |
def flat(x, output_name="flatten"):
""" takes a tensor of rank > 2 and return a tensor of shape [?,n]"""
shape = x.get_shape().as_list()
n = np.prod(shape[1:])
x_flat = tf.reshape(x, [-1, n])
return tf.identity(x_flat, name=output_name) | 34c96ce4eb377d8bcbf25411115df11553b14bb7 | 3,629,167 |
from operator import sub
def preprocess_value(value): # TODO add preprocessing for noise and other stuff
"""
Preprocess value with regex to clear noise and data
Parameters
----------
value: str
string to be preprocessed
Returns
-------
preprocessed: str
value that is... | a124e64c6b53b5632ef9d26e7d0242e983a95c6c | 3,629,168 |
import os
def get_molecule(molecule):
"""Call read_xyz for molecule.
Extract symbols and geometry for given molecule from data folder.
Parameters
----------
molecule : string
prefix of the .xyz file
Returns
-------
molecule : `dict`
This output is described in :func:... | f3e2a737713a899befe578d6bde90d288ede4a94 | 3,629,169 |
def connect_to_database():
""" Attempt to connect to sqlite database. Return connection object."""
try:
connection = sqlite3.connect('blackjack_terminal')
print("DB Connected!")
except Exception, e:
print e
sys.exit(1)
return connection | a8df927370e395f08ae22aff0589b87db822220b | 3,629,170 |
def div_up(a, b):
"""Return the upper bound of a divide operation."""
return (a + b - 1) // b | e297f2d08972ebc667d1f3eadca25ef885ef5453 | 3,629,171 |
def handle_info():
"""
This function is called when you register your Battlesnake on play.battlesnake.com
See https://docs.battlesnake.com/guides/getting-started#step-4-register-your-battlesnake
It controls your Battlesnake appearance and author permissions.
For customization options, see https://d... | 8ad42644adf2c77469efbf2656a6297384da4188 | 3,629,172 |
from datetime import datetime
def story_root(story):
"""story_root()
Serves the root page of a story
Accessed at '/story/<story' via a GET request
"""
# Gets the DocumentReference to the story document in Firestore
story_ref = db.collection('stories').document(story)
# Gets the DocumentS... | e9cc07349368324d6a8859390dc5bcfb7c52d71c | 3,629,173 |
from numscons.core.utils import pkg_to_path
def get_scons_pkg_build_dir(pkg):
"""Return the build directory for the given package (foo.bar).
The path is relative to the top setup.py"""
return pjoin(get_scons_build_dir(), pkg_to_path(pkg)) | 6e6e346fdd12f5f595f8c2938ce8fe14ae012716 | 3,629,174 |
def oklab_to_linear_srgb(lab):
"""Convert from Oklab to linear sRGB."""
return util.dot(LMS_TO_SRGBL, [c ** 3 for c in util.dot(OKLAB_TO_LMS3, lab)]) | 6c0bd205285d9e26c0c6cb27e689b288eee075c0 | 3,629,175 |
def rjust(text: str, length: int) -> str:
"""Like str.rjust() but ignore all ANSI controlling characters."""
return " " * (length - len(strip_ansi(text))) + text | e32de595293837c780f97098ee302ce4ce002117 | 3,629,176 |
def solar_elevation_angle(solar_zenith_angle):
"""Returns Solar Angle in Degrees, with Solar Zenith Angle, solar_zenith_angle."""
solar_elevation_angle = 90 - solar_zenith_angle
return solar_elevation_angle | f896c5d0608171f3e5bd37cede1965fe57846d07 | 3,629,177 |
def vector3d_to_quaternion(x):
"""Convert a tensor of 3D vectors to a quaternion.
Prepends a 0 to the last dimension, i.e. [[1,2,3]] -> [[0,1,2,3]].
Args:
x: A `tf.Tensor` of rank R, the last dimension must be 3.
Returns:
A `Quaternion` of Rank R with the last dimension being 4.
Rais... | 2175bd7bf2a7f2cda4bd3d5603dfc04497966d3e | 3,629,178 |
def record_read_permission_factory(record=None):
"""Pre-configured record read permission factory."""
PermissionPolicy = get_record_permission_policy()
return PermissionPolicy(action='read', record=record) | e9cc5829345ad904c619569edd5d0670904faadc | 3,629,179 |
import requests
def fetch_66_cookie():
"""
获取 cookies
:return:
"""
cookie_url = 'http://www.66ip.cn/'
headers = {
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3",
"Accept-Encoding": "gzip, deflat... | 55225b4b132b16a7b97615c78f46034fac8cb0bb | 3,629,180 |
def query_address(address):
"""
Example: curl localhost:8080/queries/1234
"""
return get_score(address) | 6c03893c0bf581ec766a6c6f43f7398099a72e87 | 3,629,181 |
def marshal(resp, schema):
"""
prepares the response object with the specified schema
:param resp: the falcon response object
:param schema: the schema class that should be used to validate the response
:return: falcon.Response
"""
data = resp
resp_ = None
if isinstance(data, list):
... | f7bcbe258a96998aac3be7fde95b640651b41fdf | 3,629,182 |
def ethereum_tester(
patch_genesis_gas_limit,
):
"""Returns an instance of an Ethereum tester"""
tester = EthereumTester(PyEVMBackend())
tester.set_fork_block('FORK_BYZANTIUM', 0)
return tester | bcecb6caaef4905e05343645710508a06c8bb64c | 3,629,183 |
import requests
def fetch_form(formid):
"""
Fetch Ona Form.
"""
headers = {"Authorization": "Token {}".format(ONA_TOKEN)}
url = urljoin(ONA_URI, "/api/v1/forms/{}.json".format(formid))
response = requests.get(url, headers=headers)
return response.json() if response.status_code == 200 else... | be3a09994929292d3ad98b4f6f769823f0bb02d0 | 3,629,184 |
def get_token_from_http_header(request):
"""Retrieves the http authorization header from the request"""
token = None
try:
header = request.META.get(HTTP_AUTHORIZATION_HEADER, "")
except AttributeError:
header = ""
try:
prefix, payload = header.split()
except ValueErro... | 951d00b6f571d591a3785971ad1bdec46107f3ca | 3,629,185 |
def choose_line(path_with_lines):
""" Choose one line for each stations in path_with_lines list
Args:
path_with_lines(list): A list of dictionaries of stations and lines
Returns:
final_path(list): A list of dictionaries of station, line, and token
"""
final_path = []
i = ... | 7548d49a652f1cc2d4c75cee06ed63099713e733 | 3,629,186 |
def get_multiclass_predictions_and_correctness(probabilities, labels, top_k=1):
"""Returns predicted class, correctness boolean vector."""
_validate_probabilities(probabilities, multiclass=True)
_check_rank_nonempty(rank=1, labels=labels)
_check_rank_nonempty(rank=2, probabilities=probabilities)
if top_k == ... | 25937b5f4aa0dc77dbb4f0c40b5d6120fe3624b7 | 3,629,187 |
from subprocess import getoutput
import tarfile
import click
import os
import shutil
def download_frappe_assets(verbose=True):
"""Downloads and sets up Frappe assets if they exist based on the current
commit HEAD.
Returns True if correctly setup else returns False.
"""
assets_setup = False
frappe_head = getout... | 16f4146e41f2914cbcaa8a7fcaed995183f96331 | 3,629,188 |
def compute_gradient_penalty(discriminator, interpolated):
"""Computes the gradient penalty for a discriminator.
According to [https://arxiv.org/abs/1704.00028]
Args:
discriminator: The discriminator to compute the gradient
penalty for.
interpolated: The interpolation between re... | 51386af15dff536eabad8ea89a25ea2591df8638 | 3,629,189 |
import torch
def build_grid(resolution, device):
"""
Building the grid for linear embedding
:param device: As we create a new tensor, we need to put it on the device as well
:param resolution: tuple of integers (height, width)
:return: Tensor of shape [1, height, height, 4]
"""
ranges = [n... | 490d1d6ddb7aa40dbf89a1cd802c79c907652f19 | 3,629,190 |
from typing import Optional
from typing import Dict
from typing import Union
from datetime import datetime
def get_fit_point_data(frame: fitdecode.records.FitDataMessage) -> Optional[Dict[str, Union[float, int, str, datetime]]]:
"""Extract some data from an FIT frame representing a track point
and return it a... | 2fc0ecf014de8e947eaacdafbb6485afacb5db7c | 3,629,191 |
from typing import Mapping
import six
import os
def read(config_values):
"""Reads an ordered list of configuration values and deep merge the values in reverse order."""
if not config_values:
raise PolyaxonConfigurationError('Cannot read config_value: `{}`'.format(config_values))
config_values = t... | 3dfed9bf313ed3beb1350480ec6ec40a18843869 | 3,629,192 |
def from_time (year=None, month=None, day=None, hours=None, minutes=None, seconds=None, microseconds=None, timezone=None):
"""Convenience wrapper to take a series of date/time elements and return a WMI time
of the form `yyyymmddHHMMSS.mmmmmm+UUU`. All elements may be int, string or
omitted altogether. If omitted,... | b0f9d7b9610b23ef23867453389558b22473b74e | 3,629,193 |
def makeit_ssa(exprs):
"""
Convert an iterable of Eqs into Static Single Assignment (SSA) form.
"""
# Identify recurring LHSs
seen = {}
for i, e in enumerate(exprs):
seen.setdefault(e.lhs, []).append(i)
# Optimization: don't waste time reconstructing stuff if already in SSA form
... | 627d21c6f941e859686e41c3aafc1a81c4b4213e | 3,629,194 |
import sys
def get_vocabulary(fobj, threshold):
"""Read text and return dictionary that encodes vocabulary
"""
p_dict = dict()
add_c = 0
for line in fobj:
phrase = line.strip('\r\n ').split(' ||| ')
src_list = phrase[0].split(' ')
trg_list = phrase[1].split(' ')
if... | 7ed39da7e652c3108b5f27a021d19331104ee3e8 | 3,629,195 |
def parse_ucsc_file_index(stream, base_url):
"""Turn a UCSC DCC files.txt index into a dictionary of name-value pairs
"""
file_index = {}
for line in stream:
filename, attribute_line = line.split('\t')
filename = base_url + filename
attributes = {}
for assignment in attr... | 2d74bae9c7f2584ff8d859c8d2781faa3f6631b5 | 3,629,196 |
def AUC_PR(true_vessel_img, pred_vessel_img, save_fname):
"""
Precision-recall curve
"""
precision, recall, _ = precision_recall_curve(true_vessel_img.flatten(), pred_vessel_img.flatten(), pos_label=1)
save_obj({"precision":precision, "recall":recall}, save_fname)
AUC_prec_rec = auc(recall, pre... | 42dfa61e733788957b86ea6f00cceccfc65c20f0 | 3,629,197 |
def download_foot_bones():
"""Download foot bones dataset."""
return _download_and_read('fsu/footbones.ply') | 1220029e6ac06b5b6d570ffed02a73b4373e9c61 | 3,629,198 |
def _select_list_subset_schema():
""" schema for select_list_subset type """
return schemas.load(_SELECT_LIST_SUBSET_KEY) | 00721c12da47bd85bedbde7c99c5ae3de9299a3b | 3,629,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.