content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def last_num_index(word_: str) -> int: """ :param word_: :return: int; the index of the last numeric character reading the word ltr """ numbers = '0123456789' return max(i for i in range(len(word_)) if word_[i] in numbers)
cd3a55f06784a030bc0442024214988bf5451707
648,900
def serialise_ctx(ctx): """ Convert context to serialisable list """ ctx_list = [] if type(ctx) is not list: ctx = [ctx] for c in ctx: ctx_list.append((c.device_id, c.device_typeid)) return ctx_list
1e95d8e3b078cd3890b318429b035409532558b8
648,901
def count_musicians_range(musicians, instrument=None): """Return a count of musicians by their chosen instrument. If no instrument is provided by the caller then count all musicians. If an instrument is provided (e.g., 'trumpet') count only musicians whose instrument matches the passed in instrument...
8a2bcf7bdb7b7006fc7474b07d0f5c8ada92735a
648,902
def is_promiscuous(table): """ A staticmethod that takes a codon table as a dictionary and returns True if it represents a promiscuous table and False if not. Parameters ---------- dict table: a python dict representing the codon table Returns ------- bool ambiguous: boolean repres...
5f857548bff100bcba64b9223da01238bd12a640
648,905
from warnings import warn def _iterate_rules(rules, topology_graph, typemap, max_iter): """Iterate through all the rules until the white- and blacklists converge. Parameters ---------- rules : dict A dictionary mapping rule names (typically atomtype names) to SMARTSGraphs that evaluat...
d8d58efc9d0b2cd21b9d02eec187f82ada190384
648,907
import difflib def difflib_overlap(word_token1: list, word_token2: list) -> float: """ Get similarity percentage from matching sequences between two strings """ seq = difflib.SequenceMatcher(a=word_token1, b=word_token2) # Return similarity percentage based on difflib library Sequence Matcher return...
0cd770e1c71f387600a008247413eaa63d587804
648,908
from typing import Any from typing import Callable def find_nonmatching_fields(item: Any, match_fn: Callable[[Any], bool], *fields): """Check that the given fields of an object match the output of a function. :param item: Any object with attributes to check. :param match_fn: A callable function. Each att...
e1c31c03c73536ff3f23e1bfa9908700777ed231
648,909
def get_node_labels(session): """Returns all node labels in use in the database.""" result = session.run("MATCH (n) RETURN DISTINCT labels(n) as label") labels = [] for record in result: labels.append(record.get("label")[0]) return labels
bad38259676bc9d3657677e51eaf6890dde82080
648,910
import json def json_reader(file_path): """ open and loads json files """ with open(file_path) as file: json_dict = json.load(file) return json_dict
b62f08c0b0e5afcec396d91a9c799a56d780b740
648,911
def _XYDict(x_value, y_value, first='x', second='y'): """Take in x and y coordinates and return in dictionary form. Args: x_value: The value of the x coordinate. y_value: The value of the y coordinate. first: The key for first field. second: The key for second field. Returns: A dict with a x...
2db919b053d053f8e5bd5489cfb3f43f4cf555ff
648,914
def sb_elem(qe: float, n_cells: int, n: int, m: int) -> float: """ Calculated from formula (5) via recursive approach from Appendix A Sperling, J., Vogel, W., & Agarwal, G. S. (2014). Quantum state engineering by click counting. Physical Review A, 89(4), 043829. for arbitrary quantum efficiency...
b912265646ece17e1e18c7ca19d15c1e81bd514c
648,915
import json def load_config(config_filepath): """ Using a json file with the master configuration (config file for each part of the pipeline), return a dictionary containing the entire configuration settings in a hierarchical fashion. """ with open(config_filepath) as cnfg: config = json....
51d9784990c4ad6e86edff8803caad89dcf22fff
648,916
def get_mount_info(pools, volumes, actions, fstab): """ Return a list of argument dicts to pass to the mount module to manage mounts. The overall approach is to remove existing mounts associated with file systems we are removing and those with changed mount points, re-adding them with the n...
e9d6d2cb4af2f9a344207d99b023757f84053f3d
648,917
def span2toks(span, document): """ :param span: span array representing [start, end] :param document: list of tokens from which to extract span tokens :return: tokens from document indicated by span indices """ return document[span[0]:span[1] + 1]
a46570c5275ec9c987e999beabc967e284b62b1a
648,918
def find_nearest_datapoint(lat, lon, ds): """Find the point in the dataset closest to the given latitude and longitude""" datapoint_lats = ds.coords.indexes["latitude"] datapoint_lons = ds.coords.indexes["longitude"] lat_nearest = min(datapoint_lats, key=lambda x: abs(x - lat)) lon_nearest = min(dat...
ffc106e0ac092ce32d0e499369898f2139ac9ab9
648,919
def ignore_files(files, ignore): """Ignore files based on a search term of interest. Parameters ---------- files : list of str File list. ignore : str String to use to drop files from list. Returns ------- list of str File list with ignored files dropped. ""...
e358e040f344e51ac83dc9fbee026e024aafada9
648,921
import torch def psnr_error(gen_frames, gt_frames, max_val_hat=1.0): """ Computes the Peak Signal to Noise Ratio error between the generated images and the ground truth images. @param gen_frames: A tensor of shape [batch_size, height, width, 3]. The frames generated by the gener...
ee43a9cb7c6381f91c7fbe140cb1fa3edc1baac5
648,922
import json def configure_mobile_chrome_preferences(path): """ Configure Android Chrome Preferences JSON file - HTTPS search URLS - Reset location data permissions - Disable camera/microphone """ GOOGLE_BASE_URL = 'https:/www.google.com/' contents = None with open(path, 'r') as f:...
ccf6465003c3018efb41b4ca0b44a5d129dafa0a
648,923
def credentials_get(credentials): """Service Layer to get credentials""" return credentials.get_Credentials()
911495032142b908368839a88d0ffae4ea044991
648,924
def check_compatible_modifiers_only( antecedent_mention, mention, offset2string): """ Compatible modifiers only The `mention`s modifiers are all included in the modifiers of the `antecedent_mention`. (...) For this feature we only use modifiers that are nouns or adjectives. (Thus `main_modi...
e617d7ea9df1a026bc286b507ea0485c8496e33c
648,925
def BoxLength(box): """Returns the box length given the box coordinates.""" return box[1::2] - box[0::2]
68dd9db68975a646a850e138e4033bab7f26638c
648,926
import numpy as np def fft(data, n, res=512): """ Get spectrum data in log scale using iterpolation. :param data: 1D array - sound data array :param n: int - total data result :param res: int - fft resolution before interpolation """ data = np.fft.fft(data, res) data = np.abs(data)[:int(res * .8)] x...
45ef1cceb0fdab758d850b8c0b055c9128d13d1e
648,927
def convCoord(v): """swizzle, the quake order is wacky. also scale by an arbitrary amount.""" scale = 1.0/15.0 return (v[1]*scale, v[2]*scale, v[0]*scale)
ad1e6a03592cf7e03093b5fb1d21a29f65acfbaa
648,928
def get_analyze_query(graph_name): """Format an ANALYZE query with the name of the inserted RDF graph.""" return f"ANALYZE {graph_name}"
d78ad2584b6a9470dfcdd574fbaffb40b7f5594e
648,929
def validate(observation): """Make sure the observation table is valid, or raise an error.""" if observation is not None and type(observation) == dict: return observation elif type(observation) == list: return observation else: raise RuntimeError('Must return dictionary from act(...
5e7fe767f8229f514517742de5b4c50b0ee7c388
648,930
def clean_data_dict(data_dict): """Add some key/value pairs to the data dict, if they are missing. Args: data_dict - dictionary containing data for LFADS Returns: data_dict with some keys filled in, if they are absent. """ keys = ['train_truth', 'train_ext_input', 'valid_data', 'valid_truth...
c9a2be6cc2a65fa83775a3e0061920932cca0ea6
648,931
import argparse def get_arguments(): """ Get parsed passed in arguments. """ parser = argparse.ArgumentParser() parser.add_argument( '-c', '--config', metavar='path_to_config_dir', default="config", help="Directory that contains the Home Assistant configuration") parser...
3a28e42ca4f29db4870ed695b1b1a99b5dcd5e4e
648,932
def convert_number(number, denominators): """ Convert floats to mixed fractions """ int_number = int(number) if int_number == number: return int_number, 0, 1 frac_number = abs(number - int_number) if not denominators: denominators = range(1, 21) for denominator in denominators:...
f69c6b3fcbc8ead6018481f8857791c0d9bef6af
648,933
import os def get_subdirs(root_dir: str): """Returns all subdirectories in `root_dir`.""" subdirs = [ os.path.join(root_dir, i) for i in os.listdir(root_dir) if os.path.isdir(os.path.join(root_dir, i)) ] return subdirs
6cf64f069a99a725f2f81e04f5073cf55bb074af
648,934
from functools import reduce import operator def product(values, base=1): """Get the product of the given values. :param values: An iterable of values to be multiplied. :param base: Applied to the beginning of the calculation. :type base: int """ return reduce(operator.mul, values, base)
c645ec9f354f4ef265026128dc0914c3a60b8d1f
648,935
def get_reply_text(msg): """Возвращает текст пересланного (отвеченного) сообщения или пустоту""" return msg._data['reply_to_message']['text'][0:1024] if 'reply_to_message' in msg._data else ''
38713927946d942f3fe3a2e71fad53f74c61a711
648,936
import calendar def _timegm(sec, min, hour, mday, mon, year, wday=0, yday=0, isdst=0): """Replacement for perl built-in timegm function""" if year < 1900: year += 1900 return calendar.timegm((year, mon+1, mday, hour, min, sec, 0, 1, -1))
d84ec2dc52e8c835d6cb63f6153f266e6425cec5
648,937
import sys import os def WindowsPathToMsysPath(path): """Translate a Windows pathname to an MSYS pathname. Necessary because we call out to ssh/scp, which are MSYS binaries and expect MSYS paths.""" if sys.platform != 'win32': return path (drive, path) = os.path.splitdrive(os.path.abspath(...
361df9b8ed7e60cfcc8f515eb3a988834b9f6f52
648,938
def get_prices(vuelo): """ Funcion que retorna una lista de diccionarios con las distintas tarifas """ tarifas = vuelo.find_elements_by_xpath('//div[@class="fares-table-container"]//tfoot//td[contains(@class,"fare-")]') precio_tarifa=[] for tarifa in tarifas: nombre= tarifa.find_element_...
8f96e8f72657d0648d313a60dbe94d55e6c6eeed
648,939
def main(): """test module """ return 0
7fc9119854adf17111e211671b7252e16795219c
648,940
def experiment_rank_by_num_firsts(experiment_pivot_df): """Creates experiment level ranking by number of first places in per benchmark rankings (higher is better).""" # Rank fuzzers in each benchmark block. pivot_ranked = experiment_pivot_df.rank('columns', na...
9cf6b13128ed488a158a42271e652432d18f71fd
648,941
def get_name_from_kwarg(var): """ Given some kwarg name, return the original variable name. :param var: A string with a (internal) kwarg name :return: The original variable name """ return var.replace('#kwarg_', '')
da84fa89814bc6bd44afcaef1bd673c137288711
648,942
def coalesce(df, *cols, no_scalar=False): """Fills in missing values with subsequently defined columns. Element-wise equivalent of: (col[0] or col[1] or ... or col[-1]) The last provided value in *cols is assumed to be a scalar, and .fillna(col[-1]) is called unless `no_scalar` is set to True. """ ...
5456b29eaa40610ff3f396651264c109359db345
648,943
def root_page(wagtail_initial_data): """ On start Wagtail provides one page with ID=1 and it's called "Root page" """ return wagtail_initial_data
6a36cc4edf9baf90f867f35aea3b51b20c7c0dd2
648,946
def get_i18n_block(inifile_or_dict, key, pop=False): """Extracts an i18n block from an ini file or dictionary for a given key. If "pop", delete keys from "inifile_or_dict". """ rv = {} for k in list(inifile_or_dict): if k == key: # English is the internal default language with pr...
600eaff8ba32037173752cd8bbbb3645499d8648
648,947
from typing import List from pathlib import Path def find_archives(path='.', prefix='results') -> List[Path]: """List all results archives at given location""" path = Path(path).expanduser().absolute() if path.is_file(): return [path] return sorted(path.rglob(f'{prefix}_*.zip'))
791a652e67439f2c9d611d5d0fe12f34e61445c6
648,948
def update_network_in_metric(ml_channel_id, ml_channel_name): """Update the metrics of the "Network In (sum)" dashboard dashboard widget""" result = [] entry = ["MediaLive", "NetworkIn", "ChannelId", ml_channel_id, "Pipeline", "0", {"label": ml_channel_name + "-0"}] result.append(entry) entry = ["Me...
636555c6cd061f2daf3cafb2598b3c687e33cc8f
648,949
def load_def_config(): """ Get the default configuration dictionary. Returns ------- config : dict dictionary of default values that are required to run corazon pipeline """ config = dict() config = { "det_window" : 65, "noise_window" : 27, "n_si...
b51c5a1732bccadc28a0d58c05ced142b23336bc
648,950
def get_appendix_data(df, table): """ Given Appendix A DataFrame df and table name, return Sequence, Start, and End numbers as lists. """ df = df[df['name'] == table] return df['seq'].tolist(), df['start'].tolist(), df['end'].tolist()
46ec1a9b5c0c065d9a261981efb5d7bb625971a9
648,951
def make_display_name_linear(comp_grounding): """Return display name from compositional grounding with linear joining.""" entries = tuple(entry[0].split('/')[-1].replace('_', ' ') if entry else None for entry in comp_grounding) entries = [entry for entry in entries if entry is not None] ...
16066f8247ed6ff2bf872bf785b1bb81c3653cad
648,952
def main(): """ The main function to execute upon call. Returns ------- int returns integer 0 for safe executions. """ print("Program to add two numbers.\n") # two float values num1 = 1.5 num2 = 4.5 # Adding the two given numbers sum_val = float(num1) + float...
f51c99b6a12b13c022ab7c262a44fe33a5186141
648,953
def example_db(): """ Purpose: Set example db for redis Args: N/A Return: example_db (Pytest Fixture (Int)): example db for redis """ return 7
281efe99056d1f3ff15fa3bda6d0714c283e43c8
648,954
def is_nonzero(delta): """Return True if any element of 2D list is nonzero.""" nonzero = False for row in delta: for element in row: if element != 0: nonzero = True return nonzero
e166902466012f0670b17d67e9dc3348c928021b
648,955
def parse_tags(tags): """ >>> parse_tags('writing') 'writing' >>> parse_tags(['news', 'steemit', 3, {'5': {}, '3': {}, '1': {}}, {'39': {}, '45': {}, '11': {}}, {}, 'esteem']) ['news', 'steemit', 'esteem'] >>> parse_tags(['dlive', 'dlive-broadcast', 'game', 'DLIVEGAMING']) ['dlive', 'dliv...
fae032a58e4c477febddc1e6ea6851a95654a637
648,956
def doFilter(pTable): """ remove all cell candidates and corresponding cell pairs that have no CPA candidate """ # get a list of all cell candidates that have at least one candidate in at least one cell pair mappedCands = {} for pair in pTable.getCellPairs(): subjKey = (pair['subj_id'],...
9efacb612d0be1b41aae97f0c20fe50e0c02fb48
648,957
import re def html_to_json(soup): """ """ # Scrape just PDF links for pdf_link in soup.select('.gs_or_ggsm a'): pdf_file_link = pdf_link['href'] print(pdf_file_link) # JSON data will be collected here data = [] # Container where all needed data is located for result...
d68a8f3493967c65efbc8023ad820df4f6d74a0d
648,959
def sort_categories(revenue_data): """ Need to sort the category data so that its matches what is showed in the national budget. """ revenue = [] duties_total = 0 other_total = 0 for r in revenue_data: if ('Customs duties' in r['category_two']) or ('excise duties' in r['category_...
304a000b6fa61c3f357d72565290cc40f776e2ad
648,961
import re def account_token(doc): """Flag user accounts with custom .is_account attribute""" pattern = re.compile(r"@\w+") for token in doc: if bool(re.match(pattern, token.text)): token._.is_account = True return doc
bc45f53a36f5a58e8573608f5a0ea3e60bfe4b98
648,962
import warnings def check_model(model: str) -> str: """Check model is 'aces' or 'btsettl'. Parameters ---------- model: str Model name. Should be either 'aces' or 'btsettl'. Returns ------- model: str Valid model output; either 'aces' or 'btsettl'. """ if model == "ph...
8ebafa33f25de2dc50340e9526494b03bf90165a
648,963
import os import sys def get_http_prompt_path(): """Get the path to http-prompt executable.""" python_dir = os.path.dirname(sys.executable) bin_name = 'http-prompt' if sys.platform == 'win32': bin_name += '.exe' paths = [ os.path.join(python_dir, bin_name), os.path.join(py...
436cc42aa8e32fae49d0a9968655246e1a224978
648,964
import tqdm def encode_lemmas( candidate_df, stopwords, word_mapper, entity_fieldnames=["disease_start", "disease_end", "gene_start", "gene_end"], entity_one="DISEASE_ENTITY", entity_two="GENE_ENTITY", ): """ This function is designed to provide index numbers for each provided lemma. ...
8a5f43accbb3bd37ff16e71d40ea894bc2e02010
648,965
def rstrip_special(line, JUNK="\n \t"): """ Returns the given line stripped of specific trailing characters (spaces, tabs, and newlines by default). Note that line.rstrip() would also strip sundry control characters, the loss of which can interfere with Emacs editing, for one thing. (Used by t...
1848e931c464ff4b82fcb2d188d95d536b6512d6
648,966
import yaml def get_data(yml_file): """read YAML file and return database""" ### many loading modes are available ### RoundTripLoader allow to keep comments but the types of returned data are not regular python data, ex: ruamel.yaml.scalarfloat.ScalarFloat ruamel.yaml.comments.CommentedSeq #dico = yaml.round_trip...
c6ad5428adc68445aa94bf2debeabcf1c4454bc3
648,967
import re from pathlib import Path def get_bibtex(filename): """ Tries to extract a bibtex key from a filename and returns it. If no bibtex key is found the function returns the filename (without suffix). """ bibtex = re.match(r'^[a-zA-Z]*\d{4}[a-z]?', Path(filename).stem) if bibtex: bibt...
f511a3beb4168605fccf9ffb420c75d6e9577f00
648,968
def requirements_file_to_list(fn="requirements.txt"): """read a requirements file and create a list that can be used in setup. """ with open(fn, 'r') as f: return [x.rstrip() for x in list(f) if x and not x.startswith('#')]
7bf8f1d183685945e08d64bf2430279ad9effb52
648,969
import sys def normalize_to_dpi(font_size): """ Normalize the given font size based on the system DPI. """ if sys.platform == "darwin": # macos is lame return font_size + 2 return font_size
2f3bf434fedd433a7eec8c189b4f730cb2c2e049
648,970
import json def get_tote_contents(json_file): """Return tote contents data from picking json. Returns: data (list): tote contents data written in picking json file. """ with open(json_file, 'r') as f: tote_contents = json.load(f)['tote_contents'] return tote_contents
54b3374d717cdb5ec469ea1b204a93ad164396da
648,973
def showphase(repo, ctx, templ, **args): """:phase: String. The changeset phase name.""" return ctx.phasestr()
6a8ac3e99f227179323a0e5904bf3139ef994a4b
648,974
def resolve_aliases(kwargs, aliases): """Check and resolve to a standard label for any potential aliases. Parameters ---------- kwargs : dict Dictionary of labels and their values. aliases : dict Dictionary of label names and their list of aliases. Returns ------- out_k...
ba99c25ad2afc190e48e512de6e08d3a51bd643b
648,975
import argparse def _get_params() -> tuple: """Get the paths to the files Returns: A tuple containing the two paths """ parser = argparse.ArgumentParser(description='Compares two image files by size and pixel value') parser.add_argument('first_file', type=argparse.FileType('r'), help='The...
83c5db37c082e60c82ac7ab25e42d4e6a0c6d979
648,978
import torch def save_checkpoint(model, optimizer, save_directory, lr=0.001, epochs=5, hidden_units=512, device='cpu'): """ Save the checkpoint :param model: trained model object :param optimizer: optimizer object :return: None; saves a file for the checkpoint """ ch...
57f9f91ad0df61c938956d7cda4f9a26f2cc50fe
648,979
def remove_cols_2(df): """ Migration function to extract only the specified columns in teh DataFrame """ cols_to_keep = [ 'location', 'target', 'type', 'quantile', 'forecast_date', 'target_end_date', 'value' ] return df.loc[:, cols_to_keep]...
1e670cc588e59613594d93ef38c83224229560c4
648,980
def get_traits_dict(): """Building dictionary with Traits names, paths to traits are being built at get_files_dict()""" traits_dict = dict([]) traits_dict['height'] = 'Height' traits_dict['diabetes_BMI_Adjusted']='Diabetes' traits_dict['diabetes_BMI_Unadjusted']='Diabetes' traits_dict['ADHD'] = ...
ca01f16d47758c36088dd63cf6bcf3c00b0543fb
648,982
import re def password_validation_check(pwd): """ checking password validation Args: pwd (str) : password string Return: True or False (boolean) : the result of checking validation """ # 비밀 번호 길이 확인 (6~12) if len(pwd) < 6 or len(pwd) > 12: print(pwd, '의 길이가 적당...
4407ad7214b7ca93f5633aa623e552abeb8e9a7a
648,983
from pathlib import Path import subprocess def ensure_notebooks(https_url, dst_folder): """ Download pre-rendered notebooks from a tar archive """ dst_folder = Path(dst_folder) if dst_folder.exists(): print(f"Found pre-rendered notebooks in {dst_folder}") return True print(f"...
cca83b77b22e83f63eb07fb6c7d9f9a8c928a50f
648,984
def alfa_for_file(alfa): """Generate standard name for angles. This is mainly used by the file_name function. @author: Pedro Leal """ alfa = '%.2f' % alfa inter, dec = alfa.split('.') inter_number = int(inter) inter = '%.2d' % inter_number if inter_number < 0: inter = 'n' +...
abace4de87c2248fe6c5644dd336c5948c558136
648,985
import re def rename_state_keys(state, keys_regex, replacement): """Rename keys from state that match a regex; replacement can use capture groups""" regex = re.compile(keys_regex) return { (k if not regex.findall(k) else regex.sub(replacement, k)): v for k, v in state.items() }
0ecd6353e31b927c16f365076acac6e67a44493d
648,986
def hsv_to_rgb(h, s, v): """Converts HSV value to RGB values Hue is in range 0-359 (degrees), value/saturation are in range 0-1 (float) Direct implementation of: http://en.wikipedia.org/wiki/HSL_and_HSV#Conversion_from_HSV_to_RGB """ h, s, v = [float(x) for x in (h, s, v)] hi = (h / 60) % ...
bb50f18b05b93e3990d32b63259aff0a7d05cd49
648,987
import sys import os from pathlib import Path def convert_path(path): """ Convert path to POSIX path Args: path(str): input path Returns: str: absolute path in POSIX format """ if not (sys.version_info.major < 3 and os.name == 'nt'): return Path(path).expanduser().res...
3b06909d4c0026f273c30f4f9519ffa482306d24
648,988
from typing import Tuple def check_class_number(class_number: str) -> Tuple[bool, str]: """ Check class number""" if int(class_number) < 1 or int(class_number) > 18: return False, "Le numéro de classe doit être compris entre 1 et 18" return True, ""
3c4da994f5d8e377e96501524a9703dee6dcdfbd
648,989
def load_sims(list_file): """ Parameters ---------- list_file : str Returns ------- dict {str : list of str} """ sims = {} with open(list_file) as f: sims_list = f.readlines() for line in sims_list: if line[0] != '#': sim_name, *p...
aff40e8ea3e1a077ef9ca70d55e675c278b1d3aa
648,990
import os def create_dir(path): """ Test whether a path exists, and create dirs in path (if not exist). :param path: path to check whether it exists or not. :return: boolean - True if path exists, or False """ try: if not os.path.exists(path): os.makedirs(path) retu...
5cae34544ec8397a9b990e9fdec9ad2921ee1886
648,991
def pascal_segmentation_lut(): """Return look-up table with number and correspondng class names for PASCAL VOC segmentation dataset. Two special classes are: 0 - background and 255 - ambigious region. All others are numerated from 1 to 20. Returns ------- classes_lut : dict look...
12314ac49c12b715fd23f58a1a47a118da380adc
648,992
import torch def get_sigma(rho: torch.Tensor) -> torch.Tensor: """transforms rho into variance sigma""" return torch.log(1.0 + torch.exp(rho))
e0b831ae2d67e706ef5368521d3d87d7a2eabf59
648,993
def siemens_t2star_to_r2star(t2star): """Mimics Siemens scanner inversion of t2star to r2star. Does not provide the correct value for a small segment of the colormap though. Parameters ---------- t2star : ndarray T2* map that has been loaded from a siemens dicom file. This map is expected ...
b10c53382780c298be83c5568441fe101e366ec0
648,994
def pad(string, max_len): """ add some leading spaces to string to bring it up to max_len. """ string = str(string) return " "*(max_len - len(string)) + string
85eba565deee01771018740f31f40440e035746c
648,995
import requests def validate_local_graylog_up(): """Test to see if a localhost instance of Graylog is currently running""" try: requests.get("http://127.0.0.1:9000/api") return True except Exception: return False
f8ce5cb348b1784e46c1b69d69bf3344acb892cf
648,996
def get_coverage_of_namespace(assembly, covered_lines, name_space, total_lines): """Get the coverage of a namespace.""" assembly_name = assembly["@Name"] assembly_covered_lines = assembly["@CoveredStatements"] assembly_total_lines = assembly["@TotalStatements"] if assembly_name.startswith(name_spac...
f250e5d6c3595043e8ed122532fe7a0b12cdfb97
648,997
def has_next_page(json_data): """Check for more labels.""" page_info = json_data.get("data").get( "repository").get("labels").get("pageInfo") if page_info.get("hasNextPage"): return True return False
460d34e77d3c54b7f5b97558a3b246f9d5483eb6
648,998
def get_grid_coordinates(imgnum,gridsize,w,h): """ given an image number in our sprite, map the coordinates to it in X,Y,W,H format""" y = (imgnum - 1)/gridsize x = (imgnum -1) - (y * gridsize) imgx = x * w imgy =y * h return "%s,%s,%s,%s" % (imgx,imgy,w,h)
48f1e22b06b1a03f15e89acf8e2c5bf893f42e9e
648,999
import argparse def parse_arguments(): """ Parse arguments from the commandline, that is, input and output file. """ parser = argparse.ArgumentParser( description="Calculates the longest increasing and " "decreasing substrings from a string provided as input file, and write the answer " ...
312976bbdf52696d14062f46b12548d0017e7ef9
649,000
def trans_attr(attr, lang): """ Returns the name of the translated attribute of the object <attribute>_<lang_iso_code>. For example: name_es (name attribute in Spanish) @param attr Attribute whose name will form the name translated attribute. @param lang ISO Language code that will be the suffix of the translated ...
d3abdc85cbcec8b8e97b4e7d754b4d82a4f23c73
649,001
import time def time_fn(lbd): """ Times an expression. If you need to time the operation: result = heavy_function() Then just write: result = time_fn(lambda : heavy_function()) """ start = time.time() res = lbd() end = time.time() print("TIME: %...
25e4da8b8fd7dcaaad1d774322c342d5fd4347ff
649,002
def begin(stacklogger): """Log the default begin message""" return stacklogger.log()
c934693d83c32715c73a44b440b8fbab55cea919
649,004
def _cell(row, col): """convert x,y to a cell address """ row = row+1 col_letter = chr(ord('A') + col) return f"{col_letter}{row}"
d819009a85161b357cb37a8ac23ec82f167d8330
649,005
def import_tmuxinator(session_config): """Return tmuxp config from a `tmuxinator`_ yaml config. .. _tmuxinator: https://github.com/aziz/tmuxinator Parameters ---------- session_config : dict python dict for session configuration. Returns ------- dict """ tmuxp_config ...
d240cc693d521ebbace8d38959567897c9efde75
649,006
import sys def getCommandPath(): """ GEt the first elem in the command path Or send the usage """ if len(sys.argv) > 1: return sys.argv[1] else: print("Usage : python3 createDoc.py [binary-path]") print("Example: python3 createDoc.py /usr/bin/qarnot") print(" ...
ee9cbf0c26e39ddac18f7c56138b750b29d69746
649,008
from typing import Dict from typing import Any from typing import Optional from typing import List def _bonds_peturbation( nbo: Dict[str, Any], index: int, poss_coord: Dict[Optional[int], List[Optional[int]]], energy_cutoff: float, metal_indices: List[int], ): """ Extract bonds from "pertu...
16d368221e23982268ef59375ac72175b4c9b098
649,009
import json def get_team_member(integration_context: dict, team_member_id: str) -> dict: """ Searches for a team member :param integration_context: Cached object to search for team member in :param team_member_id: Team member ID to search for :return: Found team member object """ team_memb...
8c552a006e5bd31f6f780b67662c601c7628021e
649,010
import struct def int2bytes(i): """ Convert int to bytes. :param i: 32 bit integer inside range -2147483648, 2147483647 :return: 4 bytes """ if not isinstance(i, int): raise TypeError("i must be int") return struct.pack("i", i)
56ac6d09ce065c0446555ce513e4508e0e3e6d94
649,012
def build_speechlet_response(output, card_title=None, card_content=None, reprompt='', should_end_session=True): """ Contructs ``response`` dictionary with the proper struture to allow Alexa to talk to the user. Optionally takes ``card_title`` and ``card_content`` to build ou...
875ff03bd6bd3e346bb7168591aaf8cd09a7496c
649,013
import collections import os def extra_json_serializer(obj): """ json module does not know to encode deque, PurePath,... """ if isinstance(obj, (collections.deque,)): return list(obj) elif hasattr(obj, "__fspath__"): # mainly for pathlib.PurePath return os.fspath(obj) elif hasattr(obj...
16d6a7b7a879dfe7d72d4804907a13aa5b95d3e3
649,014
from functools import reduce def sma_mothod(series, pos, window=5): """ :param series: 列向量 :param pos: 被插值的位置 :param window: 为取前后的数据个数 :return: """ y = series[list(range(pos - window, pos)) + list(range(pos + 1, pos + 1 + window))] # 取数 y = y[y.notnull()] return reduce(lambda a, b...
30ced1e1b8e2f83169c1fead82e857c532440332
649,015
def fib2(n, d): """ a much more efficient Fibonacci using dict (memoization) e.g. n=34 generates just 57 calls for fib2 vs. over 11 million for for fib! """ # global numFibCalls # numFibCalls += 1 if n in d: # if already computed, just look it up --- of course better using lru_cache ...
629711c2050366397ca6de35fd4deaee401a07ff
649,017
def get_file_content_type(extension): """ :param string extension: file extension :returns string: mime type based on file extension """ try: mime_types = { 'docx': 'application/vnd.openxmlformats-officedocument' '.wordprocessingml.document', 'xls...
a4932ae7f994e90198d27c6b6949794cc2742823
649,018