content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def map_vocabulary(docs, vocabulary): """ Maps sentencs and labels to vectors based on a vocabulary. """ mapped = np.array([[vocabulary[word] for word in doc] for doc in docs]) return mapped
b5b39aeac6306709a4b4ac10a29d40a2006d57ff
3,638,331
def mobilenetv3_large_minimal_100(pretrained=False, **kwargs): """ MobileNet V3 Large (Minimalistic) 1.0 """ # NOTE for train set drop_rate=0.2 model = _gen_mobilenet_v3('mobilenetv3_large_minimal_100', 1.0, pretrained=pretrained, **kwargs) return model
717a67b1ab7cb0ad7a6c8d40ea4b0b29108eff94
3,638,332
def get_identity(user, identity_uuid): """ Given the (request) user and an identity uuid, return None or an Active Identity """ try: identity_list = get_identity_list(user) if not identity_list: raise CoreIdentity.DoesNotExist( "No identities found for use...
800e47d8782fc5e71e97192f76713032eade9441
3,638,333
def same_strange_looking_function(param1, callback_fn): """ This function is documented, but the function is identical to some_strange_looking_function and should result in the same hash """ tail = param1[-1] # return the callback value from the tail of param whatever that is return callback...
438becf6803e6b25a200a34e18eb648aaa4b6fbb
3,638,334
def __extractFunction(text, jsDoc, classConstructor): """ Extracts a function depending of its pattern: 'function declaration': function <name>(<parameters>) { <realization> }[;] 'named function expression': <variable> = function <name>(<...
992604ccd1e56da6706cf2e4ec2955c2c9ecfa7e
3,638,336
def vocabulary_size(tokens): """Returns the vocabulary size count defined as the number of alphabetic characters as defined by the Python str.isalpha method. This is a case-sensitive count. `tokens` is a list of token strings.""" vocab_list = set(token for token in tokens if token.isalpha()) return ...
5e26e1be98a3e82737277458758f0fd65a64fe8f
3,638,337
from typing import Dict from typing import Any from typing import Optional from typing import Tuple def max_iteration_for_analysis(query: Dict[str, Any], db: cosem_db.MongoCosemDB, check_evals_complete: bool = False, conv_it:...
b5d0bebd2af634ac72f8bc318276d0f7c03114f2
3,638,338
def getMatirces(Dynamics, Cost): """ This functions takes the dynamics class as input and outputs the required matrices and cvxpy.variables to turn the covariance steering problem into a finite dimensional optimization problem. """ Alist = Dynamics.Alist Blist = Dynamics.Blist Dlist = Dy...
50de11ba3f3d1528f7ff577861613b96f8e35254
3,638,339
def get_transit_boundary_indices(time, transit_size): """ Determines transit boundaries from sorted time of transit cut out :param time (1D np.array) sorted times of transit cut out :param transit_size (float) size of the transit crop window in days :returns tuple: [0...
cd3775d72690eb4539e0434b0ac7f715d14374a6
3,638,340
def decode_gbe_string(s): """This helper function turns gbe output strings into dataframes""" columns, df = s.replace('","',';').replace('"','').split('\n') df = pd.DataFrame([column.split(',') for column in df.split(';')][:-1]).transpose().ffill().iloc[:-1] df.columns = [c.replace('tr_','') for c in co...
0a2d262b2653f736ef8ae7c7ed4b969faf80e9bf
3,638,342
import re def get_scihub_namespaces(xml): """Take an xml string and return a dict of namespace prefixes to namespaces mapping.""" nss = {} matches = re.findall(r'\s+xmlns:?(\w*?)\s*=\s*[\'"](.*?)[\'"]', xml.decode('utf-8')) for match in matches: prefix = match[0]; ns = match[1] ...
b1d5a32d7583a655c59fa5175bdd133899bf6223
3,638,343
def valid_verify_email(form, email): """ Returns true if "email" is equal the first email """ try: if(form.email.data!=form.email_verify.data): raise ValidationError('Email address is not the same') if models.Account.pull_by_email(form.email.data) is not None: pri...
16073bb559e06759632323289f49e127bb9f8cb1
3,638,344
def _computePolyVal(poly, value): """ Evaluates a polynomial at a specific value. :param poly: a list of polynomial coefficients, (first item = highest degree to last item = constant term). :param value: number used to evaluate poly :return: a number, the evaluation of poly with value """ #return numpy.polyval...
0377ba0757439409824b89b207485a99f804cb41
3,638,345
from io import StringIO def fix_e26(source): """Format block comments.""" if '#' not in source: # Optimization. return source string_line_numbers = multiline_string_lines(source, include_docstrings=True) fixed_lines = [] sio = Strin...
ec569e442c2244421afa94cc8316478c55377220
3,638,346
def graph_distance(tree, node1, node2=None): """ Return shortest distance from node1 to node2, or just update all node.distance shortest to node1 """ for node in tree.nodes(): node.distance = inf node.back = None # node backwards towards node1 fringe = Queue([node1]) while fri...
0764d2a687933631d592e1b6d40ceec8d629036c
3,638,347
def trunicos(b): """Return a unit-distance embedding of the truncated icosahedron graph.""" p0 = star_radius(5)*root(1,20,1) p1 = p0 + root(1,20,1) p2 = mpc(b, 0.5) p3 = cu(p2, p1) p4 = cu(p3, p1*root(1,5,-1)) p5 = cu(p4, p2*root(1,5,-1)) return (symmetrise((p0, p1, p2, p3, p4, p5), "D5"...
018112497882a6f0a572cf2c1c222cdf36ca95e9
3,638,348
import torch def histogram2d( x1: torch.Tensor, x2: torch.Tensor, bins: torch.Tensor, bandwidth: torch.Tensor, epsilon: float = 1e-10 ) -> torch.Tensor: """Function that estimates the 2d histogram of the input tensor. The calculation uses kernel density estimation which requires a bandwidth (smoothing) p...
5e360f1e9350a29664e3beb1d0cc6ba3024647b9
3,638,349
import json def webhooks_v2(request): """ Handles all known webhooks from stripe, and calls signals. Plug in as you need. """ if request.method != "POST": return HttpResponse("Invalid Request.", status=400) event_json = json.loads(request.body) event_key = event_json['type'].repla...
afa86e189c417a147ae05fa46e89d985207c403b
3,638,350
def nth(iterable, n, default=None): """ Returns the nth item or a default value :param iterable: The iterable to retrieve the item from :param n: index of the item to retrieve. Must be >= 0 :param default: the value to return if the index isn't valid :return: the nth item, or the default value i...
9f0eb8a31d8b4499d8538f6aefc9dba8231b27e0
3,638,351
import types def _dict_items(typingctx, d): """Get dictionary iterator for .items()""" resty = types.DictItemsIterableType(d) sig = resty(d) codegen = _iterator_codegen(resty) return sig, codegen
6435320c6ba490b85c3ef4c065f55cef0d7d2c8e
3,638,352
def odd_desc(count): """ Replace ___ with a single call to range to return a list of descending odd numbers ending with 1 For e.g if count = 2, return a list of 2 odds [3,1]. See the test below if it is not clear """ return list(reversed(range(1,count*2,2)))
2f90095c5b25f8ac33f3bb86d3f46e67932bc78a
3,638,353
def retrieval_score(test_ratings: pd.DataFrame, recommender, remove_known_pos: bool = False, metric: str = 'mrr') -> float: """ Mean Average Precision / Mean Reciprocal Rank of first relevant item @ N """ N = recommender.N user_scores = [] ...
c7167eef0195496ea460dcbe63926028c430433e
3,638,354
def test_dump_load_keras_model_with_dict(tmpdir, save_and_load): """Test whether tensorflow ser/de-ser work for models returning dictionaries""" class DummyModel(tf.keras.Model): def __init__(self): super().__init__() def _random_method(self): pass def call(sel...
5fcaf73e5a0b138a04091573782a2c03f4459f15
3,638,355
def stemmer_middle_high_german(text_l, rem_umlauts=True, exceptions=exc_dict): """text_l: text in string format rem_umlauts: choose whether to remove umlauts from string exceptions: hard-coded dictionary for the cases the algorithm fails""" # Normalize text text_l = normalize_middle_high_german( ...
608ec49ad36ee5ae7ad41fe4eab5d9f7c65eb609
3,638,356
def test_queue_trials(start_connected_emptyhead_cluster): """Tests explicit oversubscription for autoscaling. Tune oversubscribes a trial when `queue_trials=True`, but does not block other trials from running. """ cluster = start_connected_emptyhead_cluster runner = TrialRunner() def creat...
fed9fe1458db15f871ccd4afff942c0d022a9b8a
3,638,357
def get_bboxes(outputs, proposals, num_proposals, num_classes, im_shape, im_scale, max_per_image=100, thresh=0.001, nms_thresh=0.4): """ Returns bounding boxes for detected objects, organized by class. Transforms the proposals from the region proposal network to bounding box predictions ...
09e5eb94f35672e77980c89e71fcb9ed6b460ab4
3,638,358
def air_transport_per_year_by_country(country): """Returns the number of passenger carried per year of the given country.""" cur = get_db().execute('SELECT Year, Value FROM Indicators WHERE CountryCode="{}" AND IndicatorCode="IS.AIR.PSGR"'.format(country)) air_transport = cur.fetchall() cur.close() ...
4ca85c537c5bc7ccda332af977f1252b14672235
3,638,359
def outside_range(number, min_range, max_range): """ Returns True if `number` is between `min_range` and `max_range` exclusive. """ return number < min_range or number > max_range
dc3889fbabb74db38b8558537413ebc5bc613d05
3,638,360
import re def is_string_constant(node): """Checks whether the :code:`node` is a string constant.""" return is_leaf(node) and re.match('^\"[^\"]*\"$', node) is not None
5a62c513bc856571e62c40b9d14bdefb67be4c79
3,638,361
from typing import List def is_list_type(t) -> bool: """ Return True if ``t`` is ``List`` python type """ # print(t, getattr(t, '__origin__', None) is list) return t == list or is_pa_type(t, pa.types.is_list) or ( hasattr(t, '__origin__') and t.__origin__ in (list, List) ) or ( ...
7da1ea98dccc4341a6db7a3e13e9f9bd278bd984
3,638,362
from datetime import datetime def get_measure_of_money_supply(): """ 从 Sina 获取 中国货币供应量数据。 Returns: 返回获取到的数据表。数据从1978.1开始。 Examples: .. code-block:: python >>> from finance_datareader_py.sina import get_measure_of_money_supply >>> df = get_measure_of_money_supply() ...
304cf05be6a226e7da46ec16e36a6632f02848c5
3,638,363
def make_inverter_path(wire, inverted): """ Create site pip path through an inverter. """ if inverted: return [('site_pip', '{}INV'.format(wire), '{}_B'.format(wire)), ('inverter', '{}INV'.format(wire))] else: return [('site_pip', '{}INV'.format(wire), wire)]
066c4bbad0f65fec587b12fc7a2947246401b877
3,638,365
def constant(t, length): """ ezgal.sfhs.constant( ages, length ) Burst of constant starformation from t=0 to t=length """ if type(t) == type(np.array([])): sfr = np.zeros(t.size) m = t <= length if m.sum(): sfr[m] = 1.0 return sfr else: return 0.0 if t > length el...
bfbc32042512465c7fecc50d976b369ac8e2c9fe
3,638,367
def model_setup_fn(attrs): """Generate the setup function for models.""" model = load_model(attrs['type'], attrs['data']) def func(self): self.model = model self.type = attrs['type'] self.data = attrs['data'] self.network_type = attrs['network_type'] self.dto = attr...
4f0ffa9e1de3f60edef847faf319f3c5a4bef28d
3,638,368
def _mkdir(space, dirname, mode=0777, recursive=False, w_ctx=None): """ mkdir - Makes directory """ mode = 0x7FFFFFFF & mode if not _valid_fname(dirname): space.ec.warn("mkdir() expects parameter 1 to " "be a valid path, string given") return space.w_False if not ...
c16b5e0100c50e300fcf9268383f20b1cb5c11b5
3,638,369
import decimal def prepare_fixed_decimal(data, schema): """Converts decimal.Decimal to fixed length bytes array""" if not isinstance(data, decimal.Decimal): return data scale = schema.get('scale', 0) size = schema['size'] # based on https://github.com/apache/avro/pull/82/ sign, digit...
5dc5ae8355842e175e1fa83394a63b37c04bdade
3,638,370
from typing import Any def device_traits() -> dict[str, Any]: """Fixture that sets default traits used for devices.""" return {"sdm.devices.traits.Info": {"customName": "My Sensor"}}
1ccaeac4a716706915654d24270c24dac0210977
3,638,371
def calculate_equivalent_diameter(areas): """Calculate the equivalent diameters of a list or numpy array of areas. :param areas: List or numpy array of areas. :return: List of equivalent diameters. """ areas = np.asarray(areas) diameters = np.sqrt(4 * areas / np.pi) return diameters.tolis...
a353883cf148819d9f298167e73acd60b89720e5
3,638,373
def truncation_error(stencil: list, deriv: int, interval: str = DEFAULT_INTERVAL): """ derive the leading-order of error term in the finite difference equation based on the given stencil. Args: stencil (list of int): relative point numbers used for discretization. deriv (int...
e3b8d312d551ed88ead3690b285659d56865e6e0
3,638,374
def cmd_renderurl(cfg, command, argv): """Renders a single url of your blog to stdout.""" parser = build_parser('%prog renderurl [options] <url> [<url>...]') parser.add_option('--headers', action='store_true', dest='headers', default=False, help='Option that caus...
2073c71c459357c0b6a9661596cad34196fd6c24
3,638,376
def combine_expressions(expressions, relation='AND', licensing=Licensing()): """ Return a combined license expression string with relation, given a list of license expressions strings. For example: >>> a = 'mit' >>> b = 'gpl' >>> combine_expressions([a, b]) 'mit AND gpl' >>> assert ...
8955522546a8b803caf0b1c6a3c6e8752cb35a19
3,638,377
import sqlite3 def get_prof_details(prof_id): """ Returns the details of the professor in same order as DB. """ cursor = sqlite3.connect('./db.sqlite3').cursor() cursor.execute("SELECT * FROM professor WHERE prof_id = ?;", (prof_id)) return cursor.fetchone()
668652474009abdda36d3e97fb5d30074f0a2755
3,638,379
def available_help(mod, ending="_command"): """Returns the dochelp from all functions in this module that have _command at the end.""" help_text = [] for key in mod.__dict__: if key.endswith(ending): name = key.split(ending)[0] help_text.append(name + ":\n" + mod.__dict__...
9afa1525c016aa74dd4b3eb91851890da3590524
3,638,382
from functools import reduce import operator def __s_polynomial(g, h): """ Computes the S-polynomial of g, h. The S-polynomial is a polynomial built explicitly so that the leading terms cancel when combining g and h linearly. """ deg_g = __multidegree(g) deg_h = __multidegree(h) max_deg =...
49aa5b5b1dbebde1309aaa9fd2cb5947a010709f
3,638,383
def generate_map_chunk(size_x: int, size_y: int, biome_type: str, x_offset: int = 0, y_offset: int = 0): """ Function responsible for generating map chunk in specified or random biome type, map chunk is basically a rectangular part of a map; generated array is basically nested list representing ...
42863b7058bfce23b1123c14db562483254bdc21
3,638,384
def test_process_cycle(zs2_file_name, verbose=True): """This is a test to check if util output changed in an incompatible manner. A zs2 file is read, converted to XML, and back-converted to a raw datastream.""" if verbose: print('Decoding %s...' % zs2_file_name) data_stream = _parser.l...
6417362a9bdaa4086865f0b8fc510dda186534f7
3,638,386
def get_dev_risk(weight, error): """ :param weight: shape [N, 1], the importance weight for N source samples in the validation set :param error: shape [N, 1], the error value for each source sample in the validation set (typically 0 for correct classification and 1 for wrong classification) """ ...
7278a8827dd48c341d9f294a3fed3a8b2e3c71ae
3,638,387
import torch def skewness_fn(x, dim=1): """Calculates skewness of data "x" along dimension "dim".""" std, mean = torch.std_mean(x, dim) n = torch.Tensor([x.shape[dim]]).to(x.device) eps = 1e-6 # for stability sample_bias_adjustment = torch.sqrt(n * (n - 1)) / (n - 2) skewness = sample_bias_a...
ae0bdea16c1461a2e407ed57279557bc8c7f56de
3,638,388
import random def encrypt(message): """ Self-developed encryption method that uses base conversion """ base = random.randint(3, 9) number_list = [] for i in message: number_list.append(keys.index(i)+1) converted_number_list = [] for i in number_list: converted_number_list.appen...
967d45341fb8a5ec87f946ba6fc0a603f491485e
3,638,389
def get_signature_algorithm(algorithm_type_string): """convert a string into a key_type (TFTF_SIGNATURE_TYPE_xxx) returns a numeric key_type, or raises an exception if invalid """ try: return TFTF_SIGNATURE_ALGORITHMS[algorithm_type_string] except: raise ValueError("Unknown algorith...
41ca226dc7e6c1c0f8d5b8592803d6555630902c
3,638,390
def corrgroups60(display=False): """ A simulated dataset with tight correlations among distinct groups of features. """ # set a constant seed old_seed = np.random.seed() np.random.seed(0) # generate dataset with known correlation N = 1000 M = 60 # set one coefficent from each grou...
5a80116890ff262a164f48421871107c4cdaf8a6
3,638,392
def alpha_nu_gao08(profile, **kwargs): """log normal distribution of alpha about the alpha--peak height relation from Gao+2008""" z = kwargs["z"] alpha = kwargs["alpha"] # scatter in dex if "sigma_alpha" in kwargs: sigma_alpha = kwargs["sigma_alpha"] else: # take scatter fr...
393fdc6c87d4bf61fc367e7f9033bac24b9d6cea
3,638,393
import base64 def get_feed_entries(helper, name, stats): """Pulls the indicators from the minemeld feed.""" feed_url = helper.get_arg('feed_url') feed_creds = helper.get_arg('credentials') feed_headers = {} # If auth is specified, add it as a header. if feed_creds is not None: auth = '...
e881eebaaa9c31bc8d0abdd8b8f4aaeb9efcffe6
3,638,394
def get_skeleton_definition(character): """ Returns skeleton definition of the given character :param character: str, HIK character name :return: dict """ hik_bones = dict() hik_count = maya.cmds.hikGetNodeCount() for i in range(hik_count): bone = get_skeleton_node(character, i)...
f76d4613f3a8adec649ea689d049ccff2966783c
3,638,395
def get_f_a_st( fuel="C3H8", oxidizer="O2:1 N2:3.76", mech="gri30.cti" ): """ Calculate the stoichiometric fuel/air ratio of an undiluted mixture using Cantera. Calculates using only x_fuel to allow for compound oxidizer (e.g. air) Parameters ---------- fuel : str ...
ecd711d8a1d5499e47ccbedebfb5641aec7c7a8b
3,638,396
def get_parser_args(args=None): """ Transform args (``None``, ``str``, ``list``, ``dict``) to parser-compatible (list of strings) args. Parameters ---------- args : string, list, dict, default=None Arguments. If dict, '--' are added in front and there should not be positional arguments. ...
41b607a6ebf12526efcd38469192b398419327bf
3,638,397
def parse_time_to_min(time): """Convert a duration to an integer in minutes. Example ------- >>> parse_time_to_min("2m 30s") 2.5 """ if " " in time: return sum([parse_time_to_min(t) for t in time.split(" ")]) time = time.strip() for unit, value in time_units.items(): ...
6bf9656694ba4787bf9fd3e7c269d9c84e3ed143
3,638,398
def relate_stream_island(stream_layer, island_layer): """ Return the streams inside or delimiting islands. The topology is defined by DE-9IM matrices. :param stream_layer: the layer of the river network :stream_layer type: QgisVectorLayer object (lines) :param island_layer: the layer of the...
1d6c90349808f6364cc8b1461b09a0c31df6d9d3
3,638,399
def stringify_array(v, maxDepth=None, maxItems=-1, maxStrlen=-1): """ Convert a dict to a string representation. Parameters: d(dict) : the data dict to convert maxDepth (int|None): if > 0, then ellipsise structures deeper than th...
17bf5008c7a263c102f0fa03fdcc708c0fcc9a0f
3,638,400
import pickle def rpickle(picke_file, state=None): """ Save the state of the gps file treated """ logger.warning('Running rpickle ...') results = [] if picke_file.isfile(): with open(picke_file, 'rb') as read_pickle: results += pickle.load(read_pickle) # print results ...
a3f0cc46d6992032d008053e679ec75c64805141
3,638,401
def should_print(test_function): """should_print is a helper for testing code that uses print For example, if you had a function like this: ```python def hello(name): print('Hello,', name) ``` You might want to test that it prints "Hello, Nate" if you give it the name "Nate". To d...
16a1f675d3dced411fe5a6ffdc566db61ca7890f
3,638,403
def produce_segmentation(indices: list[list[int]], wav_name: str) -> list[dict]: """produces the segmentation yaml content from the indices of the probabilistic_dac Args: indices (list[list[int]]): output of the probabilistic_dac function wav_name (str): the name of the wav file (with the .wav ...
cd8267e90f5e69589325a4e261d3f8136b36cc53
3,638,405
def trac_get_tracs_for_object(obj, user=None, trac_type=None): """ Returns tracs for a specific object. """ content_type = ContentType.objects.get_for_model(type(obj)) qs = Trac.objects.filter(content_type=content_type, object_id=obj.pk) if user: qs = qs.filter(user=user) if trac_typ...
9617fc5e417e40fb27bfe90b2f87434902cdb70b
3,638,406
def size_from_ftp(ftp, url): """Get size of a file on an FTP server. Parameters ---------- ftp : FTP An open ftplib FTP session. url : str File URL. Returns ------- int Size in bytes. """ url = urlparse(url) return ftp.size(url.path)
50d21fa95669a9863b32de3a67eda78de713fe7c
3,638,407
def set_name_line(hole_lines, name): """Define the label of each line of the hole Parameters ---------- hole_lines: list a list of line object of the slot name: str the name to give to the line Returns ------- hole_lines: list List of line object with label ...
a57667f269dac62d39fa127b2a4bcd438a8a989b
3,638,408
import torch def dist_to_boxes(points, boxes): """ Calculates combined distance for each point to all boxes :param points: (N, 3) :param boxes: (N, 7) [x, y, z, h, w, l, ry] :return: distances_array: (M) torch.Tensor of [(N), (N), ...] distances """ distances_array = torch.Tensor([]) b...
b3305ec8a4c8d5e0d5cf520e9e22d2c5377fe1de
3,638,409
def blackwhite2D(data,xsize=None,ysize=None,show=1): """blackwhite2D(data,xsize=None,ysize=None,show=1)) - display list or array data as black white image default popup window with (300x300) pixels """ if type(data) == type([]): data = array(data) w,h = data.shape[1],data.shape[0] ...
78a76fab9f3eb989697b695c8d7b82c877f8dc9a
3,638,411
def contains_digit(s): """Find all files that contain a number and store their patterns. """ isdigit = str.isdigit return any(map(isdigit, s))
941bcee8b6fbca6a60a8845f88a3b5765e3711bb
3,638,412
def to_signed(dtype): """ Return dtype that can hold data of passed dtype but is signed. Raise ValueError if no such dtype exists. Parameters ---------- dtype : `numpy.dtype` dtype whose values the new dtype needs to be able to represent. Returns ------- `numpy.dtype` "...
7be15d324eef6f9686a5866a92ad365a67949424
3,638,413
def listen_for_wakeword(): """Continuously detecting the appeareance of wakeword from the audio stream. Higher priority than the listen() function. Returns: (bool): return True if detected wakeword, False otherwise. """ gotWakeWord = core.listen_for_wakeword() return gotWakeWord
49f600ed303fb9bea11cb9247653c66272fc5491
3,638,414
from scipy.stats import kurtosis def kurtosis(x,y): """ Calculate kurtosis of the probability distribution of the forecast error if an observation and forecast vector are given. Both vectors must have same length, so pairs of elements with same index are compared. Description: Ku...
b4242f58db8a48dbe9bec03ec641ae78858c28f7
3,638,416
def preprocess_text(sentence): """Handle some weird edge cases in parsing, like 'i' needing to be capitalized to be correctly identified as a pronoun""" cleaned = [] words = sentence.split(' ') for w in words: if w == 'i': w = 'I' if w == "i'm": w = "I'm" ...
4e1d69eaf0adc1ede6bc67563e499602e320e76b
3,638,417
def csr_scale_rows(*args): """ csr_scale_rows(npy_int32 const n_row, npy_int32 const n_col, npy_int32 const [] Ap, npy_int32 const [] Aj, npy_bool_wrapper [] Ax, npy_bool_wrapper const [] Xx) csr_scale_rows(npy_int32 const n_row, npy_int32 const n_col, npy_int32 const [] Ap, npy_int32 const [] Aj, ...
887f6c51d297649232d6fd297380c551dbb47008
3,638,420
def complexity_hjorth(signal): """**Hjorth's Complexity and Parameters** Hjorth Parameters are indicators of statistical properties initially introduced by Hjorth (1970) to describe the general characteristics of an EEG trace in a few quantitative terms, but which can applied to any time series. The pa...
af5b5fb8925055da4cf48facadd1bed257e40f76
3,638,422
import pandas def load_gecko(): """ target variable is column "A375 Percent rank" """ data_nonessential = pandas.read_excel(settings.pj(settings.offtarget_data_dir, 'GeCKOv2_Non_essentials_Achilles_A375_complete.xls')) #(4697, 31) data_all_A375 = pandas.read_csv(settings.pj(settings.offtarget_data...
31c2db07261fb1b242f4c52808c3b7e6312b1e54
3,638,423
def get_sample_eclat(name): """Read a tweet sample from a sample file and return it in a format eclat can process. """ sampleFile = open(name) X = [] Y = [] line = sampleFile.readline() while line != '': row = line.split() Y.append(int(row[0])) x = [] ...
dd5daa2cd19b087c4b59379b8d3b2c2ea9ec27de
3,638,424
from datetime import datetime def submission_storage_path(instance, filename): """ Function DocString """ string = '/'.join(['submissions', instance.submission_user.user_nick, str(instance.submission_question.question_level), str(instance.submission_question.question_level_id)]) string += '/'+...
587785869da8906234bb572e9d635a892dc3270b
3,638,425
def distance_to_center(n): """Return Manhattan distance to center of spiral of length <n>.""" dist = distances_to_center() for _ in range(n - 1): next(dist) return next(dist)
1301d0370a3f3dca72fb003073522376fd0790c0
3,638,426
from typing import List from typing import Mapping from typing import Any from typing import Optional import inspect async def _assert_preconditions_async(preconditions: List[List[Contract]], resolved_kwargs: Mapping[str, Any]) -> Optional[BaseException]: """Assert that the p...
d89c355ed56e350a619e1d7324c8341bb74f827c
3,638,428
import re def moveGeneratorFromStrList (betaStringList, string_mode = True): """ generate the final output of move sequence as a list of dictionary. Input : ['F5-LH', 'F5-RH', 'E8-LH', 'H10-RH', 'E13-LH', 'I14-RH', 'E15-LH', 'G18-RH'] Length of the list: how many moves in this climb to the target...
c2905fffd9d1873c79239199027697e5c6162731
3,638,429
from datetime import datetime def generateVtBar(row): """生成K线""" bar = VtBarData() symbol, exchange = row['symbol'].split('.') bar.symbol = symbol bar.exchange = exchangeMapReverse[exchange] if bar.exchange in ['SSE', 'SZSE']: bar.vtSymbol = '.'.join([bar.symbol, bar.exc...
5beecf78f932c8e1bf76c680157ecd29fbdf9567
3,638,430
import sqlite3 def index_with_links(): """post request that the form link uses """ db = sqlite3.connect('link_shortner.db') c = db.cursor() link = request.forms.get('link') generated_id = gen_id() #row = db.execute('SELECT * from links where link_id=?', generate_id).fetchone() c.execut...
38e4ee6e63bacbc55a40533759c06b836a050e56
3,638,431
def divide_blend(img_x: np.ndarray, img_y: np.ndarray) -> np.ndarray: """ Blend image x and y in 'divide' mode :param img_x: input grayscale image on top :param img_y: input grayscale image at bottom :return: """ result = np.zeros_like(img_x, np.float_) height, width = img_x.shape f...
27207b209c871a794162ee5b2932344a185668e7
3,638,433
def init_wavefunction(n_sites,bond_dim,**kwargs): """ A function that initializes the coefficients of a wavefunction for L sites (from 0 to L-1) and arranges them in a tensor of dimension n_0 x n_1 x ... x n_L for L sites. SVD is applied to this tensor iteratively to obtain the matrix product state. ...
8f1a4d456945d9a345f560ee3d87dadbf353e7d3
3,638,435
def num_channels_to_num_groups(num_channels): """Returns number of groups to use in a GroupNorm layer with a given number of channels. Note that these choices are hyperparameters. Args: num_channels (int): Number of channels. """ if num_channels < 8: return 1 if num_channels < 3...
e2095fba2b1b9cdada72d354ddcd781d99e4aa48
3,638,436
def response_message(status, message, status_code): """ method to handle response messages """ return jsonify({ "status": status, "message": message }), status_code
e9dd25f237f264835d507af01a71ef9c826bf28d
3,638,437
def glDrawBuffers( baseOperation, n=None, bufs=None ): """glDrawBuffers( bufs ) -> bufs Wrapper will calculate n from dims of bufs if only one argument is provided... """ if bufs is None: bufs = n n = None bufs = arrays.GLenumArray.asArray( bufs ) if n is None: n = a...
ef5a83ea633138d4cb18d8d2d20736d8c1942bc0
3,638,438
def compare_rendered(obj1, obj2): """ Return True/False if the normalized rendered version of two folium map objects are the equal or not. """ return normalize(obj1) == normalize(obj2)
b7debf048ea41b882003283b6e3b94d257f0e0fa
3,638,439
async def _get_device_client_adapter(settings_object): """ get a device client adapter for the given settings object """ if not settings_object.device_id and not settings_object.id_scope: return None adapter = adapters.create_adapter(settings_object.adapter_address, "device_client") ad...
411b52a4e916d55b46933afbfa4e8513243b4397
3,638,440
def is_reserved(word): """ Determines if word is reserved :param word: String representing the variable :return: True if word is reserved and False otherwise """ lorw = ['define','define-struct'] return word in lorw
0b0e3706bcafe36fc52e6384617223078a141fb2
3,638,441
def verify_figure_hash(name, figure=None): """ Verifies whether a figure has the same hash as the named hash in the current hash library. If the hash library does not contain the specified name, the hash is added to the library. Parameters ---------- name : string The identifier for the...
09ee240c9efbeddd4a0f33401d80b918175a579e
3,638,442
def x_span_contains_y(x_spans, y_spans): """ Return whether all elements of y_spans are contained by some elements of x_spans :param x_spans: :type x_spans: :param y_spans: :type y_spans: """ for i, j in y_spans: match_found = False for m, n in x_spans: i...
c366a5a5543e2fe9f6325cd3d31eccffb921693c
3,638,443
import time def log(fn): """ logging decorator for the for the REST method calls. Gets all important information about the request and response, takes the time to complete the calls and writes it to the logs. """ def wrapped(self, *args): try: start = time() ret...
8efcfcf043c220565092971749a12876a55641dc
3,638,445
def deal_line(text_str1, text_str2, para_bound=None): """行合并和段落拆分""" global result_text text_str2 = text_str2.strip() len_text_str2 = len(text_str2) if len_text_str2 > 3 and len(set(text_str2)) == 1: # 处理 ***** 这类分割线 st = list(set(text_str2))[0] # new_file.write(' ' + st * 24 +...
b984cefd842071fed3359ac36f8bae46e916e956
3,638,446
def resized_image(image: np.ndarray, max_size: int) -> np.ndarray: """Resize image to feature_process_size.""" h, w = image.shape[:2] size = max(w, h) if 0 < max_size < size: dsize = w * max_size // size, h * max_size // size return cv2.resize(image, dsize=dsize, interpolation=cv2.INTER_...
a32f0639b8b59cef8817861d123b5c304b7c243c
3,638,447
def load_folder_list(args, ndict): """ Args: dict : "name_run" -> path """ l = [] for p in ndict: print("loading %s" % p) l.append(load_pickle_to_dataframe(args, p)) d = pd.concat(l) d = d.sort_values("name_run") print("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%...
bd434fd93b3cb06a18d40edc48f8119442e7f0ff
3,638,448
def charge_initial(): """ Not currently in use, parking spot id gets passed in and it carries over and passes it into the stripe charge view. """ spot_id = int(request.args.get('id')) spot = AddressEntry.query.get(spot_id) return render_template('users/charge_initial.html', key=stripe_keys['...
f971b5c69954ce2026d2c4b08d6877c9f7da6067
3,638,449
import csv def read_csv_from_file(file): """ Reads the CSV data from the open file handle and returns a list of dicts. Assumes the CSV data includes a header row and uses that header row as fieldnames in the dict. The following fields are required and are case-sensitive: - ``artist`` ...
89cfce0be6270076230051a6e852d1add3f4dcaf
3,638,450
def identify_denonavr_receivers(): """ Identify DenonAVR using SSDP and SCPD queries. Returns a list of dictionaries which includes all discovered Denon AVR devices with keys "host", "modelName", "friendlyName", "presentationURL". """ # Sending SSDP broadcast message to get devices devices ...
712cba308d150ec179a390c27ae6931595cdffa9
3,638,452
def get_index_settings(index): """Returns ES settings for this index""" return (get_es().indices.get_settings(index=index) .get(index, {}).get('settings', {}))
6d5d13bc30fdf8db666206bb07c3310394f3ff44
3,638,453