content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import six def scale_result(result, scaler): """Return scaled result. Args: result (dict): Result. scaler (number): Factor by which results need to be scaled. Returns: dict: Scaled result. """ scaled_result = {} for key, val in six.iteritems(result): scaled_r...
d7a8001b617d516d71a2526207937bf31351737e
658,601
import re def process_node(group, cur_type, remove=None): """Remove portions of the code based on the config.""" if remove is None or cur_type not in remove: return group result = [] remove_strs = remove[cur_type] for line in group: for remove_str in remove_strs: line...
ab51741b27e0d009c5bf434497065748de9c2790
658,602
def cross(o, a, b): """Cross-product for vectors o-a and o-b """ xo, yo = o xa, ya = a xb, yb = b return (xa - xo)*(yb - yo) - (ya - yo)*(xb - xo)
188f06c8f034eb6017bfc8c619d11d1f97451e41
658,603
import re def findall(string, substring): """ Find the index of all occurences of a substring in a string. @arg string: @type string: string @arg substring: @type substring: string @returns: List of indices. @rtype: list[int] """ occurences = [] for i in re.finditer(subs...
b6a60ec42813d7018a64078fb94802a10858ec1d
658,604
from typing import Union def get_annotation_class(annotation: type) -> type: """Helper method to retrieve type annotation. Args: annotation (type): Type hint """ # typing.Optional if getattr(annotation, "__origin__", None) is Union: return annotation.__args__[0] else: ...
3946315b7e45baacf1f5a907406bfeb5087bcc54
658,605
def instructions(scr): """ Think about something really clever for this part as this is very important """ scr.clear() scr.draw_text(text = "You will now be shown a few examples of " + "the tasks that you are supposed to perform.\n\n They will be " + "followed by the real experiments.\n"+ "\n\n ...
58a8c6deac1298553186797a9fce5aa786761078
658,606
import functools def partialclass(cls, *args, **kwargs): """ Partially initialize a class by binding its `__init__` method with the given input arguments. The returned class can be initialized by passing the remaining arguments required for initialization. Parameters ---------- cls : type ...
1e9140f67f0e3c896a43c1ee9546c610b1254f6c
658,607
def set_kwargs_from_dflt(passed: dict, dflt: dict) -> dict: """Updates ++passed++ dictionary to add any missing keys and assign corresponding default values, with missing keys and default values as defined by ++dflt++""" for key, val in dflt.items(): passed.setdefault(key, val) return pass...
3c0555c3276a20adbbc08f1a398605c6e6d37bd9
658,608
import math def ph_from_hydroxide(concentration): """Returns the pH from the hydroxide ion concentration.""" return 14 + math.log(concentration)
8e92bc5f438ded444c78ec988d2e4e9fe78114fb
658,609
def dont_linkify_urls(attrs, new=False): """Prevent file extensions to convert to links. This is a callback function used by bleach.linkify(). Prevent strings ending with substrings in `file_exts` to be converted to links unless it starts with http or https. """ file_exts = ('.py', '.md', '.sh'...
e0ab3b0a004a2f6a3adca9ca24f0c33c6fc34d3a
658,610
import itertools import functools def dict_combinations(*dict_list_lists): """Given a list of lists of dictionaries return the list of all possible dictionaries resulting from the unions of sampling a dictionary from each list. Basically given a list of lists of dictionaries, returns all the dict...
d8e6f2df24b91d142023ee42b315e388ee9bcfb2
658,611
def check_if_odd(sum: int = 36) -> int: """ Check if the last digit in the sum is even or odd. If even return 0. If odd then floor division by 10 is used to remove the last number. Process continues until sum becomes 0 because no more numbers. >>> check_if_odd(36) 0 >>> check_if_odd(33) ...
1157a64fe94fd253224a5564ff0dd5c900b845a7
658,613
def OUTPUT(out): """Get dictionary serialization for an output object. Parameters ---------- out: vizier.viztrail.module.output.OutputObject Object in module output stream Returns ------- dict """ return {'type': out.type, 'value': out.value}
d3e452c3c45bf848a71e5c6dc158fd0318469b7d
658,614
def test_model(model, data_list, apply_mcca=False): """produce the new features by using the trained model outdim_size: dimension of new features apply_linear_cca: if to apply linear CCA on the new features # Returns new features packed like """ # the data_list is arranged thus:...
9cd819f698a2c7975e875cad82231f7030fa2843
658,616
from typing import Dict from typing import Any import json def load_model_data(filename: str) -> Dict[Any, Any]: """ Loads some model_data that was generated by the model. :param filename: The name of the model_data file to open. :return: The JSON model_data, loaded as a `dict`. ...
9dfc1b79af9bc5c074d13b24c649b320f909b132
658,617
from threading import Thread from functools import wraps def run_async_fun(func): """ run_async(func) function decorator, intended to make "func" run in a separate thread (asynchronously). Returns the created Thread object E.g.: @run_async def task1(): do_something @run_async def task...
171158d9f8f45aad33f97532f2e74e5486d73dd1
658,618
import json def generate_json_field(self, row, json_str): """ Generates the json for the given row. The json is formatted to 1 line for easier search when generating the django models. """ data = json.loads(str(json_str)) if row: data['fields'].append({ 'f...
1dab0e7bae1df295d3c4bd677e5cab55b05b2fb4
658,619
def _leisure_test(norw): """Tests if a node or way is a leisure place""" return 'leisure' in norw.tags
81ab60140f7146a0777abbec482e9fc73597b652
658,620
def combine(*args): """Wait for an arbitrary list of futures and return them as a list""" return list(args)
785aad6ffc3dfdbb076aabd5fa5c3eb708d97c37
658,621
def sanitize_properties(properties): """ Ensures we don't pass any invalid values (e.g. nulls) to hubspot_timestamp Args: properties (dict): the dict of properties to be sanitized Returns: dict: the sanitized dict """ return { key: value if valu...
3cb806e23a665258989e34369d3d343ade01349e
658,622
from typing import Any def log_response(response: Any) -> str: """ renders a python-requests response as json or as a string """ try: log_body = response.json() except ValueError: log_body = response.content[:40] return log_body
8bc2f4a6cbc48abd10af0942bafe8db957a4f39a
658,623
def _parse_conll_identifier( value: str, line: int, field: str, *, non_zero=False ) -> int: """Parse a CoNLL token identifier, raise the appropriate exception if it is invalid. Just propagate the exception if `value` does not parse to an integer. If `non_zero` is truthy, raise an exception if `va...
c5f1d186cbc07de931a412e314de22e4dfb46fe6
658,624
import os import json def _get_header(filepath, is_root_script, python_version): """To execute converted shellpy file we need to add a header to it. The header contains needed imports and required code :param filepath: A shellpy file that is being converted. It is needed to get modification time of it an...
cfa024ced18cf5252d24b8553d00bd597bea01c5
658,625
import argparse def parse_args(): """ Parse command line arguments. :return: """ parser = argparse.ArgumentParser("DLG") parser.add_argument("--use_gpu", type=bool, default=False, help="Whether to use GPU or not.") parser.add_argument("--batc...
cccd2cd58d7d0e82973fea44bc942bdef0263f34
658,626
def exploreSize(it): """Returns first element and length of array""" if isinstance(it, str): raise TypeError("Just here to terminate shape()") sentinel = object(); it = iter(it) o = next(it, sentinel); count = 1 if o is sentinel: return None, 0 try: while True: next(it); count += 1 e...
be002be818ec6f9841e5bb44e4dca2eabf5ee882
658,627
def _process_line(line): """Escape string literals and strip newline characters.""" if not isinstance(line, str): raise TypeError("Routine lines should be strings.") if line.endswith('\n'): line = line[:-1] return line
2368aeb49ae4cb70386332d6965273235a554604
658,628
def HasSeparator(line): """To tell if a separator ends in line""" if line[-1] == '\n': return True return False
7acc31565504a57949425c5dec6a1c189940d0f8
658,629
from functools import reduce import math def NevilleEvenRound( inxvals, inyvals, xeval ): """Implementation of Neville's algorithm for evaluating an nth order polynomial that goes through n+1 points (n+1 is the length of inpoints) at the point x. This implementation is modified first by the assumption that the pol...
4417c28459e973f1c60370c58821f07a0b7a059c
658,630
def backup_data(): """Backup data stored in Firestore.""" return NotImplementedError
ee1a4e1137167ef8b67379f20a89da0f6184ac22
658,631
def execHLTInstr(operand, acc): """Execute any halt instructions here (instruction.T_XX)""" print("executed HLT %d" % str(operand)) # DEFINE USER HLT INSTRUCTIONS HERE return acc
fca595b11310879d3bf36c9fe1e49a4bdadc69bd
658,632
def get_set_sizes(df): """ get sizes of training and test sets based on size of dataset. testing set: 10% of training set :return: training_set_size, testing_set_size """ data_set_size = len(df.index) training_set_size = data_set_size * 0.9 testing_set_size = data_set_size * 0.1 r...
e07495f651814e32743cecd42d23b9f7dd187a74
658,633
import argparse def parse_args(args): """ Parse all arguments """ parser = argparse.ArgumentParser( prog="vcf_to_ml_table", description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument('vcf', metavar='VCF', type=str, help='VCF files to tabulate') args ...
afbd49949dc30d519a67827881390974a4e18ea1
658,634
import logging def get_logger(name): """ Return a multiprocess safe logger. :param str name: Name of the logger. :return: A multiprocess safe logger. :rtype: :py:class:`logging.Logger`. """ return logging.getLogger(name)
a5143cc3c4929f8a9c889f055b3b01d8fed2865e
658,635
import re def ask_yes_no_question(question): """ Asks the user to answer the given question with yes or no. Yes, Y, No and N are accepted as valid responses (case insensitive). :param question: the question to be answered :type question: str :return: the user's answer :rtype: bool """ ...
a3a2e537e259afcbe032fba73e03036b3c281e90
658,636
def get_ajax_msg(msg, success): """ ajax提示信息 :param msg: str:msg :param success: str: :return: """ return success if msg is 'ok' else msg
abf72690e06f80a491249589e2b979d0a14a11ba
658,637
import inspect def get_redshift_methods(cosmology, allow_private=True, allow_z2=True): """Get redshift methods from a cosmology. Parameters ---------- cosmology : |Cosmology| class or instance Returns ------- set[str] """ methods = set() for n in dir(cosmology): try: ...
b1227d935acd7694e7bf948072acb7444b7ac38e
658,638
def calc_local_cohesion(word_pairs, sentences): """Calculates local cohesion by a probability score between 0 and 1. 1 indicates a fully local coherent text. Args: word_pairs (dict) - All word pairs of text sentences (Array) - List of all sentences Return: Float - Local coh...
0b184c02aa9c54bb0047849757c432a2863f7228
658,639
import torch def standard_roi_head__simple_test(ctx, self, x, proposals, img_metas, **kwargs): """Rewrite `simple_test` of `StandardRoIHead` for default backend. This function returns detection result as Tensor instead of numpy array. Args: ctx (ContextCall...
864333d4a0700df7be30915a46448e011b41e652
658,640
import requests def _wiki_request(**params): """ Make a request to the Wikipedia API using the given search parameters. Returns a parsed dict of the JSON response. """ api_url = "http://en.wikipedia.org/w/api.php" params['format'] = "json" params['action'] = "query" headers = { 'User-Agent': "wikipedia/0....
92378392e3898c96f4518d5803f1d3dc5dc1d76d
658,641
import re def strip_tags(text): """String tags for a better vocabulary.""" return re.sub('<[^<]+?>', '', text).strip()
687a1ed39e1265640ff33ea6bdeab7d2957af995
658,642
def automatically_create_accounts_for_new_users() -> bool: """When true, then a new account is automatically created when a new user tries to login""" return True
85445ff821178254ef1e133b04c08ed61cbb878e
658,643
def HTMLColorToRGB(colorstring): """ convert #RRGGBB to an (R, G, B) tuple """ colorstring = colorstring.strip() if colorstring[0] == '#': colorstring = colorstring[1:] if len(colorstring) != 6: raise ValueError, "input #%s is not in #RRGGBB format" % colorstring r, g, b = colorstring[:2], colorstring[2:4], colo...
baa81f68696164744419eb5e478ad9f1eea46783
658,644
import torch def choose_best(agg_vals,agg_locs,agg_modes,K): """ Choose the best. """ return agg_vals[0],agg_locs[0] agg_vals = torch.cat(agg_vals,dim=1) agg_locs = torch.cat(agg_locs,dim=3) agg_modes = torch.cat(agg_modes,dim=1) vals,locs,modes = [],[],[] nimages = agg_vals.shape...
dbb75bb21dd5af9bacdfa1a5838786cdac694ece
658,645
import os def get_coordinates_from(data_path): """Retorna a lista de coordenadas das arestas. Lê o arquivo passado como argumento e retorna as coordenadas de todas as arestas por meio de um array no formato [['x_1', 'y_1'], ['x_2', 'y_2'], ..., ['x_n', 'y_n']] onde o i-ésimo par da lista co...
1b34b7424aabd3941e0af529b9badb890d8661d9
658,646
def pad_sentence_batch(sentence_batch, pad_int): """ pad the batch sequence, make sure every batch has same sequence_length :param sentence_batch: :param pad_int: :return: """ max_sentence = max([len(sentence) for sentence in sentence_batch]) return [sentence + [pad_int] * (max_sentence ...
42eae2ca8bedcd4aa6f9be27ec1be5543e60aa5f
658,648
def calc_distance(mol, atom1, atom2): """ Calculates the distance between two atoms on a given molecule. Args: mol (RDKit Mol): The molecule containing the two atoms. atom1 (int): The index of the first atom on the molecule. atom2 (int): The index if the second atom on the molecule....
355a4e1ae29ef0a9425d4b9b5af731f454d4bbc9
658,649
def normalize_file_mode(selected): """ :param selected: :return: """ if selected in ['a', 'w']: pass elif selected == 'replace': selected = 'w' elif selected == 'append': selected = 'a' else: raise AssertionError('This should be impossible - but:\n' ...
c5fbec4d93ce9f162d77aec705b6681a548ca55a
658,650
def get_env_name_network_license_manager(): """Specifies the path to valid license file or address of a network license server""" return "MLM_LICENSE_FILE"
6f5af88aa17cccb4547658908dc60190e24a0c45
658,651
def check_inputs(station,year,doy,snr_type): """ inputs to Lomb Scargle and Rinex translation codes are checked for sensibility. Returns true or false to code can exit. Error messages sent to the screen author: kristine m. larson 2019sep22 """ exitSys = False if len(station) != 4: ...
65e1e57d73e425569b421bc3dee7f67179ce338e
658,652
import re import glob def get_ergowear_trial_files(ergowear_trial_path): """Find all files of an ergowear trial inside a directory. Args: ergowear_trial_path(str): path to the trial directory containing ergowear files. Returns: (list[str]): list with all ergowear trial paths ...
ff67f5b1e357c341cd6e74ffe4b52f1ee131ea4e
658,653
import pickle def load_data(in_file): """load data from file Parameters ---------- in_file: str input file path Returns ------- data: loaded data """ with open(in_file, 'rb') as f: data = pickle.load(f) return data
f6dec6b0a3eb8ed606d59223c64dd841e9369df8
658,655
def is_logged_in(session): """Return whether user is logged into session `session`""" return 'user' in session
cb167a756ba2324afce81fc285043efcd0369ae4
658,656
def addListsByValue(a, b): """ returns a new array containing the sums of the two array arguments (c[0] = a[0 + b[0], etc.) """ c = [] for x, y in zip(a, b): c.append(x + y) return c
16b47a5cdf2c7d91a0d788cb3684f2194384121d
658,657
import random def select_parent_roulette(population, scores): """ Select a parent using the roulette. """ fitness_acc = 0 fitness_sum = sum(scores) # if fitness sum is 0, just select a random parent if fitness_sum == 0: return random.choice(population) roulette = random.randrange(fi...
ce0299d7ae42a9e3673fb25f69ff6ae959163bc7
658,658
import re def get_names_list(string_list): """Get list of activity names""" values = re.split(r'[, \[ \]]', string_list) values = [each.strip("'") for each in values if each != ''] return values
548e0de780bf157c0bc3975c8c6fe12ecaf6d818
658,659
def get_wait_for_acknowledgement_of(response_modifier): """ Gets the `wait_for_acknowledgement` value of the given response modifier. Parameters ---------- wait_for_acknowledgement : `None`, ``ResponseModifier`` The respective response modifier if any, Returns ------- w...
e1c1fa2115a6bffae50237cf051d9e01fe6d7838
658,660
import yaml def load_information(file_address): """Function that takes information on login/OAuth access from an external YAML file and loads it as a dictionary. It also loads the settings as a dictionary. Both are returned in a tuple. :return: A tuple containing two dictionaries, one for authenticat...
6d1e06260740df5d6fc7cc65fe098026611d3ab4
658,661
def clamp_bbox(bbox, shape): """ Clamp a bounding box to the dimensions of an array Parameters ---------- bbox: ndarray([i1, i2, j1, j2]) A bounding box shape: tuple Dimensions to which to clamp """ [i1, i2, j1, j2] = bbox j1 = max(0, int(j1)) i1 = max(0, int(i1))...
d50391a17882c4070a8780d2ad745545741329d2
658,662
import re def sanitise_username(username): """ Sanitise a username for use in a keypair name. """ return re.sub("[^a-zA-Z0-9]+", "-", username)
be3fa6b9140bc5ef0707f25cd784d9cca682f990
658,663
def read_config(in_name): """ Read a fromage config file. Parameters ---------- in_name : str Name of the file to read Returns ------- settings : dict A dictionary with the keywords and the user inputs as strings """ with open(in_name, "r") as data: line...
c71913e91027e737a18b1ee9e43cad19e27efed6
658,664
import os def get_dict_path(path): """ Returns: The path of the the julius dict file as string """ return os.path.join(path, 'dict')
0b8af15d8301afab298d1cee87f0ecac8df5641e
658,665
from typing import Any import subprocess import json def _list(item: str) -> Any: """Run an `xcrun simctl` command with JSON output.""" full_command = "xcrun simctl list %s --json" % (item,) # Deliberately don't catch the exception - we want it to bubble up output = subprocess.run(full_command, univer...
1fe623b039765b4c7f13b84ec48d0bad8216e42e
658,666
def get_dict_val(dict, key_name): """ Receives the arguments = dict, key_name Returns the value """ return dict.get(key_name)
5039a33819cb2755c4a30bc0f1e8cc5c7671413a
658,667
import argparse def parse_args(): """Parse input arguments""" parser = argparse.ArgumentParser(description='GPU resource monitoring.') parser.add_argument( '-n-gpus', '--num-gpus', type=int, default=8, help='Number of GPUs you need.') parser.add_argument( '-m', '--memory', type...
e397e1d63f89e33f5d3472b97615c94eb8c16d3e
658,668
def frankenmerge(frankenstein, organ_indices, donor_info, feature): """Merge a new organ into the frankenstein image""" frankenstein[tuple(organ_indices)] = (0.2 * frankenstein[tuple(organ_indices)] + (1.0-0.2) ...
2a47322639cb1cc0e33d2f9b1a070b2027ffe73a
658,669
def ClearCombiningFunctionUnlessBasicSpecSet(ref, args, req=None): """Clear basic field (and default combine function) if spec not provided.""" del ref # unused if req is None: return req if not args.IsSpecified('basic_level_spec'): req.accessLevel.reset('basic') return req
2574d9c90af7de8ea825c15a6f2de265674cb87c
658,670
import re def trim_data_file_name(name): """"Remove date in name for easier tracking in the repo.""" return re.sub(r"(.*DOH COVID Data Drop_ \d{8} - )", r"", name)
24bdf26923e9b09c944fe1615f51c93b6488a1c6
658,671
import functools def no_dupes(function, *args, **kwargs): """ :return: The results of the function as a list without any dupes """ @functools.wraps(function) def decorator(self): return list(set(list(function(self)))) return decorator
19d47f5cf1d68496fad632fa040fe1a72f069042
658,672
def alwaysTrue( x ): """This function always returns True - its used for multiple value selection function to accept all other values""" return True
b5f925b9444c2b14759788872adad99366a65371
658,674
def index(request): """ Simple Hello IgglePigglePartyPants """ return 'Hello IgglePigglePartyPants!'
8a6f95cb0f2663cd21b20277362d2101f37d7c85
658,676
import os import glob def find_dirs(path, dir_name): """.""" include_dirs = [] name = os.path.basename(path) if name == dir_name: include_dirs.append(path) else: sub_paths = glob.glob(path + '/*') sub_paths = [p for p in sub_paths if os.path.isdir(p)] for sub_path i...
cc9660e250ad870500faf1fc639d456628a8b94f
658,677
import logging import time def new_stdout_logger(level=logging.INFO): """Make a temporary pgclone logger to go to stdout""" logger = logging.Logger(f'pgclone-logger-{int(time.time())}') logger.setLevel(level) handler = logging.StreamHandler() handler.setLevel(level) logger.addHandler(handler) ...
13dff03258171f04d1ae3a475fd2656211654742
658,678
def get_input(argp): """ Returns the user input. """ if not argp.fromf: return argp.input with open(argp.input) as f: return f.read()
5a426cb39b407b8ca6ef99135a8edd422fc6c324
658,679
def _http_error_message(e): """Returns a formatted error message from the raw HTTPError. """ return '\n'.join(e.response.text.splitlines()[1:]) + '\n' + str(e)
ebbe80a75e9dbe0111934a6f67f2e8244c7cf32e
658,680
def str2float(str_val, err_val=None): """ Convert a string to a float value, returning an error value if an error occurs. If no error value is provided then an exception is thrown. :param str_val: string variable containing float value. :param err_val: value to be returned if error occurs. If N...
e4eeda0335b47fd1eeda9e3c49349975a8e1744b
658,681
import sys import os def src(filename): """Find the python source file for a .pyc, .pyo or $py.class file on jython. Returns the filename provided if it is not a python source file. """ if filename is None: return filename if sys.platform.startswith('java') and filename.endswith('$py.c...
0bbe4cc7656b9b4dceefd704ba1867bc8bbf78c7
658,682
def attr(tag, key): """Retrieve an attribute value from a tag.""" for k, v in tag.attrs: if k==key: return v return None
7eeca510727b9bb3af6a6b099bf6da23647865ea
658,685
from pathlib import Path def get_datadir( datarepository: Path, sim_type: str = "historical", dd_type: str = "hdd", Tb=18.0, aggr_window="monthly", method="average", ) -> Path: """ >>> get_datadir("cm/cm_hdd_cdd/testdata").as_posix() "cm/cm_hdd_cdd/testdata/historical/hdd/18.0/mont...
a3ce94289022898a76114125d882f3b0111e355a
658,686
def get_channel_enum(channel_array, channel_type): """ Return true if the offer was presented in the channel type given. """ return channel_type in channel_array
48ca03037f4c346592840c1fc172251ce5a54b95
658,687
def reverseComplement(dna_seq): """ Returns the reverse complement of the DNA sequence. """ tmpseq = dna_seq.upper(); revcomp = '' for nucleotide in tmpseq: if nucleotide == 'A': revcomp += 'T' elif nucleotide == 'T': revcomp += 'A' elif nucleotide...
a9d28d6c44204492ee1dcf6e314aacfc260cec39
658,688
import numpy def make_fir_model(onsets,tslength,hrflength=48,tr=1): """ generate an FIR model design matrix this only works for a single condition """ X=numpy.zeros((tslength,int(hrflength/tr))) for i in range(hrflength): for o in onsets: try: X[o+i,i]=1 ...
7e91f34b25abcb818f08cb8d0b13ddd65d8d2a9d
658,689
def non_empty(title: str, value: str, join_with: str = " -> ", newline=True) -> str: """ Return a one-line formatted string of "title -> value" but only if value is a non-empty string. Otherwise return an empty string >>> non_empty(title="title", value="value") 'title -> value\\n' >>> non_empty...
fa7b2c332d72acf1f8b2196152504448b574d384
658,690
import os def create_file_if_missing(filename, content): """ Create file if missing, so we do not override any possibly introduced changes :param filename: :param content: :return: """ if os.path.lexists(filename): return False dirname = os.path.dirname(filename) if not...
eed41e5ee97db91958233d5c23f1bb7b02a31452
658,691
import os def count_lines(filename): """ returns integer of number of lines :param filename: name of file. :type filename: str :return: number of lines in the file """ if not os.path.exists(filename): raise IOError("Please make sure that " + filename + " exists. Could not be foun...
0592fc9fc42762471f3ff0479e1837ea612340dd
658,693
def load_stored_item(cache, path, item): """Load `item` stored at `path` in `cache`.""" return cache.load_module(path, item.change_time - 1)
b561b3a1fb6ad95bdcda8726113322b35d0b712f
658,694
def __material_bk(d): """ Fixed length data fields for books. """ return (d[0:4], d[4], d[5], d[6:10], d[10], d[11], d[12], d[13], d[14], d[15], d[16])
9a03733a69b1274aa1b3735c1e6dfcb57a203be5
658,695
def count_line(path): """ :param path: path to input file :return: the line number of line """ with open(path) as f: return len([_ for _ in f])
de9859e58090801be9d72702d5475813950fa807
658,697
import logging def build_and_check_sets_experiments(all_vars): """ Description: First we create a variable called 'setExps', which is a dict that goes from set name to a list of experiments belonging to that set (set is equivalent to 'lane'). We then double check that ...
11ff41cee7bd654d85ed8cbc189f41213bc0ae8b
658,698
def __read_opt_rng(opt_rng_json_dict): """ Transfer dict read from json to a dict of opt inputs. Args: opt_rng_json_dict: dict object read from json file. Returns: A dict of opt inputs. """ opt_rng = {} for k, v in opt_rng_json_dict["opt_ranges"].items(): opt_rng[k] = [] ...
26e3118f0b158f4f16e483af334439886d25577b
658,699
def prob_mass_green_from_ndvi(ndvi, old_min=0.3, old_max=0.9): """ Calculate probability mass for greenness from NDVI values :param ndvi: :param old_min: :param old_max: :return: """ if ndvi < old_min: return 0 elif ndvi >= old_max: return 1 else: new_max ...
cba7ac7679d79d8b6d997c63fe7f9a406a00f023
658,700
def identify_meshes(dir_): """List meshes and identify the challenge/track in a directory tree.""" meshes_track1 = list(dir_.glob("**/*_normalized.npz")) meshes_track2 = list(dir_.glob("**/fusion_textured.npz")) meshes_challenge2 = list(dir_.glob("**/model_*.obj")) if meshes_track1: meshes =...
6bbfbe5acc8222a8c8e0c44b24b2cdbf756179fe
658,701
from typing import Dict def parse_hold_reboot_flag(ota_element: Dict) -> bool: """Helper function for installer to check holdReboot flag from the manifest file @return: holdReboot value if holdReboot key present else None """ return ota_element['holdReboot'] if 'holdReboot' in ota_element else False
c5052a3810d8819f8b8c01f06e02fb9501e04333
658,702
def snapshot_state_post_measure_statevector_ket_nondeterministic(): """Snapshot Statevector test circuits reference final statevector""" targets = [] # Snapshot |000> + i|111> targets.append({'0x0': {'0x0': 1}, '0x7': {'0x7': 1j}, }) # Snapshot |+++> targ...
b96f1206e6f32cb6ce0c5859c40898aa67d11076
658,703
def irreversible_duty_sentence_data(request, get_component_data): """Duty sentence test cases that are syntactically correct but are not in the canonical rendering format with spaces and commas in the correct places.""" expected, component_data = request.param return expected, [get_component_data(*a...
db09681bf5d5f16051980f8b5393212cd1f80270
658,704
def bubblesort(x): """ Describe how you are sorting `x` """ assert 1 == 2 return x
25b8d4b417a2ccc42d79aa1fd0af86dfca33e630
658,705
async def trigger_mot_unique(message): """Règle d'IA : réaction à un mot unique (le répète). Args: message (~discord.Message): message auquel réagir. Returns: - ``True`` -- si le message correspond et qu'une réponse a été envoyée - ``False`` -- sinon """ if len(me...
b5492465fc1bd78c94ad566f1868b39ed257165c
658,706
import subprocess def cancel_slurm_job(jobid): """Cancel the Slurm job""" # have to load modules within the function # cancel the job using scancel p = subprocess.run(["scancel", jobid], universal_newlines=True, check=False, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) ...
b0bc46679e8d0a153680944f6f51f858b85cc3e7
658,707
def preserve_legacy_templated_args(input): """Converts legacy uses of `$` to `$$` so that the new call to ctx.expand_make_variables Converts any lone `$` that is not proceeded by a `(` to `$$. Also converts legacy `$(rlocation ` to `$$(rlocation ` as that is a commonly used bash function so we don't want t...
7af0484af0e5097c130f41f7162d68279d78c64d
658,708
import re def validate_short_name(value): """Raise exception if short name fails to match constraints.""" short_name_pattern = r'^[^\/:*?"<>|.]+[^\/:*?"<>|]*$' if value and not re.match(short_name_pattern, value): return fr"satisfy regular expression pattern: {short_name_pattern}" return ""
b45e105b08cb6d1efd0acd15a999531304fd495b
658,710
def parse_range(des_number): """ Range :return: Int reprenting element of the range """ ids = [] for des_group in des_number.split(","): # When we have ";", we should parse it normally if "-" in des_group: start, end = tuple([int(x) for x in des_group.split("-")]) i...
a1639f1f660a294ece210b56c8d465200dda2e30
658,712