content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def format_sbatch_options(**sbatch_options): """Format sbatch options""" options = [] for k, v in sbatch_options.items(): val = "" if v is not None: val = f"={v}" options.append(f"--{k}{val}") return options
ac2db5d485a4cad15260b29cff9eda1fa4d0a647
671,267
def overlap(onset, frame, crds_tree, radius): """ Compute the overlap with a reference configuration defined in a CoordinatesTree. Args: onset: Initial frame, this is only used to get the frame index frame: The current configuration crds_tree: A CoordinatesTree of the reference conf...
8bf5380bcec14b238181ee9c74c05b739b59ad7a
671,268
def bytes2NativeString(x, encoding='utf-8'): """ Convert C{bytes} to a native C{str}. On Python 3 and higher, str and bytes are not equivalent. In this case, decode the bytes, and return a native string. On Python 2 and lower, str and bytes are equivalent. In this case, just just ret...
158b56d0aef3c71921e1106ed74d1bfde33c79c3
671,269
import requests def exec_request(url, timeout): """Executes request given in url and returns a dictionary with content""" data = requests.get(url, timeout=timeout) data.raise_for_status() # Raise in case of failed status return data.json()
63522420fe36e0e38c41c42b43a65208354bee1e
671,270
def is_tachycardic(hr, age): """Evaluates if posted heart rate is tachycardic Method curated by Braden Garrison Tachycardia is defined as a heart rate that is above normal resting rate. Specific tachycardic values are dependent upon patient age. More info about tachycardia and its diagnosis can be...
3acde139d26ac6a1f59fc59e3abc9f82de51accd
671,272
def api_config(): """Returns basic Cachet API configuration.""" return { 'url': "https://dummy.tld/api/v1", 'token': 'aaaaaaaaaaaaaaaaaaaa', }
d53766d707aa0a3d0d22fe0e1557923f8c4fe588
671,273
def _select_bins(x, idx): """ Performs gather to select the bin in the correct way on batched inputs """ idx = idx.clamp(min=0, max=x.size(-1) - 1) """ Broadcast dimensions of idx over x idx ~ (batch_dims, input_dim, 1) x ~ (context_batch_dims, input_dim, count_bins) Note that by co...
3c16f1d532930c8e18a7eed16cd06b9a5c98670e
671,274
import argparse def parse_args(): """Parses command-line arguments.""" parser = argparse.ArgumentParser( description="""A histogram-based TVLA described in "Fast Leakage Assessment" by O. Reparaz, B. Gierlichs and I. Verbauwhede (https://eprint.iacr.org/2017/624.pdf).""" ) parser.add_...
f5873c6a5e90a5a950272e87487cf9f0add1516c
671,275
def Compare(token1, token2): """Compares two tokens and determines their relative order. Args: token1: The first token to compare. token2: The second token to compare. Returns: A negative integer, zero, or a positive integer as the first token is before, equal, or after the second ...
fee9db18382d62faf0748cecfe1fad1f8124caee
671,276
def _get_inner_type(typestr): """ Given a str like 'org.apache...ReversedType(LongType)', return just 'LongType' """ first_paren = typestr.find('(') return typestr[first_paren + 1:-1]
abe352046f82f9b78f625a34791878276e28fb03
671,277
import functools import torch def accuracy_wrapper(func): """ Wraps accuracy funcs so that they behave like the other funcs """ @functools.wraps(func) def wrapped_func(weights, *args, **kwargs): # remove features new_weights = torch.sum(weights, -1) ret = func(new_weights, *args, *...
013111ac3614a86a3eaa835369d96cca25bb0742
671,278
def link(text: str, url: str) -> str: """Turns the given text into a link using <a> tags. :param text: The text for the link :param url: The url for the link """ return f'<a href="{url}">{text}</a>'
4bebfd4b7311b5dcc1a0717f36210bff96c847ab
671,279
def convert_string_to_value(value: str): """convert a string to value with the most appropriate type""" if value.lower() == "true": return True if value.lower() == "false": return False if value == "null": return None try: return eval(value) except: # noqa E722 ...
66a2b19eec6dcdae342b82e6e60438ee41027f25
671,280
def set_fba_name(source, year): """ Generate name of FBA used when saving parquet :param source: str, source :param year: str, year :return: str, name of parquet """ return source if year is None else f'{source}_{year}'
a7c5c484de1badad53c7cdb5ba6afb9bb81ec524
671,281
from optparse import OptionParser def parse_options(): """Process command line arguments""" usage = r"""%prog [options] <voxel_file>""" p = OptionParser(usage=usage) p.add_option('-o', '--output', action='store', dest='output', default='plot', help='Path to output SILO or VTK file.') p.add_opt...
4137981667d240ee66be610b509557c1cd03674f
671,282
def aramaic_turoyo_input_normal(field, text): """ Prepare a string from one of the query fields for subsequent processing: replace common shortcuts with valid characters of Turoyo (Neo-Aramaic). """ if field not in ('wf', 'lex', 'root'): return text text = text.replace('\'', 'ʕ') ...
6e89e73697510adae0213d1052cfe9844fe87a4c
671,283
import optparse def build_cli_parser() -> optparse.OptionParser: """ Generate OptionParser to handle command line switches :return: optparse.OptionParser """ usage = "usage: %prog [options]" desc = "Encode, using percent encoding, a Carbon Black query" cmd_parser = optparse.OptionParser(...
220109d9ae816d8f8144abdf29631e24f4a587e7
671,284
def Dictionary_to_XmlTupleString(python_dictionary): """transforms a python dictionary into a xml line in the form <Tuple key1="value1" key2="value2"..keyN="valueN" />""" prefix="<Tuple " postfix=" />" inner="" xml_out="" for key,value in python_dictionary.items(): inner=inner+'{0}="...
fe6a52b10dccc4e836bb12ec1c5b26017d075dcf
671,285
def remove_fields_duplicated(bids_fields): """Remove duplicated fields in a list. Args: bids_fields: List of fields Returns: list """ seen = set() seen_add = seen.add return [x for x in bids_fields if not (x in seen or seen_add(x))]
ad2571310762370805fe5ee42840a0f685ae7f14
671,286
def get_image_modality(image_modality): """Change image_modality (string) to rgb (bool), flow (bool) and audio (bool) for efficiency""" if image_modality.lower() == "all": rgb = flow = audio = True elif image_modality.lower() == "joint": rgb = flow = True audio = False elif imag...
4c8485c67c2c568c473c6bfbf36b9d732a2fdbd2
671,287
from typing import Dict from typing import Any def post_has_code(answer: Dict[str, Any]) -> bool: """Quick string check to avoid expensive parse""" return "<pre><code" in answer["body"] and "</code>" in answer["body"]
bc940ec27713a357c0146746786150353f58795d
671,288
import uuid def get_role_data(lr_pwd): """This function returns the role data""" data = { "rolcanlogin": "true", "rolconnlimit": -1, "rolcreaterole": "true", "rolinherit": "true", "rolmembership": [], "rolname": "test_role_%s" % str(uuid.uuid4())[1:8], "...
a90d82e8748ae1fbe525c029093b7abdc4ee5376
671,289
def repack_blockheader(dic): """ Repack blockheader dic bit flag parameters into status and mode. """ dic["status"] = (dic["S_DATA"] * 0x1 + dic["S_SPEC"] * 0x2 + dic["S_32"] * 0x4 + dic["S_FLOAT"] * 0x8 + dic["S_COMPLEX"] * 0x10 + dic["S_HYPERCOMPLEX"] * 0x20 ...
14174eaa346da8bcc20d76b07275a062a8d704cd
671,290
def atk_dataset_names(): """Returns list of datasets used by Fan, Yanbo, et al. "Learning with average top-k loss." Advances in Neural Information Processing Systems. 2017. """ return [ "monk3", "phoneme", "madelon", "spambase", "titanic", "australian"...
a9848840960ea9fbbe43e4fb07008f321be2566d
671,291
def gensim_top_k_similar(model, row, field_name, k): """ Returns the top k similar word vectors from a word embedding model. Args ---- model (gensim.models): Gensim word embedding model. row (pandas.Dataframe): Row extracted from a dataframe. field_name (str): Name of dataframe col...
42da539f47c1c17a5cca709004480236da0be872
671,292
def get_scan_resource_label(system_type: str) -> str: """ Given a system type, returns the label to use in scan output """ resource_label_map = { "redshift_cluster": "Redshift Cluster", "rds_instance": "RDS Instance", "rds_cluster": "RDS Cluster", } resource_label = resou...
8bb47f7b90d653f726a0e410786fa2d5876accbf
671,293
import os def Makedirs(path): """ A wrapper around os.makedirs() which will not throw an exception if the directory already exists. @param path: The directory path to attempt to create. @type path: C{str} @raise OSError: for any errors the underlying implementation of C{os.makedirs()} w...
97e44d3d9f37c309dcbde17d9d95714b20a12cd9
671,296
def replaceValue(mapping, old, new, strategy=None): """ Replace old values with new ones following dict strategy. The parameter strategy is None per default for inplace operation. A copy operation is injected via strateg values like copy.copy or copy.deepcopy Note: A dict is returned regardles...
750067aa862b5c0da0e121240a548d3c3b3b14ed
671,297
def object_rule_func(selections: dict, selection: str) -> dict: """ Choose 4 objects Per choice If hat != None and we choose Gash OR we choose an object that conflicts with an already chosen object OR we choose an object that's already been chosen ignore the choic...
5bf41ce547d22ed4687b5cf09020ef26dc7a3a53
671,299
def flipud(arr): """Flip an image-like array vertically. dtype support:: * ``uint8``: yes; fully tested * ``uint16``: yes; fully tested * ``uint32``: yes; fully tested * ``uint64``: yes; fully tested * ``int8``: yes; fully tested * ``int16``: yes; fully tested ...
4306dccf4e5d5310206c05f61bdad26e7db6c62c
671,300
import os def directoriesOnly(aList): """directoriesOnly() takes a list of items from a directory and purges anything from the list that is not a directory. """ bList = [] for i in aList: if os.path.isdir(i): bList.append(i) return bList
05224f738df4851ab0d2717a884100f0e03bcf4f
671,301
def isIn( obj, container ): """ Returns a boolean whether or not 'obj' is present in 'container'. """ return obj in container
e0da69589466c30b6fc9865352fdd87c2733ea67
671,302
import requests import io def import_legacy_files(file_link): """Download file from legacy.""" # needed to ignore the migrator in the legacy statistics download_request_headers = {"User-Agent": "CDS-ILS Migrator"} file_response = requests.get( file_link, stream=True, headers=download_request_...
edad97a01c59c6b57ddd0d2b788cf3631933d539
671,303
def merge_data_column(ONP_csv): """ Function to merge 'data channel' column into one column. """ DataChannelMerge = ONP_csv[ [ " data_channel_is_lifestyle", " data_channel_is_entertainment", " data_channel_is_bus", " data_channel_is_socmed", ...
a4f211fb454b37696ac3c63f06823664c31f95cf
671,305
def clark_equation(l, emax, kd): """Clark equation for receptor-response. The Clark equation corresponds to single-state receptor activation model with a linear effect response: L + R <--kd--> LR* ---> Effect, such that Effect is directly proportional to the receptor occupation LR*. Note th...
abc9099dca3b32b18e7d219b57124b0a6c0a7ee9
671,306
def MjdToDate(mjd, year, month, day): """ mar abr 9 21:41:49 COT 2013 >>> import gpsdate >>> mjd = gpsdate.GpsToMjd(1735, 81769) >>> gpsdate.MjdToDate(mjd, 1980, 1, 6) (2013, 4, 7) >>> """ J = mjd + 2400001 + 68569; C = 4 * J / 146097; J = J - (1460...
0ba0591d1891a1a70a2277f3f2ef899e53bac39d
671,307
import hashlib def wep_make_gravatar_img(email: str) -> str: """ Returns a string pointing to a Gravatar image based on an email address. Args: email: the email associated with a given Gravatar image Returns: a link of the form <https://www.gravatar.com/avatar/:hash>, where `...
8a2fb564850351ecbf6a47c81293bcc5181d7731
671,308
import numpy def ncube_points(*xyz): """Given the end points of an n-cube aligned with the coordinate axes, this returns the corner points of the cube in the correct data structure. """ return numpy.moveaxis(numpy.array(numpy.meshgrid(*xyz, indexing="ij")), 0, -1)
df62f4d1e1c086f73d05bb3feae338d18b05bbb4
671,309
def nest_toc_tokens(toc_list): """Given an unsorted list with errors and skips, return a nested one. [{'level': 1}, {'level': 2}] => [{'level': 1, 'children': [{'level': 2, 'children': []}]}] A wrong list is also converted: [{'level': 2}, {'level': 1}] => [{'level': 2, 'children': []}, ...
1ec90a82b29cd2405e5859e605889b2433ffe52c
671,310
def config_section_data(): """Produce the default configuration section for app.config, when called by `resilient-circuits config [-c|-u]` """ config_data = u"""[fn_floss] # Floss Function # Use the following floss_options variable to specify the commandline options to be used by # the floss package...
e08a00ae05e14ad2bd2a709ff6a0bf35f7e7d0cb
671,311
def info_method_tester(d): """Test info() method.""" d_info = d.info() assert isinstance(d_info, str) assert len(d_info) > 0 return d_info
3a8e8ddeeed3795b1f39e771a906c6e7cfcbd7ae
671,312
def total_travel_distance(journey): """ Return the total travel distance of your PyCon journey in kilometers rounded to one decimal. """ return round(sum(trip.distance for trip in journey),1) pass
add1401e8b718054570a410d3874a08abe7e3b4b
671,313
from numpy import copy, asarray, exp def qsat(t,p): """ usage: es = qsat(t,p) Returns saturation vapor pressure es (mb) given t(C) and p(mb). After Buck, 1981: J.Appl.Meteor., 20, 1527-1532 Returns ndarray float for any numeric object input. """ t2 = copy(asarray(t, dtype=float)) # con...
287fe02b6c7d72b883ab893be6b148a07f447b7b
671,314
import os def exists(path): """ Check for a file or folder existence :param str path: File or folder (folder must end with slash or backslash). :returns: True if successed :rtype: bool example:: success = xbmcvfs.exists(path) """ return os.path.exists(path)
db55206aef5ac7397651c01a398953b3c8a4baf7
671,315
def _get_prometheus_base_config(): """ Generate a basic configuration dictionary for prometheus :return: dictionary """ conf = dict() conf['global'] = {'evaluation_interval': '5s', 'scrape_interval': '5s'} conf['scrape_configs'] = [] return conf
7bd0999bdca2c6772694bd229800adf294ffcbc9
671,316
def selection_sort(L): """ Implementation of a selection sort algorithm Complexity: O(n^2) :param L: List-object """ index = 0 while index != len(L): for i in range(index, len(L)): if L[i] < L[index]: L[index], L[i] = L[i], L[index] index += 1 ...
3cddaf75ccef2dd70e0005494d360d7679a7ce44
671,317
def _get_opt_provider(target, provider): """Returns the given provider on target, if present.""" return target[provider] if provider in target else None
e310f22e5e73ec80640ff0b61e5dcbe55278d2ab
671,318
def unique_tenderers(tender): """leave only unique tenderers as required by standard""" bids = tender.get('bids') if not bids: return tenderers = [tenderer for bid in bids for tenderer in bid.get('tenderers', [])] return {t['identifier']['id']: t for t in tenderers}.values() if tenderers els...
0f4476f6e84b1a4a0b756fc07b1526681f6b1146
671,319
def _diversity(population): """Calculates the diversity of a population. Args: population (list): The population to evaluate. Returns: The percentage of individuals for which no exact duplicate exists elsewhere in the population. """ population = [str(p) for p in population] fr...
3726faa018775ba0e6c3778f12ce931f45727bc1
671,320
import itertools def find_common_target_relation_combination_in_relations_by_parameter_name(relations_by_parameter_name): """ find the common targets in relations list. [relation, [relation]] will only be called with multiple relations by parameter name """ selected_relations = False def has...
43e22bdebee1711c6b8648ca2e49b6f0a8eb0d7b
671,321
def luminance_newhall1943(V, **kwargs): """ Returns the *luminance* :math:`R_Y` of given *Munsell* value :math:`V` using *Sidney M. Newhall, Dorothy Nickerson, and Deane B. Judd (1943)* method. Parameters ---------- V : numeric *Munsell* value :math:`V`. \*\*kwargs : \*\*, optio...
3806a6957aaca700f3f3477eaa33746b37c33249
671,322
def left_tack(*, alpha=None, omega): """Define monadic same and dyadic left. Monadic case: ⊣ 3 3 Dyadic case: 1 2 3 ⊣ 4 5 6 1 2 3 """ return alpha if alpha is not None else omega
e55eed58d8ffafd0a1f5cba985c9cf4b22abefb9
671,324
import collections import json def load_queries(path: str): """ Loads queries into a dictionary of query_id -> (query, question) """ queries = collections.OrderedDict() with open(path) as f: raw_json = f.read() parsed_json = json.loads(raw_json) for topic in parsed_json: ...
da76fe53f1f55d38ed09ad608b50f2183d5322c3
671,325
import base64 import requests import json def client_login(url, module_id, password): """ This method gets a token for a registered user """ login_string = module_id + ':' + password cred = bytes(login_string, 'utf-8') encoded_cred = base64.b64encode(cred).decode("utf-8") header = {"Author...
a997c6f3d8c2a3f0133073e78830f509e88d4591
671,326
def format_and_check_update_part_request(request): """ parses the update request return dictionary Parameters: ------------ request: hpn0:[rev0:]column0:value0,hpn1:[rev0]:]column1:value1,[...] or list hpnN: hera part number, first entry must have one, if absent propagate first ...
37795123a7d2e7e75fff943be4e5ab4ae6fd93b8
671,327
import os import sys import re def message(sentence, argument, type_m=None): """ Return a message in the correct format. :param sentence: (string) the message we want to return. :param argument: (Argument object) a Lazyparser argument. :param type_m: (string or None) the type of the message to di...
91b673f51a7d343f87f8bb36d6df732b7cc9dc49
671,328
def mel_sampling( audio, frame_duration_ms = 1200, overlap_ms = 200, sample_rate = 16000 ): """ Generates audio frames from audio. This is for melspectrogram generative model. Takes the desired frame duration in milliseconds, the audio, and the sample rate. Parameters ---------- audio: np.a...
72cb22ba976d6f91a9b69953d8bedcd33c4ab294
671,329
def examine_neighbors(g, x, y): """ Examine the 8 neighbors of the cell at coordinates "x" by "y", and return the number of neighbor cells which are closed. """ c = 0 w, h = g.size() if x - 1 >= 0: if g.get(x - 1, y): c += 1 if x + 1 < w: if g.get(x + 1, y):...
1ec8701aef08d8bf0af4f432028ba857aaff7a7c
671,330
import json import logging def get_points_from_geojson(s, fname): """ Parses a typical GeoJSON file containing one or more Polygon or MultiPolygon features. These JSON files are the preferred way to serialize QuPath annotations, for example. See https://qupath.readthedocs.io/en/latest/docs/scripting/o...
ab6a93ccc11faf579905e6cb6d0a3789b7e5f026
671,331
def sorted_dicts(sparkdf, start_column, end_column, var): """ Utility function to create sorted dicts for pool function. """ pandasdf = sparkdf.toPandas() starts_dict = dict(zip(pandasdf[start_column], pandasdf[var])) ends_dict = dict(zip(pandasdf[end_column], pandasdf[var])) starts_sor...
e549e11b09b44f4ca34797d65961123fdb184b0c
671,332
import torch def sampleFromCdomain(params,xi,device=torch.device("cpu")): """ """ # x=2*np.random.rand(n)-1 # y=2*np.random.rand(n)-1 # samplefromdomain=np.stack((x,y),axis=-1) # xo=0.05*np.random.rand(n)-0.025 # yo=0.05*np.random.rand(n)-0.025 # samplefromdomain2=np.stack((xo,yo),axi...
909a6c746f11ceb49e604818fcf2ce604585e010
671,333
def keyAffinityMatch(keyAffinity, Users=[], identityOrder=[], keyAffinityOfUsers=[]): """ """ identityOrder_Affinity = [] identity_rank = [] not_found = [] found = 0 for index in range(0,len(Users)): if (int(keyAffinity) == int(keyAffinityOfUsers[index])): identityOrde...
4dda04a8939eb493f2a516ce738c3060b558a3a1
671,334
def reverse(s): """Write a function that takes a string as a parameter and returns a new string that is the reverse of the old string.""" if len(s) == 1: return s return reverse(s[1:]) + s[0]
b237f98bedcc9ccc635626764f393ed70bf031bd
671,335
def determine_nonschema_privileges_for_schema(role, objkind, schema, dbcontext): """ Determine all non-schema privileges granted to a given role for all objects of objkind in the specified schema. Results will be returned as two sets: objects granted write access and objects granted read access. We...
aa7a0583dbf135b45448ffb663c548a40e47e934
671,337
def parse_line(line): """ A line is of the form #id @ x,y: widthxheight """ _id, _, tail = line.partition("@") coords, _, dims = tail.partition(":") x, y = list(map(int, coords.split(","))) width, height = list(map(int, dims.split("x"))) return (_id, x, y, width, height)
cb552dabc978f3c3c6ebb2c0eb3ab3f4a970dfb1
671,338
def number_freq_plots(runs, map_label): """Calculate the number of plots needed for allfreq plots and frequency histogram plots """ num_cpu_plots = len(map_label) has_devfreq_data = False for run in runs: if len(run.devfreq_in_power.data_frame) > 0: has_devfreq_data = True ...
0e7253fb20fcb790019b3e409222f5d26126ae48
671,339
import os import sys def get_image_type(filename: str): """Check if it is an IMG3 or IMG4 format.""" if not os.path.isfile(filename): print("[e] %s : file not found" % filename) sys.exit(-1) with open(filename, "rb") as file: magic = file.read(4) if magic == b"3gmI": ...
6bd6fdfe9fd15993f769ce0d4b54871f1a4f7060
671,340
def input_int(text, min=0, max=1): """ for setup and statistic repeats """ while True: try: x = input(text) if x != '': x = int(x) if x > max: x = max print(f'Input set to {max}') elif x <...
ab1d94e7aef3b9acf7f07505e37edec6f02343e0
671,342
import json def is_valid_json(invalid_json): """ Is the given string valid JSON? """ got_exception = True try: json.loads(invalid_json) got_exception = False except Exception as e: pass return got_exception is False
fe74ce5dc2ede636c640627e5a79618ee2b789dc
671,343
def lp_norm(prediction, target, p=2.0): """Function to calculate LP-Norm loss term. Args: prediction (torch.Tensor): target (torch.Tensor): p (float, optional): Order of norm. Defaults to 2.0. Returns: torch.Tensor: """ return (prediction - target).abs().pow(p).s...
468f912decb6ef09ec6239f7201bdd3133b15e92
671,344
def jwt_response_payload_handler(token, user): """ 自定义jwt认证成功返回数据 """ return { 'token': token, 'id': user.id, 'username': user.username }
5217b27ed8c0bca4a03a84a8f53e66f4adc13f65
671,345
def calcluate_value(env, gamma, values, s, a): """ V_pi(s) = sum ( Pass' * [ Rass' + gamma*V_pi(s') ] ) """ value = sum( [ env.p(next_s, s, a) * ( env.r(next_s, s, a) + gamma * values[next_s] ) for next_s in range(env.n_states) ] ) ...
fed4c28f8d851e49b3db2ff9ef1ee931512dc76e
671,347
import numpy def epsilon_lte(a, b): """a <= b, using floating point epsilon value.""" float_epsilon = numpy.finfo(numpy.float32).eps return float_epsilon > a - b
398127dd88ac2b9e8fda2fa371f9880c17873ca5
671,348
def get_region(context): """ Return the AWS account region for the executing lambda function. Args: context: AWS lambda Context Object http://docs.aws.amazon.com/lambda/latest/dg/python-context-object.html Returns: str : AWS Account Region """ return str(context.invoked_functi...
220a63aef52d97ec8bd5bc6803b7a33803cdaf2f
671,349
import argparse def parse_arguments() -> argparse.Namespace: """Parse the arguments.""" parser = argparse.ArgumentParser(description="motchallenge to scalabel") parser.add_argument( "--input", "-i", help="path to MOTChallenge data (images + annotations).", ) parser.add_argu...
17bee511aafe65711f084703c5f0648e0132a765
671,350
def getAtomInteractionList(): """ storing label of interacting atoms """ labels = {} labels['acid'] = {'SER': ['OG'], 'THR': ['OG1'], 'CYS': ['SG'], 'TYR': ['OH'], 'LYS': ['NZ'], 'GLN': ['H...
c424fbb33c902e1535843cc5e04b421326b83641
671,351
import glob import os def get_files_list(folder_path, filter_term, sort): """Return the list of files, applying filter.""" query = folder_path + filter_term """files_list = glob.glob(query)""" if sort == "name": files_list = sorted(glob.glob(query)) elif sort == "size": files_list ...
179e0c875c77af5e9d7ae13a235066e90f239db1
671,352
def find_min_pos(input_list): """Function to find index with minimum value.""" length = len(input_list) if length == 0: return -1 curr_min = input_list[0] curr_min_index = 0 for j in range(1, length): if curr_min > input_list[j]: curr_min = input_list[j] curr_min_index = j return cu...
d2d72b0fdf6ada026f7675f37ff7223384ec076f
671,353
def rotations(n): """Returns rotations of digits of n""" if n < 10: return [n] digits = [d for d in str(n)] rotations = [] for i in range(len(digits)): rotated = digits[i:] + digits[:i] rotations.append(int("".join(rotated))) return rotations
6357143403458665dc0743479fc0f75e278e163c
671,354
import requests import time def get_limited(url, params = None, auth = None): """ Get a GitHub API response, keeping in mind that we may be rate-limited by the abuse system """ number_of_retries = 0 resp = requests.get(url, params = params, auth=auth) while resp.status_code == 403 and number_o...
93674a23a108c129f692a5f83177d6f3962614d5
671,355
import collections def index_rules_by_namespace(rules): """ compute the rules that fit into each namespace found within the given rules. for example, given: - c2/shell :: create reverse shell - c2/file-transfer :: download and write a file return the index: c2/shell: [create reve...
f812e632ad35996f0245187c988d4f1ae18c42fb
671,356
def which_argument(arguments, options): """Return which of the given constant options was specified in the given argument source parsed by docopt.""" for check in options: if arguments[check]: return check
7e0e9983bd5c510a0cb1d01f3e9a31b32a01b7f3
671,357
def each_n(iterable, n): """Iterate iterable with n-tuples.""" a = iter(iterable) return zip(*[a] * n)
620e0656d4b00bb32cc981f2ef1de96dd8cf7059
671,358
import copy def _format_label(label_txt, values, date, date_format=None): """ Replaces '{date}' and other placeholders in label_txt by formatting with date string and values given by -v key=value """ values = copy.deepcopy(values) if 'date' not in values: values['date'] = date.strftim...
75ce6bfe453e59b831d6ab18b927926ec6ece0ab
671,359
def construct_constraint(year, index): """ This function is a convenience function that returns a valid demand constraint for one year. The wrapper function construct_constraint is needed because we need a reference to year in the wrapped meet_demand function in model.buy[year, supplier, block] and mode...
77dbbf75f23bbc2494fdb0a0b465c77fe2cd86de
671,360
def tagvalue_analysis(genome, key, pivot_var=['elem','version'], vrank=1): """Return a table that contains the number of unique elements for each tag value, element type and version, for a given tag key INPUT: genome = pandas DataFrame with OSM element tag history, key = tag key that will be focused o...
d00fc4cd0431b7cb75ed8e2ec616fd7280a448ce
671,361
def parse(file_name): """Parse the data file into a list of int""" with open(file_name, "r") as f: return [int(x) for x in f.readline().split(",")]
c8781f2a75f7d1913f2cbe29a66ef4af3df1ce76
671,362
from typing import Optional def PathFromLabel(label: str) -> Optional[str]: """Create a workspace relative path from a bazel label. Args: A bazel label, e.g. "//foo:bar.cc". Returns: A workspace-relative path, e.g. "foo/bar.cc". If the label does not resolve to a path, returns None. """ # First, ...
679c65b7bbd46ed92094339ce57555f346d3a3a8
671,363
def multiplicative_inverse(a, b): # Euclid's extended algorithm for finding the multiplicative inverse of two numbers """Returns a tuple (r, i, j) such that r = gcd(a, b) = ia + jb """ # r = gcd(a,b) i = multiplicitive inverse of a mod b # or j = multiplicitive inverse of b mod a # Neg...
883eaf8a28f2b967f167908539939369059018ed
671,364
import typing import hashlib def get_hashed_percentage_for_object_ids( object_ids: typing.Iterable[int], iterations: int = 1 ) -> float: """ Given a list of object ids, get a floating point number between 0 and 1 based on the hash of those ids. This should give the same value every time for any li...
910fd689e79392f4bf9a7da1e6025a507a627d0f
671,365
def check_poly_types(df): """ Special checks to ensure the Poly_Types field adheres to what we want apart from domain/schema checks. Args: df: Pandas dataframe of feature class table containing the field 'Poly_Type' Returns: errors: list of error message strings to print to the c...
22682646404d350271cffbb50134fb6c63b9dcba
671,366
def get_html_click(): """Builder for this format. Returns: Json containing the creative data """ return """<!DOCTYPE HTML><html lang="en-us"> <head> <meta name="ad.size" content="width=[[width]],height=[[expandedHeight]]"> <script> var clickTag = "[[clicktag_url]]"; var tpl = { expanded: false }; tpl....
291dae92576155a93547b18938557e8ab61a40c3
671,367
import platform def get_os(): """ The function will output the client platform """ return platform.system()
d9f86131e61acef869c781d843e58b78db8a174c
671,368
def _field_index(header, field_names, index): """Determine a field index. If the index passed is already a valid index, that index is returned. Otherwise, the header is searched for a field name matching any of the passed field names, and the index of the first one found is returned. If no mat...
6a8797d5972fec4cdc0cf5030397a90545a66177
671,369
import torch def _sigmoid_then_2d(x): """Transform 1-dim logits to valid y_proba Sigmoid is applied to x to transform it to probabilities. Then concatenate the probabilities with 1 - these probabilities to return a correctly formed ``y_proba``. This is required for sklearn, which expects probabil...
5aced9f0d20e4167cc84f818c2e4b9274cb2ab49
671,370
import re def parse_combined_float_list(float_string_list): """Parses a list of strings, where each element of the list is a single string which is a list of floats to be parsed. Assumes the data delimiter is whitespace or comma, and removes any white space at the beginning and end of the string a...
4e985cc90dc35fc8adf4a04eac8a9117c07653a8
671,371
def nested_get(nested_dict, keys): """ :param nested_dict: dictionary :param keys: list of keys :return: return back object """ for key in keys: if isinstance(nested_dict, list): nested_dict = nested_dict[0][key] else: nested_dict = nested_dict[key] re...
bf68819bdc1da8284ff944a4f909730e9ed2a26d
671,372
def create_value_dict(data_agg, super_star_avg_prices_2_agents, super_star_avg_prices_3_agents ): """ A function to create a comprehensive dictionary with all values that we need to create the plot. Args: data_agg (DataFrame): Da...
fc7797ff939f25214c53d4fe359fe488a45bf233
671,373
def get_referenced_filenames(license_matches): """ Return a list of unique referenced filenames found in the rules of a list of ``license_matches`` """ unique_filenames = [] for license_match in license_matches: for filename in license_match['matched_rule']['referenced_filenames']: ...
4340cc1bf9c00c206032743e98a86ececb42e2ff
671,374
import re def snippets_to_script(snippet_list): """Create a script out of the snippet list such that it can be invokable via chroot's -c command""" replace_dict = {r'\$': r'\\$', r'\`': r'\\`'} final_list = [] for snippet in snippet_list: # replace the escaped character...
15b5f43604ee64aec91f3ad622d28fcc306c99d2
671,375