content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def _daily_prevalence(data): """ Returns a series where each value is a true fraction of currently infected population. Args: (dict): tracker data loaded from pkl file. Returns: (np.array): 1D array where each value is the above described fraction """ n_infected_per_day = data[...
2a5b83c09d9f06a8021c27dec45be9a872f3a9bb
1,700
from operator import or_ def users_view(page): """ The user view page Returns: a rendered user view template """ user_search = request.args.get("search") user_role = request.args.get("user_role") users_query = model.User.query if user_search: term = "%" + user_search...
9646b76721ec26f9177bff99cca02d0c4b5a7954
1,701
def serial_christie_power_state(connection): """Ask a Christie projector for its power state and parse the response""" connection.reset_input_buffer() response = serial_send_command(connection, "(PWR?)", char_to_read=21) result = None if len(response) > 0: if "PWR!001" in response: ...
4ce78b773ecf2f4ed9a515e4653512a461a82f24
1,702
def cuda_tanh(a): """ Hyperbolic tangent of GPUArray elements. Parameters: a (gpu): GPUArray with elements to be operated on. Returns: gpu: tanh(GPUArray) Examples: >>> a = cuda_tanh(cuda_give([0, pi / 4])) array([ 0., 0.6557942]) >>> type(a) <class 'p...
6d7608c943ded7eeeb37194a4d938aa4e47c16ef
1,703
def normalize_multi_header(df): """将有MultiIndex的column字符串做标准化处理,去掉两边空格等""" df_copy = df.copy() df_copy_columns = [ tuple(y.strip().lower() for y in x) for x in df_copy.columns ] df_copy.columns = pd.core.index.MultiIndex.from_tuples(df_copy_columns) return df_copy
acd75a73919f1fd9b8f8c57e2f70cbb607634c82
1,704
def scapy_packet_Packet_hasflag(self, field_name, value): """Is the specified flag value set in the named field""" field, val = self.getfield_and_val(field_name) if isinstance(field, EnumField): if val not in field.i2s: return False return field.i2s[val] == value else: return (1 << field.names.index([value...
77b4a1d772e61c7bfaaf7e9d9d3debe95f799f62
1,705
def grid_points_2d(length, width, div, width_div=None): """Returns a regularly spaced grid of points occupying a rectangular region of length x width partitioned into div intervals. If different spacing is desired in width, then width_div can be specified, otherwise it will default to div. If div < 2 i...
d041f563bb8d3cd84e1829f49e6786b0331e1ef0
1,706
import itertools def analytic_gradient(circuit, parameter=None): """Return the analytic gradient of the input circuit.""" if parameter is not None: if parameter not in circuit.parameters: raise ValueError('Parameter not in this circuit.') if len(circuit._parameter_table[parameter...
126357a3aa25a1a38e5226657f92e626cb8b2339
1,707
def _get_shipping_voucher_discount_for_cart(voucher, cart): """Calculate discount value for a voucher of shipping type.""" if not cart.is_shipping_required(): msg = pgettext( 'Voucher not applicable', 'Your order does not require shipping.') raise NotApplicable(msg) s...
cba3299f02d3cc2169e9ad8367b8c5e67a08a459
1,708
def ottawa(location, **kwargs): """Ottawa Provider :param location: Your search location you want geocoded. """ return get(location, provider='ottawa', **kwargs)
b1e32842ce887b72f317c5b88cbcb390524b59af
1,709
import copy import random def entries(): """ Basic data for a test case """ return copy.deepcopy( {"arb_key": "text", "randn": random.randint(0, 10), "nested": {"ntop": 0, "nmid": {"list": ["a", "b"]}, "lowest": {"x": {"a": -1, "b": 1}}}, "collection": {1, 2, 3}})
5d6cde325b69e43598f9d0158ae5989a4d70b54c
1,710
def count_ref_alleles(variant, *traits): """Count reference allels for a variant Parameters ---------- variant : a Variant as from funcgenom the variant for which alleles should be counted *traits : str the traits for which alleles should be counted Returns -------...
10ea3468f5de8f2b77bb97b27b888af808c541b7
1,711
def preprocess_image(image, image_sz=48): """ Preprocess an image. Most of this is stuff that needs to be done for the Keras CNN model to work, as recommended by: https://chsasank.github.io/keras-tutorial.html """ # we need to convert to saturation, and value (HSV) coordinates hsv_image = color...
ade5d63ad8e2a25622795d15c90c1e062a76006d
1,712
def pspace_independent(a, b): """ Tests for independence between a and b by checking if their PSpaces have overlapping symbols. This is a sufficient but not necessary condition for independence and is intended to be used internally. Notes ===== pspace_independent(a, b) implies independent(...
5c6a253e266af1673c6e05c4b7f81b04a1201803
1,713
def img_aspect_ratio(width, height): """ Returns an image's aspect ratio. If the image has a common aspect ratio, returns the aspect ratio in the format x:y, otherwise, just returns width/height. """ ratio = round(width/height, 2) for ar, val in COMMON_ASPECT_RATIOS.items(): if ratio...
82104f3d4105fd4c22bc4cfed51e4c8261d32079
1,714
def _get_active_sculpting_mesh_for_deformer(deformer): """ If sculpting is enabled on the deformer, return the output mesh. Otherwise, return None. """ # If sculpting is enabled, .tweak[0] will be connected to the .tweakLocation of # a mesh. connections = cmds.listConnections('%s.tweak[0]' ...
a0864999d6aec487a23bac4dfb602f01b0b45d8f
1,715
def get_client_versions(): """Gets the client versions (or client equivalent for server). Returns: A list of client versions (or client equivalent for server). E.g. '10' for Windows 10 and Windows Server 2016. """ version_nubmer = get_os_version_number() if version_nubmer in _WIN32_CLIENT_NAMES: ...
0954754b608b745d2dbc9f6c83bd85bc0c2549e2
1,716
from CA import caget from CA import caput def PV_property(name,default_value=nan): """EPICS Channel Access Process Variable as class property""" def prefix(self): prefix = "" if hasattr(self,"prefix"): prefix = self.prefix if hasattr(self,"__prefix__"): prefix = self.__prefix__ ...
745fe42d760f42dbc4e729d45256dd291be7e5b3
1,717
import six def _stream_files(curr_header, fn, mesos_files): """Apply `fn` in parallel to each file in `mesos_files`. `fn` must return a list of strings, and these strings are then printed serially as separate lines. `curr_header` is the most recently printed header. It's used to group lines. E...
9d6cc9a238c831017b0426d9cd21d42d26812365
1,718
import sys def supported_platform(logger): """Checks if this script is running on supported platform. Args: logger: A valid logger instance to log debug/error messages. Returns: True if this platform is supported. """ # TODO(billy): Look into supporting Windows in the near future. logger.debug("...
f7f9566fe06bb96f3d213d94bdfb195e4f22b33f
1,719
import random def random_in_range(a: int, b: int) -> int: """ Return a random number r with a <= r <= b. """ return random.randint(a, b)
611c2754ace92eac4951f42e1e31af2f441ed0c2
1,720
import sqlite3 from datetime import datetime def count_items(): """ :returns: a dictionary with counts in fields 'total', 'done'. """ con = sqlite3.connect(PROGRESS_DB_FILE_NAME) cur = con.cursor() # do not count root cur.execute("SELECT COUNT(*) FROM item WHERE pk<>0") total = cur.fet...
904c72b74603fd9a9c2a1c249641ba61a7b85b04
1,721
def app() -> None: """This app renders the Data Analyzer page""" # TEXT: st.write( """ # Data Analysis Dashboard Please provide an asset name to display historical data. """ ) # INPUTs: st.sidebar.title("Parameters") col1, col2, c...
6890ed875368eec3271f8ee0625d4182aaeb769d
1,722
import re def valida_cnpj(cnpj): """ Valida CNPJs, retornando apenas a string de números válida. # CNPJs errados >>> validar_cnpj('abcdefghijklmn') False >>> validar_cnpj('123') False >>> validar_cnpj('') False >>> validar_cnpj(None) False >>> validar_cnpj('12345678901...
4b3d2591e6f196cccdd8d68089e36f22ba1d1a98
1,723
def km_miles(kilometers): """Usage: Convert kilometers to miles""" return kilometers/1.609
5480c065f904dfc1959691e158653fd0e6bb67e6
1,724
def is_enterprise_learner(user): """ Check if the given user belongs to an enterprise. Cache the value if an enterprise learner is found. Arguments: user (User): Django User object. Returns: (bool): True if given user is an enterprise learner. """ cached_is_enterprise_key = get...
76bbf24dafec3ec26ec23504b8d064fbe5c21c52
1,725
def point_cloud(depth, colors): """Transform a depth image into a point cloud with one point for each pixel in the image, using the camera transform for a camera centred at cx, cy with field of view fx, fy. depth is a 2-D ndarray with shape (rows, cols) containing depths from 1 to 254 inclusive. Th...
75aa681fa817b29e23ed76beb8504ef1bbaa5d67
1,726
import tqdm def structural_email(data, pos_parser=True, bytedata_parser_threshold=50, reference_parser_match_type=2): """ This is a parser pipeline, parser order matters. 1. string => structure email to separate => header, body, others 2. body => remove typo and some irrelevant words => body 3. bo...
b68227f10ae6e78f6e12ab174e2360c0828e2038
1,727
import six def build_batches(data, conf, turn_cut_type='tail', term_cut_type='tail'): """ Build batches """ _turns_batches = [] _tt_turns_len_batches = [] _every_turn_len_batches = [] _response_batches = [] _response_len_batches = [] _label_batches = [] batch_len = len(data[...
e82411d5b51171c9590bd5f150dfeca666b3a3a6
1,728
def is_notebook(): """Check if pyaedt is running in Jupyter or not. Returns ------- bool """ try: shell = get_ipython().__class__.__name__ if shell == "ZMQInteractiveShell": return True # Jupyter notebook or qtconsole else: return False excep...
51c0806ba17cbaef5732379a5e9c68d8eb171d31
1,729
def strategy(history, memory): """ Tit-for-tat, except we punish them N times in a row if this is the Nth time they've initiated a defection. memory: (initiatedDefections, remainingPunitiveDefections) """ if memory is not None and memory[1] > 0: choice = 0 memory = (memory[0], m...
bf8d09417c246f9f88a721dfcc4408f49195fd1a
1,730
def get_primitives(name=None, primitive_type=None, primitive_subtype=None): """Get a list of the available primitives. Optionally filter by primitive type: ``transformation`` or ``aggregation``. Args: primitive_type (str): Filter by primitive type. ``transformation`` or ``aggregation``...
c833a2b1d52dc135a4518aa6fa7147ae58b73b9a
1,731
def _unpack_batch_channel(data, old_shape): """Unpack the data channel dimension. """ data = nnvm.sym.transpose(data, axes=(0, 4, 1, 5, 2, 3)) data = nnvm.sym.reshape(data, shape=old_shape) return data
1b59f6fbceabef3a28b4180a5bc808621e11c6b7
1,732
def get_branch_user(branch): """Get user name for given branch.""" with Command('git', 'log', '--pretty=tformat:%an', '-1', branch) as cmd: for line in cmd: return line
0845dc69cbd949c1f739ca877c0b182740fa7bdb
1,733
from .qtmultimedia import find_system_cameras from electrum_cintamani import qrscanner def find_system_cameras() -> Mapping[str, str]: """Returns a camera_description -> camera_path map.""" if sys.platform == 'darwin' or sys.platform in ('windows', 'win32'): try: except ImportError as e: ...
adefb85f99494f71e1c55e74f8b4e589d96daacf
1,734
def _shape_list(x): """Return list of dims, statically where possible.""" static = x.get_shape().as_list() shape = tf.shape(x) ret = [] for i, static_dim in enumerate(static): dim = static_dim or shape[i] ret.append(dim) return ret
0add2ba771dd99817654ce48c745db5c5f09d3aa
1,735
import packaging def upgrade_common(ctx, config, deploy_style): """ Common code for upgrading """ remotes = upgrade_remote_to_config(ctx, config) project = config.get('project', 'ceph') extra_pkgs = config.get('extra_packages', []) log.info('extra packages: {packages}'.format(packages=ext...
13840203bceb6b6ae069d47fa03a278dac3b0bc6
1,736
def convert2define(name): """ returns the name of the define used according to 'name' which is the name of the file """ header = toupper(toalphanum(name)) return "__" + header + "__"
9f48181310db2732a26b846cb8270eb44bd06004
1,737
def url_exists(url): """ Checks if a url exists :param url: :return: """ p = urlparse(url) conn = httplib.HTTPConnection(p.netloc) conn.request('HEAD', p.path) resp = conn.getresponse() return resp.status == 301 or resp.status == 200
3ef7d71fed0c85d4e75e910e5354b817c656c0d7
1,738
def add_header(cmd): """ :param cmd: the command with its values :return: adds a header and returns it, ready to be send """ # get the length of the length of the cmd (for how many spaces needed) header = str(len(cmd)) for i in range(get_digits(len(cmd)), HEADERSIZE): header = heade...
91a23eaee6ddd01ce5b5d62b3d43221b25bcd541
1,739
def stat_selector(player, stat, in_path, year): """ Selects stat for player in game year selected Parameters ---------- player The player being assessed (str) stat The stat being assessed (str) in_path The path to the folder containing player data (str) year ...
7f04086e4e3baee273baa1b90e1e0735856091d5
1,740
import torch def get_cali_samples(train_data_loader, num_samples, no_label=True): """Generate sub-dataset for calibration. Args: train_data_loader (torch.utils.data.DataLoader): num_samples (int): no_label (bool, optional): If the dataloader has no labels. Defaults to True. Ret...
297ea0384b1e7f0a6ea51fc37325e57eb1cb8afa
1,741
from typing import List from typing import Tuple import requests import json def fetch_available_litteraturbanken_books() -> List[Tuple[str, str]]: """Fetch available books from Litteraturbanken.""" url = "https://litteraturbanken.se/api/list_all/etext?exclude=text,parts,sourcedesc,pages,errata&filter_and=%7B...
ff14af499335c6229d1f8d995c343c62fff7db74
1,742
def soup_from_psf(psf): """ Returns a Soup from a .psf file """ soup = pdbatoms.Soup() curr_res_num = None is_header = True for line in open(psf): if is_header: if "NATOM" in line: n_atom = int(line.split()[0]) is_header = False continue words = line.split() atom_nu...
6b84e9428bec66e65b0d06dd81b238370f1602a8
1,743
def check_api(): """ 复核货品入库 post req: withlock { erp_order_code, lines: [{ barcode, location, lpn, qty },] w_user_code, w_user_name } """ w_user_code = request.json.pop('w_user_code', None) w_user_name = request.json.pop('w_user_na...
7c91f2c9068f762cb6681210f52ffe7d1a6ca259
1,744
def quadratic_form(u, Q, v, workers=1, **kwargs): """ Compute the quadratic form uQv, with broadcasting Parameters ---------- u : (..., M) array The u vectors of the quadratic form uQv Q : (..., M, N) array The Q matrices of the quadratic form uQv v : (..., N) array ...
6cd0abdf3d49ce38ba61ba6da9ee107663b1a8b9
1,745
def reorg(dat): """This function grabs the data from the dictionary of data types (organized by ID), and combines them into the :class:`dolfyn.ADPdata` object. """ outdat = apb.ADPdata() cfg = outdat['config'] = db.config(_type='Nortek AD2CP') cfh = cfg['filehead config'] = dat['filehead con...
2389be25e7052016a6a710803b7b661a7eb1606c
1,746
import os def human2pickett(name: str, reduction="A", linear=True, nuclei=0): """ Function for translating a Hamiltonian parameter to a Pickett identifier. An alternative way of doing this is to programmatically generate the Pickett identifiers, and just use format string to outpu...
683713e660e6e65846d32c7d018024674c4732f8
1,747
def get_oauth2_service_account_keys(): """A getter that returns the required OAuth2 service account keys. Returns: A tuple containing the required keys as strs. """ return _OAUTH2_SERVICE_ACCOUNT_KEYS
bcded81a6884dc40b9f2ccb32e8b14df450b6fd6
1,748
from pathlib import Path from typing import Any import sys import toml def read_conf_file( toml_path: Path, file_desc: str, schema_type: str, ) -> Any: """Read TOML configuration and verify against schema.""" if not toml_path.exists(): logger.error(f'{file_desc} file "{toml_path}" does not...
0004c188d3bce92399a3b3e72cc0ce6225d1e4d6
1,749
import json import os def mocked_requests_post(*args, **kwargs): """Mock to replace requests.post""" class MockResponse: """Mock class for KustoResponse.""" def __init__(self, json_data, status_code): self.json_data = json_data self.text = text_type(json_data) ...
017cf98285e77b7684cb37b3d65f9dd292f505b1
1,750
def grammar_info(df, col): """return three separate attributes with clean abstract, flesh score and sentence count""" df['clean_abstract'] = clean_text(df[col]) df['flesch_score'] = df[col].apply(flesch_score) df['sentence_count'] = sentence_count(df[col]) return df
7606121f68434a760255cca10e75840ca058c50c
1,751
import os import re def read_file_list(bld, file): """ Read and process a file list file (.waf_file) and manage duplicate files and possible globbing patterns to prepare the list for injestion by the project :param bld: The build context :param file: The .waf_file file list to process ...
28fa2d07085a572b9e3e33ef508c82b8c4f1bf42
1,752
def landing(): """Landing page""" return render_template('public/index.html')
462b8f4451008832c6883be64dc23712bc76c907
1,753
def uniform_decay(distance_array, scale): """ Transform a measurement array using a uniform distribution. The output is 1 below the scale parameter and 0 above it. Some sample values. Measurements are in multiple of ``scale``; decay value are in fractions of the maximum value: +--------------...
e643e7e962d3b6e29c2c23c0aa682e77a539d04b
1,754
def pid_to_service(pid): """ Check if a PID belongs to a systemd service and return its name. Return None if the PID does not belong to a service. Uses DBUS if available. """ if dbus: return _pid_to_service_dbus(pid) else: return _pid_to_service_systemctl(pid)
925f67611d83b3304db673e5e3d0c0a7dafd8211
1,755
def Frequencies(bands, src): """ Count the number of scalars in each band. :param: bands - the bands. :param: src - the vtkPolyData source. :return: The frequencies of the scalars in each band. """ freq = dict() for i in range(len(bands)): freq[i] = 0; tuples = src.GetPoint...
081e37f0d2d9d5a70266b24372d75d94d86fcbb0
1,756
from typing import Callable import torch from typing import Dict def get_loss_fn(loss: str) -> Callable[..., torch.Tensor]: """ Get loss function as a PyTorch functional loss based on the name of the loss function. Choices include 'cross_entropy', 'nll_loss', and 'kl_div'. Args: loss: a stri...
ebbb20dba1b7573c615c35d683a59c9a5151b0e9
1,757
def FormatAddress(chainIDAlias: str, hrp: str, addr: bytes) -> str: """FormatAddress takes in a chain prefix, HRP, and byte slice to produce a string for an address.""" addr_str = FormatBech32(hrp, addr) return f"{chainIDAlias}{addressSep}{addr_str}"
4004e2367e13abb890d22b653b4ac849bf615d1a
1,758
from typing import List from operator import or_ async def get_journal_scopes( db_session: Session, user_id: str, user_group_id_list: List[str], journal_id: UUID ) -> List[JournalPermissions]: """ Returns list of all permissions (group user belongs to and user) for provided user and journal. """ j...
2f3fcc3cbfdc124a10ee04a716c76f7e2144e0de
1,759
import re def clean_script_title(script_title): """Cleans up a TV/movie title to save it as a file name. """ clean_title = re.sub(r'\s+', ' ', script_title).strip() clean_title = clean_title.replace('\\', BACKSLASH) clean_title = clean_title.replace('/', SLASH) clean_title = clean_title.replace(':', COLON...
6dcee3b05e9654e65e0f8eb78be9383d349adff2
1,760
import time import os import subprocess import threading import signal def runCmd(cmd, timeout=42, sh=False, env=None, retry=0): """ Execute an external command, read the output and return it. @param cmd (str|list of str): command to be executed @param timeout (int): timeout in sec, after which the co...
d7a7054589af1f9cf30a2048eecacc4bc9d4044b
1,761
def _calc_cumsum_matrix_jit(X, w_list, p_ar, open_begin): """Fast implementation by numba.jit.""" len_x, len_y = X.shape # cumsum matrix D = np.ones((len_x, len_y), dtype=np.float64) * np.inf if open_begin: X = np.vstack((np.zeros((1, X.shape[1])), X)) D = np.vstack((np.zeros((1, D....
a282f68ca5789c97582f9535b5a255066bba44d9
1,762
def create_field_texture_coordinates(fieldmodule: Fieldmodule, name="texture coordinates", components_count=3, managed=False) -> FieldFiniteElement: """ Create texture coordinates finite element field of supplied name with number of components 1, 2, or 3 and the componen...
e19e964e0828006beae3c9e71f30fb0c846de1de
1,763
import uuid def get_cert_sha1_by_openssl(certraw: str) -> str: """calc the sha1 of a certificate, return openssl result str""" res: str = None tmpname = None try: tmpname = tmppath / f"{uuid.uuid1()}.crt" while tmpname.exists(): tmpname = tmppath / f"{uuid.uuid1()}.crt" ...
4b92531473e8488a87d14c8ecc8c88d4d0adef0d
1,764
import os import glob def get_files(root_path, extension='*.*'): """ - root_path: Path raiz a partir de onde serão realizadas a busca - extension: Extensão de arquivo usado para filtrar o retorno - retorna: Retorna todos os arquivos recursivamente a partir de um path raiz """ retu...
a5ed8a24eb20ad86fe1c4dba2a9028bd639f4f57
1,765
from typing import Union def get_dderivative_skewness(uni_ts: Union[pd.Series, np.ndarray], step_size: int = 1) -> np.float64: """ :return: The skewness of the difference derivative of univariate time series within the function we use step_size to find derivative (default value of step_size is 1)...
11688b0cbd5dde2539cc3d5cfa8c5dccb9432f55
1,766
def extract_query(e: Event, f, woi, data): """ create a query array from the the event :param data: :param e: :param doi: """ assert woi[0] > 0 and woi[1] > 0 e_start_index = resolve_esi(e, data) st = int(e_start_index - woi[0] * f) ed = int(e_start_index + woi[0] * f) return...
7109e28a265ff49054036e4e4c16ace0fc5eebda
1,767
import ctypes def getForegroundClassNameUnicode(hwnd=None): """ Returns a unicode string containing the class name of the specified application window. If hwnd parameter is None, frontmost window will be queried. """ if hwnd is None: hwnd = win32gui.GetForegroundWindow() # Maximu...
82147d3da4c9374078bbeba64ef6968982dc2550
1,768
def read_mapping_from_csv(bind): """ Calls read_csv() and parses the loaded array into a dictionary. The dictionary is defined as follows: { "teams": { *team-name*: { "ldap": [] }, .... }, "folders: { *folder-id*: { "name": *folder-name*...
8ffe1b5f489bb3428cb0b2dd3cc7f9eafe9ecf27
1,769
from typing import Sequence from typing import Tuple def primal_update( agent_id: int, A: np.ndarray, W: np.ndarray, x: np.ndarray, z: np.ndarray, lam: np.ndarray, prev_x: np.ndarray, prev_z: np.ndarray, objective_grad: np.ndarray, feasible_set: CCS, alpha: float, tau: ...
6a13bb9147b74c3803482f53273ebc831ca1662b
1,770
def norm_cmap(values, cmap, normalize, cm, mn, mx): """ Normalize and set colormap Parameters ---------- values Series or array to be normalized cmap matplotlib Colormap normalize matplotlib.colors.Normalize cm matplotl...
25515df37fe6b7060acf681287156af2c58d4c03
1,771
def _cpx(odss_tuple, nterm, ncond): """ This function transforms the raw data for electric parameters (voltage, current...) in a suitable complex array :param odss_tuple: tuple of nphases*2 floats (returned by odsswr as couples of real, imag components, for each phase of each terminal) :type od...
f5931915550bb7ec9e713689c3d79997973eb252
1,772
def get_l2_distance_arad(X1, X2, Z1, Z2, \ width=0.2, cut_distance=6.0, r_width=1.0, c_width=0.5): """ Calculates the Gaussian distance matrix D for atomic ARAD for two sets of molecules K is calculated using an OpenMP parallel Fortran routine. Arguments: ============== ...
77a4656a6f0014453991b8619ea4c53c6eec2c78
1,773
def _swap_endian(val, length): """ Swap the endianness of a number """ if length <= 8: return val if length <= 16: return (val & 0xFF00) >> 8 | (val & 0xFF) << 8 if length <= 32: return ((val & 0xFF000000) >> 24 | (val & 0x00FF0000) >> 8 | ...
4b3b879ad04e43e9454b904ba65420a8d477b629
1,774
def get_analysis(output, topology, traj): """ Calls analysis fixture with the right arguments depending on the trajectory type. Parameters ----------- output : str Path to simulation 'output' folder. topology : str Path to the topology file. traj : str Trajectory typ...
0382f4e672aba3ab754de7d26d27c7921239951f
1,775
def get_callback_class(module_name, subtype): """ Can return None. If no class implementation exists for the given subtype, the module is searched for a BASE_CALLBACKS_CLASS implemention which is used if found. """ module = _get_module_from_name(module_name) if subtype is None: return _get_c...
cf04ddcc28c43b82db44d8be96419efbc166330f
1,776
def index(): """Toon de metingen""" return render_template('index.html', metingen=Meting.query.all())
3d92b912c0af513b6d20a094799f7dfb60220a75
1,777
def about(template): """ Attach a template to a step which can be used to generate documentation about the step. """ def decorator(step_function): step_function._about_template = template return step_function return decorator
7c00256e39481247857b34dcd5b7783a39b0a8bd
1,778
import torch def _extend_batch_dim(t: torch.Tensor, new_batch_dim: int) -> torch.Tensor: """ Given a tensor `t` of shape [B x D1 x D2 x ...] we output the same tensor repeated along the batch dimension ([new_batch_dim x D1 x D2 x ...]). """ num_non_batch_dims = len(t.shape[1:]) repeat_shape = ...
7ee1d0930f843a9d31bcc4934d675109f3b2df9b
1,779
import os import csv import random def read_GTSRB_train(directory, shuffle = True): """ Read the training portion of GTSRB database. Each class has an own index file. """ print('Reading trainset index...') entries = [] for class_id in range(num_classes): # each class is in a separa...
278813bf2aabc1f721f23d5ee466fb1444b8ca84
1,780
def get_client(config): """ get_client returns a feature client configured using data found in the settings of the current application. """ storage = _features_from_settings(config.registry.settings) return Client(storage)
650f0d294514a4d13afd9ab010d6d4bdd4045c43
1,781
import copy from ibeis.init import filter_annots from ibeis.expt import experiment_helpers import six def print_results(ibs, testres): """ Prints results from an experiment harness run. Rows store different qaids (query annotation ids) Cols store different configurations (algorithm parameters) Ar...
265a3ae3e44b3816ed541521e24fb2aa52d1989b
1,782
from datetime import datetime def fra_months(z): # Apologies, this function is verbose--function modeled after SSA regulations """A function that returns the number of months from date of birth to FRA based on SSA chart""" # Declare global variable global months_to_fra # If date of birth is 1/1/1938...
70ba416f6415fd5db08244ae7543db0573f74b2d
1,783
def set_global_format_spec(formats: SpecDict): """Set the global default format specifiers. Parameters ---------- formats: dict[type, str] Class-based format identifiers. Returns ------- old_spec : MultiFormatSpec The previous globally-set formatters. Example -----...
1494a6ff2ad71aa9ed0d20bc0620a124d404e5da
1,784
def gen_base_pass(length=15): """ Generate base password. - A new password will be generated on each call. :param length: <int> password length. :return: <str> base password. """ generator = PassGen() return generator.make_password(length=length)
571683589e13b8dcbd74573b31e5fc7644360bfe
1,785
def split_component_chars(address_parts): """ :param address_parts: list of the form [(<address_part_1>, <address_part_1_label>), .... ] returns [(<char_0>, <address_comp_for_char_0), (<char_1>, <address_comp_for_char_1),.., (<char_n-1>, <address_comp_for_char_n-1)] """ char_arr = [] for addres...
f4f3dd59378a689e9048cee96b8d6f12e9d8fe21
1,786
import json def report_metrics(topic, message): """ 将metric数据通过datamanage上报到存储中 :param topic: 需要上报的topic :param message: 需要上报的打点数据 :return: 上报结果 """ try: res = DataManageApi.metrics.report({"kafka_topic": topic, MESSAGE: message, TAGS: [DEFAULT_GEOG_AREA_TAG]}) logger.info(...
28f0bf1671b4116b26b8dba3f0c0a34174a0597a
1,787
def wg_completion_scripts_cb(data, completion_item, buffer, completion): """ Complete with known script names, for command '/weeget'. """ global wg_scripts wg_read_scripts(download_list=False) if len(wg_scripts) > 0: for id, script in wg_scripts.items(): weechat.hook_completion_list_...
b9dc0d5e736cfeb1dc98d09b8e12c6a52696d89d
1,788
def getG(source): """ Read the Graph from a textfile """ G = {} Grev = {} for i in range(1,N+1): G[i] = [] Grev[i] = [] fin = open(source) for line in fin: v1 = int(line.split()[0]) v2 = int(line.split()[1]) G[v1].append(v2) Grev[v2].append(v...
6e9a8a5c69267403ee3c624670c60af547d37a46
1,789
import re def remove_version(code): """ Remove any version directive """ pattern = '\#\s*version[^\r\n]*\n' regex = re.compile(pattern, re.MULTILINE|re.DOTALL) return regex.sub('\n', code)
101ada9490137a879ea287076989a732942368f8
1,790
def unlabeled_balls_in_labeled_boxes(balls, box_sizes): """ OVERVIEW This function returns a generator that produces all distinct distributions of indistinguishable balls among labeled boxes with specified box sizes (capacities). This is a generalization of the most common formulation of the problem,...
6390226744c2d4b756b43e880707accc333893d5
1,791
def beginning_next_non_empty_line(bdata, i): """ doc """ while bdata[i] not in EOL: i += 1 while bdata[i] in EOL: i += 1 return i
0a372729a7ad794a9385d87be39d62b1e6831b71
1,792
import collections def VisualizeBoxes(image, boxes, classes, scores, class_id_to_name, min_score_thresh=.25, line_thickness=4, groundtruth_box_visualization_color='black', ...
b02216a5a2e7fa7029dd0fea298efd1d593bab88
1,793
from datetime import datetime import sys def tagDataskp(dList, start, end, name): """ Toma una posición para obtener de la lista dList. """ try: #if end is not None: if end: #tagdata = ",".join(dList[start:end + 1]) tagdata = dList[start:end + 1] el...
13d611b92dcd61377a68b53b47331260a9936f09
1,794
def cal_softplus(x): """Calculate softplus.""" return np.log(np.exp(x) + 1)
a966826f1e508ca1a197e63396ae9e2f779bcf96
1,795
import os import pickle def load_list_from_disk_with_pickle(path_to_list: str) -> list: """This function loads a list from disk Args: path_to_list (str): path to where the list is saved Returns: loaded_list (list): loaded list Raises: AssertionError: if list path does not exist...
abaf968c1b71bba83edac0e6d91b8eeb0dddc517
1,796
def prepare_spark_conversion(df: pd.DataFrame) -> pd.DataFrame: """Pandas does not distinguish NULL and NaN values. Everything null-like is converted to NaN. However, spark does distinguish NULL and NaN for example. To enable correct spark dataframe creation with NULL and NaN values, the `PANDAS_NULL` c...
f18ddfc3e77809908bf8fa365c1acf8a8d5069c6
1,797
import requests import token from sys import api_version def get_user_vk_id(id): """ :param id: Числовой ID пользователя VK :return: Ссылка на пользователя """ response = requests.get('{}users.get?user_ids={}&fields=domain&access_token={}&v={}' .format(api_address, id, ...
bc82fc4e3a72adb3c8c1cdf4838351ee7aa608ad
1,798
import scipy def controllable_staircase( A, B, C, D, E, tol=1e-9, ): """ Implementation of COMPUTATION OF IRREDUCIBLE GENERALIZED STATE-SPACE REALIZATIONS ANDRAS VARGA using givens rotations. it is very slow, but numerically stable TODO, add pivoting, TODO, make...
fb2e2f162aad45a1bdbb21a67207576539700b0e
1,799