content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def create_attribute(representation_uuid, attribute_name): """create a representation of an attribute of a representation""" try: uuid = get_bus().create_attribute(representation_uuid, attribute_name, public=True) return JsonResponse({'type': 'uuid', 'uuid': uuid}) except Exception as except...
f1ddfbc634b459a7e3f179125fd323beb871957d
3,640,200
from typing import Optional import subprocess import warnings def get_current_git_hash(raise_on_error: bool = False) -> Optional[str]: """ Return git hash of the latest commit Parameters ---------- raise_on_error: bool, optional If False (default), will return None, when it fails to obtain co...
7a17dc7e0574b7f3da91f009714226f855723427
3,640,201
def check_shift(start_time, end_time, final_minute, starting_minute, record): """ Função que verifica o turno da chamada e calcula o valor da ligação :param start_time: :param end_time: :param final_minute: :param starting_minute: :return value: """ nem_start_time = start_time + (st...
666883348347e8408b087ac63acd8608ff589a1c
3,640,202
import hashlib def s3_avatar_represent(user_id, tablename="auth_user", gravatar=False, **attr): """ Represent a User as their profile picture or Gravatar @param tablename: either "auth_user" or "pr_person" depending on which table the 'user_id' refers to @param a...
2c537a57a5d20ed8b4329338883f209fa9678fc4
3,640,203
from typing import Dict from typing import List import pathlib import json def json_loader(path_to_json_file: str) -> Dict[str, List[str]]: """Reads a JSON file and converts its content in a dictionary. Parameters ---------- path_to_json_file: str The path to the JSON file. Returns -...
d3f26504078e72e1522981a4d8ca5b60c3b8cf23
3,640,204
def get_region_solution_attribute(data, region_id, attribute, func, intervention): """Extract region solution attribute""" regions = data.get('NEMSPDCaseFile').get('NemSpdOutputs').get('RegionSolution') for i in regions: if (i['@RegionID'] == region_id) and (i['@Intervention'] == intervention): ...
0dc26e54ae5f16f8b3158ec00a5dc0bc58776408
3,640,205
def conv1x1(in_planes: int, out_planes: int) -> nn.Conv2d: """1x1 convolution""" return nn.Conv2d(in_planes, out_planes, kernel_size=1, bias=True)
2c8fcb8e04084ce35a2ae595b457fdf68fd27723
3,640,206
def make_ratio_map(amap, bmap): """Get the ratio of two PISA 2 style maps (amap/bmap) and return as another PISA 2 style map.""" validate_maps(amap, bmap) with np.errstate(divide='ignore', invalid='ignore'): result = {'ebins': amap['ebins'], 'czbins': amap['czbins'], ...
9497ddadd6d983b3094107aceadbdc1e2f1fb0a7
3,640,207
from typing import Collection from typing import Mapping from typing import Sequence import math def _compose_duration( components_tags: Collection[Tags]) -> Mapping[str, Sequence[str]]: """Returns summed duration tags.""" duration_seconds_values = [ component_tags.one_or_none(DURATION_SECONDS...
99bebed06628627211a117c738d89790d11adc1b
3,640,208
def feature_spatial(fslDir, tempDir, aromaDir, melIC): """ This function extracts the spatial feature scores. For each IC it determines the fraction of the mixture modeled thresholded Z-maps respecitvely located within the CSF or at the brain edges, using predefined standardized masks. Parameters ------------------...
fb515a61bd81533b3b79f9cd500ad5b77723b527
3,640,209
from datetime import datetime def str_to_date(date_str, fmt=DATE_STR_FMT): """Convert string date to datetime object.""" return datetime.datetime.strptime(date_str, fmt).date()
102f384b479b217259c9bbfe36c8b66909daee50
3,640,210
import time import json def create_elasticsearch_domain(name, account_id, boto_session, lambda_role, cidr): """ Create Elastic Search Domain """ boto_elasticsearch = boto_session.client('es') total_time = 0 resource = "arn:aws:es:ap-southeast-2:{0}:domain/{1}/*".format(account_id, name) ...
5e33bd1454a2b3d1ce3bc1cc181b44497ce6035a
3,640,211
def get_user(email): """ param: username returns User instance with user data, the MySQL error handle by the try-except senteces """ result = {} connection = _connect_to_db() try: with connection.cursor() as cursor: row_count = 0 e = 'none' # Read...
f05a59dc95ade5157d09d26a7d899fd9b19d3526
3,640,212
def index(request): """ A example of Function-based view method: get request: None response: type: html """ return HttpResponse("Hello, world. You're at the polls index.")
1fe400e5f08728eef5834268d219a3f109325114
3,640,213
import requests def make_https_request(logger, url, jobs_manager, download=False, timeout_attempt=0): """ Utility function for making HTTPs requests. """ try: req = requests_retry_session().get(url, timeout=120) req.raise_for_status() except requests.exceptions.ConnectionError as c...
825d1d79dc44e571fed4437fb1fbebc60bfef669
3,640,214
def info(): """ Displays on the website of the page. @TODO - Add index.html for the site of Ubik. :return: response for each get request on '/'. """ return about_response()
1460d166c2cde36e931803b24fd235c1e100aa0d
3,640,215
def falshsort(): """ Do from here: https://en.wikipedia.org/wiki/Flashsort :return: None """ return None
359dc737a6611ebd6a73dd7761a6ade97b44b7ab
3,640,216
import random def random_word(text, label, label_map, tokenizer, sel_prob): """ Masking some random tokens for Language Model task with probabilities as in the original BERT paper. :param tokens: list of str, tokenized sentence. :param tokenizer: Tokenizer, object used for tokenization (we need it's v...
46e7ac7d9fd0d82bbfef97a9a88efd0599bbc3b3
3,640,217
def ITERATIVETEST_Error_Of_Input_Parameter_inZSubsample(): """Tests occurrence of an error because of an invalid input value provided at field "inZSubsample".""" Logging.infoHTML( "<b>ToDo: Add more \"TestData\" objects to maximize variations!</b>" ) testDataVariations = { "Invalid_Variation_1" : __getInvalid...
8de38b2ceaf1312442f170a75f96cec7ec9fdd7b
3,640,218
import numpy def _match_storm_objects(first_prediction_dict, second_prediction_dict, top_match_dir_name): """Matches storm objects between first and second prediction files. F = number of storm objects in first prediction file :param first_prediction_dict: Dictionary returned by...
9c3bc60e99dc3d07cbd661b7187833e26f18d6f7
3,640,219
from typing import Optional from typing import cast def get_default_branch(base_url: str, auth: Optional[AuthBase], ssl_verify: bool = True) -> dict: """Fetch a reference. :param base_url: base Nessie url :param auth: Authentication settings :param ssl_verify: ignore ssl errors if False :return: ...
e2ac587705c82c95edeb415b79ca15746e9e9b78
3,640,220
import csv def make_source_thesaurus(source_thesaurus=SOURCE_THESAURUS_FILE): """ Get dict mapping country name to `SourceObject` for the country. Parameters ---------- source_thesaurus : str Filepath for the source thesaurus data. Returns ------- Dict of {"Country": SourceObject} pairs. """ with open(s...
43109eb3c9f9dedccae5bf692abebb0d66d09f7f
3,640,221
import re def extract_filter(s): """Extracts a filter from str `s` Parameters ---------- s : str * A str that may or may not have a filter identified by ', that HUMAN VALUE' Returns ------- s : str * str `s` without the parsed_filter included parsed_filter : dict ...
2a8dad70429fdc6295a44794f0c2ac6f19150f31
3,640,222
from typing import Tuple from typing import Union def sigmoid( x, sigmoid_type: str = "tanh", normalization_range: Tuple[Union[float, int], Union[float, int]] = (0, 1) ): """ A sigmoid function. From Wikipedia (https://en.wikipedia.org/wiki/Sigmoid_function): A sigmoid function...
b9d660d20f7e398a2e57ad0b907ab52c4a88cc36
3,640,223
def interp(x, x1, y1, x2, y2): """Find a point along a line""" return ((x2 - x) * y1 + (x - x1) * y2) / (x2 - x1)
3af4575c017a32619a5bb2866a7faea5ff5c760d
3,640,224
def msm_distance_measure_getter(X): """ generate the msm distance measure :param X: dataset to derive parameter ranges from :return: distance measure and parameter range dictionary """ n_dimensions = 1 # todo use other dimensions return { "distance_measure": [cython_wrapper(msm_dist...
1185658474f3a2b9bc17be67c665bdd0a211dce7
3,640,225
def gen_cpmfgp_test_data_from_config_file(config_file_name, raw_func, num_tr_data, num_te_data): """ Generates datasets for CP Multi-fidelity GP fitting. """ # Generate data def _generate_data(_proc_func, _config, _num_data): """ Generates data. """ ZX_proc = sample_from_config_space(_config, _num_data)...
c6efaf34601f5b02153fca3ea0926115d1adb918
3,640,226
def csv_to_postgres(engine, file: str, table_name: str): """ Given a *.csv filepath, create a populated table in a database :param engine: SQLAlchemy connection/engine for the target database :param file: Full filepath of the *.csv file :param table_name: ...
e8a913a32a3b0f7d9d617fa000f0b232e9824736
3,640,227
def _custom_padd(a, min_power_of_2=1024, min_zero_padd=50, zero_padd_ratio=0.5): """ Private helper to make a zeros-mirror-zeros padd to the next power of two of a. Parameters ---------- arrays : np.ndarray, array to padd. min_power_of_2 : int (default=512), mi...
eb7f9d675113b8f53558d911462209c2f72c3ce3
3,640,228
def encode_multipart_formdata(fields, files): """ Encode multipart data to be used in data import adapted from: http://code.activestate.com/recipes/146306/ :param fields: sequence of (name, value) elements for regular form fields. :param files: sequence of (name, filename, value) elements for data ...
17cd1ce08d7aac005a07b77517c4644565083cb8
3,640,229
def is_recording(): """ return current state of recording key macro """ global recording return recording
73f3a28d5d37bdc300768d48a6cc8f2ac81c2cf0
3,640,230
from typing import Union from pathlib import Path from typing import List from typing import Dict from typing import Optional import asyncio def download_image_urls( urls_filename: Union[Path, str], synsets: List[str], max_concurrent: int = 50, rewrite: bool = False ) -> Dict[str, Optional[List[str]]]...
36bc1e2993cfd01ef9fca91354f970ffb980a919
3,640,231
def generate_new_split(lines1, lines2, rng, cutoff=14937): """Takes lines1 and lines2 and combines, shuffles and split again. Useful for working with random splits of data""" lines = [l for l in lines1] # lines1 may not be a list but rather iterable lines.extend(lines2) perm = rng.permutation(len(lines...
cac058f44bd5cb729517a1aeb67295a30dac2eb5
3,640,232
import time def train_classification(base_iter, model, dataloader, epoch, criterion, optimizer, cfg, writer=None): """Task of training vide...
8564fe2d520d54c81165adb5025aebb9916ab9b5
3,640,233
import logging def get_top5(prediction): """return top5 index and value of input array""" length = np.prod(prediction.size) pre = np.reshape(prediction, [length]) ind = np.argsort(pre) ind = ind[length - 5 :] value = pre[ind] ind = ind[::-1] value = value[::-1] res_str = "" l...
607ad0b9eee550e1bb389a9a92a76472155bea16
3,640,234
def calculate_parentheses(cases): """Calculate all cases in parameter 'cases' return : case that calculate and it's 24 else return 'No Solutions' Example and Doctest : >>> nums = [5, 5, 9, 5] >>> cases = generate_all_combinations(nums, '+-*/') >>> calculate_parentheses(cases) '( ( 5 + 5 ) +...
b8d51d677e16ed27c0b46ad0f4fe98751ea9759e
3,640,235
import hashlib import hmac import struct def pbkdf2(hash_algorithm, password, salt, iterations, key_length): """ PBKDF2 from PKCS#5 :param hash_algorithm: The string name of the hash algorithm to use: "sha1", "sha224", "sha256", "sha384", "sha512" :param password: ...
8a3799a2c73b3b3be96f67252f210bc5d114d334
3,640,236
import time def getLocalUtcTimeStamp(): """ Get the universal timestamp for this machine. """ t = time.mktime(time.gmtime()) isDst = time.localtime().tm_isdst return t - isDst * 60 * 60
54eed0893d03f3b6a76de0d36fc3f1ff5b35f64f
3,640,237
def melt_then_pivot_query(df, inspect_result, semiology_term): """ if happy all are the same semiology, after insepction of QUERY_SEMIOLOGY, melt then pivot_table: --- inspect_result is a df Ali Alim-Marvasti July 2019 """ # find all localisation columns present: localisation_l...
97ebd8f30d4b031a6b12412421ad0e4e2458c003
3,640,238
from typing import List from typing import Tuple def maze_solver(maze: List[List[int]]) -> List[Tuple[int, int]]: """ Finds the path that a light ray would take through a maze. :param maze: 2D grid of cells, where 0 = empty cell, -1 = mirror at -45 degrees, 1 = mirror at 45 degrees :return: The coordinates that t...
4ea26e1dec318c9a41babf617d26662d35fe54c1
3,640,239
def looks_like_fasta(test_text): """Determine if text looks like FASTA formatted data. Looks to find at least two lines. The first line MUST start with '>' and the second line must NOT start with '>'. Ignores any starting whitespace. """ text = test_text.strip() return FASTA_START.match(...
352cde2d0d4de692e0598a96d19107ac04a66f53
3,640,240
import signal def firwin_kaiser_bsf(f_stop1, f_pass1, f_pass2, f_stop2, d_stop, fs=1.0, N_bump=0, status=True): """ Design an FIR bandstop filter using the sinc() kernel and a Kaiser window. The filter order is determined based on f_stop1 Hz, f_pass1 Hz, f_pass2 Hz, f_stop2 Hz, ...
d5fccbcb9721707f0653065ad7c27d904cc05b97
3,640,241
from typing import List def extract_text(html_text) -> List[List[str]]: """ :param html_text: :return: """ lines = [i.text.replace("\xa0", "") for i in html_text.find("div", attrs={"class": "contentus"}).findAll("h3")] return [line.split(" ") for line in lines if line]
19dfdd513e48f2662dc51661bfeca4b1155762a3
3,640,242
from typing import Iterable from typing import Tuple from re import X from typing import Mapping from typing import List def multidict(pairs: Iterable[Tuple[X, Y]]) -> Mapping[X, List[Y]]: """Accumulate a multidict from a list of pairs.""" rv = defaultdict(list) for key, value in pairs: rv[key].ap...
c94567169a8ea4e3d7fd9a8e5c2a990625181be8
3,640,243
import glob def read_images(pathname): """ Read the images to a list given a path like 'images/cropped/*' :param pathname: file path :return: a list of color images and a list of corresponding file names """ images_path = sorted(glob.glob(pathname)) images = [] names = [] for path ...
9fd4644baa2ca5db204cd7ce442e85bc0d9e3166
3,640,244
import subprocess def cov(path): """ Run a test coverage report. :param path: Test coverage path :return: Subprocess call result """ cmd = "py.test --cov-report term-missing --cov {0}".format(path) return subprocess.call(cmd, shell=True)
521b78f712510b6438ad5bad45c951ddb0e1b623
3,640,245
def visualize_camera_movement(image1, image1_points, image2, image2_points, is_show_img_after_move=False): """ Plot the camera movement between two consecutive image frames :param image1: First image at time stamp t :param image1_points: Feature vector for the first image :param image2: First image...
5f92bf44885e62ebdc502e8c98ba1466cb8d5279
3,640,246
def get_rgb_masks(data, separate_green=False): """Get the RGGB Bayer pattern for the given data. See `get_rgb_data` for description of data. Args: data (`numpy.array`): An array of data representing an image. separate_green (bool, optional): If the two green channels should be separated, ...
cf31103ca4248ccd96fb89181d0e48d5b71201c5
3,640,247
def _parse_ax(*args, **kwargs): """ Parse plotting *args, **kwargs for an AxesSubplot. This allows for axes and colormap to be passed as keyword or position. Returns AxesSubplot, colormap, kwargs with *args removed""" axes = kwargs.pop('axes', None) cmap = kwargs.get('cmap', None) if ...
78658e2cf66fad184c057b9392b918ffb48406be
3,640,248
import google.colab # noqa: F401 import IPython import IPython def _get_context(): """Determine the most specific context that we're in. Implementation from TensorBoard: https://git.io/JvObD. Returns: _CONTEXT_COLAB: If in Colab with an IPython notebook context. _CONTEXT_IPYTHON: If not in Colab...
b81205aedbe2222019fa6b7e9dc5fb638536869f
3,640,249
def loadSHSMFCCs(IDs): """ Load all of the 12-dim MFCC features """ IDDict = getSHSIDDict() fin = open("SHSDataset/MFCC/bt_aligned_mfccs_shs.txt") mfccs = {} count = 0 while True: ID = fin.readline().rstrip() if not ID: break ID = IDDict[ID] if...
04d82be79d6e89c5f9b6304be82d049bf6af63f5
3,640,250
def __createTransactionElement(doc,tran): """ Return a DOM element represents the transaction given (tran) """ tranEle = doc.createElement("transaction") symbolEle = __createSimpleNodeWithText(doc, "symbol", tran.symbol) buyEle = __createSimpleNodeWithText(doc, "buy", "true" if tran.buy else "fa...
c09fc6abf4cb9599be23bcf6c91c6cc60330df0a
3,640,251
def received_information(update: Update, context: CallbackContext) -> int: """Store info provided by user and ask for the next category.""" text = update.message.text category = context.user_data['choice'] context.user_data[category] = text.lower() del context.user_data['choice'] update.message...
e7b93516975a497f6da11383969a14aeb31e6278
3,640,252
def set_payout_amount(): """ define amount of insurance payout NB must match what was defined in contract constructor at deployment """ return 500000e18
30ff7b07cbbe28b3150be2f1f470236875c8d0e3
3,640,253
def process_season_data(*args) -> pd.DataFrame: """ Takes multiple season data frames, cleans each and combines into single dataframe. """ return pd.concat( map( lambda df: basketball_reference.process_df_season_summary( df=df, url_type="season_summary_per_game" ...
9c2d46ba2b491382e91613e0dc0a35b68e4188cf
3,640,254
def build_frame(station_num: int, snapshots_num: int): """Function to build citi_bike Frame. Args: station_num (int): Number of stations. snapshot_num (int): Number of in-memory snapshots. Returns: CitibikeFrame: Frame instance for citi-bike scenario. """ matrices_cls = gen...
2fd09885f488a4b42f9a2a4a19dfdd5c10743ef9
3,640,255
def rucklidge(XYZ, t, k=2, a=6.7): """ The Rucklidge Attractor. x0 = (0.1,0,0) """ x, y, z = XYZ x_dt = -k * x + y * (a - z) y_dt = x z_dt = -z + y**2 return x_dt, y_dt, z_dt
9d10aa89fb684a95474d45399ae09a38b507913c
3,640,256
import os def resolve(dirs, *paths): """ Joins `paths` onto each dir in `dirs` using `os.path.join` until one of the join results is found to exist and returns the existent result. :param dirs: A list of dir strings to resolve against :param paths: Path components to join onto each dir in `dirs` ...
d9f8b8e4049091ab0354b56e283f322ddd3d37e0
3,640,257
def multiext(prefix, *extensions): """Expand a given prefix with multiple extensions (e.g. .txt, .csv, _peaks.bed, ...).""" if any((r"/" in ext or r"\\" in ext) for ext in extensions): raise WorkflowError( r"Extensions for multiext may not contain path delimiters " r"(/,\)." ) re...
39bda078a856cb14fc65174ff48be81909b9034a
3,640,258
def sum_range(n, total=0): """Sum the integers from 1 to n. Obviously the same as n(n+1)/2, but this is a test, not a demo. >>> sum_range(1) 1 >>> sum_range(100) 5050 >>> sum_range(100000) 5000050000L """ if not n: return total else: raise TailCall(sum_range...
6126dd1012346a388ddc37c5a8965f3662b8ad7d
3,640,259
import logging import time import pickle def parallel_evaluation_mp(candidates, args): """ Evaluate the candidates in parallel using ``multiprocessing``. This function allows parallel evaluation of candidate solutions. It uses the standard multiprocessing library to accomplish the parallelization...
4562a976306ec8c3684d079b307a4fb1a83d09ab
3,640,260
from tcrsampler.sampler import TCRsampler def _default_tcrsampler_human_beta(default_background = None, default_background_if_missing=None): """ Responsible for providing the default human beta sampler 'britanova_human_beta_t_cb.tsv.sampler.tsv' Returns ------- t : tcrsampler.sampler.TCRsampler ...
15b682b3e14e9496514efaf287b10ae6acb12441
3,640,261
def _dblock_to_raw( mkh5_f, dblock_path, garv_annotations=None, apparatus_yaml=None, ): """convert one mkh5 datablock+header into one mne.RawArray Ingest one mkh5 format data block and return an mne.RawArray populated with enough data and channel information to use mne.viz and the mne.Epochs, mne.E...
cee5823fa1ab4e3cd9be345cf83858bd61a01b51
3,640,262
def _get_positive_mask(positive_selection, cls_softmax, cls_gt): """Gets the positive mask based on the ground truth box classifications Args: positive_selection: positive selection method (e.g. 'corr_cls', 'not_bkg') cls_softmax: prediction classification softmax scores cls...
8a8e4317f99f691c038b40d7656656f532eba884
3,640,263
def max_min_index(name_index): """Return maximum and minimum value with country of a column from df.""" country_and_name = df_copy[["country", name_index]] counrties_in_name_index = country_and_name.sort_values(name_index).dropna() min_value = [ list(counrties_in_name_index[name_index])[0], ...
7bce42a4d05b52b8e6f0a6d91cecf7775a9484a4
3,640,264
def add_bold_line(latex: str, index: int) -> str: """Makes a provided line number bold """ lines = latex.splitlines() cells = lines[index].split("&") lines[index] = r'\bfseries ' + r'& \bfseries '.join(cells) return '\n'.join(lines)
637338ea9ec576c780ccfa0b37d47a670465cdbb
3,640,265
def square(V,resp,weight): """Computes the expansion coefficients with a least squares regression""" if np.any(weight): Vt = V.T v1 = Vt.dot(np.transpose(weight*Vt)) v2 = Vt.dot(np.transpose(weight*resp.T)) coef = np.linalg.solve(v1,v2) else: coef = np.linalg.lstsq(V,r...
076f580a16c233a087edafb1efd57b9fa194a666
3,640,266
def _unwrap_function(func): """Unwrap decorated functions to allow fetching types from them.""" while hasattr(func, "__wrapped__"): func = func.__wrapped__ return func
8c7a9f5b08dc91b9ae2c8387fbd4860bb554d561
3,640,267
def get_data(exception: bool = True, key_form: str = "data") -> "dict or None": """Função captura os dados de uma rota. A captura é feita caso a rota seja com `JSON` ou `Multipart-form` caso contrario lança um exceção. As imagens são capturadas na função `get_files`. `exception` campo boleano opcional ...
15cd4257e7849d4400231d7e5c2a025b16ad7db5
3,640,268
def get_dec_log(uid): """Convenience method to look up inc_log for a uid.""" rv = query_db('select dec_log from user where uid = ?', [uid], one=True) return rv[0] if rv else None
8927ce657cbabfd1e0f4e852e6163702ab5b3841
3,640,269
def removeItem(request): """ Removes item from logged in customers basket. """ if request.method == 'POST': cust = User.objects.get(username=request.user.username) item_id = request.POST["item_id"] item = Item.objects.get(id=item_id) b_item = Basket.objects.get(customer=cust, item=item) if(b_item): b_i...
80514a322f727478311b7a1b49bd9da8ac7b0d28
3,640,270
def read_file(repo, name): """Read JSON files.""" with open(repo + '/' + name + '.txt') as file: data = [d.rstrip() for d in file.readlines()] file.close() return data
4d91e4c68a4f132dc6ebb41cc51df66bd555107a
3,640,271
def add_end_slash(value: str): """ Added a slash at the end of value """ if type(value) != str: return value return value if value.endswith("/") else value + "/"
bc8f41898c50120ad7ca8b814ff03d19c1c64c27
3,640,272
def shift_fill(a, n, axis=0, fill=0.0, reverse=False): """ shift n spaces backward along axis, filling rest in with 0's. if n is negative, shifts forward. """ shifted = np.roll(a, n, axis=axis) shifted[:n] = fill return shifted
5287eefe7491442e3192069bce4faf975e54344a
3,640,273
from typing import Union def str2bool(v:Union[str, bool]) -> bool: """ finished, checked, converts a "boolean" value possibly in the format of str to bool Parameters ---------- v: str or bool, the "boolean" value Returns ------- b: bool, `v` in the format of bool ...
2f102239ce395ece25022320443ffc6d7183968e
3,640,274
def _none_or_int_or_list(val): """Input conversion - expecting None, int, or a list of ints""" if val is None: return None elif isinstance(val, list): return list(map(int, val)) else: return int(val)
1958c64175a1cd63f8a42044b40b84d7cf8baed2
3,640,275
def hour_of_day(datetime_col): """Returns the hour from a datetime column.""" return datetime_col.dt.hour
18b2f6e16ccbcb488f3863968466fda14f669d8b
3,640,276
def pad_lists(lists, pad_token, seq_lens_idx=[]): """ Pads unordered lists of different lengths to all have the same length (max length) and orders length descendingly Arguments: lists : list of 1d lists with different lengths (list[list[int]]) pad_token : padding value (int) seq...
76a2a9934dfca478e7db43a93db7e56c181a3b3f
3,640,277
def sum_naturals(n): """Sum the first N natural numbers >>> sum_naturals(5) 15 """ total = 0 k = 1 while k <= n: total += k k += 1 return total
4c59057cd82083d615c72a59f682dd218a657ea0
3,640,278
def _gaussian_log_sf(x, mu, sigma): """Log SF of a normal distribution.""" if not isinstance(x, chainer.Variable): x = chainer.Variable(x) return _log_ndtr(-(x - mu) / sigma)
3f33918bf78fc3ab4064f05d038232df218416f6
3,640,279
def sort_list_files(list_patches, list_masks): """ Sorts a list of patches and masks depending on their id. :param list_patches: List of name of patches in the folder, that we want to sort. :param list_masks: List of name of masks in the folder, that we want to sort. :return: List of sorted lists, r...
91557475bf145862ea88ad9f86cef82135eddd6c
3,640,280
def get_model(name): """ get_model """ if name not in __factory: raise KeyError("unknown model:", name) return __factory[name]
00fff4e3596aec487b16fd1114b7d026d6790568
3,640,281
import configparser def defaults_to_cfg(): """ Creates a blank template cfg with all accepted fields and reasonable default values Returns: config (ConfigParser): configuration object containing defaults """ config = configparser.ConfigParser(allow_no_value=True) config.add_section("General...
f521d0caee3c9f062eb78e7d5c2562030a741aaf
3,640,282
def check_sentence_for_coins(sentence: str) -> str: """Returns the corresponding binance pair if a string contains any words refering to a followed coins Args: sentence (str): the sentence Returns: str: the binance pair if it contains a coins, otherwise returns 'NO_PAIR' """ coin = n...
a9d041ff6c2bcca1c424b059956c33016f93300d
3,640,283
def to24Bit(color8Bit): """The method allows you to convert the 8-bit index created by the color.to8Bit method to 24-bit color value.""" # We ignore first one, so we need to shift palette indexing by one return palette[color8Bit + 1]
b84d2262883a7b3415ae46f174418dc79ef800dc
3,640,284
import shlex import sys import json def read_json_method(data): """ Reformatting Valve key/value format to JSON and returning JSON. """ # default vars parent = [] depth = 0 vdict = {} # init json and add opening bracket vjson = "{" # replace tabs with spaces data.rep...
f8b266145f44e99c83fd5e0dbe2ccd8e60e4feb2
3,640,285
def make_bag(): """Create a bag.""" return from_sequence( [1, 2], npartitions=2 ).map(allocate_50mb).sum().apply(no_allocate)
8c939dd389ab09811dbbf77aaf479832ab7463d0
3,640,286
def get_testdata_files(pattern="*"): """ Return test data files from dicom3d data root directory """ data_path = join(DATA_ROOT, 'test_files') files = walk_data( base=data_path, pattern=pattern, search_files=True, search_dirs=False) return [filename for filename in files if not filename.endswith('.py')]
9739db355914b288b2fcb29874fcc50d6a2b4487
3,640,287
def safe_text(obj): """Safely turns an object into a textual representation. Calls str(), then on Python 2 decodes the result. """ result = qcore.safe_str(obj) if isinstance(result, bytes): try: result = result.decode("utf-8") except Exception as e: result =...
4d20d5c42b79b6dbb6f8282d74bfd461ffd1dc75
3,640,288
from typing import List def evaluate_blueprints(blueprint_q: mp.Queue, input_size: List[int]) -> List[BlueprintGenome]: """ Consumes blueprints off the blueprints queue, evaluates them and adds them back to the queue if all of their evaluations have not been completed for the curre...
c87d0a37fe32d2af6594564afc44d16adf616737
3,640,289
import tempfile import shlex def run_noble_coder(text, noble_coder): """ Run Noble Coder Args: text: the text to feed into Noble Coder noble_coder: the execution path of Noble Coder Returns: The perturbation agent """ pert_agent = None with tempfile.TemporaryDirect...
20bcee89ddda7c8abc108a42621867017a7e4d63
3,640,290
def xor(*args): """True if exactly one of the arguments of the iterable is True. >>> xor(0,1,0,) True >>> xor(1,2,3,) False >>> xor(False, False, False) False >>> xor("kalimera", "kalinuxta") False >>> xor("", "a", "") True >>> xor("", "", "") False """ retur...
86bbe0350dd18a2508120cec9672661e1aa56ce0
3,640,291
from utils import check_dir import coeff from version import __version__ def proc(log_file, thread, circ_file, hisat_bam, rnaser_file, reads, outdir, prefix, anchor, lib_type): """ Build pseudo circular reference index and perform reads re-alignment Extract BSJ and FSJ reads from alignment results Re...
f0cbe9a93cf81a0177895602bc706c08841d30c0
3,640,292
def zjitter(jitter=0.0, radius=5): """ scan jitter is in terms of the fractional pixel difference when moving the laser in the z-direction """ psfsize = np.array([2.0, 1.0, 3.0]) # create a base image of one particle s0 = init.create_single_particle_state(imsize=4*radius, radiu...
7fae2f750cd80708e7cd881a05d535a00b4ecb38
3,640,293
def append_column(rec, col, name=None, format=None): """ Append a column to the end of a records array. Parameters ---------- rec : recarray Records array. col : array_like Array or similar object which will be converted into the new column. name : str, optional Name...
f851ef69946937cbb100d424ddb8502b906940bd
3,640,294
import copy def dfa2nfa(dfa): """Copy DFA to an NFA, so remove determinism restriction.""" nfa = copy.deepcopy(dfa) nfa.transitions._deterministic = False nfa.automaton_type = 'Non-Deterministic Finite Automaton' return nfa
eed8e651a51e71599a38288665604add3d8a0a3d
3,640,295
def count_related_m2m(model, field): """Return a Subquery suitable for annotating a m2m field count.""" subquery = Subquery(model.objects.filter(**{"pk": OuterRef("pk")}).order_by().annotate(c=Count(field)).values("c")) return Coalesce(subquery, 0)
e772c8d55a1d9778077eaf9cbebfc51948361e1c
3,640,296
def create_car(sql: Session, car: CarsCreate): """ Create a record of car with its Name & Price """ new_car = Cars( Name=car.Name, Price=car.Price ) sql.add(new_car) sql.commit() sql.refresh(new_car) return new_car
33fda0b653950989bd1b61ae1ee689db05576877
3,640,297
import time def train(train_loader, model, criterion, optimizer, args, epoch): """Train process""" '''Set up configuration''' batch_time = AverageMeter() data_time = AverageMeter() am_loss = AverageMeter() vec_loss = AverageMeter() dis_loss = AverageMeter() ske_loss = AverageMeter() ...
fb83156f3915f34dd92d4060b62b77644dd65f8b
3,640,298
import os import yaml def fetch_folder_config(path): """Fetch config file of folder. Args: path (str): path to the wanted folder of the config. Returns: dict. the loaded config file. """ config = {} config_path = os.path.join(path, DOC_YML) if os.path.exists(config_path):...
b78393e8d97147227c0648050f749e48e13a54b5
3,640,299