content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def win_path_check(path): """ Format a file path correctly for Windows """ if IS_WIN: return path.replace("\\", "/").replace(":", "\\:") return path
ef338386462af2f38cc2c645c36b02f25be014ff
40,900
from typing import Callable def signal_or() -> Callable[[int, int], int]: """A circuit element performing a bitwise OR on two signals.""" return lambda x, y: limit_signal(x | y)
1ffceeda3c6d74ed4a433a3eb50cbeff0c5d0aaf
40,901
import requests def create_github_issue_helper(ctx, issue): """Logic for dev command""" url = f"https://api.github.com/repos/{REPO_OWNER}/{REPO_NAME}/issues" headers = dict(Authorization=f"token {GITHUB_PAT}", Accept="application/vnd.github.v3+json") data = { "title": issue,...
88c9e21a9da4fed67cbe6dba73c2afbf2ec2d648
40,902
from fastf1 import events import warnings def get_session(*args, **kwargs): """ .. deprecated:: 2.2 replaced by :func:`fastf1.get_session` """ # TODO remove warnings.warn("`fastf1.core.get_session` has been deprecated and will be" "removed in a future version.\n" ...
0aa1852ec0dd5879d403bc3a572fab84df471e37
40,903
def add_user(): """ Endpoint to add user Json passed by POST: ex. { "id": "jibao" } :return: 201, object created or 409, object already exist """ user_id = request.json['id'] obj_created = db_manager.add_user(user_id) if not obj_created: abort(409) return make_re...
69b25ff7e4cf8724762ec1772fe77e3ab915216a
40,904
def get_report_format(self, filename): """各帳票フォーマットの格納場所を取得する。 :param self: :param filename: :return: """ prefix = 'reports/{}/'.format(self.parking_lot.name) return prefix + filename
206804eb32803db12cf8de74b22574f2e94e510e
40,905
import sys def _encodehack(s): """ :param s: input string :type s: :class:str or :class:bytes: or :class:unicode Yields either UTF-8 decodeable bytestring (PY2) or PY3 unicode str. """ if sys.version_info[0] > 2: if type(s) == str: return s # type(s) is PY...
471d80c5bf35ade97d82b77eb7d628e86924643f
40,906
def read_float(field: str) -> float: """Read a float.""" return float(field) if field != "" else float('nan')
ce6f862c9696e3f84ba20b58a0acdce5c1e212b0
40,907
from datetime import datetime def seconds_into_year(now): """Compute the number of seconds into the current year. Args: now: Current time. Returns: Number of seconds since January 1 at midnight on the same year as now. """ year_start = datetime.datetime(now.year, 1, 1, 0, 0, 0, tzinf...
371dcd25cad62a9d769a8145c88c332256625d2e
40,908
def get_available_quantity_for_stock(stock): """Count how many stock items are available.""" quantity_allocated = get_quantity_allocated_for_stock(stock) return max(stock.quantity - quantity_allocated, 0)
f56420858effd12373a42939c7a1a329205506a3
40,909
def _to_rnn_cell(cell_or_type, num_units, num_layers): """Constructs and return an `RNNCell`. Args: cell_or_type: Either a string identifying the `RNNCell` type, a subclass of `RNNCell` or an instance of an `RNNCell`. num_units: The number of units in the `RNNCell`. num_layers: The number of laye...
fe5629d6dd525af91b92dcd0c8fcf3a37f5cdf19
40,910
from typing import List from typing import Dict from typing import Counter def layout_aware_vocabulary_vector( results: List[Dict], number_of_words: int, classification_targets: List[str] ) -> List[str]: """Create a layout aware vocabulary vector Finds the most popular words per l...
38aa95768863c1ca70a07b43d608a278713b1461
40,911
def main_menu_bar(widget): """ Create a main menu bar. This requires setting `menu_bar=True` in the `concur.integrations.glfw.main` method. Otherwise, space wouldn't be reserved for the menu bar, and it would lay on top of window contents. Main menu bar must be created outside any windows. Se...
e811ffeeb9cb3cf361e845b79f6f387c6148f64b
40,912
import re def GetDestFromParam(param, prefix=None): """Returns a conventional dest name given param name with optional prefix.""" name = param.replace('-', '_').strip('_') if prefix: name = prefix + '_' + name return resource_property.ConvertToSnakeCase( re.sub('s?I[Dd]$', '', name)).strip('_')
7f2274d4bdc322dbc24e3cee252615db37078b18
40,913
def get_trigger_name(operation, source_table, when): """Non-PostgreSQL trigger name""" op_initial = operation.lower()[0] when_initial = when.lower()[0] return f"trigger_{source_table}_{when_initial}{op_initial}r"
4e67005512fee99dd1bf5ed8b5d979e747d27b9f
40,914
def cycle_graph(n: int) -> Graph: """ Construct the unweighted cycle graph on :math:`n` vertices. :param n: The number of vertices in the graph :return: The cycle graph on :math:`n` vertices, as a `Graph` object. :raises ValueError: if the number of vertices is not a positive integer. :Example...
37f378c0cf1c13aa33cdec644cfb2c4863d83109
40,915
import os import json def load_canonical(exercise, spec_path): """ Loads the canonical data for an exercise as a nested dictionary """ full_path = os.path.join(spec_path, "exercises", exercise, "canonical-data.json") with open(full_path) as f: spec = json.load(f) spec["properties"] = g...
4159cb5909843194e76ab880344504bb0413d506
40,916
def mailing_keyboard(mailing_status, notification_status, language_code): """Make keyboard for mailing parameters""" keyboard = [ [ # buttons names and callback according to current states make_button( (buttons.ALLOW_MAILING if mailing_status == c...
1127179bfb2155c165374db8560d7fc79110e2c2
40,917
def calculate_fold_change(reads, normalized_counts, control_samples, treatment_samples, pseudocount, replicate): """ Create a dataframe with index as guide ids Calculate log2 ratio (foldchange) between treated and control reads :param reads: Dataframe containing read counts (guide level) :param norm...
2f92d7afd3f8738a4d911bf4cd64db7b8898bdac
40,918
import functools import asyncio def wrap_coroutine(func, event_loop, before_test): """Return a sync wrapper around an async function to be executed in the event loop.""" @functools.wraps(func) def inner(**kwargs): if before_test is not None: before_test() coro = func(**kwargs) ...
1ddc4bc70a2def3ce989b1fdc44262bcdb0e35f8
40,919
def get_deprt(lista): """Add together from row with same index.""" base = [] for item in lista: base.append(item) resultado = set(base) return resultado
ecc3026d7674fcd90100db7d0b82cbc4376f1e4e
40,920
import typing import uuid def dot_tree( root: behaviour.Behaviour, visibility_level: common.VisibilityLevel=common.VisibilityLevel.DETAIL, collapse_decorators: bool=False, with_blackboard_variables: bool=False, with_qualified_names: bool=False): """ Paint your tree on a...
08fda4f3c97387e1c1e47b8e7a400278811b42df
40,921
def get_events_with_abstract_reviewer_convener(user, dt=None): """ Return a dict of event ids and the abstract reviewing related roles the user has in that event. :param user: A `User` :param dt: Only include events taking place on/after that date """ data = defaultdict(set) # global re...
84274d5e93ff3183d9f4a1348492e91ea24f6fef
40,922
def h5gr_to_workup_input(gr, format): """Return a dictionary containing important parameters for working up a phasekick dataset. The dictionary contains: y: Cantilever oscillation data dt: spacing between t0: Initial time t1: Time with V = V_1 t2: Time wit...
0b89955de12922805558bd55da49c2bdbe564618
40,923
import contextlib def colocation_cm(colocation, name=None, op=None): """Gets a context manager to colocate ops.""" if colocation: return tf.colocate_with(tf.no_op(name) if op is None else op) return contextlib.suppress()
eaab7ad7f8fba9bd25d2af028a4afc371c4cbedb
40,924
def inverse_helper_col_row_multiply(matrix, i, j, value): """Helper to multiply matrix with identity matrix having replaced value. Args: matrix: A matrix (list of lists). i: A column index. j: A row index. value: A value to place at the given row/column. Returns: A ...
559ea43939b9d78b73c4ac718a26e9d897775b29
40,925
def get_dummy_image_name(): """ Returns the name of the dummy image """ return "python-logo.jpeg"
0a3a3664d06449641eb5ca32e03edd64d31eb63b
40,926
import os def get_default_locale_callable(): """ Wrapper function so that the default mapping is only built when needed """ exec_dir = os.path.dirname(os.path.realpath(__file__)) xml_path = os.path.join(exec_dir, "data", "FacebookLocales.xml") fb_locales = _build_locale_table(xml_path) d...
1f7b0cbd2c4219b698af268336a62f7e484f2d12
40,927
def s(*args, **kwargs): """ Create a RedisCluster instance with 'init_slot_cache' set to false """ s = _get_client(RedisCluster, init_slot_cache=False, **kwargs) assert s.connection_pool.nodes.slots == {} assert s.connection_pool.nodes.nodes == {} return s
b3975a6b65798fc33080ec138c8f5ad406e592e1
40,928
def svd_thresh(input_data, threshold=None, n_pc=None, thresh_type='hard'): """Threshold the singular values. This method thresholds the input data using singular value decomposition. Parameters ---------- input_data : numpy.ndarray Input data array, 2D matrix threshold : float or numpy...
8b897b0fccb150138f9b95824e0c26258b5a2d73
40,929
import base64 def decode_image(field): """Decode a base64 encoded image to a list of floats. Args: field: base64 encoded string Returns: numpy.array """ array = np.frombuffer(base64.b64decode(field), dtype=np.uint8) image_array = cv2.imdecode(array, cv2.IMREAD_ANYCOLOR) # BGR ...
939dfb7658eb8a41757bf855c2e5388f6b8162ba
40,930
def compute_layer_style_cost(a_S, a_G): """ Arguments: a_S -- tensor of dimension (1, n_H, n_W, n_C), hidden layer activations representing style of the image S a_G -- tensor of dimension (1, n_H, n_W, n_C), hidden layer activations representing style of the image G Returns: J_style_layer...
5210fa06e6145fd864adc6b6733e397114947c75
40,931
def check_punctuation(words): """Check to see if there's a period in the sentence.""" punctuation = [".", ",", "?"] return [word for word in words if word in punctuation]
4de89db149924ae3d457e57a3f9edac5dd4ae18a
40,932
def log_users(): """ API for authentication microservice. Creates an entry to be stored temporarily in a global dictionary. ''' """ global logged_in_users_flag # Receive response from Authenticate microservice new_user = request.json logged_in_users_flag[new_user[0]] = new_u...
04c529737eeb47d3d276e36bd8d7dea9733465e8
40,933
def _GetIngressChanges(args): """Returns changes to ingress traffic allowed based on the flags.""" platform = platforms.GetPlatform() if platform == platforms.PLATFORM_MANAGED: return config_changes.SetAnnotationChange(service.INGRESS_ANNOTATION, args.ingress) e...
6b22ae1b0b9642072cd69c4419b1036cb35fd08f
40,934
import os def get_current_socket_names(): """ Get all cybld socket names """ ret = list() for socket_file in os.listdir(get_base_path()): if socket_file.startswith(SOCKET_BASE_NAME): ret.append(socket_file) ret.sort() return ret
aa0d8ea8306dd2ff5f9dbd2af402b3a7d613d201
40,935
def get_page(page_number: int, cards: str, page_template: str, section_template: str, contexts: list, is_card_backs: bool=False, is_filler: bool=False, exclude_section: bool=False) -> str: """ Populate a page with cards. """ ...
37b238fdd7dfe6c257ae3729db1660134318a311
40,936
def prepare_updates_dict(updates): """ Prepare a Theano `updates` dictionary. Ensure that both keys and values are valid entries. NB, this function is heavily coupled with its clients, and not intended for general use.. """ def prepare_key(key, val): if not isinstance(key, SharedVa...
c8f8c829cc7608a06d63aced4cadd3278447ddeb
40,937
import collections def optimize_graph(graph: Graph) -> Graph: """ Perform a pass of the graph, removing any redundant DUP nodes that we added (which have Node.optimizable = True). A redundant DUP node is when a DUP node has only one output. In this case, the DUP node is superfulous and can be remo...
afb8dbac88e6ffcfb1ae881195e32826749053c4
40,938
def get_label_conf(y_vec): """ Returns the confidence and the label of the most probable class given a vector of class confidences :param y_vec: (np.ndarray) vector of class confidences, nb of instances as first dimension :return: (np.ndarray, np.ndarray) confidences and labels """ assert len(y_...
b5205cee207451eb6bd897657ab23bd3bbaf035c
40,939
def unique_rows_tol(data, tol=1e-12, return_index=False, return_inverse=False): """ This function returns the unique rows of the input matrix within that are within the specified tolerance. Parameters ---------- data: numpy array (m x n) tol: double tolerance of comparison for each ...
11223616645f56199c40f8a71ad5f20283636b84
40,940
def transformed_retrace( q_tm1: ArrayLike, q_t: ArrayLike, a_tm1: ArrayLike, a_t: ArrayLike, r_t: ArrayLike, discount_t: ArrayLike, pi_t: ArrayLike, mu_t: ArrayLike, lambda_: float, eps: float = 1e-8, stop_target_gradients: bool = True, tx_pair: TxPair = IDENTITY_PAIR, ) ...
50390be415af3d45bb5220ccd2ddefd21ca7916d
40,941
def api_all_feeds(request): """ This views to retreive feeds """ if request.is_ajax(): return JsonResponse(get_feeds())
92287f3d1cf9da484c8734eb634728f48bfde0c8
40,942
import os def is_windows(): """ Return ``True`` if running on Windows. :rtype: bool """ return os.name == "nt"
81fb198b36230f8aa901df34a988d33c6973a837
40,943
import requests import time def get_clip_info(clip_id, user): """Use given clip id to fetch info from Twitch API.""" # Note: Twitch recommends giving the API 15 seconds to fetch a newly # created clip. If 15 seconds passes and we receive nothing, we can # assume that no clip was created. failures...
341075ed180b5e241f6a7f278aade55276fcb2e2
40,944
import torch def Accuarcy_find(pred, tar, device): """ This function calculates the the accuarcy and confussion matrix """ if device == "cpu": ft = torch.FloatTensor else: ft = torch.cuda.FloatTensor tar = tar.view(-1, tar.shape[-1]) art_pred = pred[:, 1] >= 0.5 # what the...
83e1d5825360afaa549835cecd6b1d85665311f1
40,945
def resolve_ipv6(name, flags=0): """Lookup an AAAA record for a given *name*. To disable searching for this query, set *flags* to ``QUERY_NO_SEARCH``. Returns (ttl, list of packed IPs). """ waiter = Waiter() core.dns_resolve_ipv6(name, flags, waiter.switch_args) result, _type, ttl, addrs = ...
2aad1a3d77cfd08e11f898626cfc700c596be3a7
40,946
from typing import Optional def knn_assigned_text_sectors( run: Optional[Run] = None, clustered: bool = True, ): """the text sectors of the K nearest neighbours after reassignment""" run = run or get_run("ClusterReassignFlow") if clustered: return run.data.knn_assigned_text_sectors els...
1dbd82b838f3986246eec8b0b2b1cc1dced2c2cd
40,947
from typing import Iterable from typing import Union from typing import List from typing import Tuple import os import hashlib def get_hashed_combo_path( root_dir: str, subdir: str, task: str, combos: Iterable[Union[List[str], Tuple[str, str]]], ) -> str: """ Return a unique path for the given...
b81b5d9d3b17a43daf4023200f7b7e40a26eb21e
40,948
import array from operator import inv def arma_forecast(time_series, phis=array([]), thetas=array([]), mu=0., sigma=1., future_periods=20): """ Return forecasts for a time series modeled with the given ARMA model. Parameters ---------- time_series : ndarray of shape (n,1) The ...
f525551193f2f9f3055cd4ab2e19309aaea257ed
40,949
def sign_assertion(root, cert1, cert2, key): """Sign the SAML assertion in the response using the IdP key""" try: print('[*] Signing the SAML assertion') assertion_id = root.find("{urn:oasis:names:tc:SAML:2.0:assertion}Assertion").get("ID") signer = XMLSigner(c14n_algorithm="http://www.w...
51f5b6d4383248a180b9ef05bc82dd91209c776a
40,950
def poweriter(A,numiter): """ poweriter(A,numiter) Perform `numiter` power iterations with the matrix `A`, starting from a random vector, and return a vector of eigenvalue estimates and the final eigenvector approximation. """ n = A.shape[0] x = randn(n) x = x/norm(x,Inf) gamma = zeros(numiter) for k in range...
d838678e51c4b220312d96b557157dacef092b32
40,951
import itertools def opendata_postal_codes_v1(db): """ API v1 data postal codes route. Example:: GET /api/v1/opendata/postal_codes .. note:: Filtering can be done through the ``filter`` GET param, according to JSON API spec (http://jsonapi.org/recommendations/#filtering). ...
a22f9db460edb71da5d9c81d18b1ba25f0074a31
40,952
def get_valid_group(id, name): """ Returns a valid group object """ group = Group() group.id = id group.name = name return group
bdca0f5f019dab318244510405d16527930a1e50
40,953
def svn_repos_authz_check_access(*args): """ svn_repos_authz_check_access(svn_authz_t authz, char repos_name, char path, char user, svn_repos_authz_access_t required_access, apr_pool_t pool) -> svn_error_t """ return _repos.svn_repos_authz_check_access(*args)
9aa1295a4e8794a35afca8d9143862bfa151d482
40,954
def mark_for_testing(**kwargs): """Mark module for testing.""" def decorator(cls): _MARKED_CLASSES.append(MarkedClass(cls, **kwargs)) return cls return decorator
9ab69a2899efd940fda600d25494a27cfd4b45d0
40,955
def load_ref_system(): """ Returns propane as found in the IQMol fragment library. All credit to https://github.com/nutjunkie/IQmol """ return psr.make_system(""" H 1.9131 -0.1215 1.0479 C 1.2683 -0.0636 0.1619 H 1.5702 0.8259 -0.4068...
dbc076a7ede811be956af3f2037c6885e442eee1
40,956
import calendar from datetime import datetime def make_test_time_old() -> context.Time: """Generates unix timestamp for an old date.""" return test_context.TestTime(calendar.timegm(datetime.date(1970, 1, 1).timetuple()))
eb8b2a78f25be93d433489c9bc1bbd7b3e93ba80
40,957
def get_stream_inventory_report_link_for_region(point: Point): """ Returns Fish Inventory Data Query (FIDQ) links for streams within this watershed area. """ point_3005 = transform(transform_4326_3005, point) # look up region that this point is in cql_filter = f"""INTERSECTS(SHAPE, {point_3...
e96584aac8f70745244d342836f9f885de644889
40,958
def baymodel_data_with_missing_flavor(): """Generates random baymodel data with missing flavor :returns: BayModelEntity with generated data """ return baymodel_data(keypair_id=config.Config.keypair_id, image_id=config.Config.image_id)
094e3f1e24299275b33fadbe4f7566a62d2a624c
40,959
def run_intcode(memory, input_list, instr_ptr=0, input_ptr=0, previous_output=None): """Run an Intcode program from memory""" output = previous_output while instr_ptr < len(memory): instruction = memory[instr_ptr] digits = list_digits(instruction) # extract opcode opcode_pai...
5651ff72dd502145f45688425e4e952051eeb5e5
40,960
from typing import Optional def get_engine_sampler(processor_id: str, gate_set_name: str, project_id: Optional[str] = None) \ -> 'cirq.google.QuantumEngineSampler': """Get an EngineSampler assuming some sensible defaults. This uses the environment variable GOOGLE_CLOUD_PROJECT ...
3aa2fc89ee2c8800ae6d0e16331b6432cc5bd429
40,961
import random def frequency_sampling_paragraph(thief_vocab, thief_probs, para_len=None): """Sample words according to a unigram frequency to build a paragraph.""" if para_len is None: # randomly choose a length from 75 to 500 para_len = np.random.randint(75, 500) assert len(thief_probs) == len(thief_voc...
de76270092d951b7c4aaeb0f999569b4e76e6978
40,962
import csv def cast_cadastro_cliente(): """ Função que acessa os itens do arquivo bd_cliente_rotativo em modo read e, faz o append dos dados para a lista_cadastro para iteração. :return: Condição que informa que não existe nenhum veiculo cadastrada para iterar """ try: with open('bd_c...
23ee1b504343eba1e2b0f775f6690ff919de9b99
40,963
def generate_pool_name(**kwargs): """Generate a pool name. This function takes keyword arguments, usually the connection arguments and tries to generate a name for the pool. Args: **kwargs: Arbitrary keyword arguments with the connection arguments. Raises: PoolError: If the name c...
e03d7daf92a4b810753cad9eb5943d58e68b6423
40,964
def cluster_domain_DBScan( x: np.ndarray, y: np.ndarray, time: np.ndarray, ) -> np.ndarray: """ return the cluster ID based on the given data using DBScan @param x: event position x vector @param y: event position y vector @param time: event TOA vector @returns: clustering results ...
29d3ad8ccad1189326b31ad33acfdfc1a84dcbeb
40,965
def retrofit_neural(X, in_edges, out_edges, k=5, n_iter=100, alpha=None, beta=None, tol=1e-2, lr=0.5, lam=1e-5, verbose=0, lr_decay=0.9, batch_size=32, patience=20): """ Retrofit according to the neural penalty function. Parameters ---------- X : np.arra...
1945c80390aedc0c5e94c41cd9eac89b1507f0c0
40,966
def fake_create_test_db(self, verbosity=1, autoclobber=False): """Simplified version of BaseDatabaseCreation.create_test_db.""" test_database_name = self._get_test_db_name() if verbosity >= 1: test_db_repr = '' if verbosity >= 2: test_db_repr = " ('%s')" % test_database_name ...
cc63a9e2075451cc314b4ef497299b2b7e490c4c
40,967
def value_from_choices_label(label, choices): """ Return the choices value for a given label """ # Search choices by label result = None for choices_value, choices_label in choices: if label == choices_label: result = choices_value # If search by label failed, check if we...
52dee6ae49adb1e10a7453009fdf29e07dd1ab82
40,968
def find_nearest_kp_2d(pcl2d, kps2d): """ find nearest 2d distance keypoint for every point in pcl. :param pcl2d: [N,2] N points' xyz :param kps2d: [K,2] K points' xyz :return: nearest_kps2d [N,2] Nearest keypoint coordinate of every points. """ N, _ = pcl2d.shape K, _ = kps2d.shape ...
8d0f0cae1157e2dacef79238077dbcef919f2892
40,969
def get_trace_data_from_device(client): """Get the trace data using RPC from a Client""" data = b'' service = client.client.channel(1).rpcs.pw.trace.TraceService result = service.GetTraceData().responses for streamed_data in result: data = data + bytes([len(streamed_data.data)]) data...
227e0b141f7bfa8d7c2f9b4b77e2e5643b77ead2
40,970
def make_word(parts, sub, i): """Replace a syllable in a list of words, and return the joined word.""" j = 0 for part in parts: for k in range(len(part)): if i == j: part[k] = sub return ' '.join(''.join(p for p in part) for part in parts) j +=...
869aa94f60b819b38ad7ddc315b65d862cf525e0
40,971
def calc_anchors_pillar_center(proposals, l=7, h=7, w=7, anchor_offset=[0.5, 0.5, 0.5]): """ calc the proposals' center location of each grid proposals: [bs, 6]: [xmin, xmax, ymin, ymax, zmin, zmax] return: anchors_pillars: [batch_size, l, h, w, 3] """ proposal_unstack = tf.unstack(pro...
bee9c4c64acd87bb28109ad379d8eb612154288e
40,972
def acq_max(ac, gp, y_max, bounds, random_state, n_warmup=10000, n_iter=10): """ A function to find the maximum of the acquisition function It uses a combination of random sampling (cheap) and the 'L-BFGS-B' optimization method. First by sampling `n_warmup` (1e5) points at random, and then running ...
5e0a4dc4f6c9ffa6fc102c360e8d1c7fb91de782
40,973
def number_negatives(seq): """Number of negative residues a protein sequence""" # Convert sequence to upper case seq = seq.upper() for aa in seq: if aa not in bootcamp_utils.aa.keys(): raise RuntimeError(aa + ' is not a valid amino acid.') # Count E's and D's, since these are t...
19bf9498732fb73914f892944fbf525397742dc0
40,974
def dcmread_scale(fn): """Transform from path of raw pixel data to scaled one and inversing (if the case)""" dcm = dcmread(fn) return dcm_scale(dcm)
7e76f5b9e8b0935d9859a42db917002ab45c80ea
40,975
import re def parse(lines): """ Parse a list of lines from nose output. :param lines: list of nose error output lines. :returns: nose output augmented with specially formatted lines adapted to this plugin errorformat which will populate Vim clist. """ results = [] lines = iter(li...
59f2a89fd16b4bfcaa020dfc6bccde62b1ea1511
40,976
import struct import sys import itertools import six import collections def total_size(obj): """Returns the approximate total memory footprint an object.""" seen = set() def sizeof(current_obj): try: return _sizeof(current_obj) except Exception: # pylint: disable=broad-except # Not sure wha...
3d1387eb74da146f033c6824852cba83463d2404
40,977
import attr def attr_lt(accessing_obj, accessed_obj, *args, **kwargs): """ Usage: attr_gt(attrname, 54) Only true if access_obj's attribute < the value given. """ return attr(accessing_obj, accessed_obj, *args, **{'compare':'lt'})
88903d0921e5d4efaa25561dbf93e12403896256
40,978
import locale import math def format_col(df, col_name, rounding=0, currency=False, percent=False): """Function to format numerical Pandas Dataframe columns (one at a time). WARNING: This function will convert the column to strings. Apply this function as the last step in your script. Output is the formatted ...
a049c3a5f0ce28c3ec54ad0988e2679d512c6135
40,979
def slice_signal(signal, window_size, stride=0.5): """ Return windows of the given signal by sweeping in stride fractions of window """ assert signal.ndim == 1, signal.ndim n_samples = signal.shape[0] offset = int(window_size * stride) slices = [] for beg_i, end_i in zip(range(0, n_s...
b99202008858cd610aaf4a7969a897e88a2ba5fa
40,980
def create_mysql_oursql(username, password, host, port, database, **kwargs): # pragma: no cover """ create an engine connected to a mysql database using oursql. """ return create_engine( _create_mysql_oursql(username, password, host, port, database), **kwargs )
d1fac26b36f4045fe1bfe797b2929b888867531e
40,981
from typing import Optional def post_primary(user: User, number: str) -> FluxData: """ view to mark one of the (verified) phone numbers of the logged in user as the primary phone number. Returns a listing of all phones for the logged in user. """ proofing_user = ProofingUser.from_user(user, c...
23011b0ed91de3ff8166d7cf389fb148d674caa7
40,982
def does_nothing(profile): """ evaluate if the profile is just doing nothing to the loss. this allows to save some memory and compulation time and memory during the calculation :param profile: np.array of fm_profile_dtype or fm_profile_step_dtype profile :return: boolean : True i...
cfd7db22cc206bce85d677f6d0e2186c7b65a0f0
40,983
def pis_pasep(formatting: bool=True, data_only: bool=True) -> str: """Gere o código do PIS/PASEP aleatório.""" r = fordev_request( content_length=26, referer='gerador_de_pis_pasep', payload={ 'acao': 'gerar_pis', 'pontuacao': 'S' if formatting else 'N' } ...
cb0d9944b00210e3f278b74e7858c601a01e8e82
40,984
def tab_clickable_evt() -> str: """Adds javascript code within HTML at the bottom that allows the interactivity with tabs. Returns ------- str javascript code in HTML to process interactive tabs """ return """ <script> function menu(evt, menu_name) { var i, tab...
bc15f819ef615200d09a356e250bc2d41710b36a
40,985
def urban_patches(built_up, transform): """Identify urban patches.""" built_up = binary_closing(built_up, iterations=int( 100 / transform.a), border_value=1) patch_geoms = [] for geom, value in shapes(built_up.astype('uint8'), connectivity=4, transform=transform): if value == 1: ...
41e1eca80a45a54d3f96db8f7b849e793d3307bc
40,986
def add_new_comp(mol, option=None, comp_id=None): """Function to add a new compound to the database given an RDKit molecule Takes an RDKit molecule. Option of LIG to return original smiles with the Compound object Returns a compound object for the RDKit molecule.""" # Neutralise and desalt compound the ...
10fec0a63daa328d31ab82cd315358c1371a3e9a
40,987
def get_resource_tokens(source, data_only=False, tokenize_variables=False): """Parses the given source to resource file tokens. Otherwise same as :func:`get_tokens` but the source is considered to be a resource file. This affects, for example, what settings are valid. """ lexer = Lexer(ResourceFile...
922d07a83310fb58d3be07d1de0e4065bace2409
40,988
from typing import Dict def aggregate_author_stance_preds(preds: np.ndarray) -> Dict[int, float]: """ describe what's going on """ max_pred_indices = np.argmax(preds, axis=1) max_pred_values = np.max(preds, axis=1) max_index_value_pairs = zip(max_pred_indices, max_pred_values) max_index_va...
37e1e7bc894ad3cc712047c1fed31266ebb80e51
40,989
import os import io import PIL import hashlib def dict_to_tf_example(data, dataset_directory, label_map_dict, ignore_difficult_instances=False, image_subdirectory='JPEGImages'): """Convert XML derived dict to tf.Example prot...
0b9b9bf86e4ffb0f6dafe31e927833a08334a637
40,990
import os import csv def load_prisoner_locations_from_file(filename): """ Load prisoner locations matching test NOMIS data """ csv_path = os.path.join(os.path.dirname(__file__), os.path.pardir, 'fixtures', filename) with open(csv_path) as f: csv_reader = csv.DictReader(f) prisoner...
4c085f510c8685e8a733f36872efc6b8faabe1e3
40,991
def data_mnist(datadir='/tmp/', train_start=0, train_end=60000, test_start=0, test_end=10000): """ Load and preprocess MNIST dataset :param datadir: path to folder where data should be stored :param train_start: index of first training set example :param train_end: index of last train...
49924f5ecaefb7fcc122e178001cbf704c961741
40,992
def validate_input_config(config): """Validate that the input source is valid""" input_manifest_s3_uri = config.get("inputManifestS3Uri") chain_from_job_name = config.get("chainFromJobName") if input_manifest_s3_uri and not chain_from_job_name: return None if not input_manifest_s3_uri and ...
4a2788c421225b7c38ec9414285e38d3323ac1ab
40,993
def create_app(config=None, testing=False, cli=False): """Application factory, used to create application """ app = Flask('insta_pic') configure_app(app, testing) configure_extensions(app, cli) register_blueprints(app) @app.errorhandler(Exception) def error_handler(e): return j...
0ddf25cc0dbc0c9073e977bc5b1a2b4ed700614f
40,994
def get_cast_table(paths, player_data, blocklist): """ Create an aggregated CastTable from GamParse output file(s) :param paths: a list of paths to GamParse output :param player_data: a PlayerData object :param blocklist: a list of spells to be ignored :return: a CastTable object """ re...
b4e99b0231687982c5d62083f63be9d9cdd9440e
40,995
def polygon_area(polygon): """ Get the area of a polygon which is represented by a 2D array of points. Area is computed using the Shoelace Algorithm. Args: polygon: 2D array of points. """ x = polygon[:, 0] y = polygon[:, 1] area = (np.dot(x, np.roll(y, -1)) - np.dot...
90431d15f0a0cf57b7983daf2510f2c4493fb48d
40,996
def isValidAutoIp(ip): """Checks an IPv4 or IPv6 address where "auto" is a valid value""" if ip != "auto": try: isValidIpv4(ip) except TypeError: isValidIpv6(ip) return True
0385c5153fc333c03925ec3eb8e4a3269f3d3341
40,997
def addScaleBar(ax, *args, **kwargs): """ Utility function to add a scalebar to a plot. Args: ax (`matplotlib.axes.Axes`): axes object to which to add the scale bar *args: arguments passed on to `.ScaleBar` **kwargs: key-word arguments passed on to `.ScaleBar` Returns: ...
340d0eefe86081742e383f8e64e932974e06231e
40,998
def containsAny(seq, aset): """ Check whether sequence seq contains ANY of the items in aset. """ for c in seq: if c in aset: return True return False
a83040058110dc773da3e694418c4711f0e7dc61
40,999