content
stringlengths
22
815k
id
int64
0
4.91M
def get_additional_features(eventlog_df): """ Transforms the initial eventlog dataset into a dataframe with trace vectors that describe the Peformance Perspective of joruneys. Input: eventlog_df: [DataFrame] clean eventlog (one touchpoint per row) Output: A dataframe with t...
67,500
def get_sequence(structure, label=None, return_type=None): """Get the sequence of amino acid residues from a PDB file Determines the sequence from the order of amino acid residues in the Protein Data Bank (PDB) file. The SEQRES records in the PDB file are not used, because it is sometimes different fro...
67,501
def printout(channels, samples_per_channel, noises, correlations, data_path): """Format analysis results and print them to the screen and to a file. """ # Try to parse the filename, but if that doesn't go well, just # display the whole filepath instead. try: input_V, setup, date = parse_...
67,502
def add_axis(head, axis, naxis, crpix, crval, cdelt, ctype, cunit): """ Adds an axis to the fits cube """ head['NAXIS'] = head['NAXIS'] + 1 head['NAXIS{0}'.format(axis)] = naxis head['CRPIX{0}'.format(axis)] = crpix head['CRVAL{0}'.format(axis)] = crval head['CDELT{0}'.format(axis)]...
67,503
def CalcMD5(filepath): """generate a md5 code by a file path""" with open(filepath,'rb') as f: md5obj = hashlib.md5() md5obj.update(f.read()) return md5obj.hexdigest()
67,504
def get_tf1(d): """ Returns the first order trend filtering matrix for d features. Output ------- D: array-like, shape (d -1, d) The kth order difference matrix returned in a sparse matrix format. """ D = diags(diagonals=[-np.ones(d), np.ones(d - 1)], offsets=[0, 1]) D = D.tocsc...
67,505
def positionnal_token_frequency(direction_directe, direction_indirecte, nlp): # CORRECT ! """la fonction qui met en évidence la fréquence de l'apparition des tokens aux positions initiales (1 ou 2 mot de la phrase) ou finales (le dernier ou l'avant dernier mot de la phrase) pour deux directions passées en argument...
67,506
def accepted_mimetypes(request, default='text/html'): """ returns the accepted mimetypes of an HTTP/1.1 request It returns a dictionary of the accepted mimetypes as keys and their priorities as values. """ accepted_strings = request.requestHeaders.getRawHeaders( 'Accept', [default]) acc...
67,507
def read_model(model_configuration, path, train_dataset): """ Creates ModelEntity based on model_configuration and data stored at path. """ if path.endswith(".bin") or path.endswith(".xml"): model_adapters = { "openvino.xml": ModelAdapter(read_binary(path[:-4] + ".xml")), ...
67,508
def num2hex(num, width=1): """将数字转换为指定长度的十六进制字符串 Args: num (int): 输入数字 width (int, optional): 指定字符串长度. Defaults to 1. Returns: str: 输入数字的十六进制字符串表示 """ return '{:0>{width}}'.format(hex(num)[2:].replace('L', ''), width=width)
67,509
def save_elements_json(name: str, line: str = None, mode="w"): """Save elements to file, by lines JSON elments.""" with open(name, mode) as _file: if line: _file.write(line + "\n")
67,510
def test_lfs_migrate(runner, project, client): """Test ``renku storage migrate`` command for large files in git.""" for _file in ["dataset_file", "workflow_file", "regular_file"]: (client.path / _file).write_text(_file) client.repo.git.add("*") client.repo.index.commit("add files") result...
67,511
def count_locked(): """ Count number of distinct locked tiles that could still be runing on aws lambda """ tiles = db.SQL("""SELECT tile, subx, suby, filter, count(filter) FROM mosaic_tiles_exposures t, exposure_files e WHERE t.expid = e.eid AND t...
67,512
def Title(): """ Return a :class:`zope.schema.interfaces.IField` representing the standard title of some object. This should be stored in the `title` field. """ return PlainTextLine( max_length=140, # twitter required=False, title=u"The human-readable title of this objec...
67,513
def test_max_pool2d_memory(): """Test the memory usage""" # arguments and test data N, H, W, CI, kernel_size, stride, padding, dilation = 128, 28, 28, 8, 3, 2, 1, 1 ceil_mode, return_indices = False, False print("========== MaxPool2d Memory Test ==========") for dtype in ['float32', 'float16']:...
67,514
def deactivate(): """ This method is required to deactivate Github from Datapod First remove the keys registry from ~/.ssh/config file """ ##somwhow remove hostname github in config in .ssh ##delete the datapod key of the rmeote Code Repo like github return
67,515
def is_ip_address(ipaddr): """ Simple helper to determine if given string is an ip address or subnet """ try: ipaddress.ip_interface(ipaddr) return True except ValueError: return False
67,516
def clear_team_text(data): """ Function clears table if rows are not valid (doesn't hold jumper data), for team and mixed competition only. :param data: data pulled from team-pdfs :return: list of jumpers rows """ data_to_skip = ['Assistant', '"ruhrgas"', 'Ski-Jumping', 'Official', 'Finish', 'J...
67,517
def _merge_retry_options(retry_options, overrides): """Helper for ``construct_settings()``. Takes two retry options, and merges them into a single RetryOption instance. Args: retry_options (RetryOptions): The base RetryOptions. overrides (RetryOptions): The RetryOptions used for overriding ``r...
67,518
def tg_healthcheck_port(x): """ Property: TargetGroup.HealthCheckPort """ if isinstance(x, str) and x == "traffic-port": return x return network_port(x)
67,519
def isjson(value): """ Return whether or not given value is valid JSON. If the value is valid JSON, this function returns ``True``, otherwise ``False``. Examples:: >>> isjson('{"Key": {"Key": {"Key": 123}}}') True >>> isjson('{ key: "value" }') False :param value:...
67,520
def IDTtoxyz(Inc, Dec, Btot): """Convert from Inclination, Declination, Total intensity of earth field to x, y, z """ Bx = Btot * np.cos(Inc / 180.0 * np.pi) * np.sin(Dec / 180.0 * np.pi) By = Btot * np.cos(Inc / 180.0 * np.pi) * np.cos(Dec / 180.0 * np.pi) Bz = Btot * np.sin(Inc / 180.0 * np.pi...
67,521
def conv_2d(x, n_filters: int, kernel_size: int, stride: int, max_pool: bool = False): """ Conv2D layer :param x: input to the layer :param n_filters: Number of filters for the layer :param kernel_size: Size of the kernel :param stride: Stride to apply :param max_pool: Add a max pooling laye...
67,522
def set_jinja_filters(env): """ Used to add custom Jinja2 filters to the env """ import pykwiki.jinja_filters as jinja_filters env.filters['idsafe'] = jinja_filters.idsafe return env
67,523
def check_version(repo, commit, commitkey_len=None): """ E.g. check_version('http://github.com/tskit-dev/tsinfer', 'efbafff') Check that this module is installed, and return the installation dir and short commit hash. If `commit`=='' then we download and save under libname_ and don't check the ...
67,524
def main(gdalversion, runtime, deploy): """Build and Deploy Layers.""" client = docker.from_env() docker_name = f"lambgeo/titiler:gdal{gdalversion}" click.echo(f"Building image: {docker_name}...") client.images.build( path="./", dockerfile="Dockerfile", tag=docker_name, ...
67,525
def get_dicom_data(path): """ Given dicom data file path, return the corresponding dicom data. """ return pydicom.read_file(path)
67,526
def assert_equal(actual: Literal["y"], desired: Literal["y"]): """ usage.statsmodels: 1 """ ...
67,527
def test_upgrade_downgrade_reattach_bcol_todifferent_org(client, jwt, session, keycloak_mock): # pylint:disable=unused-argument """Assert that an org can be updated via PUT.""" headers = factory_auth_header(jwt=jwt, claims=TestJwtClaims.public_user_role)...
67,528
def register_local_model(registered_class: Type[model_lib.Model]) -> None: """Register given local class.""" _MODEL_REGISTRY[_LOCAL_MODEL_KEY] = registered_class
67,529
def get_stats(data): """ Given a data set from get_data, the function returns an array where each row contains the mean and standard deviation for a fixed system size. Parameters ---------- data : ndarray A 2-dimentional numpy array containing resulting approximation ratios. Ea...
67,530
def concatenate_segments(segments, max_break='30m', max_heading_rate=5): """ Concatenate consecutive segments if they meet the requirements defined by the maximum ship break allowed and the maximum heading deviation allowed. Parameters --------- segments : list of Datasets The list of segments to compare betwe...
67,531
def _discount_cumsum(x: np.array, discount: float): """ magic from rllab for computing discounted cumulative sums of vectors. input: vector x, [x0, x1, x2] output: [x0 + discount * x1 + discount^2 * x2, x1 + discount * x2, x2] """ return sc...
67,532
def is_pythagorean_triplet(a, b, c): """Determine whether the provided numbers are a Pythagorean triplet. Arguments: a, b, c (int): Three integers. Returns: Boolean: True is the provided numbers are a Pythagorean triplet, False otherwise. """ return (a < b < c) and (a**2 + b**2 == ...
67,533
def preprocess_image(img_path: str, output_file: str, **kwargs) -> str: """ Preprocess the images for SpineStraightening, put healthy mask, patient scan, patient mask in the same orientation "PIL" :param img_path: str, path of image :param output_file: str, output filename :param kwargs: orientation...
67,534
def tune_search(train, test, fine_tune, project_name, verb, bayopt_trials): """Define the search space using keras-tuner and bayesian optimization""" hypermodel = NASnet_transfer(input_shape=(331, 331, 3), fine_tune=fine_tune) tuner = BayesianOptimization( hypermodel, max_trials=bayopt_tria...
67,535
def url_to_path(url: str): """Converts an incoming url into a path-slug.""" return slugify(url, max_length=199)
67,536
def later_than(after, before): """ True if then is later or equal to that """ if isinstance(after, six.string_types): after = str_to_time(after) elif isinstance(after, int): after = time.gmtime(after) if isinstance(before, six.string_types): before = str_to_time(before) elif...
67,537
def make_adjacency_graph(frcs, bu_msg, max_dist=3): """Make a graph based on contour adjacency.""" preproc_pos = np.transpose(np.nonzero(bu_msg > 0))[:, 1:] preproc_tree = cKDTree(preproc_pos) # Assign each preproc to the closest F1 f1_bus_tree = cKDTree(frcs[:, 1:]) _, preproc_to_f1 = f1_bus_tr...
67,538
def main(arg_dict): """Tests the sweep's basic functions""" use_dummy = arg_dict['use_dummy'] with sweep_helpers.create_sweep_w_error('/dev/ttyUSB0', use_dummy) as (sweep, err): if err: output_json_message( {'type': "update", 'status': "failed", 'msg': err}) ...
67,539
def drop_connect(inputs, p, training): """ Drop connect. """ if not training: return inputs batch_size = inputs.shape[0] keep_prob = 1 - p # random_tensor = keep_prob random_tensor = torch.rand([batch_size, 1, 1, 1], dtype=inputs.dtype, device=inputs.device) + keep_prob binary_tensor ...
67,540
def years_ago(years, from_date=None): """ Return datetime that was n years from some date (defaulting to right now) :param years: :param from_date: default `now` :return: """ if from_date is None: from_date = datetime.now() return from_date - relativedelta(years=years)
67,541
def state(name): """ prints the current state of device specified via NAME """ dev_props = get_device_from_config(config, name) print(json.dumps(get_json_state(dev_props)))
67,542
def export_kpis(df_adopt, df_water): """Add KPIs to existing csv file. Args: df_adopt: (DataFrame): KPIs about watered trees df_water: (DataFrame): KPIs about adoptes trees Output: daten/giessdenkiez_KPIs.csv """ # preprocess data result = df_adopt.join(df_water) ti...
67,543
def get_iters(mnist, batch_size): """Get MNIST iterators.""" train_iter = mx.io.NDArrayIter(mnist['train_data'], mnist['train_label'], batch_size, shuffle=True) val_iter = mx.io.NDArrayIter(mnist['test_d...
67,544
def _run_nary_op(op: str, kop: str, stub: synthesis_service_pb2_grpc.SynthesisServiceStub, num_inputs: int) -> List[delay_model_pb2.DataPoint]: """Characterizes an nary op.""" results = [] for bit_count in _bitwidth_sweep(0): results.append( _build_data_point_bit_type...
67,545
def GhostNet(input_shape=None, include_top=True, weights='imagenet', input_tensor=None, cfgs=DEFAULT_CFGS, width=1.0, dropout_rate=0.2, pooling=None, classes=1000, **kwargs): """Instantiates the Ghos...
67,546
def list2words(l): """列表转换word对象列表""" return [Word(i) for i in l]
67,547
def _passwd_tar_impl(ctx): """Core implementation of passwd_tar.""" f = "".join(["%s:x:%s:%s:%s:%s:%s\n" % ( entry[PasswdFileContentProviderInfo].username, entry[PasswdFileContentProviderInfo].uid, entry[PasswdFileContentProviderInfo].gid, entry[PasswdFileContentProviderInfo].inf...
67,548
def min_risk(mu, H, target_return=0.0, shortselling=True, verbose=False): """ Minimum Variance Portfolio min w'Hw s.t. w'mu = target_return sum(w) = 1 w >= 0 (if no shortselling) In conic form min s2 s.t. ...
67,549
def multi_replace(search, replace, path): """Replace search with replace in all filenames and file contents in directory path. @type search: string @param search: The old string. @type replace: string @param replace: The new string. @type path: string @param path: The path in ...
67,550
def test_data_model(): """Test data model definitions.""" params = dict(name="test", type_=str, is_required=True) data_model = DataModel("test", [Attribute(**params)]) data_model._check_validity() with pytest.raises(ValueError): data_model = DataModel("test", [Attribute(**params), Attribut...
67,551
def extract_JK(pos_seq): """The 'JK' method in Handler et al. 2016. Returns token positions of valid ngrams.""" def find_ngrams(input_list, num_): '''get ngrams of len n from input list''' return zip(*[input_list[i:] for i in range(num_)]) # copied from M and S chp 5''' patterns = set(['AN', 'NN', 'AAN', 'AN...
67,552
def get_child_logger(*names: str): """Returns a child logger of the project-level logger with the name toolshed.<name>.""" return logging.getLogger("toolshed." + '.'.join(names))
67,553
def plotResult(img, out, std_resize_image, energyFunction, scale, img_name): """ Plot the original image with its mean energy, energy map and the resized image with its mean energy. """ fig = plt.figure(figsize=(10, 10)) # Fix message blinking when hover fig.canvas.toolbar.set_message = lam...
67,554
def validate_pcrPlate_position_samplesetitems( samplesetitems, pcrPlateRow, samplesetitem_id, sampleset=None ): """ 1) validate pcrPlateRow position selected for sampleSetItem is unique 2) for Ampliseq on Chef pcrPlateRow value is required If validating with a dict of samplesetitems, "p...
67,555
def sequential_frequencies( df, seqID, query="sequence", seqType="protein", cleanExtra=True, cleanUnused=-1 ): """Generates a :class:`.SequenceFrame` for the frequencies of the sequences in the :class:`.DesignFrame` with ``seqID`` identifier. If there is a ``reference_sequence``...
67,556
def get_csv_config(model): """Returns a configuration object based on the given model.""" if model == Accession: return AccessionCSVConfig elif model == Donor: return DonorCSVConfig elif model == Object: return ObjectCSVConfig else: return GenericCSVConfig
67,557
def load_pretrained_params( model: Model, url: Optional[str] = None, hash_prefix: Optional[str] = None, overwrite: bool = False, internal_name: str = 'weights', **kwargs: Any, ) -> None: """Load a set of parameters onto a model >>> from doctr.models import load_pretrained_params >>>...
67,558
def delete_organization_config_rule(OrganizationConfigRuleName=None): """ Deletes the specified organization config rule and all of its evaluation results from all member accounts in that organization. Only a master account can delete an organization config rule. AWS Config sets the state of a rule to DELET...
67,559
def import_vae(env: str, cams: list, mvae_mode: str, img_width: int, img_height: int) -> MultiCamVae: """ Loads an existing vae set with the specified properties, or returns an already cached goal set :param env: the name of the environment, e.g. FetchReach-v1 :param cams: the list of camera names, e.g...
67,560
def get_comment_tree(pid, sid, comments, root=None, only_after=None, uid=None, provide_context=True, include_history=False, postmeta=None): """ Returns a fully paginated and expanded comment tree. TODO: Move to misc and implement globally @param include_history: @param pid: post fo...
67,561
async def api_portal_restrictions(req: fastapi.Request): """ Returns all restrictions for the current user. """ keyword_restrictions, query_s = profile(restrictions, portal, req) return { 'profile': { 'query': query_s, }, 'data': keyword_restrictions, 'no...
67,562
def load_key(encryption_key_path): """ Read an encryption key """ if Path(encryption_key_path).is_file(): return open(encryption_key_path, "rb").read() else: console.print(f"[red] File does not exist[/red]: {encryption_key_path}") sys.exit(1)
67,563
def get_feature_extractor(name, *args, **kwargs): """Return appropriate feature extractor as a function Args: name (str): *args : *kwargs: Returns: extractor (function): feature extractor """ # TODO: select feature extractor by name extractor = None if name == 'sift': def sift_ext...
67,564
def cartesian_pose(args): """ Move the robot arm to the specified configuration. Call using: $ rosrun intera_examples go_to_cartesian_pose.py [arguments: see below] -p 0.4 -0.3 0.18 -o 0.0 1.0 0.0 0.0 -t right_hand --> Go to position: x=0.4, y=-0.3, z=0.18 meters --> with quaternion orient...
67,565
def test_basic_call_async(): """ The most basic Happy-Path test for Hug APIs using async """ @hug_core.local() async def hello_world(): return "Hello World!" assert hello_world() == "Hello World!"
67,566
def delete_ebs_volumes(): """Delete all the EBS volumes :return: None """ client = boto3.client('ec2') print('Deleting EBS volumes') volumes_resp = client.describe_volumes( MaxResults=500 ) while True: for vol in volumes_resp['Volumes']: volume_id = vol['Vol...
67,567
def Anomalies(Serie): """ Make anomalies compared with the annual cycle INPUTS Serie : Pandas DataFrame with data """ Ciclo = Cycles(Serie, type='annual') Devtd = Cycles(Serie, type='annual',percentiles='std') Anom = Serie.copy() for i in range(len(Serie)): med = Ciclo[Serie....
67,568
def test_spm_compatibility(): """"test python API with legacy C++ tool outputs NOTE: hard-coded strings are generated by spm v0.1.82 """ testfile = root + "/tedlium2.txt" nbpe = 100 bpemode = "unigram" bpemodel = "test_spm" # test train spm.SentencePieceTrainer.Train( f'--i...
67,569
def close_con(session): """ Nothing to say :param session: A section object :return: """ session.close() return 'Session closed'
67,570
def install(development: bool, lockfile: str, quiet: bool): """Install dependencies from lockfile using PIP""" ballad = core.Ballad() ballad.lockfile_name = lockfile if not development: ballad.environment = "production" ballad.install(quiet)
67,571
async def async_turn_off(opp: OpenPeerPower, entity_id: str | None = None) -> None: """Turn off specified media player or all.""" data = {ATTR_ENTITY_ID: entity_id} if entity_id else {} await opp.services.async_call(MP_DOMAIN, SERVICE_TURN_OFF, data)
67,572
def test_cli_change_exact(): """ Test cli change for exact commands """ commands = ["show ipv6 bgp neighbors", "show lldp traffic"] expect = ["show ipv6 bgp peers", "show lldp counters"] for c, e in zip(commands, expect): assert e == cli_convert(c, 2) assert c == cli_convert(e, ...
67,573
def get_message_maps( force_refresh: bool = False, ) -> Tuple[Dict[str, Node], Dict[str, Client]]: """Gets Node and Client protobufs, computes their internal statuses, and return their maps. If the cache doesn't contain the message maps, this function reads the Nodes and Clients from the remote reporting s...
67,574
def getlogger(pkg='', handler=None): """ 패키지 혹은 채널 로거 logging.getLogger(package_name) or logg.getLogger() :param pkg: str """ from .caller import caller if not pkg: m = caller.modulename() s = m.split('.', 1) if len(s) > 1: pkg = s[0] if haslogger(pk...
67,575
def add_group(name, fname, fpath=os.path.join(config.get('path','db_dir'), 'Object'), proxy=True): """Add a Blender group to the current scene. Add a group of Blender objects (all the parts of a single object, most likely) from another file to the current scene. Optionally, add as a proxy object (all obj...
67,576
def test_mst_student(): """ I manually created a numoy array with dimessions 7x7 and I previousl know the shortest path is 7. """ x=np.array([[0., 2., 3., 0., 0., 0., 0.], [2., 0., 1. ,1., 4., 0. ,0.], [3., 1. ,0., 0., 0., 5. ,0.], [1., 0., 0., 0., 1., 0. ,0.], [0. ,4., 0., 1.,...
67,577
def safe_str_convert(s, strict=False): """Convert a string to ASCII without throwing a unicode decode error. @param s (any) The thing to convert to a str. @param strict (boolean) If True make sure that there are no unprintable characters in the given string (if s is a str). If False do no modifica...
67,578
def _vectorize_voxels(voxels_linear, size_x, size_y): """ Convert linear array of voxel indices to 3D array of voxel indices. Inputs: voxels_linear (np vector of ints) - linear array of indicies size_x (int) - size of voxel space in x direction (in voxels) size_y (int) - size of voxel space in ...
67,579
def _get_user_dir(): """Get the users data directory location.""" app_name = pkg_resources.require('zegami-cli')[0].project_name return user_data_dir(app_name, 'zegami')
67,580
def collect_derivatives(expressions): """ Exploit linearity of finite-differences to collect `Derivative`'s of same type. This may help CIRE creating fewer temporaries while catching larger redundant sub-expressions. """ processed = [] for e in expressions: # Track type and number of...
67,581
def main(): """Send test metric to AWS CloudWatch""" logging.basicConfig(level=logging.DEBUG) cloud_watch = create_cloud_watch( 'Test Namespace', asynchronous=False, buffered=False, dummy=False, dimensions={'By intent': 'Test'}, ) cloud_watch.log('awsme-test',...
67,582
def test_set_window_desktop(window_id: int, xsession: XSession): """Tests that a desktop can be assigned to a window.""" desktop_count = xsession.get_desktop_count() if desktop_count < 2: pytest.skip( f"Number of desktops {desktop_count} is less than required value: 2" ) de...
67,583
def pdf(X, m, S): """ Calculates the probability density function of a Gaussian distribution: X is a numpy.ndarray of shape (n, d) containing the data points whose PDF should be evaluated m is a numpy.ndarray of shape (d,) containing the mean of the distribution S is a numpy.ndarray of shape (d...
67,584
def find_correct_weight(program_weights, program, correction): """Return new weight for node.""" return program_weights[program] + correction
67,585
def test_if_in_condition_objects_value(): """Test that we can do if is statement on objectss.""" test = [ {'val': 'target'}, [ IfStatement(**{ 'condition': 'in', 'target': [{'val': 'target'}], 'then': 'value2', }), ]...
67,586
def bubble_sort(data, size): """ Implementação de um algoritmo de ubble sort com recursão. Argumentos: data: lista. Lista que será ordenada size: int. Tamanho da lista Retorna a lista "data" ordenada. """ swap = False for i in range(0, size - 1): if data[i] > data[i + 1]: ...
67,587
def flatten(iterator, dont_flatten=()): """Flattens all iterable elements in the given iterator recursively and returns the resulting flat iterator. Can optionally be passed a list of classes to avoid flattening. Will not flatten strings or bytes due to recursion errors.""" for element in iterator: ...
67,588
def test_fees_with_corp_type_and_filing_type_with_invalid_start_date(session, client, jwt, app): """Assert that the endpoint returns 400.""" # Insert a record first and then query for it token = jwt.create_jwt(get_claims(), token_header) headers = {'Authorization': f'Bearer {token}', 'content-type': 'ap...
67,589
def segment_mask(segment_ids: JTensor, source_segment_ids: Optional[JTensor] = None, dtype: jnp.dtype = jnp.float32) -> JTensor: """Computes (non-causal) segment mask. Args: segment_ids: a JTensor of shape [B, T], the segment that each token belongs to. source_segmen...
67,590
def handle_keys(): """ This version use keypad (hence KP?). Not tested. """ global fov_recompute global mouse_coord keypress = False for event in tdl.event.get(): if event.type == 'KEYDOWN': user_input = event keypress = True if event.type == 'MOU...
67,591
def test_for(item, min_version=None, callback=extract_version): """Test to see if item is importable, and optionally check against a minimum version. If min_version is given, the default behavior is to check against the `__version__` attribute of the item, but specifying `callback` allows you to ex...
67,592
def errcheck_object(result, func, args): """Checks the return value of NormFileEnqueue and NormDataEnqueue""" if result == ctypes.c_void_p.in_dll(libnorm, "NORM_OBJECT_INVALID"): raise NormError( "Error creating object from function '%s'" % func.__name__) return result
67,593
def parseArgs(): """ CLI inputs """ log.info('Parsing command-line arguments...') parser = argparse.ArgumentParser(description='Explore enzyme-screening variability historically') subparsers = parser.add_subparsers(help='Choose mode of operation') plot_parser = subparsers.add_parser('only-pl...
67,594
def encode(delta_str, n_vertices, base, m=False): """Encodes delta string as a big integer. Args: delta_str: A string with delta coordinates in reference to min_x and min_y, min_x and min_y also included n_vertices: Number of vertices in the polygon base Returns: A...
67,595
def test(device): """ Test if set_voc_tuning_parameters() and get_voc_tuning_parameters() work as expected. """ device.set_voc_tuning_parameters(110, 16, 12, 90, 40, 200) voc_index_offset, learning_time_offset_hours, learning_time_gain_hours, \ gating_max_duration_minutes, std_initial, g...
67,596
def get_most_common_elements(iterator): """Returns a generator containing a descending list of most common elements.""" if not isinstance(iterator, list): raise TypeError("iterator must be a list.") grouped = [(key, len(list(group))) for key, group in groupby(sorted(iterator))] return sorted(gr...
67,597
def build_starlette_request(scope, serialized_body: bytes): """Build and return a Starlette Request from ASGI payload. This function is intended to be used immediately before task invocation happens. """ # Simulates receiving HTTP body from TCP socket. In reality, the body has # already been ...
67,598
def expand_environment_variables(config): """Expand environment variables in a nested config dictionary This function will recursively search through any nested dictionaries and/or lists. Parameters ---------- config : dict, iterable, or str Input object to search for environment varia...
67,599