content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import logging from datetime import datetime def check_date(schedule, msg): """ Check with a regex the data as user input, can accept several formats """ match = REGEX_DATE.match(msg.content) if not match: schedule.custom_response = "Votre format de date est invalide." logging.info...
f7d9a31f063525d2a0c66c87fdcfccc53d21f28a
3,604,600
def choose_word(file_path, index): """ :param file_path: :param index: :return: tuple (num of words without duplicates, the word of the given index in the file """ file_input = open(file_path, "r") count_of_words = len(set(file_input.read().split(" "))) file_input.seek(0) lines = fil...
9c038574509918a4e91c316cde749dda322ef0e1
3,604,601
def getCommentsByThread(dbSession, tid): """gets all comments associated with a thread, ordered by time""" comments = dbSession.query(Comment).filter(Comment.thread_id == tid).order_by(Comment.time_created.desc()) if comments: return comments.all() return None
6a9c7e4f708cb68da0922c29154b0869cedff257
3,604,602
import json def get_l2_t_from_file(diffusion_file): """ :param diffusion_file: json file with diffusion results :return: The function takes from the file the experimental values of D and lifetime, It returns a list with values of time from 0 to lifetime. With D computes the respective values of l². ...
c284e39af1e15bd6adf236a52455da45aae22382
3,604,603
def generate_false_pertinents_replace(text, present, m, neighbors, n_best_co_occurrence, proba_change=0.5, forbidden=[], forbidden_tags=['PRP$'], forbidden_words=['be'], top_n=50, temperature=.4, pos=['NOUN', 'VERB', 'ADJ', 'ADV', 'ADP', 'DET'], use_proba=T...
3104877924b4dbbd8108b9ed64cc3feae398858c
3,604,604
import argparse def parse_args(): """ Parse input arguments """ parser = argparse.ArgumentParser(description='Convert Open Images annotations into MS Coco format') parser.add_argument('-p', '--predictions', dest='predictions', help='coco style prediction file (.json)', ...
931b397f964ec5e6de43a03bca10c88d9a0082d9
3,604,605
import os def get_env_token(): """ Get GitHub OAuth token from "GITHUB_TOKEN" environment variable. :return: GitHub OAuth token. """ token = None if "GITHUB_TOKEN" not in os.environ else os.environ["GITHUB_TOKEN"] return token
dcee0fcef76b5ccdef094ae7fc40212c633d37c5
3,604,606
def eigenfaces(X: ndarray, n_comp): """ Performs PCA to project faces in a reduced space. Parameters ---------- X: ndarray faces to project (shape: (n_samples, w*h)) n_comp: int number of principal components Returns ------- tuple proj_faces: the projected f...
0d5f76c1848c91128a5ae7d2d8357c756e313062
3,604,607
def assignment(G, weight="weight", resolution=1): """ Assign community partition to the graph by Louvain method""" if G.number_of_edges(): part = community.best_partition( G, weight=weight, resolution=resolution) modu = community.modularity(part, G) else: part = {n: n for...
f9b24cbf2ea1b1c1c512781a44a2204b0354d6f8
3,604,608
import select async def create_code(session: AsyncSession, longUrl: str): """Encodes a URL to a shortened URL. """ code = await generate_code() generate_count = 0 while generate_count < 10 and (await session.execute(select(models.LongToCode).where(models.LongToCode.code == code))).first(): ...
4476ab4e75767cb4c65ecd0cc953c49f99c39cf8
3,604,609
def load_train_data(): """ Loading the train data from data set :return: Training components """ # Data preparation for train and test raw_data_set = data_controller.load_data_file(FLAGS.positive_train_data_path, FLAGS.negative_train_data_path, ...
6696209e7ffdae8951c14462cd2345460506857e
3,604,610
def collect_trainable_variables(modules): """Collects all trainable variables of modules. Trainable variables included in multiple modules occur only once in the returned list. Args: modules: A (list of) instance of the subclasses of :class:`~texar.modules.ModuleBase`. Returns...
e478563a59cfd940138f2344747037280c1c7447
3,604,611
def _get_split_cnn_model(img_dim, n_channels, num_partitions, blocks_per_partition): """Creates a test model that is split into `num_partitions` smaller models.""" models = [tf.keras.Sequential() for _ in range(num_partitions)] models[0].add(layers.Input(shape=(img_dim, img_dim, n_channel...
f626bc31bd0392aa888ce99067611a5642207d14
3,604,612
def ccall_except_check(x): """ >>> ccall_except_check(41) 42 >>> ccall_except_check(-2) -1 >>> ccall_except_check(0) Traceback (most recent call last): ValueError """ if x == 0: raise ValueError return x+1
f4a877f63a189b39fea477af218438de2e6c2a78
3,604,613
from pathlib import Path import tokenize def convert_to_tracer(file, placeholder): """ Eats a filename of a text file. Normalizes and tokenizes the text. Converts it to tsv in the TRACER input format. Writes the tsv file. Depends on normalize(), save_abbreviations() and tokenize(...
90a4dc0acd9a051a77935a0907da07b4a6178f01
3,604,614
def loadSVMLightData(filename): """ Load a file containing train/test data following the svmlight input format. :param filename: The input data file :return: The tuple (ITEMS, COMMENTS), where ITEMS is a list of tuples (TARGET, [(FEATURE,VALUE)], INFO) and COMMENTS is a list of comment line...
21ead993836806e27bee6846f23643051b2c3230
3,604,615
import glob import os def find_file(search): """Find the most recent file matching a glob string. Parameters ---------- search : str Glob string to search. Returns ------- filename : str Most recently modified file that matches the search. """ files = glob.glob(s...
6fa63bc42b47dd7aead27b10d01424d4c2618e84
3,604,616
import os def _GetDockerfileCreator(info, config_cleanup=None): """Returns a function to create a dockerfile if the user doesn't have one. Args: info: (googlecloudsdk.api_lib.app.yaml_parsing.ServiceYamlInfo) The service config. config_cleanup: (callable() or None) If a temporary Dockerfile has alr...
cd4da32f93c9c048c8f3635961d86ccf91bddc2d
3,604,617
import scipy def get_rotation_matrix(a,b,c,Order): """ [R, Q] = GetRotationMatrix(a,b,c,Order) Computes a rotation matrix R between the coefficients of Spherical Harmonic sound field descriptions before and after rotation. Note that R is block diagonal, since rotations only involve coefficien...
8b360a0fd19e90e6babe247665950b3731a01865
3,604,618
import json import requests def publish(topic, data): """ Push an event to the Hermes. Args: topic: name of the topic data: data to push Returns: message id from Hermes """ # TODO: try-except if not HERMES_SETTINGS.ENABLED: logger.debug('Hermes integration...
4091602d27ffd805e08f54beaf09b4f0360055ad
3,604,619
def packet_write(dxl_id, reg0, *register_values): """Create an instruction packet to write data in the DXL control table. Args: dxl_id: An integer representing the DXL ID number reg0: An integer representing the register index in the control table *register_values: A list containing inte...
991fe6a983858bb2febc9b8f1d8008e50f2560f2
3,604,620
def WbDiscover( network, forTime = 5 ): """ This function looks for webbricks on the provided network. The network parameter is in the form nn.nn.nn.nn/bits and identifies a subnet accessible to the current computer. The result is a list of dictionaries where there is a dictionary entry for each ...
64df27860a70e36c52f262ade1256c9723324804
3,604,621
def num_fragmentations(df, obj_frequencies): """Total number of switches from tracked to not tracked.""" fra = 0 for o in obj_frequencies.index: # Find first and last time object was not missed (track span). Then count # the number switches from NOT MISS to MISS state. dfo = df[df.OI...
5d7bcebfeb486499eb8c102789db6cf9141f9247
3,604,622
def canon_did(uri: str) -> str: """ Convert a URI into a DID if need be, left-stripping 'did:mydata:' if present. Args: uri: input URI or DID Raises: ValueError: for invalid input. """ if ok_did(uri): return uri if uri.startswith("did:mydata:"): mydata_di...
62a5363759c88efeba5283bcce13710e1b2b23a8
3,604,623
def sort_tss_tts_files(tss, tts, genome_size): """ Sort the tss and tts files and combine them into a TS file # IDEA: create a function where you sort only and another one to merge and clean the TS file. """ # combine the two file to keep the lines consistents/together ts = pd.me...
d76c19e3fdb449f5892c8ba502ea8c054ac83181
3,604,624
def input_prompt(prompt): """ Get user input :param prompt: the prompt to display to the user """ return input(prompt)
b780278c37f048d1ea61f36af0947b683c5f9b9c
3,604,625
def retail_score(flu_space, access_variables): """ Scores/weights for retail development. """ # access columns prox_pers = 'persons_to_within15_OpAuto' prox_jobs = 'sb_jobs_to_within15_OpAuto' prox_retail_jobs = 'sb_jobs_in_retl_to_within15_OpAuto' prox_retail_space = 'job_spaces_in_ret...
95e47991d5cbeaaf4db0e2b99e95a146813a17e1
3,604,626
from peachpy.x86_64.registers import Register, MaskedRegister from peachpy.x86_64.pseudo import Label from peachpy.x86_64.function import LocalVariable from peachpy.literal import Constant from peachpy import Argument from peachpy.util import is_int, is_int64 from copy import copy, deepcopy from copy import copy, deepc...
7c727f0965caad6c37df68d90e2e0d618374be5f
3,604,627
def virtualaddress(target, **kwds): """Returns a pointer to /target/ where value is a va""" kwds.setdefault('__name__', 'virtualaddress') if 'type' in kwds: return dyn.opointer(target, CalculateRelativeAddress, kwds.pop('type'), **kwds) return dyn.opointer(target, CalculateRelativeAddress, **kwd...
d1c6082e897bf8737aae58cf473e4ae73da93e88
3,604,628
def safeintorbignumber(value): """safely converts value to integer or 10M""" try: return int(value) except ValueError: return 10000000
de665dc11ba27c6846412b706cf833e46dc26758
3,604,629
import numpy import math def sigmamix(pfile, j, a, b, r1 , r2 = None): """returns sigma corresponding to r1 and r2 radius for mixed window. w1(a) corresponds to r1, w2(b) corresponds r2""" k, p = numpy.loadtxt(pfile, unpack = True) if r2 is None: r2 = r1 if a == "T": w1 ...
103fb8d0102b57f0eebde953fc6db8cc7996d4ed
3,604,630
import requests import re import json def get_figshare_article(article_id): """ Given a figshare article id, return a JSON object containing the article metadata :param article_id: :return: JSON object containing Figshare metadata """ version = re.compile('v[0-9]*') article_result = reques...
375bbb36226f002e8a7c85b8e2b1a28f13f52443
3,604,631
def isNumber(s): """ Tests whether an input is a number Parameters ---------- s : string or a number Any string or number which needs to be type-checked as a number Returns ------- isNum : Bool Returns True if 's' can be converted to a float Returns False if con...
bd1bae27814ddca22c39d6411df3581e8116c324
3,604,632
import os def _validate_ml_id(app_id, run_id): """Validates if there was an experiment run previously from the same app id but from a different experiment (e.g. hops-util-py vs. maggy) module. """ try: prev_ml_id = os.environ["ML_ID"] except KeyError: return app_id, run_id prev...
f415c0f03f16a0db108a649682182c8b81219f0e
3,604,633
from typing import Callable from typing import Optional def get_authenticated_user_data( handler: AuthenticationHandler, username: str, password: str, password_checker: Callable[[str, str], bool] ) -> Optional[UserAuthData]: """Get user data if the authentication credentials match.""" user_dat...
279150caea1484b6f84fe71c08ea1e4b0405bdf8
3,604,634
from typing import List def get_ss_for_one_toad(name: str, variable: List[str]): """Get small series plot for one specific toad. :param name: The name of the desired toad. :param variable: Variable of interest. :return: Two plots, the kinematic and force plate small series. """ # Get the proc...
f5f1c7b4a39198e7997d5ce5393a8be02de2735b
3,604,635
def generate_road_map(sample_x, sample_y, rr, obstacle_kd_tree, height=0): """ Road map generation of the free workspace. Returned graph is wholly connected. Inputs: sample_x: [m] x positions of sampled points sample_y: [m] y positions of sampled points rr: Robot Radius[m] ob...
61043a2bea05c08d3db72d49c795143e0862a7ae
3,604,636
import cv2 def _process_contours(image, contours, hierarchy, callback, index=0, size_filter=True): """Traverse a hierachy of contours (contours containing contours) and returns bounding boxes of the smallest possible objects that still remain of interest. Parameters --------...
c4b1b88bfa97caf12fef7229d967a2b0da0eef02
3,604,637
def svn_fs_set_access(fs, access_ctx): """svn_fs_set_access(svn_fs_t * fs, svn_fs_access_t * access_ctx) -> svn_error_t""" return _fs.svn_fs_set_access(fs, access_ctx)
8eef1e5a46fbbdcc5ccbbf3140d6b64a86d8a8f1
3,604,638
def rescore_problem(entry_id, xmodule_instance_args): """Rescores a problem in a course, for all students or one specific student. `entry_id` is the id value of the InstructorTask entry that corresponds to this task. The entry contains the `course_id` that identifies the course, as well as the `task_in...
f9c1005793d38a341e87e6d129e28c300b0be498
3,604,639
def KeplerH(z, m, grav_const=1): """ with shapes (bs,2nd)""" bs, D = z.shape # of ODE dims, 2*num_particles*space_dim q = z[:, : D // 2].reshape(*m.shape, -1) p = z[:, D // 2 :].reshape(*m.shape, -1) potential_energy = KeplerV(q, m, grav_const=grav_const) kinetic_energy = EuclideanK(p, m) a...
160e4bcc6be3659265a02af15ac7e2553a771c45
3,604,640
def dGElnorm(w: Wilson, El): """Normalized distribution 1D El""" return tauBp / Btaul * dGEl(w, El)
df23eeb16f09544e09a9bebdc579afe95d88168d
3,604,641
import re def convert_to_utc(timestamp, timezone, printtz=None): """ Convert to UTC from timezone :param1 timestamp: timestamp in ISO format or YYYY-MM-DD HH24:MI:SS :param2: timezone: src timezone, :param3: printtz: return string with timezone information return: converted timestamp """ ...
4df0661ab8d5b2460a9b55a6aa664fa8592a37a8
3,604,642
def generate_log_filename(): """ Return a timestamped log filename """ return "LOG_"+strftime("(%Y-%m-%d)_%H-%M-%S", gmtime())+".txt"
507b8a1ca128fc19566f41d32437bdbeacb30b93
3,604,643
def _input_file_to_arg(input_file): """Converts a File object to string for --input_file argument to wheelmaker""" return "%s;%s" % (_path_inside_wheel(input_file), input_file.path)
a5abe5324cebdac6cd9fdd1a69c4ff7980ddc997
3,604,644
def Spurious_Fourier_train(sample): """ Spurious Fourier model hparam definition Args: sample (bool): If ''True'', hyper parameters are gonna be sampled randomly according to their given distributions. Defaults to ''False'' where the default value is chosen. """ if sample: return {...
1d165c405476e690d785efd6764cea618cc9244d
3,604,645
from typing import List from typing import Optional import types def rnn_step_with_state( model, initial_state: List[tf.Tensor], modify_state: bool, step_args=None, step_kwargs=None, state_scope_name: Optional[str] = None) -> types.ForwardFunctionReturns: """Step through RNN with persistent ...
c42af7584239fc8bed0952fd34089ad360ff4a32
3,604,646
from io import StringIO def convert_vector_drawable_stream(input_stream, color_map_stream=None) -> str: """ Convert Android Drawable XML to SVG with use of the optional color map. :param input_stream: A binary stream containing Android vector drawable :param color_map_stream: An optional color schema...
6045503884178507c907593c40c1850568469f6f
3,604,647
from typing import Sequence from typing import Optional def tensor_buffer_to_tensor( x: oneflow._oneflow_internal.BlobDesc, dtype: flow.dtype, instance_shape: Sequence[int], name: Optional[str] = None, ) -> oneflow._oneflow_internal.BlobDesc: """This operator converts the Blob's type from TensorBu...
4cf0dc4c55db1014e2327e8e64fc2bae5aa2b912
3,604,648
def read_epi_params(item_basename): """Read all the necessary EPI parameters from text files with the given basename. Args: item_basename (str): The basename for all the files we need to read. In particular the following files should exist: - basename + '.read_out_time.txt' ...
3af788073607df214c447f2b87606b2d3e1638fd
3,604,649
import select def api_private_asn_by_month(): """Network count by month --- responses: '200': description: [{"date":"2018-08-31","value":4411}, ... ] """ # OLAP-use-case cols = [sql.text("networks_by_month"), sql.text("month")] q = select(cols).select_from(sql.table("global_b...
34930770818d19733505a8c9162934f0559cb735
3,604,650
import masci_tools from masci_tools.util.parse_tasks_decorators import register_migration from masci_tools.util.parse_tasks import ParseTasks from pathlib import Path import os import shutil def fake_schemas_and_test_files(tmp_path): """ Helper fixture for add fleur schema tests Creates a Schema form the...
c04b0614006e2d12cbf074e6f5b3a69be4aff99f
3,604,651
import logging def remove_duplicate_called_graphs(comp): """Deduplicates called graphs for a subset of TFF AST constructs. Args: comp: Instance of `building_blocks.ComputationBuildingBlock` whose called graphs we wish to deduplicate, according to `tree_analysis.trees_equal`. For `comp` to be elig...
78582e96f78093c780a8f63e2c3190cdf9fd2271
3,604,652
import inspect def _commands(cli): """Extracts all public functions from `cli` Args: cli (module): where commands are executed from Returns: list of function: public functions sorted alphabetically """ res = [] for n, t in inspect.getmembers(cli): if _is_command(t, cl...
a6aaa462d5e414803df0838bb04380960c92052f
3,604,653
def from_tensor(tensor_to_convert): """Convert a tensor of tfq primitives back to Python objects. Convert a tensor representing `cirq.PauliSum` or `cirq.Circuit` objects back to Python objects. >>> my_qubits = cirq.GridQubit.rect(1, 2) >>> my_circuits = [cirq.Circuit(cirq.X(my_qubits[0])), .....
8a96d2a8e695decc7ae245fdce74f28bcf2062aa
3,604,654
def filled_int(val, length): """ Takes a value and returns a zero padded representation of the integer component. :param val: The original value. :param length: Minimum length of the returned string :return: Zero-padded integer representation (if possible) of string. Original string used if integer...
55da47570ab03c5964f3af167bb8a4f27656a660
3,604,655
def get_dut_links_remote(dut, remote_dut, local_interface): """ API to get remote port using dut, remote dut and local interface Author: Chaitanya Vella (chaitanya-vella.kumar@broadcom.com) :param dut: :param remote_dut: :param local_interface: :return: """ if "PortChannel" in local_...
f5de8d04312561d3992ed7b1091867b1b982e020
3,604,656
def connect(host="localhost", user=None, password="", db=None, port=3306, unix_socket=None, charset='', sql_mode=None, read_default_file=None, conv=decoders, use_unicode=None, client_flag=0, cursorclass=Cursor, init_command=None, connect_timeout=None, read_def...
4d843d70b555ae20d3526f345761b047984116df
3,604,657
import requests def get_config(): """Return a baseURI and session""" s = requests.Session() s.headers={'Content-Type': 'application/json'} print("\nEnter the information to connect to your Elasticsearch cluster.\n") ipHost = input("Hostname or IP: ") port = input_int("Port") auth = input...
36c6511903da31c1e910f497c54a8c1f60fd6c51
3,604,658
import torch def sph2cart_unit(u): """ :param u: N x 2 in [azimuth, inclination] :return: """ """ :param phi: azimuth, i.e., angle between x-axis and xy proj of vector r * sin(theta) :param theta: inclination, i.e., angle between vector and z-axis :return: [x, y, z] """ phi, t...
59b119dbb629a98057d051a1370385f450d3fae3
3,604,659
from typing import Callable from typing import Any from typing import Tuple def _jax_encode( message: jnp.ndarray, cdf_fun: Callable, init_cdf_state: Any, buffer_oversize: float ) -> Tuple[ndarray, int]: """JAX encoding backend function.""" # array initialization idx = jnp.array(0, jnp.int32) bit_...
2cad97cd3e98dd8809a5aa1d585374a98d373f3e
3,604,660
def coroutine(func): """ Decorator that allows to forget about the first call of a coroutine .next() method or .send(None) This call is done inside the decorator :param func: the coroutine to decorate """ def start(*args,**kwargs): cr = func(*args,**kwargs) next(cr) r...
1ab7a10c369f4882541ee81614e94d31f7acc528
3,604,661
def _scale_enum(anchor, scales): """ 生成3个不同大小的矩阵 根据给定的anchor(box), 枚举其所有可能scales的anchors(boxes) """ w, h, x_ctr, y_ctr = _whctrs(anchor) # print(w) ws = w * scales hs = h * scales anchors = _mkanchors(ws, hs, x_ctr, y_ctr) return anchors
2a3f567fa64b187a7510be97cdc8f259f9a255ad
3,604,662
def FBP_grain( g, flt, ymin, ystep, omegastep, number_y_scans ): """ Reconstruct a 2d grain shape from diffraction data using Filtered-Back-projection. """ # Measured relevant data for the considered grain omega = flt.omega[ g.mask ].copy() dty = flt.dty[g.mask].copy() sum_intensity = flt.s...
13cc9f66f03cb44fa15ec4f56de8ba9a898ba070
3,604,663
import sys def find_best_point(point, point_candidates, max_distance=sys.maxsize): """Find best point by performing L2 norm (eucledian distance) calculation""" best = None for p in point_candidates: dist = np.linalg.norm(point - p) if dist <= max_distance: max_distance = dist ...
f622bd9f4e0764923afd19077256579c38acc22f
3,604,664
def v7_group_by(iterable, key_func=None): """Group iterable by key_func. PEP8, the Python style guide, says that we should never write "key_func = lamdba x: x". Specifically it says that if we're using lambda to make a function and then assign it to a variable, we should use a def statement to mak...
5a33c8b518b33806ff64694e21601264739ee658
3,604,665
import pickle def _load_batch(fpath, label_key='labels'): """Internal utility for parsing CIFAR data. Arguments: fpath: path the file to parse. label_key: key for label data in the retrieve dictionary. Returns: A tuple `(data, labels)`. """ with open(fpath, 'rb') as f: d = ...
4311566594ac6f0f6c9573bdb3ccf162205991ae
3,604,666
def calculateHandlen(hand): """ Returns the length (number of letters) in the current hand. hand: dictionary (string int) returns: integer """ result = 0 for item in hand.keys(): result += hand[item] return result
11a5161225a5cd60a00812435b00ca407338846a
3,604,667
from datetime import datetime def ajax_audit(): """ 报价审核 :return: """ ajax_success_msg = AJAX_SUCCESS_MSG.copy() ajax_failure_msg = AJAX_FAILURE_MSG.copy() # 检查审核权限 if not permission_quotation_section_audit.can(): ext_msg = _('Permission Denied') ajax_failure_msg['msg'...
8dabf1b461cf89bfe9eb42ef72466bdd4fc43c00
3,604,668
def get_welcome_response(): """ If we wanted to initialize the session to have some attributes we could add those here """ session_attributes = {} card_title = "Welcome" speech_output = "Johnny Pi is at your command, " \ "what would you like him to do?" # If the user eit...
b11c0c1a2ae63e7c3a0e3247a98075f1cc884f8e
3,604,669
def validate_entity_predicate_structure(predicate_file: dict) -> bool: """ validate predicate, entity, and entity predicate link file structure assumed structure { "entity/predicate-1": {"another-simple-id-no-0": {"0": "simple-id-no-1"}}, "entity/predicate-2": { "another-simple/c...
3241fbe68d1080a3bd967b45f48c09ec9a3cb83f
3,604,670
def _make_rnn_cell_fn(units, cell_type=_SIMPLE_RNN_KEY): """Convenience function to create `rnn_cell_fn` for canned RNN Estimators. Args: units: Iterable of integer number of hidden units per RNN layer. cell_type: A class producing a RNN cell or a string specifying the cell type. Supported strings ar...
da8c643abb2a284145997e0662f24c5092c93fbd
3,604,671
def pkcs1Digest(data, messageLength): """ Create a message digest using the SHA1 hash algorithm according to the PKCS#1 standard. @type data: C{str} @type messageLength: C{str} """ digest = sha1(data).digest() return pkcs1Pad(ID_SHA1+digest, messageLength)
6f649c8359e40fd5d7c2aa4baebbac2918dcfbad
3,604,672
def distance_shower_camera_center(shower, tel): """ Compute the distance between all shower particles and the telescope camera center Parameters ---------- shower: class shower tel: class telescope Returns ------- numpy array of the distances. size = number of particles in the showe...
e3e953e78c0274af5962e25db4e635ffef1151c7
3,604,673
import os def manual_args(args: Namespace) -> Namespace: """function only called if no arguments have been passed to the script - mostly used for dev/debugging""" # trainer/logging args args.experiment_name = "fw_bl_m1" args.tracking_uri = os.getenv("TRACKING_URI", default="http://localhost:5000") ...
cb36edeffdc0417720a39bbf62743259438e27ff
3,604,674
def _time_ago(t: int) -> str: """Get time ago information from duration.""" if t < 3600: return f'{int(t/ 60)} minutes ago' else: return f'{int(t / 3600)} hours and {int(t/60) - int(int(t/60)/60)*60} minutes ago'
2451197f458df9b7c2ac6f5e9b1487b7e6f8211d
3,604,675
import json def fixture_building_id(): """Return Fixture Building ID from Payload.""" return json.loads(carson_load_fixture("carson_me.json"))["data"]["properties"][0][ "id" ]
a7f550203d0e5e8104a3a876036e3a757a562a3c
3,604,676
def make_shell_context(): """ Create a python CLI. return:Default import object type:'Dict' """ return dict(app=main.app, db=models.db, User=models.User,Post=models.Post)
3d11895133df5bf8f495be77fd140251cfa31166
3,604,677
def preprocess(text, min_token_length = 0, join = False): """ Method for preprocessing text Args: text: string of text min_token_length: integer value indicating min number of characters in a token join: boolean indicating if function should join the list of tokens into the str...
740fc73f7712aa630bbf0d79765fc574d1642fa8
3,604,678
def create_model(image_height, image_width, loss, optimizer): """Creates the cat face locator model. Args: image_height: The height of the input images. image_width: The width of the input images. loss: Keras loss function (name or object), e.g. "mse". optimizer: Keras optimizer...
764abfc68511c818697bd4e2f637da4d5176f348
3,604,679
import os import fnmatch def isfile_wo_ext(path): """Checks that a file exists, or exists with any extension""" path_dir = os.path.dirname(path) path_fn = os.path.basename(path) return os.path.isfile(path) or len(fnmatch.filter(os.listdir(path_dir), path_fn + '.*')) > 0
e48aead6545faf36224114ce88229d8a39b0c756
3,604,680
def nli_url(filename='urls.ini', section='URLS'): """ The config file for URLS contains sites of interest to my research """ parser = ConfigParser() parser.read(filename) urls = {} if parser.has_section(section): links = parser.items(section) for link in links: ...
0e4c8a9379d92d21c2473dd05c79a99442d54a75
3,604,681
def make_matrix_coord_map( dx, dy, serpentine=True, offset=0, rotation=0, y_flip=False): """Helper method to generate X,Y coordinate maps for strips""" result = [] for y in range(dy): if not serpentine or y % 2 == 0: result.append([(dx * y) + x + offset for x in range(dx)]) ...
b18a7bcbfae42e2cdbe2f364e6b96947b2354d32
3,604,682
import io import re from pkg_resources import resource_filename from ..helper import complete_path from typing import TextIO import os def parse_use_source(source: str) -> TextIO: """ Parse config source with converting all sources to TextIO :param source: config source :return: text io """ ...
faeea801f5b76677c7aa060b5e654b78a86bb98c
3,604,683
def categories_to_json(categories): """ categories_to_json converts categories SQLAlchemy object to json object works by simply looping over collection of objects and manually mapping each Object key to a native Python dict """ main = {} main['categories'] = [] for cat in categories: ...
34702fb12d1398395826bae71d39edd558199498
3,604,684
def call_prob(mut_cluster, r1_mappos, r2_mappos, r1_qual, r2_qual, mut_rate, base, cut_off, adjustthred): """ """ pos_prob = {"m": [], "prob": [], "read": []} for c in mut_cluster.keys(): mutcall = mut_cluster[c] # each mutcall is a df with columns: # m_r1,read,pos,ref_r1,alt_...
fcb44b438d40fdec681ec7ed03d9d22cd1fcb199
3,604,685
from typing import Sequence def get_padding_values(input_dataset_types, label_padding=-100): """Get a tensor of padding values fitting input_dataset_types. Here we pad everything with 0. and the labels with `label_padding`. This allows us to be able to recognize them later during the evaluation, even ...
b1ecf5f545f770274a4fef9eb1c2ff7c8357f817
3,604,686
def median(data, scheme=1): """Returns the median (middle) value of an iterable of numbers. >>> median([3.0, 5.0, 2.0]) 3.0 The median is the middle data point in a sorted sequence of values, and is commonly used as an average or estimate of central tendency. It is more robust than the mean fo...
c9db3f14fab717ea5cebdd2b6918db14493033f8
3,604,687
from typing import Sequence from typing import Callable from typing import Tuple from typing import Counter def _bleu_score_update( preds: Sequence[str], target: Sequence[Sequence[str]], numerator: Tensor, denominator: Tensor, preds_len: Tensor, target_len: Tensor, n_gram: int = 4, tok...
de2d1990f0f58b8b3b9590312e278464119e9198
3,604,688
def resolve_sky_coords_frame(frame, observer=None, time_obs=None): """ Return frame with appropriate attributes set for `observer` at `time_obs`. """ if isinstance(frame, str): frame_cls = _get_frame_class(frame) elif isinstance(frame, BaseCoordinateFrame): frame_cls = frame.__class_...
70674a91806d9d397574129d0f4dc1eac54d3ed4
3,604,689
def accuracy_score(df, col_true=None, col_pred=None, normalize=True): """ Compute accuracy of a predicted data set. Note that this method will trigger the defined flow to execute. :param df: predicted data frame :type df: DataFrame :param col_true: column name of true label :type col_true:...
470abd7d94ff3a49dd64cacfb3afb877c7aa73df
3,604,690
def axis_aligned_iou_loss(pred, target): """Calculate the IoU loss (1-IoU) of two set of axis aligned bounding boxes. Note that predictions and targets are one-to-one corresponded. Args: pred (torch.Tensor): Bbox predictions with shape [..., 3]. target (torch.Tensor): Bbox targets (gt) with...
66762cda10cde427d3b1ce5e1d1da89da28383f4
3,604,691
import ctypes def despeckle(input_list_data, bad, a_speckle, dgi_clip_gate=None, boundary_mask=None): """ Performs a despeckle operation on a list of data (a single ray) Args: input_list_data: A list containing float data, bad: A float that represents a missing/invalid dat...
36abc83ecc6e077a2d710925744034e12880749f
3,604,692
def velocity(estimate, actual, times=60): """Calculate velocity. >>> velocity(2, 160, times=60) 0.75 >>> velocity(3, 160, times=60) 1.125 >>> velocity(3, 160, times=80) 1.5 """ return (estimate*times)/(actual*1.)
ffdb12c7aea05f9fc8aa9e354e8db2320cbf431a
3,604,693
def _GetCurrentInjectionInfo(): """Returns a dict contains the required injections' information. This method is used to provide information for filling injection and calculating scope dependency. """ if not hasattr(_DATA, 'injection_scope_map'): injection_scope_map = {} for idx, scope in enumerate(re...
14cd486ad011bcbabd11d9ae24bac1e32ceec7f7
3,604,694
import importlib def import_from_string(val, setting_name): """ Attempt to import a class from a string representation. """ try: parts = val.split('.') module_path, class_name = '.'.join(parts[:-1]), parts[-1] module = importlib.import_module(module_path) return getattr...
71af0db959d089eb92baf885c4580fa04b6b8b87
3,604,695
def register(): """ Registers a user in the database. Before registering, checks if the username is not already in the database. The username is used to show who reviewed a book, so username has to be unique. """ if request.method == "POST": user_exists = mongo.db.users.find_one( ...
addce07f91c74c4c39ce62870974ce8e378618f6
3,604,696
def get_all_rosters(season_id_list=None, streamlit=False): """returns roster of all players across a given list of seasons""" if season_id_list is None: season_id_list = [20152016, 20162017, 20172018, 20182019] teams_df = get_teams() team_ids = teams_df.loc[:, 'id'] full_roster_df = pd.DataF...
8d0c3353b6fcb45072bcea7724b7827d6294c015
3,604,697
def my_gaussian(x_points, mu, sigma): """ Returns normalized Gaussian estimated at points `x_points`, with parameters: mean `mu` and std `sigma` Args: x_points (numpy array of floats): points at which the gaussian is evaluated mu (scalar): ...
aa10bdcef788c534405baca7ab0a868a5a9502ef
3,604,698
def _resolve(exe): """Resolve alias, raise exception if not found. :returns: ``list`` -- Argv to pass execv """ resolved = resolve_argv(exe) if not resolved: raise CommandAliasError('Unable to resolve: {}'.format(exe)) return resolved
70050ca7551e7d72edfdaa3b99ff83ce93911ca8
3,604,699