content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def add_logger_stdout(app):
"""Creates a StreamHandler logger"""
f = ContextFilter()
app.logger.addFilter(f)
stdout_handler = logging.StreamHandler(sys.stdout)
FORMAT = '%(asctime)s %(hostname)s {0} :%(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]'.format('Tester')
formatter = logging.... | 5,349,000 |
def main():
"""
Performing following actions:
1.) Reading configuration file.
2.) Connecting to database.
3.) Executing queries.
"""
rootLogger.info("Reading configuration files.")
config = configparser.ConfigParser()
config.read('dwh.cfg')
rootLogger.info("Connecting to database... | 5,349,001 |
def softmax_mask(w: torch.Tensor,
dim=-1,
mask: torch.BoolTensor = None
) -> torch.Tensor:
"""
Allows having -np.inf in w to mask out, or give explicit bool mask
:param w:
:param dim:
:param mask:
:return:
"""
if mask is None:
ma... | 5,349,002 |
def mocked_captcha_failed_call(app):
"""Monkey patch Captcha call in case of failure."""
token = app.config['dev_config']['secret_keys']['web']
httpretty.enable()
# mock dirbs core imei apis
httpretty.register_uri(httpretty.POST,
'https://www.google.com/recaptcha/api/sit... | 5,349,003 |
def modular_nli_reader(resources_or_conf: Union[dict, SharedResources] = None):
"""Creates a Modular NLI reader instance. Model defined in config."""
from jack.readers.multiple_choice.shared import MultipleChoiceSingleSupportInputModule
from jack.readers.natural_language_inference.modular_nli_model import M... | 5,349,004 |
def test_read_course_proto_correctness():
"""Test if read_course_proto() returns the right content with/without lab."""
course_raw_data = check_file_open('tests/test.json')
json_obj = course_raw_data['Test Data']
course_list = []
enrollment_dict = {}
index = 0
department_name = 'ACCT'
ea... | 5,349,005 |
def test_qttexttospeech():
"""Test the qtpy.QtTextToSpeech namespace."""
from qtpy import QtTextToSpeech
assert QtTextToSpeech.QTextToSpeech is not None
assert QtTextToSpeech.QVoice is not None
if PYSIDE2:
assert QtTextToSpeech.QTextToSpeechEngine is not None | 5,349,006 |
def move_box_and_gtt(n_targets=3,
time_limit=DEFAULT_TIME_LIMIT,
control_timestep=DEFAULT_CONTROL_TIMESTEP):
"""Loads `move_box_or_gtt` task."""
return _make_predicate_task(
n_boxes=1,
n_targets=n_targets,
include_gtt_predicates=True,
include_move_bo... | 5,349,007 |
def get_body(data_dict, database_id, media_status, media_type):
"""
获取json数据
:param media_type:
:param media_status:
:param data_dict:
:param database_id:
:return:
"""
status = ""
music_status = ""
if media_status == MediaStatus.WISH.value:
status = "想看"
musi... | 5,349,008 |
def _find_full_periods(events, quantity, capacity):
"""Find the full periods."""
full_periods = []
used = 0
full_start = None
for event_date in sorted(events):
used += events[event_date]['quantity']
if not full_start and used + quantity > capacity:
full_start = event_date... | 5,349,009 |
def crop_image(img, target_size, center):
""" crop_image """
height, width = img.shape[:2]
size = target_size
if center == True:
w_start = (width - size) / 2
h_start = (height - size) / 2
else:
w_start = random.randint(0, width - size)
h_start = random.randint(0, heig... | 5,349,010 |
def _histogram(
data=None,
bins="freedman-diaconis",
p=None,
density=False,
kind="step",
line_kwargs={},
patch_kwargs={},
**kwargs,
):
"""
Make a plot of a histogram of a data set.
Parameters
----------
data : array_like
1D array of data to make a histogram o... | 5,349,011 |
def select_path() -> None:
"""Opens popup prompting user to pick a directory. Fills 'path' entry widget with path."""
root.update()
directory = str(tkinter.filedialog.askdirectory(title= "Download Path Selection", parent= root))
root.update()
entry = find_widgets_by_name("path")
entry.delet... | 5,349,012 |
def write_test_report(project, test_rep_path):
"""
Given a project that has been evaluated (.evaluate()),
extract test data and write it to an HTML document at risk_rep_path
"""
with open(test_rep_path, 'w') as test_rep:
# test_table is a bunch of <tr> rows with <td> columns
test_tab... | 5,349,013 |
def getGarbageBlock():
"""获取正在标记的众生区块
{
?block_id=
}
返回 json
{
"is_success":bool,
"data": {"id": ,
"election_period":
"beings_block_id":
"votes":
"vote_list":
"status":
"create_time":
"""
try:
beings_block... | 5,349,014 |
def partition(items, low, high):
"""Return index `p` after in-place partitioning given items in range
`[low...high]` by choosing a pivot (TODO: document your method here) from
that range, moving pivot into index `p`, items less than pivot into range
`[low...p-1]`, and items greater than pivot into range `[p+1...hig... | 5,349,015 |
def describe(module):
""" Describe the module object passed as argument
including its classes and functions """
wi('[Module: %s]\n' % module.__name__)
indent()
count = 0
for name in dir(module):
obj = getattr(module, name)
if inspect.isclass(obj):
count += 1; describe... | 5,349,016 |
def cluster_confusion_matrix(pred_cluster:Dict, target_cluster:Dict) -> EvalUnit:
""" simulate confusion matrix
Args:
pred_cluster: Dict element: cluster_id (cluster_id from 0 to max_size)| predicted clusters
target_cluster: Dict element:cluster_id (cluster_id from 0 to max_size) | target clus... | 5,349,017 |
def change_short(x, y, limit):
"""Return abs(y - x) as a fraction of x, but with a limit.
>>> x, y = 2, 5
>>> abs(y - x) / x
1.5
>>> change_short(x, y, 100)
1.5
>>> change_short(x, y, 1) # 1 is smaller than 1.5
1
>>> x = 0
>>> change_short(x, y, 100) # No error, even though... | 5,349,018 |
def main(E_USER):
"""This is the main menu of Checkcryption.
E_USER: the encrypted username, used for verification."""
while True: # The 'crypter' loop
print('\nWhat would you like to do?')
option = input('Type \'e\' to encrypt, \'v\' to verify, or \'q\' to quit: ')
if re.matc... | 5,349,019 |
def generate_correlation_map(f, x_data, y_data, method='chisquare_spectroscopic', filter=None, resolution_diag=20, resolution_map=15, fit_args=tuple(), fit_kws={}, distance=5, npar=1):
"""Generates a correlation map for either the chisquare or the MLE method.
On the diagonal, the chisquare or loglikelihood is d... | 5,349,020 |
def _botocore_error_serializer_integration_test(
service: str,
action: str,
exception: ServiceException,
code: str,
status_code: int,
message: str,
):
"""
Performs an integration test for the error serialization using botocore as parser.
It executes the following steps:
- Load th... | 5,349,021 |
async def async_write_text(path, text):
"""Asynchronous IO writes of text data `text` to disk on the file path `path`"""
async with aiofiles.open(path, "w", encoding="utf-8") as f:
await f.write(text) | 5,349,022 |
def local_ip():
"""find out local IP, when running spark driver locally for remote cluster"""
ip = ((([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith("127.")] or [[(s.connect(
("8.8.8.8", 53)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, soc... | 5,349,023 |
def string_to_int_replacements(setting, item, for_property):
"""Maps keys to values from setting and item for replacing string
templates for settings which need to be converted to/from Strings.
"""
replacements = common_replacements(setting, item)
replacements.update({
'$string_to_in... | 5,349,024 |
def get_polytope(parser: ArgumentParser) -> None:
"""Adds arguments to parser for outputting polytope of single example"""
parser.add_argument("--word", type=str, help="Word representing the one relator", required=True) | 5,349,025 |
def get_var_path(path):
"""
get the path stored in the 'app/data' directory
:param path: string
:return: string
"""
return os.path.join(VAR_DIR, path) | 5,349,026 |
def solr_dt(instance, attribute, value):
"""A validator for ensuring a datetime string is Solr compatible."""
datetime.strptime(value, '%Y-%m-%dT%H:%M:%SZ') | 5,349,027 |
def GitClone(
clone_url: str,
destination: pathlib.Path,
shallow: bool = False,
recursive: bool = False,
timeout: int = 3600,
) -> pathlib.Path:
"""Clone a repository from Github.
Args:
clone_url: The URL of the repo to clone.
destination: The output path. If this is already a non-empty directory... | 5,349,028 |
def UnpackU32(buf, offset=0, endian='big'):
""" Unpack a 32-bit unsigned integer into 4 bytes.
Parameters:
buf - Input packed buffer.
offset - Offset in buffer.
endian - Byte order.
Return:
2-tuple of unpacked value, new buffer offset.
"""
try:
return ... | 5,349,029 |
def get_reset_token(user, expires_sec=1800):
"""
Create a specify token for reset user password
Args:
user:
expires_sec:
Returns:
token: string
"""
hash_token_password = Serializer(APP.config['SECRET_KEY'], expires_sec)
return hash_token_password.dumps({'user_name': u... | 5,349,030 |
def _on_error_resume_next(*sources: Union[Observable, Future]) -> Observable:
"""Continues an observable sequence that is terminated normally or
by an exception with the next observable sequence.
Examples:
>>> res = rx.on_error_resume_next(xs, ys, zs)
Returns:
An observable sequence th... | 5,349,031 |
def convert_literal_tuple_string_index_to_tuple(
df: pd.DataFrame, comm_before_user: bool = True, vertex_to_int: bool = False):
"""
Converts a DataFrame's literal string index of form '(community, vertex)' to a tuple (community, vertex) index.
Changes input DataFrame inplace.
"""
# convert index to column
df.... | 5,349,032 |
def prompt_for_value(field_name: str, field_type):
"""Promt the user to input a value for the parameter `field_name`."""
print_formatted_text(
f"No value found for field '{field_name}' of type '{field_type}'. "
"Please enter a value for this parameter:"
)
response = prompt("> ")
whi... | 5,349,033 |
def _send_kv_msg(sender, msg, recv_id):
"""Send kvstore message.
Parameters
----------
sender : ctypes.c_void_p
C sender handle
msg : KVStoreMsg
kvstore message
recv_id : int
receiver's ID
"""
if msg.type == KVMsgType.PULL:
tensor_id = F.zerocopy_to_dgl_n... | 5,349,034 |
def move_j(joints, accel, vel):
"""
Function that returns UR script for linear movement in joint space.
Args:
joints: A list of 6 joint angles (double).
accel: tool accel in m/s^2
accel: tool accel in m/s^2
vel: tool speed in m/s
Returns:
script: UR script
"... | 5,349,035 |
def create_dist_list(dist: str, param1: str, param2: str) -> list:
""" Creates a list with a special syntax describing a distribution
Syntax: [identifier, param1, param2 (if necessary)]
"""
dist_list: list = []
if dist == 'fix':
dist_list = ["f", float(param1)]
elif dist == 'binary'... | 5,349,036 |
def compute_arfgm(t, qd, p, qw=0.0):
"""computes relative humidity from temperature, pressure and specific humidty (qd)
This might be similar to https://unidata.github.io/MetPy/latest/api/generated/metpy.calc.relative_humidity_from_specific_humidity.html
algorithm from RemapToRemo addgm
**Arguments:*... | 5,349,037 |
def getOutputMeshpath(path, meshtype=None):
"""Returns the folder path for mesh file export as specified in the GUI.
Phobos by default creates a directory 'meshes' in the export path and subsequently creates
sub-directories of "export/path/meshes" for every format, e.g. resulting in "export/path/mesh/o... | 5,349,038 |
def load_data():
""" loads the data for this task
:return:
"""
fpath = 'images/ball.png'
radius = 70
Im = cv2.imread(fpath, 0).astype('float32')/255 # 0 .. 1
# we resize the image to speed-up the level set method
Im = cv2.resize(Im, dsize=(0, 0), fx=0.5, fy=0.5)
height, width = Im... | 5,349,039 |
def iteration_recognition(iteration=3, lists=5) -> NoReturn:
"""
Based on ~ CSC2032: Tutorial 1.4.1/2.1.1 ~ Question 3
Displays an array partially sorted by insertion sort.
The original array is display with others that are not
the original array. The user must pick out the correct
array.
... | 5,349,040 |
def validate_args(args, dhis_version):
"""
Validate arguments. Raises Exception if invalid
:param args: the argparse arguments
:param dhis_version: DHIS 2 version as an integer (e.g. 32)
:return: None
"""
if args.extend:
if not args.groups and not args.public_access:
rais... | 5,349,041 |
def create_response_body(input_json):
"""Create a json response with specific args of input JSON."""
city_name = str(input_json['name'])
country_code = str(input_json['sys']['country'])
temp_celsius = get_val_unit(input_json, 'main', 'temp', ' °C')
wind_speed = get_val_unit(input_json, 'wind', 'spee... | 5,349,042 |
def get_GESLA_surge_filename(city):
"""Get the path to the file containing GESLA-2 surge data for ‘city’."""
if city == "Brest":
filename = "brest-brest-france-refmar_SkewSurges.txt"
elif city == "La Rochelle":
filename = "la_rochelle_la_palli-la_rochelle_la_palli-france-refmar_SkewSurges.tx... | 5,349,043 |
def getAllTraj () :
""" get all trajectories from C.TRAJ_DIR """
def loadPickle (f) :
with open(osp.join(C.TRAJ_DIR, f), 'rb') as fd :
return pickle.load(fd)
return list(map(loadPickle, os.listdir(C.TRAJ_DIR))) | 5,349,044 |
def _get_count(_khoros_object, _user_id, _object_type):
"""This function returns the count of a specific user object (e.g. ``albums``, ``followers``, etc.) for a user.
:param _khoros_object: The core :py:class:`khoros.Khoros` object
:type _khoros_object: class[khoros.Khoros]
:param _user_id: The User I... | 5,349,045 |
def antiSymmetrizeSignal(y, symmetryStep):
"""
Dischard symmetric part of a signal by
taking the difference of the signal at x[n] and x[n + symmetry_step]
get your corresponding x data as x[0:len(y)/2]
Parameters
----------
y : array_like
numpy array o... | 5,349,046 |
def lms_to_rgb(img):
"""
rgb_matrix = np.array(
[[0.0809444479, -0.130504409, 0.116721066],
[0.113614708, -0.0102485335, 0.0540193266],
[-0.000365296938, -0.00412161469, 0.693511405]
]
)
"""
rgb_matrix = np.array(
[[ 2.85831110e+00, -1.62870796e+00, -2.481... | 5,349,047 |
def merge(output, students, **kwargs):
"""Read lists of students downloaded from Xidian, merge them to create a unified list."""
students_all = {}
fields = [kwargs["name_xdu"], kwargs["sid_xdu"]]
for xlsfile in students:
data = load_xls(xlsfile)
name_col, sid_col = find_column_index(... | 5,349,048 |
def timeit(func):
"""
Decorator that returns the total runtime of a function
@param func: function to be timed
@return: (func, time_taken). Time is in seconds
"""
def wrapper(*args, **kwargs) -> float:
start = time.time()
func(*args, **kwargs)
total_time = time.time() - ... | 5,349,049 |
def merge_count(data1, data2):
"""Auxiliary method to merge the lengths."""
return data1 + data2 | 5,349,050 |
def orthogonal_procrustes(fixed, moving):
"""
Implements point based registration via the Orthogonal Procrustes method.
Based on Arun's method:
Least-Squares Fitting of two, 3-D Point Sets, Arun, 1987,
`10.1109/TPAMI.1987.4767965 <http://dx.doi.org/10.1109/TPAMI.1987.4767965>`_.
Also see ... | 5,349,051 |
def make_model(arch_params, patch_size):
""" Returns the model.
Used to select the model.
"""
return RDN(arch_params, patch_size) | 5,349,052 |
def calc_error(frame, gap, method_name):
"""Calculate the error between the ground truth and the GAP prediction"""
frame.single_point(method_name=method_name, n_cores=1)
pred = frame.copy()
pred.run_gap(gap=gap, n_cores=1)
error = np.abs(pred.energy - frame.energy)
logger.info(f'|E_GAP - E_0|... | 5,349,053 |
def find_model(sender, model_name):
"""
Register new model to ORM
"""
MC = get_mc()
model = MC.get((MC.c.model_name==model_name) & (MC.c.uuid!=''))
if model:
model_inst = model.get_instance()
orm.set_model(model_name, model_inst.table_name, appname=__name__, model_path='')
... | 5,349,054 |
def list_subtitles(videos, languages, pool_class=ProviderPool, **kwargs):
"""List subtitles.
The `videos` must pass the `languages` check of :func:`check_video`.
All other parameters are passed onwards to the provided `pool_class` constructor.
:param videos: videos to list subtitles for.
:type vi... | 5,349,055 |
def public_incursion_no_expires(url, request):
""" Mock endpoint for incursion.
Public endpoint without cache
"""
return httmock.response(
status_code=200,
content=[
{
"type": "Incursion",
"state": "mobilizing",
"stagi... | 5,349,056 |
def test_get_rows_none_selected():
"""Assert that an error is raised when no rows are selected."""
atom = ATOMClassifier(X_idx, y_idx, index=True, random_state=1)
with pytest.raises(ValueError, match=r".*has to be selected.*"):
atom._get_rows(index=slice(1000, 2000)) | 5,349,057 |
def bad_topics():
""" Manage Inappropriate topics """
req = request.vars
view_info = {}
view_info['errors'] = []
tot_del = 0
if req.form_submitted:
for item in req:
if item[:9] == 'inapp_id_':
inapp_id = int(req[item])
db(db.zf_topic_inappropri... | 5,349,058 |
def run(tl_key, p_bans=tuple(), g_bans=tuple(), p_open=True, g_open=True, qr=2, enable_cfg=False, cfg_name="wxReply"):
"""
启动
:param tl_key: 图灵key
:param p_bans: 好友黑名单
:param g_bans: 群组黑名单
:param p_open: 开启自动回复
:param g_open: 开启群艾特回复
:param qr: 二维码类型
:param enable_cfg: 是否启... | 5,349,059 |
def test_items_Exception_for_elasticsearch_errs(monkeypatch):
"""An Elasticsearch error response other than a 400 results in a 500"""
monkeypatch.setattr(requests, 'post', mock_es_post_response_err)
# Simulate some unsuccessful status code from Elasticsearch, other than a
# 400 Bad Request. Say a 500 S... | 5,349,060 |
def main_loop(): # noqa: C901
"""Contain all the logic for the app"""
menu = Menu(CONFIG)
files = get_files()
current_position = 0
quit_early = False
files_exhausted = False
while not (quit_early or files_exhausted):
filename = files[current_position]
files_message = "Curren... | 5,349,061 |
def get_min_id_for_repo_mirror_config():
"""
Gets the minimum id for a repository mirroring.
"""
return RepoMirrorConfig.select(fn.Min(RepoMirrorConfig.id)).scalar() | 5,349,062 |
def check_series(
Z,
enforce_univariate=False,
allow_empty=False,
allow_numpy=True,
enforce_index_type=None,
):
"""Validate input data.
Parameters
----------
Z : pd.Series, pd.DataFrame
Univariate or multivariate time series
enforce_univariate : bool, optional (default=F... | 5,349,063 |
def save_json(data, source_airport, dest_airport, date):
"""
Saves the scraped airfares as a .json file.
Parameters
----------
data: List. Required.
A list containing all the flight information from the source airport to
the destination airport on the date specified.
s... | 5,349,064 |
def __ensure_project_registered():
""" Ensure the project configured in project.yaml has been registered. """
client = get_ai_flow_client()
project_meta = client.get_project_by_name(current_project_config().get_project_name())
pp = {}
for k, v in current_project_config().items():
pp[k] = st... | 5,349,065 |
def B(s):
"""string to byte-string in
Python 2 (including old versions that don't support b"")
and Python 3"""
if type(s)==type(u""): return s.encode('utf-8') # Python 3
return s | 5,349,066 |
def gather_tiling_strategy(data, axis):
"""Custom tiling strategy for gather op"""
strategy = list()
base = 0
for priority_value, pos in enumerate(range(len(data.shape) - 1, axis, -1)):
priority_value = priority_value + base
strategy.append(ct_util.create_constraint_on_tensor(tensor=data... | 5,349,067 |
def fetch(
uri: str, auth: Optional[str] = None, endpoint: Optional[str] = None, **data
) -> OAuthResponse:
"""Perform post given URI with auth and provided data."""
req = requests.Request("POST", uri, data=data, auth=auth)
prepared = req.prepare()
timeout = time.time() + app.config["OAUTH_FETCH_TO... | 5,349,068 |
def redscreen(main_filename, back_filename):
"""
Implements the notion of "redscreening". That is,
the image in the main_filename has its "sufficiently"
red pixels replaced with pized from the corresponding x,y
location in the image in the file back_filename.
Returns the resulting "redscreened"... | 5,349,069 |
def density_speed_conversion(N, frac_per_car=0.025, min_val=0.2):
"""
Fraction to multiply speed by if there are N nearby vehicles
"""
z = 1.0 - (frac_per_car * N)
# z = 1.0 - 0.04 * N
return max(z, min_val) | 5,349,070 |
async def test_remove_all_outputs():
"""
GIVEN
ChannelMultiple with multiple output channels.
WHEN
All output channels are removed then a item is put on src channel.
EXPECT
Item is not copied to former output channels, but is removed from
src channel.
"""
src = cr... | 5,349,071 |
def main():
"""
PARSE AND VALIDATE INTEGRATION PARAMS
"""
service_principal = demisto.params().get('credentials').get('identifier')
secret = demisto.params().get('credentials').get('password')
# Remove trailing slash to prevent wrong URL path to service
server_url = demisto.params()['url'][... | 5,349,072 |
def connect_to_amqp(sysconfig):
"""
Connect to an AMQP Server, and return the connection and Exchange.
:param sysconfig: The slickqaweb.model.systemConfiguration.amqpSystemConfiguration.AMQPSystemConfiguration instance
to use as the source of information of how to connect.
:return:... | 5,349,073 |
def int_to_datetime(int_date, ds=None):
"""Convert integer date indices to datetimes."""
if ds is None:
return TIME_ZERO + int_date * np.timedelta64(1, 'D')
if not hasattr(ds, 'original_time'):
raise ValueError('Dataset with no original_time cannot be used to '
'convert ints to dateti... | 5,349,074 |
def show_plugin(name, path, user):
"""
Show a plugin in a wordpress install and check if it is installed
name
Wordpress plugin name
path
path to wordpress install location
user
user to run the command as
CLI Example:
.. code-block:: bash
salt '*' wordpre... | 5,349,075 |
def test_trium2flat_idx():
"""Test the conversion from triangular upper index to flat array index."""
td = np.array([[1, 0], [0, 1], [0, 1]])
cm = BiCM(td)
assert cm.triumat2flat_idx(3, 5, 8) == 19
for k in range(45):
ij = cm.flat2triumat_idx(k, 10)
assert cm.triumat2flat_idx(ij[0], ... | 5,349,076 |
def send_notification(request, type_id, receipient, message):
"""Method to send out notifications."""
try:
if type_id == 2:
# Get users from this Organization unit
title = "Child tranfer IN"
org_ids = [receipient]
person_ids = get_organization_persons(org_... | 5,349,077 |
def get_receiver_type(rinex_fname):
"""
Return the receiver type (header line REC # / TYPE / VERS) found
in *rinex_fname*.
"""
with open(rinex_fname) as fid:
for line in fid:
if line.rstrip().endswith('END OF HEADER'):
break
elif line.rstrip().endswith... | 5,349,078 |
def is_cyclone_phrase(phrase):
"""Returns whether all the space-delimited words in phrases are cyclone words
A phrase is a cyclone phrase if and only if all of its component words are
cyclone words, so we first split the phrase into words using .split(), and then
check if all of the words are cyclone w... | 5,349,079 |
def _append_iwc_sensitivity(data_handler):
"""Calculates sensitivity of ice water content."""
iwc_sensitivity = _z_to_iwc(data_handler, 'Z_sensitivity')
data_handler.append_data(iwc_sensitivity, 'iwc_sensitivity') | 5,349,080 |
def wl_to_wavenumber(wl, angular=False):
"""Given wavelength in meters, convert to wavenumber in 1/cm. The wave
number represents the number of wavelengths in one cm. If angular is true,
will calculate angular wavenumber. """
if angular:
wnum = (2*np.pi)/(wl*100)
else:
wnu... | 5,349,081 |
def easeOutCubic(n):
"""A cubic tween function that begins fast and then decelerates.
Args:
n (float): The time progress, starting at 0.0 and ending at 1.0.
Returns:
(float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine().
"""
_checkRange(... | 5,349,082 |
def _evaluate_batch_beam(model, params, dico, batch, lengths, positions, langs, src_lens, trg_lens, \
gen_type, alpha, beta, gamma, dec_len, iter_mult, selected_pos, beam_size, length_penalty):
"""Run on one example"""
n_iter = dec_len * iter_mult
# log probabilities of previously prese... | 5,349,083 |
def tetrahedron(a, b, c, d, depth, vertices, edges, surfaces, config):
"""
Recursive tetrahedron fractal generation.
ARGUMENTS:
a, b, c, d - tetrahedron vertices
depth - how deep in interations
vertices, edges, surfaces - mesh data lists
config - config tuple to generate from
"""
# ... | 5,349,084 |
def _fix_entries(entries):
"""recursive function to collapse entries into correct format"""
cur_chapter_re, chapter_entry = None, None
new_entries = []
for entry in entries:
title, doxy_path, subentries = entry
if subentries is not None:
new_subentries = _fix_entries(subentri... | 5,349,085 |
def _check_bulk_delete(attempted_pairs, result):
"""
Checks if the RCv3 bulk delete command was successful.
"""
response, body = result
if response.code == 204: # All done!
return body
errors = []
non_members = pset()
for error in body["errors"]:
match = _SERVER_NOT_A_... | 5,349,086 |
def get_frontend_ui_base_url(config: "CFG") -> str:
"""
Return ui base url
"""
return as_url_folder(urljoin(get_root_frontend_url(config), FRONTEND_UI_SUBPATH)) | 5,349,087 |
def read_image(name):
"""
Reads image into a training example. Might be good to threshold it.
"""
im = Image.open(name)
pix = im.load()
example = []
for x in range(16):
for y in range(16):
example.append(pix[x, y])
return example | 5,349,088 |
def insert_info_data(xml_root, result_annotation):
"""Fill available information of annotation
Args:
xml_root: root for xml parser
result_annotation: output annotation in COCO representation
"""
log.info('Reading information data...')
version = ''
date = ''
description = ''
... | 5,349,089 |
def l3tc_underlay_lag_config_unconfig(config, dut1, dut2, po_name, members_dut1, members_dut2):
"""
:param config:
:param dut1:
:param dut2:
:param po_name:
:param members_dut1:
:param members_dut2:
:return:
"""
st.banner("{}Configuring LAG between Spine and Leaf node.".format('... | 5,349,090 |
def _xrdcp_copyjob(wb, copy_job: CopyFile, xrd_cp_args: XrdCpArgs, printout: str = '') -> int:
"""xrdcp based task that process a copyfile and it's arguments"""
if not copy_job: return
overwrite = xrd_cp_args.overwrite
batch = xrd_cp_args.batch
sources = xrd_cp_args.sources
chunks = xrd_cp_args... | 5,349,091 |
def merge_preclusters_ld(preclusters):
"""
Bundle together preclusters that share one LD snp
* [ Cluster ]
Returntype: [ Cluster ]
"""
clusters = list(preclusters)
for cluster in clusters:
chrom = cluster.gwas_snps[0].snp.chrom
start = min(gwas_snp.snp.pos for gwas_snp in cluster.gwas_snps)
end = ma... | 5,349,092 |
def cross_recurrence_matrix( xps, yps ):
"""Cross reccurence matrix.
Args:
xps (numpy.array):
yps (numpy.array):
Returns:
numpy.array : A 2D numpy array.
"""
return recurrence_matrix( xps, yps ) | 5,349,093 |
def define_panels(x, y, N=40):
"""
Discretizes the geometry into panels using 'cosine' method.
Parameters
----------
x: 1D array of floats
x-coordinate of the points defining the geometry.
y: 1D array of floats
y-coordinate of the points defining the geometry.
N: integer... | 5,349,094 |
def compile_for_llvm(function_name, def_string, optimization_level=-1,
globals_dict=None):
"""Compiles function_name, defined in def_string to be run through LLVM.
Compiles and runs def_string in a temporary namespace, pulls the
function named 'function_name' out of that namespace, opt... | 5,349,095 |
def setup():
"""
This just moves the initial setup-commands to the top for better readability
:return: -
"""
plugin.add_config("api_base", is_required=True)
plugin.add_config("api_key", is_required=True)
plugin.add_config("room_id", is_required=True)
plugin.add_config("series_tracking",... | 5,349,096 |
def setup_svm_classifier(training_data, y_training, testing_data, features, method="count", ngrams=(1,1)):
"""
Setup SVM classifier model using own implementation
Parameters
----------
training_data: Pandas dataframe
The dataframe containing the training data for the classifi... | 5,349,097 |
def buildHeaderString(keys):
"""
Use authentication keys to build a literal header string that will be
passed to the API with every call.
"""
headers = {
# Request headers
'participant-key': keys["participantKey"],
'Content-Type': 'application/json',
'Ocp-Apim-Subscription-Key': keys["subscrip... | 5,349,098 |
def parametrize_environment_file(metafunc):
"""
This param runs tests for every environment file in the template dir
"""
env_files = get_filenames_list(metafunc, [".env"])
metafunc.parametrize("env_file", env_files) | 5,349,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.