content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def my_join(iters, string): """for loop on joining textstrings""" out="" for i in range(iters): out+=string.join(", ") return out
ccdc6ddb22d1c0b362cbde12f24482b448796bea
631,835
def efield_mean_mg(E0, f, epsi, epsh): """Mean E field in the background for an isolated sphere""" return E0 / (1 - f + 3 * f * epsh / (epsi + 2 * epsh))
d2f8bab59679f7e7c6064c4b47a2867a540506dc
631,836
def usrXMLinput(mass=125., CGa=1, precision="BEST-QCD"): """generate XML input from reduced couplings CGa, Cg""" myInputTemplate = """<?xml version="1.0"?> <lilithinput> <reducedcouplings> <mass>%(mass)s</mass> <C to="ff">1.</C> <C to="VV">1.</C> <C to="gammagamma">%(CGa)s</C> <C to="gg...
a90a9b9fec78309438482fdd9eace2572c4625e7
631,837
import shutil def _termsize(fallback=(80, 24)): """ Returns the terminal size, or the fallback if it can't be retrieved""" try: columns, rows = shutil.get_terminal_size(fallback=fallback) except: return fallback return columns, rows
c1d93d1a622976140cb5208803c5eedcd44058ed
631,838
import itertools def drop_while(pred, coll): """ Returns a generator of the items in ``coll`` starting from the first item for which ``pred(item)`` returns a falsy value. Deprecated in 0.1.2. Use Python’s ``itertools.dropwhile`` instead. """ return itertools.dropwhile(pred, coll)
eaf6cd3a4f94efa9953fde965f93705908b4c9b1
631,839
def upload_merged_sample(instance, filename: str): """Deprecated, replaced by upload_reads, can't delete due to it being stuck in earlier migrations""" return f'uploads/merged_samples/{instance.sample_id}/{filename}'
7bc3a20dc27dc592d3b991d8a0a097a397b26b69
631,840
def get_id(state): """ Assigns a unique natural number to each board state. :param state: Two dimensional array containing the state of the game board :return: Id number of the state """ cell_id = 0 exponent = 8 for row in state: for column in row: if column == 1: ...
b7306437701d13d26853b7a6b098acf23ff95a65
631,841
def weekly_distances(combined): """returns weekly total distances kw args: combined -- output of weekly (dummy=True) """ return list(map(lambda goalruns: goalruns.sum_runs(), combined))
a025b178b354f5e9ee25c8f842a674fa214b6b94
631,842
def durationformat(value): """Custom Jinja filter to format duration.""" result = '%.2f' % value return result
2c5bc838ecb78cbd5fdc6370c2c79873ef63c3f5
631,843
import re def format_companies(company): """ Format the selected company so that the API can find relevant articles. """ # Remove junk at the end of the names if company[-6:] == ", Inc.": return re.sub(r' ', "-", company[:-6]) if company[-5:] == ", Inc": return re.sub(r' ', "-...
76b1e7a108c982f9bc17dc9e3299a20e3887829d
631,844
def prop_finally(printer, ast): """Prints a finally property "<> ...".""" prop_str = printer.ast_to_string(ast["prop"]) return f'<>{prop_str}'
21a728d370b02954a8c1c6eb84f9195ea1cfb4d8
631,845
from typing import Tuple def _find_start_indices(starts_with_peak: bool) -> Tuple[int, int]: """Find start indices for peaks and valleys. Args: starts_with_peak: bool indicating whether or not a peak rather than a valley comes first Returns: peak_idx: peak start index valley_idx:...
726e60a19485a4e54af1fb30efb317d64ecee595
631,848
from typing import Set import ipaddress def parse_ipa4(data: str) -> Set[str]: """ parse 'ip -o -4 a' output """ res = set() # 26: eth0 inet 169.254.207.170/16 for line in data.split("\n"): line = line.strip() if line: _, dev, _, ip_sz, *_ = line.split() ...
8d3ce38e1d166755a1bae4518e37601286ad7508
631,849
import shutil import os def which(filename, allow_symlink=False): """ Search the path for an executable, optionally ignoring symlinks Parameters ========== filename: str Filename to search for allow_symlink: bool If True, return filenames that are symlinks """ if allo...
4f170107545506826195be0ac5be548d0279dd29
631,851
import os import torch def load_model_weights(model, filename, verbose=1, cp_folder=""): """ Loads the weights of a PyTorch model. The exception handles cpu/gpu incompatibilities. Args: model (torch model): Model to load the weights to. filename (str): Name of the checkpoint. verb...
ad96878f37ab56c6f53ec0476332b8ae7c631891
631,852
def mag_zeropoint(filter_name): """ Given a filter name, return the number of photons per square centimeter per second which a star of zero'th magnitude would produce above the atmosphere. We assume that the star has a spectrum like Vega's. The numbers are pre-calculated and we just pick the approp...
bf91067e878419f535ab04a0b3b13ba499b42306
631,853
def bibser2bibstr(bib=u'', ser=u''): """Return a valid bib.series string.""" ret = bib if ser != u'': ret += u'.' + ser return ret
508dde6621597547cc3dcda26d558a58c061ffb5
631,854
import math def calculate_rectangle_size_from_batch_size(batch_size): """ Calculate the the number of tiles vertically and horizontally give a batch size :param batch_size: the batch size :return: number of tiles vertically and horizontally, batch_height and batch_width """ batch_height = int(...
468444d68bd62a6adc86b0b52eaf31ccce6303ba
631,855
def get_cell_value(col_name, col_names, row): """ we pass the name of the col and a copy of the col names row in to this fucntion so that we don't have to worry about knowing what the index of a specific col name is. """ position = col_names.index(col_name) if row and position and len(row) >...
befdb30cc0a485fd74c4238c61ba0c46335de4a5
631,856
def check_nmea_checksum(nmea_sentence): """Calculate and compare the checksum of a NMEA string. Args: nmea_sentence (str): The NMEA sentence to check. Return True if the calculated checksum of the sentence matches the one provided. """ split_sentence = nmea_sentence.split('*') if len(s...
4128c86aa698f804a0b4de3602dfc362a0eff402
631,857
from typing import List def strseq_startswith(seq_a: List[str], seq_b: List[str], start_index: int, case_insensitive=True) -> bool: """Test if seqA is starts with seqB""" if len(seq_a) - start_index < len(seq_b): return False if case_insensitive: for i in range(len(seq_b)): if...
f4fbd072cf8f724f4d59d1ee644da6786f673570
631,858
def expand_rectangle(rectangle, region, sample_sizes): """ Expands the rectangle half of the size of sampling size respecting boundaries """ for index, dimension in enumerate(rectangle): ## half of the rectangle size * dimension size / number of rectangles in dimension (sample size minus 1) delt...
efe175930955e2da3b82c37bf8d26ae9f3ac01c3
631,860
def is_whitespace(char): """ Checks if the character is a whitespace Parameters -------------- char: str A single character string to check """ # ord() returns unicode and 0x202F is the unicode for whitespace if char == " " or char == "\t" or char == "\r" or char == "\n" or or...
1bf573219dd36347025305046bb6eade38c847a9
631,862
def greedy(items, maxCost, keyFunction): """Assumes items a list, maxCost >= 0, keyFunction maps elements of items to numbers""" itemsCopy = sorted(items, key = keyFunction, reverse = True) result = [] totalValue, totalCost = 0.0, 0.0 for i in range(len(itemsCopy)): if (totalCost+itemsCo...
969cc1798bfc506246f8660832d655ec186cb168
631,863
def pass_sources_list_filter(incident, sources_list): """Checks whether the event sources of the incident contains at least one of the sources in the sources list. Args: incident (dict): The incident to check sources_list (list): The list of sources from the customer Returns: bool....
9bda8cc28a61fc70ccd2df62b05095582de40cab
631,864
import os def rename_existing_file(file_path): """ Renames a file with an index number at the end for backup """ if not os.path.exists(file_path): return None file_index = 1 while os.path.exists(file_path + "." + str(file_index)): file_index += 1 new_file_path = file_path +...
8a3b09a8e14ce31633229761d8d7dfb6b62eb25c
631,865
def backprop(X, L1, L2, Y, model): """Backprop (output to input) to dicover how much to update the net""" # O algoritmo usa backpropagation, começando a calcular o erro pelos layers # mais externos, L2, calculando seu delta que irá para L1 L2_error = Y - L2 dL2 = X.T @ L2_error # Usando o L2_de...
313af3b3cfb10f70a32a77a6a659a7e5c62a004f
631,866
import os def offset_bunch_compressors(model, script='scripts/BC_offsets.tao'): """ Sets bunch compressor offsets. """ cmd = 'call '+os.path.join(model.path, script) model.vprint(cmd) res = model.cmd(cmd) return res
b51c99a35e9739ea0a80d3c7a1d242ef54e94f34
631,867
def custom_sort(str_list, alphabet): """ Sort a list of strings by a specified alphabetical order. Params ------ str_list: list[str] List of strings to be sorted. alphabet: str Case sensitive alphabetical order for sort. Returns ------- Sorted list[str] acco...
316d1e91bccc7930ccc1ed384e4a610dd06f2cdd
631,868
import numpy def normalize(image, kind_of_normalization=0): """ Normalize given line profile by using a normalization technique based on the kind_of_normalization parameter. 0 : Scale line profile to be between 0 and 1 1 : Divide line profile through its mean value Arguments: image:...
673f939579c29a4e9b49b08e0af88bf593baeacd
631,869
def check_compatibility(selected_usb_size: int, iso_rec_size: str) -> bool: """ Function to test whether or not the usb is large enough for selected ISO :param:string: selected_usb_size pointer to selected usb device size :param:int: iso_rec_size recommended size selected ISO needs :return: true if ...
c8a823b11b78be50e088feb4198af166d0b0ffdc
631,870
import multiprocessing def isMainProcess(): """ Check if this is running in the main process. Returns ------- bool *True* if this is the main process (any thread), *False* if not. """ return not type(multiprocessing.current_process()) == multiprocessing.Process
a38cb784ebc497d9946f34a076d73bcda2d4da6f
631,871
import os def projfn_to_scrfn(proj_fn,outdir): """Converts project fn like to scratch fn Args: proj_fn: abs path to image on project outdir: where slurm-*.out files are """ assert('staging' in proj_fn) return os.path.join(outdir, proj_fn.split('staging/')[1])
b61316a05b92cbafaeb9f6b1c1d7f24c8bd9ef5a
631,872
import types def keep_upper_names(config: types.SimpleNamespace) -> None: """Remove disallowed option names from a config object, the default ``filter_`` option of the ``bootstrap()`` main function. Args: config: The config object """ def name_rejected(name: str) -> bool: """True...
35f76c221ec3ffd8e766fa9914ef8e3073ab2431
631,873
def reshape_forward(tensor, module): """ Reshapes 3d tensor to 2d one when forwarding """ tensor_size = tensor.size() reshaped_tensor = tensor.view(-1, tensor_size[-1]) reshaped_logits = module(reshaped_tensor) logits = reshaped_logits.view(tensor_size[0], tensor_size[1], -1) return log...
40b7694b0b16751e6b08833fe492e56e9966c153
631,874
def chart_title(statistic, chat, start_date, end_date): """Return title for chart displaying statistic (given as string).""" return '{statistic} in "{subject}" ({start_date} - {end_date})'.format( statistic=statistic, subject=chat.subject, start_date=start_date.Format('%d/%m/%Y'), ...
2ba51c36fd2ea36eea194b878dd1a19f34f2b69c
631,876
def greatest_common_divisor(a, b): """[ Summary: Returns the largest number which divides integers 'a' and 'b'. If 'b' is equal to 0 then 'a' is returned. Arguments calculated as absolute value. Implements Euclid's algorithm; https://en.wikipedia.org/wiki/Euclidean_algorithm#Implementations]...
c8aceea1968d4c96f8430baebe08e9ca569aca85
631,878
def find_base_style(masters): """Find a base style shared between all masters. Return empty string if none is found. """ if not masters: return "" base_style = (masters[0].name or "").split() for master in masters: style = master.name.split() base_style = [s for s in styl...
dbaacbaa0d984550b4d07ded15a116c2dd075a43
631,879
def isalphadigit_(s): """ Return ``True`` if ``s`` is a non-empty string of alphabetic characters or a non-empty string of digits or just a single ``_`` EXAMPLES:: sage: from sage.repl.preparse import isalphadigit_ sage: isalphadigit_('abc') True sage: isalphadigit_('12...
4745d8cac5abed644c754918b3f0bd640afced42
631,880
def is_music(f): """ returns if path, f, is a music file """ music_exts = ['mp3','flac','wav','ogg','wma','aiff','aac','ra','dsd','dsf'] return f.split('.')[-1] in music_exts
e05fa2654630d7072cca86b78b7205ae475fa795
631,881
import torch def autocontrast(image): """Implements Autocontrast function from PIL using TF ops. Args: image: A 3D uint8 tensor. Returns: The image after it has had autocontrast applied to it and will be of type uint8. """ def scale_channel(image): """Scale the 2D image ...
ce0dc8471d5d29b417dc485f5e3b34c50ce00edb
631,882
def runInBackground(package,currentRecipe,task,parameters): """ Celery task for running a recipe task in the background. :param package: Base package for the recipe modules. :param currentRecipe: Recipe module under which to run the task. :param task: Task to actually run....
1333e74ec2c4a29bad0c36cabec472080ee71260
631,883
def invalid_constraints__values_not_callable(): """:return: Dict in similar format to constrains but containing invalid data (values are not callable).""" return {"c1": 0, "c2": 1.}
daa82866d7f0601e772ad15a64f53940cf393ae4
631,884
import json def get_tokens(in_file='tokens.json'): """Returns the client and CLIENT_SECRET values from a json token file.""" with open(in_file) as f: data = json.load(f) return { 'CLIENT_ID': data['CLIENT_ID'], 'CLIENT_SECRET': data['CLIENT_SECRET'], 'REFRESH_TOKEN': d...
74cf48b48fb16cd83030c4d60c6b8e104ad20f56
631,885
def _get_paths(config_dict): """Return a list of all paths referenced by the config dict.""" return_list = [ config_dict["diag_table"], config_dict["data_table"], config_dict["forcing"], config_dict["initial_conditions"], ] patch_files = config_dict.get("patch_files", [])...
ed714938b58358c0405fc7dfcd1257e65dfd7b77
631,886
import torch def MSAFeaturize_fixbb_inference(seq, params): """ Turn the single sequence msa into appropriate tensor inputs Parameters: seq (torch.tensor, required): Tensor of shape [L,] of protein sequence as integers params (dict, required): Dictionary of parameters Returns...
0d45715938601b1107751bfcb900108909380145
631,887
def df_has_data(data) -> bool: """Return True if `data` DataFrame has data.""" return data is not None and not data.empty
97a75e2ec0b5cc020b789dc0d0738213436c8abb
631,888
def turnover(positions_np): """ Turnover rate """ daily_tvr = abs(positions_np[1:] - positions_np[:-1]).sum(axis=1) / 2 return {'Mean': daily_tvr.mean(), 'Std': daily_tvr.std()}
125373ec44e91a4ba7d6993695cc217c5b3c6fa2
631,889
def get_shap_values(model_manager, direct_id, target=None): """Get the SHAP values of features. Args: model_manager: ModelManager, an object containing all prediction models direct_id: the identifier of the patient's related entry in the target entity (e.g., the admission id). ...
201ecc08c87262f7dd3aa34f7b2164b6489de405
631,890
import torch def cross_entropy(log_probs, classes, reduce='mean'): """ Computes the categorical cross-entropy loss. Args: log_probs: tensor, shape(n_samples, n_classes) log probabilities over possible classes for each sample. classes: tensor of int, shape(n_classes) ...
e91e6dea318107c55763f4afbcb539a28f49f865
631,891
def to_float(value): """Transforms the Crystal-specific float notation into a floating point number. """ base, exponent = value.split("**") base = int(base) exponent = int("".join(exponent.split())) return pow(base, exponent)
01f467c0ac66cb3f282ab5f1a7400b89ac8d841a
631,892
def get_cmd(chk): """ Assemble the correct "packet-tracer" command based on the "proto" value. TCP/UDP use source/destination ports, ICMP uses type/code, and other protocols use neither. Returns a valid "packet-tracker" command that can be issued to an ASA without further modification. """ ...
9d0dd51d0f2f264d0c165dd8d80cb06ccf33fa03
631,893
def elcc_eligible_capacity_rule(mod, g, p): """ :param mod: :param g: :param p: :return: """ return mod.Capacity_MW[g, p]
2a5c0f1071ecd8fe75a464092e791b47cbe961fe
631,894
def corr_naam(name): """convert name used in program to model name and back Note: all names must be unique! """ names = (("techtaak", 'techtask'), ("programma", 'procproc')) for name1, name2 in names: if name == name1: return name2 if name == name2: return na...
7c2262ca9e24c1fb4a02e33c1ae35b62ee33dfbf
631,895
import torch def log_standard_categorical(logits: torch.Tensor): """ Calculates the cross entropy between a (one-hot) categorical vector and a standard (uniform) categorical distribution. :param p: one-hot categorical distribution :return: H(p, u) Originally from https://github.com/wohlert/se...
bcb4327e9672b6ec69ff156b990452bff778312a
631,897
def getStats(err): """Computes the average translation and rotation within a sequence (across subsequences of diff lengths).""" t_err = 0 r_err = 0 for e in err: t_err += e[2] r_err += e[1] t_err /= float(len(err)) r_err /= float(len(err)) return t_err, r_err
aa7643642eb524d8fd9f943f239b1e9f429452ae
631,898
def no_nulls_test(df): """Checks that all elements are not null""" return df.isnull().values.sum() == 0
257dc8fb596de800ea9cdb5864c7492ce9f98527
631,899
import os import yaml def load_gitlab_ci_config(workspace_root): """Return the parsed gitlab-ci-config.yml.""" file_name = os.path.join(workspace_root, "gitlab-ci-config.yml") with open(file_name) as fin: parsed_yml = yaml.load(fin, Loader=yaml.FullLoader) for field in [ "crat...
4301f9ccf324786c136f705bb940cf9a4a9d6a31
631,900
import random def col_mask(spec, T=10, num_masks=1, replace_with_zero=False): """ Column masking is applied so that t consecutive time steps [t0, t0 + t) are masked, where t is first chosen from a uniform distribution from 0 to the time mask parameter T, and t0 is chosen from [0, τ − t). We intr...
e26a12c21d021336f69f890cdafd408934c61001
631,901
import platform def _is_windows(): """Return true if the current OS is Windows, false otherwise.""" return platform.system() == 'Windows'
530b128a9f39ab813a81c5d233057134870475b1
631,902
from typing import Callable from typing import Dict import inspect def get_input_type_dict(func: Callable) -> Dict[str, type]: """ Returns a dict like {argname: type} for given function inputs Examples: >>> @dataclass >>> class Base: >>> ... >>> @dataclass >>> c...
d15298d087fe2e20b3e291dfef497b7d1cd5f5b2
631,903
import subprocess def dart_writer(path): """Returns a file object that writes Dart code to the supplied path. The code is passed through dartfmt to ensure correct formatting.""" dest = open(path, 'w') return subprocess.Popen(['dartfmt'], stdin=subprocess.PIPE, stdout=dest).stdin
620a004527cfa7eca2410207eff1ab188bc6ba99
631,904
def inverse_transform(images): """ Function inverse_transform will trans a (-1.0, 1.0) picture to a (0.0, 1.0) picture """ return (images+1.)/2.
0fdc10e78cbd8586fd60e6371cd9220c8a1478a8
631,905
def _get_rule_violation_cost(from_prod_state, to_prod_state, spec, to_ap): """Return the rule violation cost on the transition from from_prod_state to to_prod_state. This follows Definition 8 (weighted finite automaton) and Definition 9 (product automaton) in J. Tumova, G.C Hall, S. Karaman, E. Fra...
7754b1162e4f252baa5abff80f5d16d3173b9e8f
631,906
def polynomial(coefficients): """ Create a polynomial from the given list of coefficients. For example, if the coefficients are [1, 0, 3, 5], then the polynomial returned is P(t) = t^3 + 3t + 5 If the coefficients are [3, 2, -2, 9, 4, 0, 1, 0], then the polynomial returned is P(t) = 3t^7 + 2t^6 - 2t^5 + 9t^...
6b17b1cd32b56c46ea6244e5666330d84fc5d310
631,907
import os def computecorecoverage(bedgraph, bedfile): """computes the core "enzymatic" coverage for gene clusters EXPLANATION: This computation is based on the bedfile that contains the coordinates for the enzymatic genes. What happens is that the algorithm finds entries that have 0 coverage, and ...
a80c04efbfc9ede33fb9a08cd54b0822d881aa8e
631,908
import inspect def async_wrap_callback(callback): """ Wraps a function in an async function. """ if inspect.isawaitable(callback) or inspect.iscoroutine(callback) or inspect.iscoroutinefunction(callback): return callback async def wrapper(*args, **kwargs): if callback is None: ...
71c52978ace22fea391e99ae6729cf5ac085e16a
631,909
from typing import Iterable import json def dumps(objects: Iterable) -> str: """ Returns a string representation of an iterable in a string """ return "\n".join(json.dumps(obj) for obj in objects)
c4de5fd1581e39e884390adbfb4770c6a74139a7
631,910
def parseCommonSH(): """Parse common.sh in the current working directory, returning a dictionary version of its key=value pairs""" d = {} for line in open('common.sh'): cols = line.strip().split('=') if len(cols) == 2: d[cols[0]] = cols[1] return d
126c38a0a27d7094cef508b212c86152d4e683a9
631,911
def validate_parent_field(instance, value): """ Check if parent field is valid """ return instance is not None and value != instance
b2ab81a13193da41db4e7e76553c122e36d67c77
631,912
import copy def regularize(l): """ If necessary mix in a small prior for regularization. """ epsilon=1e-3 l=copy.copy(l) for i in range(0,len(l)): if l[i]==0: l[i]=epsilon return l
cde50c63fef8b22e800daeecda29998e62813850
631,913
import toml import sys def read_config(): """ Load the config from the TOML file at /config/config.toml :return: Dictionary with the config information. """ return toml.load(sys.argv[1])
94ff85e712e36ffb43212cc8c5e4526522a12b04
631,914
def get_md_energies(): """ Read the energy file containing all the energies for the MD ensemble in ../test_data/ :return: {filename: energy} dict """ path = "../test/MD_energies.txt" f = open(path) lines = f.readlines() f.close() edict = {} for line in lines: split =...
afaaf997c76452df6dd5e6e283e2102c1a1197f5
631,917
def get_dim(edgelist): """Given an adjacency list for a graph, returns the number of nodes in the graph. """ node_dict = {} node_count = 0 for edge in edgelist: p, q = edge[ :2] if p not in node_dict: node_dict[p] = True node_count += 1 if q not in...
6a85b68f0afddc1ba05e5a43d0cb52e5031da118
631,919
async def root(): """Basic Hello World.""" return {"message": "Hello Hello World"}
f4476bf4eea014e1525ae0ca4ed8aaddb1625266
631,920
import math def angle_on_plane(plane, vec1, vec2): """ Return the angle between two vectors projected onto a plane. """ plane.normalize() vec1 = vec1 - (plane * (vec1.dot(plane))) vec2 = vec2 - (plane * (vec2.dot(plane))) vec1.normalize() vec2.normalize() # Determine the angle ang...
8e724343bf38fa2aed7572e09f8f13c8d840323c
631,921
import socket def target_encrypted(target_ip: str) -> bool: """ Checks if the target is using encryption :param target_ip: Target IP running the server :type target_ip: str :return: True or false :rtype: bool """ s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((tar...
dbf2220df923867aeca85acd9db551c76959bdee
631,922
def search_codetree(tword,codetree): """ Stored in codetree with non-zero value in the terminal node """ pos = 0 while True: s = tword[pos] if s not in codetree: return 0 elif pos==len(tword)-1: return codetree[s][0] else: pos += 1 ...
5f520fd457f09fe18f350364f122bc5fcd7cd56a
631,923
def binboolflip(item): """ Convert 0 or 1 to False or True (or vice versa). The converter works as follows: - 0 > False - False > 0 - 1 > True - True > 1 :type item: integer or boolean :param item: The item to convert. >>> binboolflip(0) False >>> binboolflip(False) ...
854bd142dee085c5126d3dce38b1b13a6443386c
631,924
import argparse def parse_arguments(): """Parse command line arguments.""" parser = argparse.ArgumentParser( description="Create gene sets from DGE results table." ) parser.add_argument( "--dge_file", required=True, help="Differential expressions file." ) parser.add_argument("-...
c0cb6d03fb47a5295bed0941ba761b7a68e8cb94
631,925
def config(path): """ Set CONFIG_FILE, the path to the configuration JSON file, to the given path, and return the new path. No error or sanity checking is performed. """ global CONFIG_FILE CONFIG_FILE = path return CONFIG_FILE
3642d5f16063fcb78fe133dd957b430aea96dde3
631,926
import os import getpass import pwd def get_user(): """Try to find the user who called sudo/pkexec. Taken from https://unix.stackexchange.com/a/626389 .""" try: return os.getlogin() except OSError: # failed in some ubuntu installations and in systemd services pass try: ...
30b13e64b0ccdc75376a4aa8ba65203d813c467f
631,927
def get_way_points(relation): """ Get way points of OSM relation. @param relation: OSM relation as dictionary. @return: List of way points (OSM node ids). >>> relation_id = 660162 >>> relation = get_relation_by_id(relation_id) >>> way_points = get_way_points(relation) """ return [...
bb689b947069f3ec8ed22763c247010cd0b64748
631,928
import os def check_exception_checkpoints(ckpt_file_list): """ Check exception checkpoints size. Args: ckpt_file_list: exception checkpoints Returns: result of exception checkpoints size check. """ ckpt_size_list = [] for ckpt_file in ckpt_file_list: ckpt_size_list.append...
6634e25558760555e7900f771ff2e0a1741447ad
631,930
def split_data(x, y): """ Split data into training and validation set :return: """ training_percent = 0.7 split_idx = round(training_percent * len(y)) x_train = x[:split_idx] x_val = x[split_idx:] y_train = y[:split_idx] y_val = y[split_idx:] return x_train, y_train, x_va...
24e8cd4a0bc38f434315693ee113414d0705c7eb
631,932
import string def strip_punctuation(headline): """ Remove all punctuation from a headline to return only the words. :param headline: raw headline :return: parsed headline """ table = headline.maketrans({key: None for key in string.punctuation}) headline = headline.translate(table) ret...
2bf02d615178c1f25f7684d51f79a585dc2a6389
631,933
import os def initialize_vocabulary(vocabulary_path): """Initialize vocabulary from file. We assume the vocabulary is stored one-item-per-line, so a file: dog cat will result in a vocabulary {"dog": 0, "cat": 1}, and this function will also return the reversed-vocabulary ["dog", "cat"]. Args: ...
4ea91711216b7b65f3b920e7c0e6f8c5b243a9a9
631,934
def conditional_prob(x, y, x_thr): """ Calculate conditional probability that `y` is less than zero, given that `x` is greater than a given threshold `x_thr` """ joint_prob = y[(x > x_thr) & (y < 0)].size single_prob = y[x > x_thr].size if single_prob == 0: cond_prob = 0 else: ...
6186eb84590d6b206a9d3428d2c58cac4bbe4f79
631,935
def select_scan_no_qc(scans_meta): """Select a scan from available scans in case there is not an available QC. Args: scans_meta: DataFrame containing the metadata for images to choose among Returns: DataFrame row containing selected scan """ # We choose the first scan (not containi...
cdeb34c727ea4976db977f349a54d6b21c86f26a
631,936
def pad_sentence(sentence, window_len, lsl, rsl, mask): """ :param sentence: Sentence to pad :param window_len: The ammount of tokens in the desired sentence :param lsl: (left-side length) The current token count to the left of the central token :param rsl: (right-side length) The current token coun...
d31f4ed77dd23b84d5a1b822f641f863ab3b8e61
631,937
def create_file(repo, path, message, content): """Create a file in a github repository using Github's content create API: https://developer.github.com/v3/repos/contents/#create-a-file Will create the file at the specified path under a given repo and use the provided commit message. Content should be ...
09c609aedba0d63c179ecec6573450de8c78be2e
631,938
def get_tokens_corresponding_to_span(tokens, span): """Find the list of token(s) corresponding to span (of type text.text_span.Span) We look for exact offset match. If we cannot find an exact match, we return None :type tokens: list[nlplingo.text.text_span.Token] :type span: nlplingo.text.text_span.Span...
31892304dcd40af0768cc9fb54abb9855f3d0a5d
631,940
def get_published_branch_id(database): """Return the IDs of the published-branch courses.""" collection = 'modulestore.active_versions' projection = {'versions.published-branch': 1, '_id': 0} cursor = database[collection].find({}, projection) published_branch_ids = [] for result in cursor: ...
ea83b272be5a02c92ecd3859f25e1b3f04c566a3
631,941
def longest_consecutive_sequence(seq: str, char: str) -> int: """Return length of the longest consecutive sequence of `char` characters in string `seq`.""" assert len(char) == 1 longest = 0 current_streak = 0 for c in seq: if c == char: current_streak += 1 else: ...
08e8e0aebccc8681f7d2df4e7e6d8a2df911451b
631,942
from datetime import datetime def add_heart_rate_timestamp_info(patient_new_keys, in_heart_rate): """ Add heart_rate and timestamp to patient dictionary This function appends the information to the dictionary of an entered patient. The information being added is the "heart_rate" and "timestamp" for t...
76f2fb4df9820a3187cade934a070d25def5d7e1
631,943
def camera_name_cmp(x,y): """ Comparison function for camera names """ value_x = int(x.replace('camera_', '')) value_y = int(y.replace('camera_', '')) if value_x > value_y: return 1 elif value_y > value_x: return -1 else: return 0
7af07a9eb552e9b9782e3363d72a30aafbad7ba7
631,944
def flatten_properties(props): """ Fetch data data from api metadata properties """ ret = dict() for key, val in props.items(): if type(val) == dict: sub_props = flatten_properties(val) for subkey, subval in sub_props.items(): ret[key + '/' + subkey] = subval ...
b1ea996b900d9356bbbd457424810656173ad39b
631,945
def status(category, values, suffix=""): """Return status in human-readable format.""" size = len(values) pluralization = "" if size == 1 else "s" return "* Found {} {}{} {}.".format(size, category, pluralization, suffix)
934b7160e36a467c4e553b7904974a9fa81a2db9
631,946
def index_to_alg(cnt): """ Convert a bit index to algebraic notation """ column = "abcdefgh" [int(cnt % 8)] rank = "12345678" [int(cnt // 8)] return column + rank
e2fde3811f6488ddafa81ffe4b6ed8cc1c8703a2
631,947
import os def best_sql_url(): """Return compliant sql url from available environment variables""" env = os.environ if 'PGDATABASE' in env: return ( 'postgresql://{PGUSER}:{PGPASSWORD}@{PGHOST}/{PGDATABASE}'.format( PGUSER=env.get('PGUSER'), PGPASSWORD=env.get('PGPASSWOR...
ddb8d69d4ee77dc0295e318e8dc44c670366888e
631,948