content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def _process_location_bulk(request): """Procesa una request POST para obtener entidades en varios puntos. En caso de ocurrir un error de parseo, se retorna una respuesta HTTP 400. Args: request (flask.Request): Request POST de flask. Raises: data.DataConnectionException: En caso de ocu...
09f1ab0ba9ec33570eef492093e146e42fa72a2b
76,443
def getmodebase(mode): """ Gets the "base" mode for given mode. This function returns "L" for images that contain grayscale data, and "RGB" for images that contain color data. :param mode: Input mode. :returns: "L" or "RGB". :exception KeyError: If the input mode was not a standard mode. ...
c75672161e1a18652ed19acdc135073c3c3d370c
76,444
import re def escape_ansi(line): """It removes the ansi codes from a string.""" ansi_escape=re.compile(r'(\x9B|\x1B\[)[0-?]*[ -\/]*[@-~]') return ansi_escape.sub('',line)
ae9383b102a07a811211a88327c63e169438bc19
76,445
def extinct(repo, subset, x): """Obsolete changesets with obsolete descendants only. (EXPERIMENTAL)""" # i18n: "extinct" is a keyword getargs(x, 0, 0, _(b"extinct takes no arguments")) extincts = obsmod.getrevs(repo, b'extinct') return subset & extincts
17227d93938c0bdd2482feb3d8a459a4d7fab5cc
76,447
def check_uuid(uuid): """Check that the uuid i pass is valid.""" try: converted = UUID(uuid, version=4) except ValueError: return False return str(converted) == uuid
e24b2738c80a8cd111766c9faa0b3927635af470
76,448
def gather_2d(tensor, i, j): """2D version of tf.gather. The equivalent in Numpy would be tensor[i, j, :] Args: tensor (Tensor): a Tensor of rank at least 2 i (Tensor): row indices j (Tensor): column indices of same shape as i, or broadcastable to the same shape """ rank = ...
3fe4b5aa1c9fbf3b3f2ee2163ac826b831c5f935
76,449
def is_smf(matrix_): """ Given a rectangular :math:`n \\times m` integer matrix, determine whether it is in Smith normal form or not. Parameters ---------- matrix_ : sympy.Matrix The rectangular matrix to be decomposed Returns ------- bool True if in Smith normal form, ...
68912c59a3611906f96b4dc9aad8e930fbb0ba19
76,450
import json def test_term(model_paths, token_path, training_length=1000): """ Loads model for testing and predictions on terms from token file Args: model_paths - (list) List of model file paths token_path - (string) Path to the token file training_length - (int) Number of words to...
6701e751c9a2cc2e3154fa282ff4830e67e37a8e
76,451
def check_niimg_3d(niimg): """Check that niimg is a proper 3D niimg-like object and load it. Parameters ---------- niimg: Niimg-like object See http://nilearn.github.io/building_blocks/manipulating_mr_images.html#niimg. If niimg is a string, consider it as a path to Nifti image and ...
a2a5a8a26d19416d29318b71a351c5715eaf27c3
76,452
from astropy.cosmology import default_cosmology, z_at_value def redshift_temperature(cosmology=None, **atzkw): """Convert quantities between redshift and CMB temperature. Care should be taken to not misinterpret a relativistic, gravitational, etc redshift as a cosmological one. Parameters ------...
c69f52da7918e9f35644b52f29147e9055425189
76,453
def MaternProcess(lambdaParent = 10, lambdaDaughter = 5, radiusCluster = 5, plot=False): """ Simulate a Matern point process on a rectangle. Author: H. Paul Keeler, 2018. https://github.com/hpaulkeeler/posts/blob/master/MaternClusterRectangle/MaternClusterRectangle.py https://hpaulkeeler.com/simulat...
1536b8b632ccf5bfb72a22090e5c9cdab57845fd
76,454
def create_bootable_volume( user, provider_uuid, identity_uuid, name, size_alias, new_source_alias, source_hint=None, **kwargs ): """ **kwargs passed as data to boot_volume_instance """ identity = Identity.objects.get(uuid=identity_uuid) if not identity: rais...
dcbc736c732260bae921fa2c9964e9e0a4041ce7
76,455
def RendererNative_GetDefault(*args): """ RendererNative_GetDefault() -> RendererNative Return the default (native) implementation for this platform -- this is also the one used by default but this may be changed by calling `wx.RendererNative.Set` in which case the return value of this method may...
97679d37cf274307cc46dcd097fb47d289de6861
76,456
from typing import Optional from typing import List def compute_unmerged_commits(remote: str, target_branch: str, upstream_branch: str, format: str = '%H') -> Optional[List[str]]: """ Returns the list of commits that are not yet merged from upstream to the target branch. """ commi...
ceb59fe95a4236afcd28a04cd74e9425c2d770bf
76,457
import hashlib def hash_and_encode_file(file): """ Parameters ---------- file : :class:`pathlib.Path` object Returns: -------- hash_ : bytes filesize : int """ return encode_file(file, hash_file(file, hashlib.sha512))
ecc636894ac9350acf9eb036c6a684332a744d59
76,458
def count_unique_peaks(peaks): """Returns the number of unique peaks.""" n_unique = 0 for chrom in peaks.chroms: for peak in peaks.fetch(chrom): if not peak.iscommon: n_unique += 1 return n_unique
53da151e1e3c95ecd0bf73234878d5d1e63cce33
76,459
def _vertex_normalize(row, col_name): """Computes the value at row[col_name] normalized by vertices.""" return (float(row[col_name]) / float(row[headers.LT_NUM_VERTICES])) * 100
344a73ea00c39fc375c5ee8efc2a3f216f36491e
76,460
def uniform_random_stream(transact_type, min_delay, max_delay): """Return a new stream of transacts with random delays distributed uniformly.""" expect_transact_type(transact_type) model = transact_type.get_model() code = 'return $ mapStream (\\a -> ' + transact_type.coerce_arrival('a') + ') $ ' cod...
4a871a807644fdd9f9b44c6d5944f0fa08f22d8d
76,461
def get_fov2d_occupancy_cost( current_pos: np.ndarray, occupancy_map: np.ndarray, cost_to_go: np.ndarray, fov_size: int, flatten: bool = False, ) -> np.ndarray: """get FOV (occupancy and cost-to-go) Args: current_pos (np.ndarray): current position occupancy_map (np.ndarray):...
35e3766fc1d8258f2821c917ff10089591ab35c6
76,462
from datetime import datetime from typing import OrderedDict def show_main(): """Respond to requests for the /main page.""" db = get_db() now = datetime.datetime.now() rooms = app.config["HC_CONFIG"].values() rooms.sort(key=config_lexer.Room.sortkey) # Get the three newest counts from the data...
d975be1728104750504d2eb8b5c653eefff4389d
76,463
def get_font_dict(f): """Return a dict of font attributes for font F. Standard font attributes include: family, size, weight, slant, underline, overstrike. """ return tk_font.Font(font=f).actual()
001b900d5d7d7015cccdb65e30e2dcebaa53f7d8
76,464
def get_fitted_kde_mixture_from_z_arr(z_arr, args): """From array of z values dataset, get a fitted KDE mixture""" logger.info(f"Fitting Mixture KDE on N={len(z_arr)} z values.") kde_mixture = KdeMixture(z_arr, args) return kde_mixture
f357f7f9fbcae56180e9212e098d3dbc06ab909b
76,465
def align_skeleton(skeleton, code): """ Aligns the given skeleton with the given code, minimizing the edit distance between the two. Both skeleton and code are assumed to be valid one-line strings of code. >>> align_skeleton(skeleton="", code="") '' >>> align_skeleton(skeleton="", code="i") ...
ae9e602871a898840b4eca9067c824459b5326db
76,466
def id_exists(guest_id: int, database_connection: mysql.connector.connect) -> bool: """Returns true or false based on wheter or not a guest ID exists Arguments: guest_id (int) database_connection (mysql.connector.connect) """ return validate_id(guest_id, database_connectio...
15d4b87e0a4aff8c5938161ec1c91e10beae6ca3
76,467
def generic_cross_derivative(expr, dims, fd_order, deriv_order): """ Create a generic cross derivative for a given function. :param expr: A :class:`Function` object. :param dims: The :class:`Dimension`s w.r.t. the derivative is computed. :param order: Order of the discretization coefficient (note: ...
4ce43d1bb45a6f0bdeb5418ec493b60cb391a5d8
76,470
import requests def _get_latest_version(): """Return current ELK stack major version as an integer""" URL = 'https://www.elastic.co/guide/en/elasticsearch/reference/{}.x/deb.html' version = 5 while requests.get(URL.format(version + 1)).status_code == 200: version += 1 return version
4b5de5ad1d5305a88e9d24854e7aa77b4b4d58fa
76,471
from random import randint def quick_sort(array): """ SORTING FUNC USING QUICK SORT ALGORITHM ARG array = LIST(ARRAY) of NUMBERS """ if len(array) <= 1: return array smaller, equal, larger = [], [], [] pivot = array[randint(0, len(array)-1)] for n in array: if n < piv...
5b9ff6782874094a9cd997e05747e4ae9988fa53
76,473
import email def timeconvert(timestr): """Convert RFC 2822 defined time string into system timestamp""" timestamp = None timetuple = email.utils.parsedate_tz(timestr) if timetuple is not None: timestamp = email.utils.mktime_tz(timetuple) return timestamp
b09ec7ad37b8d6d715a55dbe54a824fcc9c0868d
76,474
def notas(*valores, sit=False): """ --> Função para analisar notas e situações de vários alunos :param valores: uma ou mais notas dos alunos (aceita várias) :param sit: valor opcional, indicando se deve ou não adicionar a situação :return: dicionário com várias informações sobre a situação da turma ...
a488b160e941a39585c95fd0e4f158b6a22f4b5f
76,475
def visualize_sr(img, halve=False): """ Visualizes the super-resolved images from the SRResNet and SRGAN for comparison with the bicubic-upsampled image and the original high-resolution (HR) image, as done in the paper. :param img: filepath of the HR iamge :param halve: halve each dimension of the ...
49a9e8d0275926c491e816f21b3249f554dadf3e
76,476
def get_quotation_pagination(page=1, per_page=10, *args, **kwargs): """ 获取列表(分页) Usage: items: 信息列表 has_next: 如果本页之后还有超过一个分页,则返回True has_prev: 如果本页之前还有超过一个分页,则返回True next_num: 返回下一页的页码 prev_num: 返回上一页的页码 iter_pages(): 页码列表 iter_pages(left_edge=2, left_...
7e8fb33a4b2d405c1adaa5308e5da272b34127d2
76,477
def calculate_confusion_matrix(labels, results): """ returns a confusion matrix """ predictions = transform_binary_predictions(results) return confusion_matrix(labels, predictions)
5b169294f3aba449f59f5e714f12b46ee63fd462
76,478
def add_columns(df: DataFrame, new_columns_mapping_dict: dict) -> DataFrame: """ We are assuming that adding columns filters out any columns that already exists """ return _add_columns(df, new_columns_mapping_dict, False)
f3e53c342343da48f99121f506fec364413c9dbb
76,479
def hex_str_to_int(hex_str: str): """'#ffffff' -> 0xffffff""" if "#" in hex_str: return int(hex_str[1:], 16) else: return int(hex_str, 16)
65fc72fcec909a5062a4881f032d9f1bbe4aeecb
76,480
def HostUpdateStateSummaryToMessage(host_update_state_summary_entity): """Convert HostUpdateStateSummary from entity to message.""" if not host_update_state_summary_entity: return None return api_messages.HostUpdateStateSummary( total=host_update_state_summary_entity.total, unknown=host_update_sta...
1d6528ca5bb8e958d80404698ea1ac66feff49bc
76,481
def pd_set_minus(df: pd.DataFrame, df_minus: pd.DataFrame) -> pd.DataFrame: """ Definition set minus: Let A, B be sets. Then A - B holds every element which is in A, but not in B In that manner we return every row of df, which is not in df_minus. Parameters ---------- df: pd.DataFrame T...
12ac9517b0adfbb440eb36d004365b8be6ab11fb
76,482
from typing import Dict from typing import Any from typing import List def get_choice(params: [Dict, Any], key: str, choices: List[Any], name: str=None): """ Gets the value of `key` in the `params` dictionary, ensuring that the value is one of the given choices. `name` is an optional description for wher...
3ff2ad4d126969f5309c42808413abd1a297c7ce
76,483
from typing import Dict def charge(payment_information: Dict, connection_params): """Performs Authorize and Capture transactions in a single run.""" auth_resp = authorize(payment_information, connection_params) if not auth_resp['is_success']: return auth_resp return [auth_resp, capture(payment...
52409ea58ab17071777c8df519294504070df429
76,484
def count_raster_bands(raster_paths: list) -> int: """Returns the total number of bands from a list of rasters. Args: raster_paths: List of raster data file paths. Returns: n_bands: total band count. """ n_bands = 0 for path in raster_paths: with rio.open(path) as src: ...
6e8c98673c48311979d0ec7f779c4b0a301eaba0
76,485
def _monochannel_to_rgb(image, rgb): """ convert monochrome image to rgb. Parameters ---------- image : ndarray rgb : list Returns ------- image_rgb: array , shape (image). """ image_rgb = normalize(image).reshape(*(image.shape + (1,))) image_rgb = image_rgb * np.asarra...
1ac56c2538e4338fde5cacbd3d6c203de73cce0a
76,486
import json def check_um_key(um_key: str) -> HttpResponse: """ 检查友盟key值, :param um_key: :return: None=状态正常,HttpResponse=状态异常,直接返回该response """ if um_key: return None else: r = { 'code': 200, 'msg': '友盟key不能为空', 'data': None } ...
dd2a5799890d10f7d292bfda38137ef8b1469b76
76,487
def get_page_url(page_num): """ generate a javbus page url when assign different page for multi-threading""" page_url = 'https://www.javbus2.pw/genre/hd/' + str(page_num) return page_url
1fef6cd0971ee1b6bfa6d143f937976dc9b5e715
76,488
import re def accuracy_score_test(list_of_lists_of_queries,story_chunk_responses,item_keyword,type_of_evaluation): """Calculate the accuracy of return the correct response from each story chunk given the keyword of the item the user input""" if type_of_evaluation=='tfidf': number_correct=0 number_incorrect=0 ...
d210f958350166a3d2942e0272c1928dae486748
76,489
def xlsw_write_row(ws, row_idx, row, fmt=None): """ ws: row_idx: row number row: a list, data to write fmt: format for cell """ for col_idx in range(len(row)): ws.write(row_idx, col_idx, row[col_idx], fmt) row_idx += 1 return row_idx
4d6da85ff95c97a30c05511cb6995e946b7ccb80
76,490
def circlecoords(c, r, imgsize, nsides=600): """ Description: Find the coordinates of a circle based on its centre and radius. Input: c - Centre of the circle. r - Radius of the circle. imgsize - Size of the image that the circle will be plotted onto. nsides - Number of sides of the convex-hull bod...
43dee7450c16aebe2cd18327210568f4efa923f6
76,493
def load_sps(param_file=None, **kwargs): """Return an ``sps`` object which is used to hold spectral libraries, perform interpolations, convolutions, etc. """ ext = param_file.split('.')[-1] if ext == 'py': setup_module = import_module_from_file(param_file) sps = setup_module.load_sps...
18318eecb272973bb2b2b669e56d73f8334a8c2e
76,494
def add_items(inventory, items): """Add or increment items in inventory using elements from the items `list`. :param inventory: dict - dictionary of existing inventory. :param items: list - list of items to update the inventory with. :return: dict - the inventory updated with the new items. """ ...
940621ae84306380073e64a843566ce104814bad
76,495
from typing import OrderedDict def sortable(func): """ Decorator for enabling sort """ def create_sort_params(*args, **kw): sort_args = request.args.getlist("_sort") # maintain order of sort fields sort_params = OrderedDict() for sort_arg in sort_args: field...
43352ccd1eaae51c5849705445acb09d2658840e
76,497
def known_datastores(): """returns names of know datastores""" return [i[0] for i in vmdk_utils.get_datastores()]
78d731792acd0828d05eef311b129bde07856a56
76,498
def usun(pid): """Usunięcie pytania o identyfikatorze pid""" p = Pytanie.query.get_or_404(pid) if request.method == 'POST': flash('Usunięto pytanie {0}'.format(p.pytanie), 'sukces') baza.session.delete(p) baza.session.commit() return redirect(url_for('index')) return rend...
736adfac9b5e8046191080cd67019f691a50e41a
76,499
def autocomplete_using_trie(string: str) -> tuple: """ >>> trie = Trie() >>> for word in words: ... trie.insert_word(word) ... >>> matches = autocomplete_using_trie("de") >>> "detergent " in matches True >>> "dog " in matches False """ suffixes = trie.find_word(string...
57f0866cd8e67d3ab5124fe6549260c27238dc7c
76,500
import math def std_pointings(directionterm='?'): """ Find beamctl direction string based on direction term. Parameters ---------- directionterm : str, '?', '', or None Source name or term for a direction. E.g. 'Z' for Zenith or 'Cas-A' for Cassiopeia A. Returns ------- ...
173ba9fea20fb56bfdddc933c6be50459a4952fd
76,502
def some_svms(): """Returns a couple of FeatureSelectionClassifiers based on SVMs with different numbers of features and/or sensitivity measure""" clfr1 = FeatureSelectionClassifier( SVM(descr = "libsvm.LinSVM(C=def)", probability = 1), SensitivityBasedFeatureSelection( ...
1268ba61584b71cb514c434ebdeb839c73c89988
76,503
def condence_attdata(attdata, maxoffset=5.): """ for provided attdata (which is a series of quaternions, rotation vectors and time points), search time segments which can be described with single rotation vector and still be accurate up to maxoffset -------- Params: attdata - attitude infor...
3472b378eb57825704d05cb728dbe0b2f6a22161
76,504
def _gaussian2d(data, sigma=0.5, size=None, **kwargs): """ Computes Gaussian filter/convolution in the GPU. Parameters ---------- data : 2 dimensional array The data to be filtered sigma : float or array of floats The standard deviation of the Gaussian filter. Controls the ...
692eb552b3a8d3a61059bc25a5455e1a551b5054
76,505
def python_pip(name, op="install", upgrade=False, venv=None, version=3, **kwargs): """Use pip to install or uninstall a Python package. - name (str): The name of the package. - op (str): The operation to perform; install, uninstall - upgrade (bool): Upgrade an installed package. - venv (str): The n...
eb11fdf7f91f28bbdd2551cb46ca3339e9407b0e
76,506
def load_db(dbname, username): """ Creates a connection to my PostgreSQL database """ engine = create_engine('postgres://%s@localhost/%s'%(username,dbname)) if not database_exists(engine.url): create_database(engine.url) connection = engine.connect() return engine, connection
3d93081e0938688df0fb49861a6178c7fe4bd6f8
76,508
def bm_generation_type(args): """ BMReport Generation Type """ gdd = GenerationData() gdd.get_data() data = gdd.as_dict() fmt = StdoutFormatter("8s", "40s", "5s", "10d", "12.3f") row_titles = fmt.titles('Code', 'Generation Type', 'Intcr', 'Output', 'Percentage') print(data) for sect i...
ad36d33a3f7c141a8431a3079cff18353ca5e240
76,509
import copy def define_for_dependencies(S_program: Stage, for_calc_task: ForCalcTask, for_input_task: ForInputTask, for_merge_task: LambdaTask) -> LambdaTask: """ Args: S_program: The program stage for_calc_task: The ForCalcTask with the function containing the bod...
4a36fbd06cd60ef0ee1a51705648f14ea5b7ecaa
76,510
def add_ast_to_vectorization_data(data, current_index, ast): """add ast to list of data for vectorization, create dictionary of indexes""" ast_dict = {} data.extend(convert([ast['tokenizedSource']])) ast_dict['source'] = current_index current_index += 1 data.extend(convert(ast['tokenizedMethod...
4ea79a653329af5df19188c1bd49dd1efb5e8620
76,511
def get_repository_metadata_by_id(app, id): """Get repository metadata from the database""" sa_session = app.model.session return sa_session.query(app.model.RepositoryMetadata).get(app.security.decode_id(id))
ec7d532e3463b29f2e9dfb72cec71212f0c49f85
76,512
def bd09mctobd09(x,y): """ Convert coordinates from BD09MC to BD09 Parameters ------- x : Series or number x coordinates y : Series or number y coordinates return ------- lng : Series or number Longitude (Converted) lat : Series or number Latitud...
14182fbb12aed2ff7b9a7a8063f5d6c40d3a5834
76,513
def fk5hz(r5, d5, date1, date2): """ Wrapper for ERFA function ``eraFk5hz``. Parameters ---------- r5 : double array d5 : double array date1 : double array date2 : double array Returns ------- rh : double array dh : double array Notes ----- The ERFA documen...
7fe9b625ba9885f05b739084debe9bbe160d6fff
76,514
import base64 def numpy_to_json(np_arr): """Encodes a numpy array to a json-serializable dict""" # TFJS only has types float32, int32, bool, string and complex64 dtype_map = { 'b': 'bool', 'i': 'int32', 'u': 'int32', 'S': 'string', 'O': 'string', 'U': 'strin...
426b6c38388008ed2ca02e119ea07169dd39d38e
76,515
def read_features(path): """ Read a list of features in feature-per-line format, where each feature is a repr and needs to be evaled. @param path path to read from """ with open(path) as f: return map(eval, f)
8bc32f064b31cef4f5d3e4ebfe0ecda5da729e1f
76,516
def create_new_sifaddr( credentials: SifchaincliCredentials, keyname ): """returns something like {"name":"9cbf3bd4-f15c-4128-bae6-a534fc8d6877","type":"local","address":"sif19u4xtckuvy2zk9r2l4063g93s3r8qc4vw0a20t","pubkey":"sifpub1addwnpepqw88ns6dmy3xwjqh4mkvuda6ezn056nxy8ldrtpkrfuvuamexv9hxyzhxm7"...
f1e754df1eb1f1d389f45bac877205746b547c0d
76,518
def PGCD(m, n): """ Détermine le PGCD de deux entiers. @param m premier entier @param n second entier @return PGCD .. exref:: :title: calcul du PGCD avec la méthode des soustractions :tag: Algorithme La fonction qui suit est l'implémen...
a77ee9a5e83b1748bff30a1d7db672456b408907
76,519
def op(name, data, display_name=None, description=None, collections=None): """Create a scalar summary op. Arguments: name: A unique name for the generated summary node. data: A real numeric rank-0 `Tensor`. Must have `dtype` castable to `float32`. display_name: Optiona...
d9202a5c4489e42ed3ca0d91235a82d8f861ac04
76,521
from datetime import datetime import json def widgetr(): """Renders the widgetr page.""" port = 56988 hosts = data_access_layer.select("hosts") hostnames = [el[1] for el in hosts] return render_template( 'widgetr.html', title='Widgetr', year=datetime.now().year, hos...
061c296269a4115b21b1acb98681edc4ebb0ec56
76,523
def get_embedding(inputs, vocab_size, hidden_size, initializer=tf.glorot_normal_initializer()): """ word/character embedding :param inputs: tf.placeholder :param vocab_size: int, size of vocab :param hidden_size: int :param initializer: weights initializer """ embedding...
e0e6a132b6c22f939f9ad9120616b362f9a6c802
76,524
def multiple(a, b): """Return the smallest number n that is a multiple of both a and b. >>> multiple(3, 4) 12 >>> multiple(14, 21) 42 """ "*** YOUR CODE HERE ***" r1 = a % b if (r1 == 0): GCD = b else: r2 = b % r1 while (r2 != 0): r1, r2 = r2,...
042dfc4d78699272b86165569139a9dc6f80e32b
76,525
import torch def gram_matrix(input_data): """ Gram Matrix for Style Loss Module a = batch size (1) b = number of feature maps c*d = number of features in a feature map Note: This specification is specific to 2d convolution """ a, b, c, d = input_data.size() featu...
6bf808534a52576a2559789c8d9080363e564a0c
76,526
from re import A def op_setr(instr, regs): """setr (set register) copies the contents of register A into register C. (Input B is ignored.)""" oregs = regs.copy() oregs[instr[C]] = oregs[instr[A]] return oregs
13d2df9a996917cfdc6d2c633986ce12399c8444
76,527
def humanize(memory, suffix="B", kilo=1024): """ Scale memory to its proper format e.g: 1253656 => '1.20 MiB' 1253656678 => '1.17 GiB' """ if kilo == 1000: units = ["", "k", "M", "G", "T", "P"] elif kilo == 1024: units = ["", "Ki", "Mi", "Gi", "Ti", "Pi"] else...
7afd033e2ead94ca8853a347ad9c8d1fa47a5e64
76,528
import random def load_metadata(metadata_path, train_size): """ Load metadata file and split entries into train and test. Parameters ---------- metadata_path : str Path to metadata file train_size : float Percentage of entries to use for training (rest used for testing) R...
c0eee8e4f123ff363f006f87fb7f51fee8c8a0cf
76,529
from typing import List from typing import Tuple def _tokoff_from_line(text: str) -> List[Tuple[int, int]]: """Produce character offsets for each token (whitespace split) For example, text = " one two three ." tokoff = [(1,4), (6,9), (10,15), (16,17)] """ tokoff = [] start = None ...
8d05ddbd3680f9658f4471430d352874bd0c5cdb
76,530
def gen_test_match_and_parse_args_input_2(): """ Not module memref """ line_args = ["A"] signature = [] arg_def = get_arg_def_template() arg_def["value_type"] = "module_name" arg_def["is_memory_location"] = True arg_def["value"] = "A" signature.append(arg_def) expected_m...
20bbd39f4d3ee527ca34009546e64411a8c086b6
76,531
def split_decimal(flt): """ split decimal params: flt : <float> float to convert returns: <tuple> ( whole number, decimal part) """ whole, dec = str(flt).split('.') # dec = int(dec) # if dec >= 5: # return int(whole) + 1, dec return [int(whole), int(dec)]
4175b3370591028bb96b5bf3eaceee3391c0b1f3
76,532
import functools def create_single_handler(resource_type): """Catch errors of the creation of a single resource. This decorator appends an error (which is an instance of some client exception class) to the return value of the create_method, changing the return value from just UUID to (UUID, error), a...
07eef17962b7442dc0daa1bb8a0938df4996e7ba
76,533
def get_tag(space): """get_tag() -> string Return the magic tag for .pyc or .pyo files.""" return space.wrap(importing.PYC_TAG)
b99bee67d068ca4b6cc3833bab76c0d729e56704
76,535
import pkg_resources def codegen_functions(client, export_file, function_names, workflow_names, action_names, artifact_type_names, output_dir, output_file): """Generate a python file that implements one or more functions""" message_destination_names = None template_file_path = pkg_re...
4742e303f1f1ce1bda5c216531dc4e74efd96157
76,536
import six def get_val(root, items, sep='.', **kwargs): """ Swagger client objects don't behave like dicts, so need a custom func to step down through keys when defined as string vars etc. Warnings: If you try to retrieve a key that doesn't exist you will get None instead of an Attrib...
82c13dba6a93374ae1f8595f9dec49557cdb5651
76,537
def prepareGiftiVertexData(darrays, filename=None): """Prepares vertex data from the given list of GIFTI data arrays. All of the data arrays are concatenated into one ``(M, N)`` array, containing ``N`` data points for ``M`` vertices. It is assumed that the given file does not contain any ``NIFTI_I...
ddc3787fc0368b9d07ad5474e3d384db4e60ba54
76,538
from typing import AnyStr from typing import List from typing import Dict def get_node_rating_monthly(tenant_id: AnyStr, node: AnyStr, namespaces: List[AnyStr]) -> List[Dict]: """ Get the monthly rating for a given node. :tenant_id (AnyStr) A string...
50177494eab904a8b089fcceec360c050b1aecb5
76,539
def refine_logger(logger, **kwargs): """Allows for the logging function to be amended with constant key/value pairs. Description: Returns back a function that will provide the logger function with pre-provided kwargs values. Useful in situations where you may log the same field multiple tim...
fdc898ed27085444bcb75b3ad551e719e9848b03
76,540
def lines(): """ Return lines of test data. """ return ["abc\n", "def\n", "ghi\n"]
0e00c0bb925ed3a9cc945578e5f879bbff7899f2
76,541
def VectorImageEnd(builder): """This method is deprecated. Please switch to End.""" return End(builder)
5c3c3fa6a7a90b485d9f7efaab89fbfebb15cf79
76,542
def constructor(name, configuration_dict, is_training, keep_prob, custom_net_parameters=None): """ constructor takes a name, a configuration dict the booleans is_training, keep_prob and optionally a custom_net_parameters dict and returns an...
190d1f1aebe5373c255800b9deb4094233490ee3
76,543
import operator def find_n_maximum(items, n, skip=False): """ This function is used to find the n max elem in a list :param items: list of items :param n: maximum number :param skip: if True, return every elem in the n maximum, not only the first n elem of a list :return: two list, the first c...
ee31b4194ba5ad7c56544efd1ef18e663750680b
76,544
def f_to_srsf(f, time, smooth=False): """ converts f to a square-root slope function (SRSF) :param f: vector of size N samples :param time: vector of size N describing the sample points :rtype: vector :return q: srsf of f """ eps = finfo(double).eps f0, g, g2 = gradient_spline(tim...
f6274244837f5351d4a9117e98922d7b4dbccf52
76,545
def dataset(request): """Renders the about page.""" assert isinstance(request, HttpRequest) return render( request, 'app/dataset.html')
6815f4e7af37b4a70a6c55b2a6e1a2afea4e3d04
76,546
def cov_dvrpmllbb_to_vxyz_single(d,e_d,e_vr,pmll,pmbb,cov_pmllbb,l,b): """ NAME: cov_dvrpmllbb_to_vxyz PURPOSE: propagate distance, radial velocity, and proper motion uncertainties to Galactic coordinates for scalar inputs INPUT: d - distance [kpc, as/mas for plx] e_d ...
2d29271892224db8969a10e21f3d638246a44f67
76,547
def enable_registration(value): """ Isolation Mode: disable registration """ if not current_user.is_admin(): abort(404) if value == 'True': state = '1' elif value == 'False': state = '0' else: return abort(400) try: sm = SiteMetadata.get(SiteMetadata.key...
ddfacc6e205296582f611e538082ad19fde01742
76,548
def cndsa2(fitnesses, constraints): """Take in an MxN array of fitnesses and an MxO array of constraints, rank according to level of constrained non-dominance. Input: fitnesses: A MxN numpy array, each row is a solution, each column is a fitness variable. constrains: A MxO numpy array, each row is a...
03a193e68491a1abacf0e576b8722de7600b6e49
76,549
import tqdm import string def get_clusters(df): """ Obtains patient groups from the given table. :param pd.DataFrame df :rtype: pd.DataFrame """ info('Calculating patient groups') g = df.groupby(['subject_id', 'visit_id']) tqdm.tqdm.pandas() clusters = g.progress_apply(_get_c...
52ef8ba214a9024c47d1aa99be99353e0c37e25c
76,551
from pyopencl.reduction import get_subset_dot_kernel def subset_dot(subset, a, b, dtype=None, queue=None, slice=None): """ .. versionadded:: 2011.1 """ krnl = get_subset_dot_kernel( a.context, dtype, subset.dtype, a.dtype, b.dtype) result, event1 = krnl(subset, a, b, queue=queue, slice...
8218a8caf030a5780134dbbf9a2ef20893d74787
76,552
from datetime import datetime def now() -> datetime.datetime: """Provides a convenient hook for mocking. datetime.datetime is native, so MagicMock can't monkeypatch it. This indirection provides a mocking point. """ return datetime.datetime.now()
57f0cde28c8d6c5bd4075f31e5eb2b460111ffb4
76,553
def opponent_colour_dimensions_inverse( P_p_1: FloatingOrArrayLike, h: FloatingOrArrayLike, M: FloatingOrArrayLike ) -> NDArray: """ Return opponent colour dimensions from given point :math:`P'_1`, hue :math:`h` in degrees and correlate of *colourfulness* :math:`M` for inverse *Hellwig and Fairchild...
02aaa2eddb1adc622b606b48dd37f20ada775e2d
76,554
from typing import Iterable def load_tasks_for_cluster(cluster_name: str) -> Iterable[EcsTask]: """ Runs ListTasks on the cluster, then runs DescribeTasks to get the details. """ tasks = load_tasks_by_arns(cluster_name, get_task_arns_in_cluster(cluster_name)) populate_ec2_ip_for_tasks(cluster_name...
26afa74795fa6c5e88e8c444d96867ab2df38a44
76,555
def linear_newmark_krenk(M,C,K,f,u0,udot0,h,gamma,beta): """ Return the solution of a system of second order differential equations obtained by Newmarks beta method Arguments --------------------------- M : double Mass matrix C : double Damping matrix K : double ...
98a5289f1e4cb4f941aa81a58cbbd198050462a3
76,556