content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def parse_c45(file_base, rootdir='.'): """ Returns an ExampleSet from the C4.5 formatted data """ schema_name = file_base + NAMES_EXT data_name = file_base + DATA_EXT schema_file = find_file(schema_name, rootdir) if schema_file is None: raise ValueError('Schema file not found') ...
14d651a48c2fe65ad68c441722c4c39854efef2a
14,535
import torch def to_numpy(tensor: torch.Tensor): """ Convert a PyTorch Tensor to a Numpy Array. """ if tensor is None: return tensor if tensor.is_quantized: tensor = tensor.dequantize() return tensor.cpu().detach().contiguous().numpy()
ed6bd50ef5db30b3df1304a0152998f2f27750c6
14,536
from flask_sqlalchemy import _wrap_with_default_query_class, SQLAlchemy def initialize_flask_sqlathanor(db): """Initialize **SQLAthanor** contents on a `Flask-SQLAlchemy`_ instance. :param db: The :class:`flask_sqlalchemy.SQLAlchemy <flask_sqlalchemy:flask_sqlalchemy.SQLAlchemy>` instance. :t...
565c010a49e9d0ac2e82b40803b4f0871b526177
14,537
def add_vcf_header( vcf_reader ): """ Function to add a new field to the vcf header Input: A vcf reader object Return: The vcf reader object with new headers added """ # Metadata vcf_reader.metadata['SMuRFCmd'] = [get_command_line()] # Formats vcf_reader.formats['VAF'] = pyvcf.parse...
36e5819de6c09c7e60638b183bfe415fc19361db
14,538
def get_seats_percent(election_data): """ This function takes a lists of lists as and argument, with each list representing a party's election results, and returns a tuple with the percentage of Bundestag seats won by various political affiliations. Parameters: election_data (list): A list of l...
a131d64747c5c0dde8511e9ec4da07252f96a6ec
14,539
def get_player_gamelog(player_id, season, season_type='Regular Season', timeout=30): """ Coleta de histórico departidas de um determinado jogador em uma determinada temporada, considerando ainda um tipo específico de temporada (pré-season, temporada regular ou playoffs). Parâmetros --------...
d21132df8a4f72055f37ef7039427f42ce03610e
14,540
import re def unbound_text_to_html5(text, language=None): """ Converts the provided text to HTML5 custom data attributes. Usage: {{text|unbound_text_to_html5:"Greek"}} """ # If the language is English, then don't bother doing anything if language is not None and language.lower() ...
1fe50c4844e126395c1aa1e8d5ba464217003557
14,541
def sort_points(points): """Sorts points first by argument, then by modulus. Parameters ---------- points : array_like (n_points, 3) The points to be sorted: (x, y, intensity) Returns ------- points_sorted : :class:`numpy.ndarray` (n_points, 3) The sorted po...
3d5ae7cdfa33abba906cefaf3cd1ab0ab5899e32
14,542
def get_pairs(scores): """ Returns pairs of indexes where the first value in the pair has a higher score than the second value in the pair. Parameters ---------- scores : list of int Contain a list of numbers Returns ------- query_pair : list of pairs This contains a list of pairs of indexes in ...
1d4bf17dffb7ec8b934701254448e5a7dfe41cf9
14,543
def make(): """Make a new migration. Returns: Response: json status message """ response = None try: with capture_print(escape=True) as content: current_app.config.get('container').make('migrator').make(request.form['name']) response = {'message': content.get_te...
24524cc1906f621e9e927d3e0b7265b65ab8ebe5
14,544
def generate_hmac(str_to_sign, secret): """Signs the specified string using the specified secret. Args: str_to_sign : string, the string to sign secret : string, the secret used to sign Returns: signed_message : string, the signed str_to_sign """ message = str_to_sign....
c773cb1f470f0f52934758e7f66fe01047419cbd
14,548
def interpolate_scores(coords: np.array, scores: np.array, coord_range: tuple, step: float = 0.001) -> np.array: """ Given a coord_range and values for specific coords - interpolate to the rest of the grid Args: coords: array of lons and lats of points that their values are known scores: arr...
2ed5660191f01018344e9b55af372f10133bc6a9
14,549
def remove_blank_from_dict(data): """Optimise data from default outputted dictionary""" if isinstance(data, dict): return dict( (key, remove_blank_from_dict(value)) for key, value in data.items() if is_not_blank(value) and is_not_blank(remove_blank_from_dict(value)) ...
ae77d0b5b9a1cffdd1832df3a5513cc79e600138
14,550
def merge_mosaic_images(mosaic_dict, mosaic_images, orig_images, Y_orig=None): """ Merge the list of mosaic images with all original images. Args: mosaic_dict: Dictionary specifying how mosaic images were created, returned from make_mosaic mosaic_images: List of all mosaic images returned from ...
d16875462c09b671db785ec101eb09028b1a7cbe
14,553
def show2D(dd, impixel=None, im=None, fig=101, verbose=1, dy=None, sigma=None, colorbar=False, title=None, midx=2, units=None): """ Show result of a 2D scan Args: dd (DataSet) impixel (array or None) im (array or None) """ if dd is None: return None extent, g0, g1,...
d9560e2dd54ed8daf8450e2db8e1f5d8357a601c
14,554
def get_job(api_key, jq_id): """ Fetch a job and its status :param api_key: user id of the client :param jq_id: job queue id :return: job queue id """ if Auth.verify_auth_key(api_key): if Auth.verify_job(api_key, jq_id): return trigger.get_job(jq_id) return abort(400)
f323386e530e354f52bcbcc6301c5fb1af4e4767
14,555
def contour_to_valid(cnt, image_shape): """Convert rect to xys, i.e., eight points The `image_shape` is used to to make sure all points return are valid, i.e., within image area """ # rect = cv2.minAreaRect(cnt) if len(cnt.shape) != 3: assert 1 < 0 rect = cnt.reshape([cnt.shape[0], cnt.s...
a4f85d77c0805903b220d3670edc5db05ea001ed
14,556
def search(datafile, query, bool_operator): """ Queries on a set of documents. :param datafile: The location of the datafile as a pathlib.Path :param query: the query text :param bool_operator: the operator. Must be one of [OR, AND] :return: the list of indexes matching the search criteria ...
6f8ec35063178e49a557de1849363568561638ed
14,557
from typing import Optional from typing import List def recurse_structures( structure: Component, ignore_components_prefix: Optional[List[str]] = None, ignore_functions_prefix: Optional[List[str]] = None, ) -> DictConfig: """Recurse over structures""" ignore_functions_prefix = ignore_functions_pr...
696e04a0184ebb7b8d2e0789e711a676c12ed89c
14,558
from spinalcordtoolbox.image import Image import dipy.reconst.dti as dti import dipy.denoise.noise_estimate as ne def compute_dti(fname_in, fname_bvals, fname_bvecs, prefix, method, evecs, file_mask): """ Compute DTI. :param fname_in: input 4d file. :param bvals: bvals txt file :param bvecs: bvecs...
149cfbc3f4fa2f3c1a33e4d4e6ee09983176e1b4
14,559
import tqdm def solve( netlist=None, parameter_values=None, experiment=None, I_init=1.0, htc=None, initial_soc=0.5, nproc=12, output_variables=None, ): """ Solves a pack simulation Parameters ---------- netlist : pandas.DataFrame A netlist of circuit elemen...
fa51e4e69a434e3a3c728b4675844c0bfa29d3fd
14,560
def global_node_entropy(data, dx=3, dy=1, taux=1, tauy=1, overlapping=True, connections="all", tie_precision=None): """ Calculates global node entropy\\ [#pessa2019]_\\ :sup:`,`\\ [#McCullough]_ for an ordinal network obtained from data. (Assumes directed and weighted edges). Parameters ---------- ...
a14e7419bcd58d41400b888443df726836e6d04a
14,561
def get_cert(certificate): """ Return the data of the certificate :returns: the certificate file contents """ cert_file = "{}/certs/{}".format(snapdata_path, certificate) with open(cert_file) as fp: cert = fp.read() return cert
da2ac96bf16a74de9ac75a46d14f3b95b5f64264
14,562
def model(data, ix_to_char, char_to_ix, num_iterations = 35000, n_a = 50, dino_names = 7, vocab_size = 27): """ Trains the model and generates dinosaur names. Arguments: data -- text corpus ix_to_char -- dictionary that maps the index to a character char_to_ix -- dictionary that maps a characte...
b1fb202b2c697cae1473c91597b39914e6197dce
14,563
import random def random_choice(gene): """ Randomly select a object, such as strings, from a list. Gene must have defined `choices` list. Args: gene (Gene): A gene with a set `choices` list. Returns: object: Selected choice. """ if not 'choices' in gene.__dict__: rais...
8a01a2039a04262aa4fc076bdd87dbf760f45253
14,564
def get_actor(payload: PayloadJSON, actor_id: int) -> ResourceJSON: """Return an actor by actor_id""" actor = ActorModel.find_by_id(actor_id) if actor is None: abort(404) return jsonify({"success": True, "actor": actor.json()},)
0808cba237e47a45dd095f86d44153f97a947e66
14,565
import string def check_if_punctuations(word: str) -> bool: """Returns ``True`` if ``word`` is just a sequence of punctuations.""" for c in word: if c not in string.punctuation: return False return True
64ba5f9dc69c59490a2ea69e7c2d938151d71b37
14,566
import re def normalize_text(string, remove_stopwords=False, stem_words=False): """ Remove punctuation, parentheses, question marks, etc. """ strip_special_chars = re.compile("[^A-Za-z0-9 ]+") string = string.lower() string = string.replace("<br />", " ") string = string.replace(r"(\().*(\...
0aff8864f526ffe194c661acc69ccb2cf91a6f24
14,567
def get_new_codes(): """ Return New Codes and Refresh DB""" db = dataset.connect(database_url) new_codes = get_code() table = db['promo'] """ Get New Codes""" new = {} for key, value in new_codes.items(): if table.find_one(promo=key) is None: new[key] = [new_codes[key...
e3ece2e8b43fa43ac4c8d384dbf55957d8bc62c6
14,568
def process_bulk_add_ip(request, formdict): """ Performs the bulk add of ips by parsing the request data. Batches some data into a cache object for performance by reducing large amounts of single database queries. :param request: Django request. :type request: :class:`django.http.HttpRequest` ...
d38bc7766f232b972637da9c92567ebde91ddf52
14,569
def gen_public_e(lambda_: int) -> int: """ Generates decrecingly smaller sequence of bytes and converts them to integer until one satisfies > lambda Continues with half the ammount of necesary bytes decreasing by one integer until gcd(candidate, lambda) == 1. """ bytes_ = 1028 + 1 candidat...
903df12b7af83be24d3ef377e2aa95a00a7df089
14,570
from typing import Union from re import T from typing import Callable def lazy(maybe_callable: Union[T, Callable[[], T]]) -> T: """ Call and return a value if callable else return it. >>> lazy(42) 42 >>> lazy(lambda: 42) 42 """ if callable(maybe_callable): return maybe_calla...
83522ae39b8ec19e86d5e30b2b0a9131a7c56a35
14,571
from random import shuffle def shuffle_list(*ls): """ shuffle multiple list at the same time :param ls: :return: """ l = list(zip(*ls)) shuffle(l) return zip(*l)
ec46e4a8da2c04cf62da2866d2d685fc796887e5
14,573
def cancer_variants(institute_id, case_name): """Show cancer variants overview.""" data = controllers.cancer_variants(store, request.args, institute_id, case_name) return data
185282e9308f7a9f8a0d7faf4c5d3608dee556cc
14,574
def nodes(G): """Returns an iterator over the graph nodes.""" return G.nodes()
3a1a543f1af4d43c79fd0083eb77fedd696547ec
14,575
from typing import Union def cyclePosition(image: np.ndarray, startPosition: position) -> Union[position, bool]: """ :param image: numpy image array :param startPosition: from where to go to Tuple (x,y) :return: newPosition (x,y), or false if new coords would fall out of bounds """ if not imag...
a4d3eaf1ddecc884f7391614ae04ff4b10029af3
14,576
def context_to_ingestion_params(context): """extract the ingestion task params from job/serving context""" featureset_uri = context.get_param("featureset") featureset = context.get_store_resource(featureset_uri) infer_options = context.get_param("infer_options", InferOptions.Null) source = context...
41925ce484bbc273caf9a8f0f33eba0e7163a7c8
14,578
def bining_for_calibration(pSigma_cal_ordered_, minL_sigma, maxL_sigma, Er_vect_cal_orderedSigma_, bins, coverage_percentile): """ Bin the values of the standard deviations observed during inference and estimate a specified coverage percentile in...
cb241f6292726a86a7505e950f32fd1c1fefd19f
14,579
def add_user(request): """注册用户""" info = {} tpl_name = 'user/add_user.html' if request.method == 'POST': # 保存用户提交数据 nickname = request.POST.get('nickname') if User.objects.filter(nickname__exact=nickname).exists(): # "昵称" 存在 info = {'error':'"昵称"存在'} ...
bbfd3bc8ed47f19f527352f39d5e5b2bdc80d450
14,580
def process_input(input_string, max_depth): """ Clean up the input, convert it to an array and compute the longest array, per feature type. """ # remove the quotes and extra spaces from the input string input_string = input_string.replace('"', '').replace(', ', ',').strip() # convert the s...
ca0fddd0b3bf145c7fc0654212ae43f02799b466
14,581
import random def generate_new_shape() -> tuple[int, list[int], list[int]]: """Generate new shape #0: hot_cell_y = [0,1,2,3] hot_cell_x = [5,5,5,5] X X X X #1: hot_cell_y = [0,0,0,0] hot_cell_x = [3,4,5,6] XXXX #2...
d7c2c710f72ed5d21b7e63779815ee7bfb8421f4
14,582
def get_process_list(process): """Analyse the process description and return the Actinia process chain and the name of the processing result :param process: The process description :return: (output_names, actinia_process_list) """ input_names, process_list = analyse_process_graph(process) outp...
f1e6689c50e00117379107fc840a09f4638c3912
14,583
def createAES(key, IV, implList=None): """Create a new AES object. :type key: str :param key: A 16, 24, or 32 byte string. :type IV: str :param IV: A 16 byte string :rtype: tlslite.utils.AES :returns: An AES object. """ if implList is None: implList = ["openssl", "pycrypto...
c41a5d028028383630b0977522a9617334c94d03
14,584
def update_status_issue(issue, status_id, notes): """Request to change the status of a problem in a redmine project. 'issue': A hash of the issue is bound to a redmine project. 'status_id': Id status used by redmine the project. 'notes': Comments about the update. Return value: 0 - on succe...
6c0118f514083d228ac1d27271d297b3e593be52
14,587
from typing import Optional def _get_avgiver_epost(root: ET.Element, ns: dict) -> Optional[str]: """ Sought: the email of the submitter Can be found in a child element (<mets:note>) of an <mets:agent> with ROLE="OTHER", OTHERROLE="SUBMITTER", TYPE="INDIVIDUAL" """ try: agent = [ ...
9be1f53fcf9799f3a559cd12b3bfa056aaac11a7
14,588
def xavier_init(fan_in, fan_out, constant=1): """ Xavier initialization of network weights\ """ low = -constant * np.sqrt(6.0 / (fan_in + fan_out)) high = constant * np.sqrt(6.0 / (fan_in + fan_out)) return tf.random_uniform((fan_in, fan_out), minval=low, maxval=high...
35b6f7b75eb44f1828d82c6743ec4751db4ff234
14,589
def strToMat3(dbstr): """ convert a string like e00, e01, e02, ... into Mat3 :param str: :return: panda Mat4 """ exx = dbstr.split(',') exxdecimal = map(float, exx) assert(len(exxdecimal) is 16) return Mat3(exxdecimal[0], exxdecimal[1], exxdecimal[2], exxdecimal[4...
8db33dc5e2fab613cd6cba00021486fe722c8d32
14,590
def map2(func, *matrix): """ Maps a function onto the elements of a matrix Also accepts multiple matrices. Thus matrix addition is map2(add, matrix1, matrix2) """ matrix2 = [] for i in xrange(len(matrix[0])): row2 = [] matrix2.append(row2) for j in xrange(len(ma...
9af6f311c80e70789ba6d623776fc2f80edbd905
14,591
def register_libtype(cls): """Registry of library types we may come across when parsing XML. This allows us to define a few helper functions to dynamically convery the XML into objects. See buildItem() below for an example. """ LIBRARY_TYPES[cls.TYPE] = cls return cls
bb94e9f73ec04be834fa6be7de0cebf7c10a57ec
14,592
def construct_tablepath(fmdict, prefix=''): """ Construct a suitable pathname for a CASA table made from fmdict, starting with prefix. prefix can contain a /. If prefix is not given, it will be set to "ephem_JPL-Horizons_%s" % fmdict['NAME'] """ if not prefix: prefix = "ephem_JPL-H...
95041aab91ac9994ef2068d5e05f6cd63969d94e
14,593
def _grad_mulAux(kern,x,y,yerr,original_kernel): """ __grad_mulAux() its necesary when we are dealing with multiple terms of sums and multiplications, example: ES*ESS + ES*ESS*WN + RQ*ES*WN and not having everything breaking apart Parameters kern = kernel in use x = range of values...
ce140d8a73a8304d0601077b5ed01f93cb17deab
14,594
def get_unbiased_p_hat(number_candidates, c1, c2, p): """Get the p_hat to unbias miracle. Args: number_candidates: The number of candidates to be sampled. c1: The factor that the conditional density of z given x is proportional to if the inner product between x and z is more than gamma. c2: The fac...
5d45696557835f2bc655b601e015bb08356fe2dd
14,595
def prox_gradf(xy, step): """Gradient step""" return xy-step*grad_f(xy)
7700850b9bfb5c5be5f0a63a678df93991673d81
14,596
import numpy import math def CBND(x, y, rho): """ A function for computing bivariate normal probabilities. :: Alan Genz Department of Mathematics Washington State University Pullman, WA 99164-3113 Email : [email protected] This function is bas...
3b418e50acec31482df7137f484d396b1673d476
14,597
def prune(root: Node, copy: bool = True) -> Node: """ Prune (or simplify) the given SPN to a minimal and equivalent SPN. :param root: The root of the SPN. :param copy: Whether to copy the SPN before pruning it. :return: A minimal and equivalent SPN. :raises ValueError: If the SPN structure is n...
e242156bca1d8a3be8ca673a6629dadf967ccb5b
14,598
def GetRevisionAndLogs(slave_location, build_num): """Get a revision number and log locations. Args: slave_location: A URL or a path to the build slave data. build_num: A build number. Returns: A pair of the revision number and a list of strings that contain locations of logs. (False, []) in ca...
fb8b25a0f33194af288d411b2218edf904ab9f14
14,599
import json def get_json(url, **kwargs): """Downloads json data and converts it to a dict""" raw = get(url, **kwargs) if raw == None: return None return json.loads(raw.decode('utf8'))
16504c03beaa1a5913f2256ad6a1871049694e14
14,600
def get_text(im): """ 得到图像中的文本部分 """ return im[3:24, 116:288]
86db2a16372aacb6cde29a2bf16c84f14f65d715
14,601
def homepage(): """Display tweets""" tweet_to_db() output = [a for a in Tweet.query.order_by(desc('time_created')).all()] # to display as hyper links for tweet in output: tweet.handle = linkyfy(tweet.handle, is_name=True) tweet.text = linkyfy(tweet.text) return render_template...
d37138ea2ed6bdf8a650e644943e330400417f57
14,602
def watch_list_main_get(): """ Render watch list page. Author: Jérémie Dierickx """ watchlist = env.get_template('watchlists.html') return header("Watch List") + watchlist.render(user_name=current_user.pseudo) + footer()
760c8f2acf4a3ea1791860568ae747b9bd35593c
14,603
def input_file(inp_str): """ Parse the input string """ # Parse the sections of the input into keyword-val dictionaries train_block = ioformat.ptt.symb_block(inp_str, '$', 'training_data') fform_block = ioformat.ptt.symb_block(inp_str, '$', 'functional_form') exec_block = ioformat.ptt.symb_bloc...
9ae7c55c59e6b89b43271836738fd4fffbf38455
14,604
def recursiveUpdate(target, source): """ Recursively update the target dictionary with the source dictionary, leaving unfound keys in place. This is different than dict.update, which removes target keys not in the source :param dict target: The dictionary to be updated :param dict source: The dicti...
e1c11d0801be9526e8e73145b1dfc7be204fc7d0
14,606
import time import requests import json def macro_bank_usa_interest_rate(): """ 美联储利率决议报告, 数据区间从19820927-至今 https://datacenter.jin10.com/reportType/dc_usa_interest_rate_decision https://cdn.jin10.com/dc/reports/dc_usa_interest_rate_decision_all.js?v=1578581921 :return: 美联储利率决议报告-今值(%) :rtype: ...
52885b4cfbb607d3ecbb0f89f19cac7e1f097ccd
14,607
def get_kwd_group(soup): """ Find the kwd-group sections for further analysis to find subject_area, research_organism, and keywords """ kwd_group = None kwd_group = extract_nodes(soup, 'kwd-group') return kwd_group
626a85b5274880d1e4520f4afe5a270e5f20832a
14,608
def read_transport_file(input_file_name): """ Reads File "input_file_name".dat, and returns lists containing the atom indices of the device atoms, as well as the atom indices of the contact atoms. Also, a dictionary "interaction_distances" is generated, which spcifies the maximum interaction distanc...
d62e3cc1dfbe2ac4865579dca86133bedb06182f
14,609
def handle_srv6_path(operation, grpc_address, grpc_port, destination, segments=None, device='', encapmode="encap", table=-1, metric=-1, bsid_addr='', fwd_engine='linux', key=None, update_db=True, db_conn=None, channel=None): """ Handle a SRv6 Path. ...
3181f9b4e99a6414c92614caee7af0ff133ad01d
14,610
def mask_outside_polygon(poly_verts, ax, facecolor=None, edgecolor=None, alpha=0.25): """ Plots a mask on the specified axis ("ax", defaults to plt.gca()) such that all areas outside of the polygon specified by "poly_verts" are masked. "poly_verts" must be a list of tuples of the verticies in the polyg...
1c46d12d7f3c92e3ff4522bb88713eae3c9138b1
14,611
def setup_data(cluster): """ Get decision boundaries by means of np.meshgrid :return: Tuple (vectors, centroids, X component of mesghgrid, Y component of meshgrid, ) """ feature_vectors, _, centroids, _, kmeans = cluster # Step size of the mesh. Decrease to increase the quality of the VQ. h...
edcfede8e8f7fc18fc9e7255127f0f14688df2f2
14,612
from datetime import datetime def list_errors( conx: Connection, ) -> t.List[t.Tuple[int, datetime.datetime, str, str, str, str]]: """Return list of all errors. The list returned contains each error as an element in the list. Each element is a tuple with the following layout: (seq nr, date, ...
2aea677d8e69a76c5a6922d9c7e6ce3078ad7488
14,614
async def get_incident(incident_id): """ Get incident --- get: summary: Get incident tags: - incidents parameters: - name: id in: path required: true description: Object ID responses: 200: ...
f70703b43944dfa2385a2a35249dd692fe18a1ba
14,615
from typing import List def partition_vector(vector, sets, fdtype: str='float64') -> List[NDArrayNfloat]: # pragma: no cover """partitions a vector""" vectors = [] for unused_aname, aset in sets: if len(aset) == 0: vectors.append(np.array([], dtype=fdtype)) continue ...
e73494d146ec56a8287c0e0e3ec3dec7f7d93c37
14,616
def calculate_G4( n_numbers, neighborsymbols, neighborpositions, G_elements, theta, zeta, eta, Rs, cutoff, cutofffxn, Ri, normalized=True, image_molecule=None, n_indices=None, weighted=False, ): """Calculate G4 symmetry function. These are 3 body or a...
5a864c615d2b835da4bb3d99435b9e2e2a40e136
14,617
def paths_from_root(graph, start): """ Generates paths from `start` to every other node in `graph` and puts it in the returned dictionary `paths`. ie.: `paths_from_node(graph, start)[node]` is a list of the edge names used to get to `node` form `start`. """ paths = {start: []} q = [start...
9b8399b67e14a6fbfe0d34c087317d06695bca65
14,619
from typing import Sequence from typing import Optional from typing import Callable from typing import Dict def list_to_dict(l:Sequence, f:Optional[Callable]=None) -> Dict: """ Convert the list to a dictionary in which keys and values are adjacent in the list. Optionally, a function `f` can be passed to apply...
a1f47582a2de8fa47bbf4c79c90165f8cf703ca1
14,620
def inner(a, b): """Computes an inner product of two arrays. Ordinary inner product of vectors for 1-D arrays (without complex conjugation). Parameters ---------- a, b : array_like If *a* and *b* are nonscalar, their shape must match. Returns ------- out : ndarray out....
248f1069251770073bc6bb4eedda0ef557aaeb9f
14,621
from typing import Sequence from re import T def remove_list_redundancies(lst: Sequence[T]) -> list[T]: """ Used instead of list(set(l)) to maintain order Keeps the last occurrence of each element """ return list(reversed(dict.fromkeys(reversed(lst))))
f17408e7c3e3f5b2994e943b668c81b71933a2c9
14,622
def bpformat(bp): """ Format the value like a 'human-readable' file size (i.e. 13 Kbp, 4.1 Mbp, 102 bp, etc.). """ try: bp = int(bp) except (TypeError, ValueError, UnicodeDecodeError): return avoid_wrapping("0 bp") def bp_number_format(value): return formats.number_f...
4c2b587b3aecd4dd287f7f04b3860f63440154a1
14,625
def get_module_id_from_event(event): """ Helper function to get the module_id from an EventHub message """ if "iothub-connection-module_id" in event.message.annotations: return event.message.annotations["iothub-connection-module-id".encode()].decode() else: return None
e183824fff183e3f95ef35c623b13245eb68a8b7
14,626
def pipe_literal_representer(dumper, data): """Create a representer for pipe literals, used internally for pyyaml.""" return dumper.represent_scalar('tag:yaml.org,2002:str', data, style='|')
b73e7d451ae50bc4638d3cb45546f2a197765717
14,627
def RecognitionNeuralNetworkModelSmall(ih, iw, ic, nl): """ A simple model used to test the machinery on TrainSmall2. ih, iw, ic - describe the dimensions of the input image mh, mw - describe the dimensions of the output mask """ dropout = 0.1 model = Sequential() model.add(Conv2D(32,...
e4ec0ccb958eb9b406c079aeb9526e5adc1f6978
14,628
def _quick_rec_str(rec): """try to print an identifiable description of a record""" if rec['tickets']: return "[tickets: %s]" % ", ".join(rec["tickets"]) else: return "%s..." % rec["raw_text"][0:25]
e666198de84fe9455ad2cee59f8ed85144589be0
14,629
from typing import Collection def A006577(start: int = 0, limit: int = 20) -> Collection[int]: """Number of halving and tripling steps to reach 1 in '3x+1' problem, or -1 if 1 is never reached. """ def steps(n: int) -> int: if n == 1: return 0 x = 0 while True: ...
47829838af8e2fdb191fdefa755e728db9c09559
14,630
def split_to_sentences_per_pages(text): """ splitting pdfminer outputted text into list of pages and cleanup paragraphs""" def split_into_sentences(line): """cleanup paragraphs""" return ifilter(None, (i.strip() for i in line.split('\n\n'))) return ifilter(None, imap(split_into_sentences...
b40ac7d6b4f3e9482897934999858271aeaf9494
14,631
def lookup(_id=None, article_id=None, user_id=None, mult=False): """ Lookup a reaction in our g.db """ query = {} if article_id: query["article_id"] = ObjectId(article_id) if user_id: query["user_id"] = ObjectId(user_id) if _id: query["_id"] = ObjectId(_id) if m...
5d3c064278da8419e6305508a3bf47bba60c818c
14,632
def connection(user='m001-student', password='m001-mongodb-basics'): """connection: This function connects mongoDB to get MongoClient Args: user (str, optional): It's user's value for URL ATLAS srv. Defaults to 'm001-student'. password (str, optional): It's password's value for URL ATLAS srv. D...
0714ffa01aa21dd71d6eefcadb0ebc2379cd3e6f
14,633
import random import asyncio async def get_selection(ctx, choices, delete=True, pm=False, message=None, force_select=False): """Returns the selected choice, or None. Choices should be a list of two-tuples of (name, choice). If delete is True, will delete the selection message and the response. If length o...
663f60c73bc6c1e3d7db5992b6dbb6d6953d0e24
14,634
def total_variation(images, name=None): """Calculate and return the total variation for one or more images. (A mirror to tf.image total_variation) The total variation is the sum of the absolute differences for neighboring pixel-values in the input images. This measures how much noise is in the ima...
c12e822cd09ff6ea5f9bbc45ffa71121de5ff3e7
14,636
def get_vivareal_data(driver_path: str, address: str, driver_options: Options = None) -> list: """ Scrapes vivareal site and build a array of maps in the following format: [ { "preço": int, "valor_de_condominio": int, "banheiros": int, "quartos": int,...
e3495c05f39e7cb301fa90e62b5a398a69658e74
14,637
import logging def extract_image(data): """Tries and extracts the image inside data (which is a zipfile)""" with ZipFile(BytesIO(data)) as zip_file: for name in zip_file.namelist()[::-1]: try: return Image.open(BytesIO(zip_file.read(name))) except UnidentifiedIm...
2aa333d493a1a3ce637fb2d42bca85bbbb089728
14,638
import six def construct_getatt(node): """ Reconstruct !GetAtt into a list """ if isinstance(node.value, (six.text_type, six.string_types)): return node.value.split(".") elif isinstance(node.value, list): return [s.value for s in node.value] else: raise ValueError("Une...
657b957a06c79905b557dd397efea2c598d8c6b3
14,639
def rss(x, y, w, b): """residual sum of squares for linear regression """ return sum((yi-(xi*wi+b))**2 for xi, yi, wi in zip(x,y, w))
955e0b5e3dcf8373fe5ef1b95244d06abe512084
14,641
def get_index(lang, index): """ Given an integer index this function will return the proper string version of the index based on the language and other considerations Parameters ---------- lang : str One of the supported languages index : int Returns ------- str ...
bcb3a88857b13eea95d5a1bb939c9c4e175ea677
14,642
def sampleFunction(x: int, y: float) -> float: """ Multiply int and float sample. :param x: x value :type x: int :param y: y value :type y: float :return: result :return type: float """ return x * y
f70708b3ece2574969834a62841da3e4506f704b
14,643
def n_elements_unique_intersection_np_axis_0(a: np.ndarray, b: np.ndarray) -> int: """ A lot faster than to calculate the real intersection: Example with small numbers: a = [1, 4, 2, 13] # len = 4 b = [1, 4, 9, 12, 25] # (len = 5) # a, b need to be unique!!! unique(concat(a,...
ce8e3cfd158205a0fa2c5f1d10622c6901bc3224
14,644
import logging def Setup(test_options): """Runs uiautomator tests on connected device(s). Args: test_options: A UIAutomatorOptions object. Returns: A tuple of (TestRunnerFactory, tests). """ test_pkg = test_package.TestPackage(test_options.uiautomator_jar, tes...
2d50c53d211bbddae495a89687cf0cf95b08b1ba
14,645
def barcode_junction_counts(inhandle): """Return count dict from vdjxml file with counts[barcode][junction]""" counts = dict() for chain in vdj.parse_VDJXML(inhandle): try: # chain may not have barcode counts_barcode = counts.setdefault(chain.barcode,dict()) except AttributeEr...
5cc29e44e34989fbd2afb4a2d34f63c7e7adf160
14,646
def is_following(user, actor): """ retorna True si el usuario esta siguiendo al actor :: {% if request.user|is_following:another_user %} You are already following {{ another_user }} {% endif %} """ return Follow.objects.is_following(user, actor)
963ccc2f75f19609943aba6b61a7522573665033
14,647
from typing import Union def rf_make_ones_tile(num_cols: int, num_rows: int, cell_type: Union[str, CellType] = CellType.float64()) -> Column: """Create column of constant tiles of one""" jfcn = RFContext.active().lookup('rf_make_ones_tile') return Column(jfcn(num_cols, num_rows, _parse_cell_type(cell_type...
8ed63c974613e0451a3d8c78eac964c93c6f8154
14,648
def get_block_hash_from_height(height): """ Request a block hash by specifying the height :param str height: a bitcoin block height :return: a bitcoin block address """ resource = f'block-height/{height}' return call_api(resource)
877f4c4268cb3c7c36bd530a38d4b32abbedcaf4
14,649
from typing import Tuple from typing import Set from typing import List def analyze_json( snippet_data_json: str, root_dir: str ) -> Tuple[Set[str], Set[str], Set[str], List[pdd.PolyglotDriftData]]: """Perform language-agnostic AST analysis on a directory This function processes a given directory's l...
9129b1fad5172f9b7054ba9b4e64cc4ece5ab09c
14,650