content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def dummy(xy_in, params, invert=False): """ """ return xy_in
74e6986c37bd1367dbc152e77b5cef2097bf8e14
698,956
import random def pick_sites(grid): """ Randomly pick two adjacent sites on a grid. @type grid: Grid object @param grid: grid """ # Pick the first site site1 = (random.randrange(grid.height), random.randrange(grid.width)) # Pick an adjacent site site2 = random.choice(grid.cells[si...
18ed6a17aae292a23cec4a66dab98b290c0c5992
698,957
from typing import Dict from typing import Set from typing import Any def unique(domains: Dict[str, Set[Any]]) -> bool: """ Each variable has exactly one value """ return all((len(domain) == 1 for domain in domains.values()))
64551d938135b1a288ca97d480abe4282eddeefd
698,958
from typing import Optional def parse_dot_notation(input: str) -> tuple[str, Optional[tuple[str, ...]]]: """ Parse dot-notation Example: parse_dot_notation('a') #-> 'a', None parse_dot_notation('a.b.c') #-> 'a', ['b', 'c'] """ name, _, sub_path_str = input.partition('.') sub_path ...
06650868fb773b41b97a839b0d423cc8f3cd4a85
698,959
def createURIString(valueString, delimiter, vocab): """This function takes a delimiter separted string of values and returns a string in which every of these values is prefixed with the specified vocab URI. >>> createURIString('nl;fr;de', ';', 'http://id.loc.gov/vocabulary/languages/') 'http://id.loc.gov/vo...
6fb6898b1531b5741dd890452c9ddd9e4db6f205
698,960
import requests from bs4 import BeautifulSoup def get_page(url, **kwargs): """Pulls in the HTML from a URL and returns the results as a BeautifulSoupt object. Parameters ---------- url : str The URL to scrape Returns ------- soup : bs4.BeautifulSoup The BeautifulSoup rep...
392c83be8b24bdeb27cf482c9df72c30b4b945dc
698,961
def parse_float(string:str) -> float: """ A function to parse string characters into float -> string: str => a string of chars, ex : "abc12a.a3" ---- => float: numbers present inside the string passed in, ex : 12.3 """ if not isinstance(string, str): raise TypeError('string must be ...
305c945979d4eb880d53207a9a1466f46cb7d981
698,963
from pathlib import Path import json def read_jupyter_as_json(filepath: Path) -> Path: """ Read in rendered notebook-- read in the JSON representation that is 'under the hood' :param filepath: path to jupyter notebook. """ with open(filepath, "r") as fout: contents = fout.read() ...
d91344b1bddcd0e1078effe6dd7947f7e04ea6af
698,964
def _to_db_str(sequential_list): """Convert a list or tuple object to a string of database format.""" entry_list = [] for _entry in sequential_list: # I know only text type need to be converted by now. More types could # be added in the future when we know. if isinstance(_entry, str)...
42a4e008964c0accb3e596dc75859641e999a0f4
698,965
import glob def get_file_sets(root_path, resnet_version, dlc_network_shuffle= 'shuffle2',dlc_network_iteration = '500000', filtered=False): """ function intended to fetch the proper network file sets for a given session. A session directory may have multiple predictions from unique DLC networks saved to a fol...
d7920667545dece6d6c4fccc6075a14c8eb53837
698,966
def histogram(s): """to check s in string""" d={} for c in s: d[c]=1+d.get(c,0) return d
4b643a05f97ae0829235b1296e37ee73ad8807f4
698,967
def _to_spdx(lic): """ we are munging this stuff from conda-build d_license = {'agpl3': ['AGPL-3', 'AGPL (>= 3)', 'AGPL', 'GNU Affero General Public License'], 'artistic2': ['Artistic-2.0', 'Artistic License 2.0'], 'gpl2': ['GPL-2', 'GPL (>= 2)',...
66aaa5fa8428ec680ab347b9a33ed7f03f18281c
698,968
import numpy def plane_fit(coordinates, center=None): """ Compute n-dimensional plane to a series or coordinates and return the normal to that plane :param coordinates: coordinates to fit a plane to :type coordinates: :numpy:ndarray :param center: point on the plane used as origin for t...
4922b42c7c8a6c4faa7227386396ebc93bc1bafb
698,969
def linear_scale_between(x1: float, x2: float, y1: float, y2: float, x: float, *, clamp=True, easing_func=None) -> float: """Standard linear interpolation function, optionally clamped (between y1 and y2)""" pct = (x - x1) / (x2 - x1) if easing_func: pct = easing_func(pct) if clamp: pc...
f488346a4fe07b82f1281b646c3a39171b5fe757
698,970
def make_dict_from_config(path, config_file): """ Function to make a dict from a configuration file Parameters --------------- path: str path dir to the config file config_file: str config file name Returns ---------- dict with the config file infos """ # open a...
fd928dde7bb9ea3d360237c34bc7c46f9f26b07a
698,971
def extract_domain(email_address): """ Given an email address, extract the domain name from it. This is done by finding the @ and then splicing the email address and returning everything found after the @. If no @ is found then the entire email address string is returned. :param email_address: ...
3e09c9cef431c09d126d8de6854990dc9351ef0d
698,972
def get_sweep_info(pul, pgf, group_idx, series_idx): """ Find the associated record in the StimTree from the PulseTree """ pul_series = pul["ch"][group_idx]["ch"][series_idx] num_sweeps_in_recorded_data = pul_series["hd"]["SeNumberSweeps"] pul_sweep = pul_series["ch"][0] stim_idx = pul_swee...
ebb2f125f9dbf45f80e088d63314a6fd10069a06
698,973
def check_solution(model, solution): """ Helper function. if solution is None, attempts to get it from the model. :param model: :param solution: :return: """ if solution is None: try: solution = model.solution except AttributeError: raise AttributeErr...
a03ee5e2033ee99caa0fd761f9d78d3d597a906b
698,974
def degTodms(ideg): """ Converts degrees to degrees:minutes:seconds :param ideg: objects coordinate in degrees :type ideg: float :return: degrees:minutes:seconds :rtype: string """ if (ideg < 0): s = -1 else: s = 1 ideg = abs(ideg) deg = int(ideg) + 0. m...
169cf4a89e7a2bd8526cf32acd1e88ec62d0237f
698,975
def build_command(input_device, rates, bits, buffers, sox_effects): """ :param input_device: device index e.g. 2 :param rates: [input, output] e.g. [48000, 48000] :param bits: [input, output] e.g. [16, 16] :param buffers: [input, sox] e.g. [512, 1024] :param sox_effects: [left, right] e.g. [['eq...
8c17f55ef8ff3d0abc8ffbdbe85a2d98306a6b37
698,976
import argparse def parse_arguments(): """ Parse command line arguments :return: Parsed arguments """ # Define and parse input arguments parser = argparse.ArgumentParser() parser.add_argument("--modeldir", help="Folder the .tflite file is located.", ...
c93178c7101fadfd1c6d42c3986e9815129ceeb6
698,977
def prepare_results(cursor_description, rows): """ Generate result in JSON format with an entry consisting of key value pairs. :param cursor_description: a tuple with query result columns :param rows: list of returned sql query values :return: dictionary """ if rows is None or len(rows) == 0...
8fcc48f0a732a200c65d27817349a0de1a5f1172
698,978
import os def process_workspace_list(arguments, config, calling_dir = os.getcwd()): """ Processes a list of arguments from command line and resolves it to a list of workspaces. Parameters ---------- arguments : list of str command line arguments to resolve to workspaces aliases : ...
d87672722a3f6ee568580efaa98cdafa8271a311
698,979
import torch def _rescale(dat, mn_out=0, mx_out=511): """ Rescales image intensities between mn_out and mx_out. """ dtype = dat.dtype device = dat.device dat[(dat == dat.min()) | ~torch.isfinite(dat) | (dat == dat.max())] = 0 # Make scaling to set image intensities between mn_out and mx_out ...
3b502094e22fe97fadfeb4ff987774385442c52e
698,980
import pkg_resources def walk(module_name, dirname, topdown=True): """ Copy of :func:`os.walk`, please refer to its doc. The only difference is that we walk in a package_resource instead of a plain directory. :type module_name: basestring :param module_name: module to search in :type dirname: ...
8a001a4673b9a123f4c4260f2226eff0c360b698
698,981
def get_flat_params(parameter_groups): """ :param parameter_groups: :return: List of parameters pulled out of parameter groups """ parameter_list = [] for parameter_group in parameter_groups: parameter_list += parameter_group['params'] return parameter_list
ef11030018341635594d07f56a23dd9aa3c1244e
698,982
def read_name_hash(read_name): """Takes a read name from an input bam and shortens & obfuscates it""" return str(abs(hash(read_name)) % 10**9)
bc1e048925f0a0e710481656f0b90e4c290c2341
698,983
def _get_updated_parsed(job_item): """ :param job_item: :return: """ return job_item.published.timetuple()
a1377d3adcbae990727abed8ecdabfb9fb2d610b
698,984
import argparse def getArguments(): """Arguments for script.""" parser = argparse.ArgumentParser() parser.add_argument("--name", default="sensorapp", help="name of the application") parser.add_argument("--app-port", type=int, default="8081", help="port to run application server") parser.add_argument("--hos...
3e9ce78bcf459a5f956b988265d0cc39834d5e41
698,985
def pressure_from_altitude(y): """ Calculate standard atmospheric pressure based on an altitude in m. The basic formula can be found many places. For instance, Munson, Young, and Okiishi, 'Fundamentals of Fluid Mechanics', p. 51. Enter: y: altitude in m. Exit: p: pressure in N/m/m. """ ...
b8f7d42b28d3448ac1a0f62079a0ae4ed672f9e9
698,986
import pandas as pd def _lsa_events_converter(events_file): """Make a model where each trial has its own regressor using least squares all (LSA) Parameters ---------- events_file : str File that contains all events from the bold run Yields ------ events : DataFrame A ...
4cc216bdf01f67dbefbd31005f0398cd217aa8a5
698,987
def get_dataset_location(bq): """Parse payload for dataset location""" # Default BQ location to EU, as that's where we prefer our datasets location = "EU" # ... but the payload knows best if "location" in bq: location = bq["location"] return location
071a5258a72b3a3a248c6e44b99b7ccc2890d3f5
698,989
def get_fws_and_tasks(workflow, fw_name_constraint=None, task_name_constraint=None): """ Helper method: given a workflow, returns back the fw_ids and task_ids that match name constraints. Used in developing multiple powerups. Args: workflow (Workflow): Workflow fw_name_constraint (str):...
28f4f2cdcc58b942ee3e0631c21bf2a3a052db35
698,990
def _get_tags(ws_info): """Get the tags relevant to search from the ws_info metadata""" metadata = ws_info[-1] if metadata.get('searchtags'): if isinstance(metadata['searchtags'], list): return metadata['searchtags'] else: return [metadata['searchtags']] else: ...
f6922f92913446284545aa73cb2b8cd7139749e8
698,991
import inspect import sys def get_module_classes(module_name): """ Get all the classes from a module """ clsmembers = inspect.getmembers(sys.modules[module_name], inspect.isclass) return clsmembers
8049c8a5c0277c86e8c334c4e158eaa90aaa0992
698,992
def _str_bool(v): """convert a string rep of yes or true to a boolean True, all else to False""" if (type(v) is str and v.lower() in ['yes', 'true']) or \ (type(v) is bool and bool(v)): return True return False
ba4663c402b94b00edb4b1a97a4ba4ed755caf85
698,993
def get_fixed_params(): """ Parameters that currently cannot be searched during HPO """ fixed_params = {'batch_size': 512, # The size of example chunks to predict on. 'n_cont_embeddings': 0, # How many continuous feature embeddings to use. 'norm_class_name': 'LayerNorm', ...
186e786f96f2a81c88423fdcd27bf28aef97b511
698,995
def to_env_dict(config): """Convert configuration object to a flat dictionary.""" entries = {} if config.has_value(): return {config.__to_env_var__(): config.node['value']} if config.has_default(): return {config.__to_env_var__(): config.node['default']} for k in config.node: ...
4c46f365e7b53d79d25dea7d062f9d985d30877d
698,996
import base64 import json def encode_base64_json(data): """ Encode dict-like data into a base64 encoded JSON string. This can be used to get dict-like data into HTTP headers / envvar. """ return base64.b64encode(bytes(json.dumps(data), 'utf-8'))
08b9d8568a59717173adf00658aad03bddb8df14
698,997
def conjugate_row(row, K): """ Returns the conjugate of a row element-wise Examples ======== >>> from sympy.matrices.densetools import conjugate_row >>> from sympy import ZZ >>> a = [ZZ(3), ZZ(2), ZZ(6)] >>> conjugate_row(a, ZZ) [3, 2, 6] """ result = [] for r in row: ...
c4c5ccb03513c32e3bc9866ef6c3a370e70d01d6
698,998
import os import sys def get_proj_incdirs(proj_dir): """ This function finds the include directories """ proj_incdir = os.environ.get("PROJ_INCDIR") incdirs = [] if proj_incdir is None: if os.path.exists(os.path.join(proj_dir, "include")): incdirs.append(os.path.join(proj_d...
f39728b8454efeef1e6729d05f4e6dd03110a90d
698,999
import os def make_absolute_path(files, root): """Make paths absolute.""" for role, path in files.items(): files[role] = os.path.join(root, path) return files
49970ca1c7d6eb4d2480fbe73093c40aec1400d6
699,000
import torch def random_mask_tokens(args, inputs, tokenizer): """ Prepare masked tokens inputs/labels for masked language modeling: 80% MASK, 10% random, 10% original. """ if len(inputs.shape) == 1: inputs = inputs.unsqueeze(0) labels = inputs.clone() input_mask = (~inputs.eq(0)).to(torch.fl...
5522b3aeedad605eb2645a3c8938315ff59b0b7c
699,001
import math def edgeweight_properties(graph, weight_label="weight"): """ Calculates properties of edge weights. Parameters ---------- graph: nx.Graph Graph to calculate the properties from weight_label: Returns ------- max_weight: number Maximum weights of an edg...
a22857d844c2235859c004bfac897b3b5c80feee
699,002
def timedelta_to_seconds(td): """ Converts a timedelta to total seconds. (This is built-in in Python 2.7) """ # we ignore microseconds for this if not td: return None return td.seconds + td.days * 24 * 3600
ef4ebd88581d8a2a1f64b9f940afbe22da8f55bc
699,003
import torch def _safe_mean(losses, num_present): """Computes a safe mean of the losses. Args: losses: `Tensor` whose elements contain individual loss measurements. num_present: The number of measurable elements in `losses`. Returns: A scalar representing the mean of `losses`. If `num_present`...
4174dead8e2fc582633589713e076871a0631de1
699,004
def _feet_to_alt_units(alt_units: str) -> float: """helper method""" if alt_units == 'm': factor = 0.3048 elif alt_units == 'ft': factor = 1. else: raise RuntimeError(f'alt_units={alt_units} is not valid; use [ft, m]') return factor
95d5208741fdff275211b9c33a901dedaa65186e
699,005
def get_proper_state(job, state): """ Return a proper job state to send to server. This function should only return 'starting', 'running', 'finished', 'holding' or 'failed'. If the internal job.serverstate is not yet set, it means it is the first server update, ie 'starting' should be sent. :pa...
ba54c1f4eee99055e73099bc381ccbb69da4b183
699,006
def are_collinear(p1, p2, p3, tolerance=0.5): """return True if 3 points are collinear. tolerance value will decide whether lines are collinear; may need to adjust it based on the XY tolerance value used for feature class""" x1, y1 = p1[0], p1[1] x2, y2 = p2[0], p2[1] x3, y3 = p3[0], p3[1] r...
337065b80e1cc1810be263bccd9c8ae66c258ed3
699,007
def transformResults(threadCounts, values, function): """Apply the function to all of the measurements""" res = {} for bm in list(values.keys()): res[bm] = [] for (nThreads, v) in zip(threadCounts, values[bm]): res[bm].append(None if v == None else function(v, nThreads)) retu...
1fe7944479b045bebd403eeb888fe0c00b012291
699,008
import math def coriolis_freq(lat): """Compute coriolis frequency. https://en.wikipedia.org/wiki/Earth%27s_rotation#Angular_speed omega = 7.2921150 ± 0.0000001×10−5 radians per second :param theta: Latitude in degrees. """ omega = 7.2921150e-5 theta = math.radians(lat) f = 2 * omega...
a5f40ef6b3862746905ab8e3cd4e77f1fdc1d484
699,009
def _msearch_success(response): """Return true if all requests in a multi search request succeeded Parameters ---------- response : requests.models.Response Returns ------- bool """ parsed = response.json() if 'responses' not in parsed: return False for result in pa...
acdac4408464120fdeb7f20a06f07aac6ca3809f
699,010
import json def get_team_port(duthost, pc): """ Dump teamd info Args: duthost: DUT host object pc: PortChannel name """ dut_team_cfg = duthost.shell("teamdctl {} config dump".format(pc))['stdout'] dut_team_port = json.loads(dut_team_cfg)['ports'].keys() return dut_team_port...
f60c18d1a4f8514ec0ee042a820eaec3902bfc24
699,012
from pathlib import Path def _get_city(path, root): """Extract the city name of standard traffic4cast like data structure path Args: path (str): Traffic4cast path: [root + city + city_test + filename] root (str): Root directory Returns: TYPE: Description """ city_path = P...
322d43c1c1f43d8d59f21a67c804fc343955816d
699,013
def reverse(graph): """replace all arcs (u, v) by arcs (v, u) in a graph""" rev_graph = [[] for node in graph] for node, _ in enumerate(graph): for neighbor in graph[node]: rev_graph[neighbor].append(node) return rev_graph
5b1b0281df529676e90ba4d27d1ab554d4a50537
699,015
def conjugado (num): """Funcion que retorna el conjugado de un numero imaginario (list 1D) -> list 1D""" num1 = num[1] * -1 return (num[0], num1)
af1dfc52b5a8967ff7399f369c8ef7bf9dd2cc17
699,016
def _get_config_value_for_remote(ctx, remote, config, key): """ Look through config, and attempt to determine the "best" value to use for a given key. For example, given:: config = { 'all': {'branch': 'master'}, 'branch': 'next' } _get_config_...
30452cde0dcb1f09763a5b10550f59d649067b08
699,017
import random def propose_any_node_flip(partition): """Flip a random node (not necessarily on the boundary) to a random part """ node = random.choice(tuple(partition.graph)) newpart = random.choice(tuple(partition.parts)) return partition.flip({node: newpart})
1ba9d747b92b707cad34c820abec9325913aca55
699,018
import string def extract_words(text): """Return the words in a tweet, not including punctuation. >>> extract_words('anything else.....not my job') ['anything', 'else', 'not', 'my', 'job'] >>> extract_words('i love my job. #winning') ['i', 'love', 'my', 'job', 'winning'] >>> extract_words('mak...
cc0b7dbc548696ed74b48dec57b386fe38adfa41
699,019
def mods_to_step_size(mods): """ Convert a set of modifier keys to a step size. :param mods: Modifier keys. :type mods: :class:`tuple`[:class:`str`] :return: Step size, by name. :rtype: :class:`str` """ if "alt" in mods: return "fine" elif "shift" in mods: return "c...
3c93fd11a8b5b0fad5cc26a35872e0616ebf7231
699,020
from typing import Optional def contains_symbol(text: str, symbols: Optional[str] = None) -> bool: """If text contains a symbol in symbols, return True.""" if symbols is None: for character in text: if character.isascii() and (not character.isalnum()): return True r...
22c6a090c93e81969fb1f4fbcb8bb88ce1bf5714
699,021
import re def process(text, pattern = '(<\/?[a-zA-Z]*>)|(\n)'): """ process - process SGML-styled text into preferred text Inputs: - text : raw text - pattern : matching pattern to remove SGML tags Outputs: - text : processed text """ # remove SGML tags text = re.sub(pattern = pattern, repl = '', string...
87f16159e015df0341f654d0f46fe5334cd11a8d
699,022
import yaml def read_parameter_file(parameter_file_path: str) -> dict: """ Reads the parameters from a yaml file into a dictionary. Parameters ---------- parameter_file_path: Path to a parameter file. Returns ------- params: Dictionary containing the parameters defined in the provide...
5f203bf596c2b1c39f14cea1e99e0c33c2f97ce2
699,023
import hashlib def make_hash(to_hash: str) -> str: """ Return a hash of to_hash. """ new_hash = hashlib.md5() new_hash.update(to_hash.encode("utf-8")) return str(new_hash.hexdigest())
7e800f7942df23256373c221428e5c24b65cabee
699,024
import os import pkgutil def find_document_issuers(issuers_dir): """ Given a path to an issuers directory, return a list of all the document issuer names that are available. """ document_issuers_dir = os.path.join(issuers_dir, "documents") return [ name for _, name, is_pkg in p...
1d177445628163d1e1b9833beb90af5a381021ca
699,025
def resolution(liste,point,n=3): """fonction permettant de savoir si les coordonnées d'un point sont trop proches des coordonnées du dernier point d'une liste""" if len(liste)==0 : #si la liste est vide return True else : point_precedent=liste[-1] if abs(point_precedent[0]-po...
401a3972b09f5959e7c7face45611539469e7a8f
699,027
def isDoor(case): """Teste si la case est une porte""" if "special_type" in case.keys(): return case['special_type'] == "door" else: return False
54a8242a8139e98867a0b3cad8597c8fe36ca685
699,028
def spatial_scenario_selection(dataframe_1, dataframe_2, dataframe_1_columns, dataframe_2_columns, ): """Intersect Polygons to collect attributes Parameters - dataframe_1 - Fir...
7c7d380d141244543d9a0a840ead456996eda006
699,030
def _beam_fit_fn_3(z, z0, Theta): """Fitting function for z0 and Theta.""" return (Theta*(z-z0))**2
76955c6464ae7a33927986d146e9000e9a45c12b
699,031
def stations_by_river(stations): """Returns a dictionary containing rivers (keys), and the stations on each river (values)""" rivers = {} for station in stations: # only add the river if station.river has been set river = station.river if river is not None: # add the stat...
7feef52d4d5c14109807e1c2e559f206b420c5cc
699,032
def json_citation_for_ij(query, score, doi): """ Because we are parsing the PDF, we cannot ensure the validity of each subfieldobtained form the parser (CERMINE) i.e title, journal, volume, authors, etc. Instead, we join all the information obtained from the parser in plain text. This plain text is the ...
1f226db5420b61cd40b88015ec727ebd84a08138
699,033
def find_combination(value, stream): """ >>> find_combination(127, [35, 20, 15, 25, 47, 40, 62, 55, 65, 95, 102, 117, 150, 182, 127, 219, 299, 277, 309, 576]) 62 """ x = 0 y = 2 while True: total = sum(stream[x:y]) if total < value: y += 1 elif total > ...
17a61c6918ce78f283bc1b641edb4c235746d428
699,034
def data_pattern(data): """ """ data = list(data.items()) data.sort(key=lambda x: x[1]) data.sort(key=lambda row: [[r[i] for n, r in data].count(x) for i, x in enumerate(row[1])]) for c in range(len(data[0][1])): values = {row[c]: i for i, (name, row) in enu...
f3805ab18f92e60e858638f2ec60e660e1819c60
699,035
def _range_checker(ip_check, first, last): """ Tests whether an ip address is within the bounds of the first and last address. :param ip_check: The ip to test if it is within first and last. :param first: The first IP in the range to test against. :param last: The last IP in the range to test again...
924e617374fdbc4cabc28cb18e63c45192da3b4c
699,037
def crr_m(ksigma, msf, crr_m7p5): """Cyclic resistance ratio corrected for m_w and confining stress""" return crr_m7p5 * ksigma * msf
76b271ac72b29ec583aa8a23aeb22e8dbf248365
699,039
import re def concatenate_lines(lines, pattern): """ concatenate lines >>> import re >>> pattern = re.compile(r"(^\s+)(.+?)") >>> lines = [u"a", u" b", u" c", u" d", u"e"] >>> concatenate_lines(lines, pattern) [u'a', u' b c d', u'e'] >>> lines = [u"a", u" b", u" c", u" d", u"e"] >>> ...
eb21d40771d16d33754aceab106770c8047a83fa
699,040
from bs4 import BeautifulSoup def parse_words(html): """解析 html 源码,返回汉字列表""" soup = BeautifulSoup(html) a_list = soup.find_all('a', attrs={'target': '_blank'}) return [x.text for x in a_list if x.text]
629ccc8be01699ea747061c3340772569109d109
699,041
def translate_status(sbd_status): """Translates the sbd status to fencing status. Key arguments: sbd_status -- status to translate (string) Return Value: status -- fencing status (string) """ status = "UNKNOWN" # Currently we only accept "clear" to be marked as online. Eventually we...
2274ff63aea9249cecacf455598a57fba1245ace
699,042
import math def entropy(data): """ Calculate informational entropy. """ entropy = 0.0 frequency = {} for instance in data: p_instance = int(round(instance/5) * 5) if p_instance in frequency: frequency[p_instance] += 1 else: frequency[p_instance] ...
4b96c229e4cc0318a764990569d2951003447a72
699,044
def plot_scatter(ax, prng, nb_samples=100): """Scatter plot.""" for mu, sigma, marker in [(-0.5, 0.75, "o"), (0.75, 1.0, "s")]: x, y = prng.normal(loc=mu, scale=sigma, size=(2, nb_samples)) ax.plot(x, y, ls="none", marker=marker) ax.set_xlabel("X-label") ax.set_title("Axes title") re...
02f23849ed4f2dded875866027eead00ebd1f0dc
699,045
def s2c_stereographic(sph): """ Stereographic projection from the sphere to the plane. """ u = sph[..., 0] v = sph[..., 1] w = sph[..., 2] return (u + 1j*v)/(1+w)
1aff6cf6accd6bb26c647f014dc964404e84b979
699,046
def text(node): """ Get all the text of an Etree node Returns ------- str """ return ''.join(node.itertext())
f5000a6220da74059230a499dc2b48057e5c4ada
699,047
from typing import Union from typing import Callable def fully_qualified_name(thing: Union[type, Callable]) -> str: """Construct the fully qualified name of a type.""" return thing.__module__ + '.' + thing.__qualname__
eacbffdcda78fa38667af0b9d7bc0c53c2fbdb1f
699,048
def remove_whitespace(text): # type: (str) -> str """strips all white-space from a string""" if text is None: return "" return "".join(text.split())
747538de63b11e49d498b2f4ccb8286975019ec8
699,049
import re def address_line1(a): """Return only the main part of a multipart address Warnings: - Only works on canonicalized addresses. Call canonicalize() first. - Returns addresses that are incorrect! - Only use the output of this function for fuzzy matching. >>> address_line1('1910 south m...
453e68ed2889e899ef339def772191c32f7997bc
699,050
from typing import Dict def _invert(mapping: Dict) -> Dict: """Invert dictionary {k: v} -> {v: k}.""" return {target: source for source, target in mapping.items()}
013894d56e95a5df273a5bed6a7acc9c49c18d10
699,051
def _options_handler(request): """Request handler for OPTIONS requests This is a request handler suitable for return from _get_handler_for_request. It returns a 200 and an empty body. Args: request (twisted.web.http.Request): Returns: Tuple[int, dict]: http code, response body. ...
319b083565551f2512a71bb671dd76cfd76063dc
699,052
import os def GetEbuildPathsFromSymLinkPaths(symlinks): """Reads the symlink(s) to get the ebuild path(s) to the package(s). Args: symlinks: A list of absolute path symlink/symlinks that point to the package's ebuild. Returns: A dictionary where the key is the absolute path of the symlink and the ...
22ae73b3939ec608a9392853031961f9e22c3234
699,053
def kind(event): """ Finds the type of an event :param event: the event :return: the type of the event """ return event.type
68f0170eac9fc06f954542769dcd0d4ef974e725
699,054
def select(*_): """ Always return None """ return None
9f29559a50440143d9e3fe46be766590516f1fc4
699,055
import struct import os def genSerial(): """ Generate a (hopefully) unique integer usable as an SSL certificate serial. """ return abs(struct.unpack('!l', os.urandom(4))[0])
bafc3d8145ff876816bbd224fee0850934ab4c31
699,056
def modular_power(a, n, p): """ 计算a^ n % p if n == 0: return 1 elif n == 1: return a % p temp = a * a % p if n & 1: return a % p * modular_power(temp, n // 2, p) % p else: return (modular_power(temp, n // 2, p)) % p 原文:https://blog.csdn.net/qq_36921652/art...
f9f234ec6532e13fcd9d393163933967ae6e7da7
699,057
def is_correct_type(item, expected_type): """Function for check if a given item has the excpected type. returns True if the expected type matches the item, False if not Parameters: -item: the piece of data we are going to check. -expected_type: the expected data type for item. """ ...
37d23e2c7dc1e630d8ead99fde09250196bd664e
699,058
def is_person(possible_person:dict): """Helper for getting party ID""" return not possible_person.get('value',{}).get('entityRepresentation',{}).get('value',{}).get('personOtherIdentification') is None
66a193cc491296fc94840c684a7066d5f1541e54
699,059
import sys def python_lt(major, minor=None, micro=None): """Returns true if the python version is less than the given major.minor.patch version.""" if sys.version_info.major < major: return True elif sys.version_info.major == major: if minor is not None: if sys.version_info.min...
24634c7565078a5fc4aa1f0e8f27ecb650e1dccb
699,060
def cells_number(rc): """ Calculates number of cells in each frame. Intedend for use on 'cells' or subsets of 'cells' tables. """ return rc[['frame', 'cell_id']].groupby('frame').agg(len).reset_index().sort('frame')['cell_id'].values
91725cc352de6a1aa31cf4f82301ed8de6e11bb4
699,061
def to_cuda(data): """ Move an object to CUDA. This function works recursively on lists and dicts, moving the values inside to cuda. Args: data (list, tuple, dict, torch.Tensor, torch.nn.Module): The data you'd like to move to the GPU. If there's a pytorch tensor or ...
28186b60bd7509d3df76646fbf41babe1a4f76e4
699,062
import numpy def coordinates(n): """ Generate a 1D array with length n, which spans [-0.5,0.5] with 0 at position n/2. See also docs for numpy.mgrid. :param n: length of array to be generated :return: 1D numpy array """ n2 = n // 2 if n % 2 == 0: return numpy.mgrid[-n2:n2]...
1371601f991432f1bad0a82fb741f050d9346d4e
699,063
def max_wkend_patterns_init(M): """ Compute maximum number of weekend worked patterns :param M: :return: """ max_patterns = 2 ** (2 * M.n_weeks.value) return max_patterns
bc3cc554c858d80bbe5f33c3deaf87465ddfe657
699,064
def indent(s, shift=1, width=4): """Indent a block of text. The indentation is applied to each line.""" indented = '\n'.join(' ' * (width * shift) + l if l else '' for l in s.splitlines()) if s[-1] == '\n': indented += '\n' return indented
34ab969f133429959463903fe7e86e18ee644f20
699,066