content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def first_where(L,val): """ First index of list L that equals val """ for pos,l in enumerate(L): if l == val: return pos return None
d7a5257d24a5ad2d7c0dc4609c8f972668f1bc28
629,897
def join_anchor_base_score(anchor_df, base_df): """Join anchor DataFrame with Base LFCs on anchor_guide Parameters ---------- anchor_df: DataFrame DataFrame with anchor and target guides base_df: DataFrame Base LFC DataFrame Returns ------- DataFrame """ joined_...
24a3ff90894f942c9ab07fe7e351999393ef9c5b
629,898
import json def parse_json(lines) -> dict: """ lines = list of strings containing json encoded data """ params = {k: [] for k in 'xyzuvw'} for line in lines: if line: try: p = json.loads(line) k = p['phasor'][:1] assert k in 'xyz' ...
62b2c22b06aefecb127e40a52e621b5b5e39053d
629,899
def configure_template_filters(app): """Configure custom Jinja2 template filters.""" @app.template_filter() def isnuc(x): return str(x).upper() in ["A", "C", "G", "T"]
ddbfea91424862683f8ee185d58756332b3b10aa
629,900
def _IsSuccessfulDmlOrDdlJob(printable_job_info): """Returns True iff the job is successful and is a DML/DDL query job.""" return ('Affected Rows' in printable_job_info or 'DDL Operation Performed' in printable_job_info)
6b03fb121213e35c7515c8d8e8c2c079dbe75f16
629,901
import re def sentences(text): """sentences. Args: text: """ # split sentences and questions. split with '.' and '?' ... text = re.split('[.?!]', text) clean_sent = [] for sent in text: clean_sent.append(sent) return clean_sent
2ec6f9a46b2d9c9032fd69fb78cc0767d1ddaf21
629,902
def non_repeat(line: str) -> str: """ the longest substring without repeating chars """ results = [] result = [] for i in range(len(line)): for c in line[i:]: if c not in result: result.append(c) else: results.append(''.join(res...
a6026d09ee133a737e14d24621854c3e54fb20a7
629,903
def get_group_users(conn, group): """List users in the group This function is not present in any way in OpenStackSDK """ users = [] data = conn._identity_client.get( '/groups/{group}/users'.format(group=group)) for user in data['users']: # Do we want to convert to proper User o...
37d7a24952098437063155b654dca0876307d007
629,904
def merge_sort(items): """ the merge sort algorithm takes in an unsorted list of numbers. returns a list in ascending order. Parameters ---------- items : list list of unordered numbers Returns ------- list list of elements in items in ascending order """ d...
d0c6f17378663c7feca8d217d08fdab37dfdcbb8
629,905
from tabulate import tabulate def list_to_html(data, has_header=True, table_format=None): """ Convenience function to convert tables to html for attaching as message text. :param data: Table data :type data: list of lists :param has_header: Flag whether data contains a header in the first row. ...
3b136afb9703758dec30aa6f8a6dab74ef491d86
629,906
import re def _find_and_replace_fields(text, field_mapping): """Perform a find and replace for field names in a json definition. Keyword arguments: text - The json to search and replace fields names field_mapping - A dictionary containing the pairs of original field names and new field names""" ...
d9f1dbccec8021bd1b84758f41012a343409f8f5
629,907
def get_from_key(item, key, reduced_key=None, delimiter="."): """ nice little tool to aid in flexibility when dealing with multilayer dicts. """ if type(item) is not dict: return item try: return item[key] except KeyError: if reduced_key is None: reduced_key =...
8512054e75548a68cf9040255a3270e6d62f0352
629,908
import typing import os def _get_builtin(filename: str) -> typing.Optional[str]: """ Get a builtin template """ builtin_file = os.path.join(os.path.dirname(__file__), 'default_template', filename) if os.path.isfile(builtin_file): with open(builtin_file, 'r', encoding='utf-8') as file: ...
352789376e5d75075fcfe2bf7dfc727cea30c6ad
629,911
def seconds_to_minutes(seconds): """ Returns a number of seconds formatted as minutes:seconds. """ return '{}:{:0>2}'.format(int(seconds / 60), seconds % 60)
f1a237db1dc58f64c608504c341731cb77cdbc2a
629,912
def has_no_e( word ): """Retruns True if the given word have no 'e', False otherwise. """ for i in word: if i == 'e': return False return True
41f44bd79119405b697406c08e036f6caf851d5b
629,913
import re def open_log(fn="SPOCK/spock_output_e1.log"): """Open P10 experimental log file.""" if not fn.endswith(".log"): raise ValueError(f"file {fn} is not a regular .log file") with open(fn, encoding="utf-8") as file: rows = file.readlines() list1 = [] list2 = [] my_regions ...
8fddbac1ed3741e46db10fbddf90ffa457476418
629,915
from typing import List import torch def make_task_gradients( grad_type: str, num_steps: int, num_tasks: int, num_layers: int, region_sizes: List[int], ) -> torch.Tensor: """ Construct dummy task gradients. """ # Generate gradients. max_layer_size = max(region_sizes) if grad_type ...
2aac6c2f0246ea2f5b1654a65af7317b794ab01b
629,916
def get_materials_dict(lm): """Build the list of coordinates corresponding to each material""" d = {} for x in range(lm.nx): for y in range(lm.ny): mat = lm.cells[x][y].material.name.lower() if mat in d: d[mat].append((x,y)) else: d...
1ab43d42c5af23cc0a609ba9b4de1c76a6eb1df1
629,917
def cria_copia_posicao (pos): """Esta funcao cria uma copia da posicao dada como argumento""" return pos.copy()
83ab4425d27dd0396c4c4f29033bf2fc5d55132f
629,918
def return_index_name(collection_name, doc_type_str, sep="__"): """Return formatted index string""" index_name = f"{collection_name}{sep}{doc_type_str}".lower() return index_name
e1d5dd8bc1dbcf767a6b163899c20ae9b5545af1
629,919
def toplevel_scope_maps(graph, maps, scope_dict = None): """ returns the toplevel scope of a set of given maps """ if not scope_dict: scope_dict = graph.scope_dict() scopes = set() for map in maps: scopes.add(scope_dict[map]) for scope in scopes: current_scope = scope...
7c7e3a1b43b7c38085d28a43dede81e72b90b1e1
629,920
import os def package_files(directory): """package up files. from stackoverflow.com how-to-add-package-data-recursively-in-python-setup-py""" paths = [] for (path, directories, filenames) in os.walk(directory): for filename in filenames: paths.append(os.path.join('..', path, filen...
a5ad6ea508059eea18a2114f1af4ffe242820c9b
629,921
from typing import Counter def compare(s, t): """ # Compare content of two (unordered lists) # https://stackoverflow.com/questions/7828867/how-to-efficiently-compare-two-unordered-lists-not-sets-in-python """ return Counter(s) == Counter(t)
35430896daea635af556c60da0ae654422873814
629,922
import yaml import os def read_parameters(yaml_file): """ function to read YAML parameter file and define output destinations """ with open(yaml_file, 'r') as f: params = yaml.safe_load(f) # record file params RECORD_FOLDER = params['records']['filepath'] parse_type = params['parse...
5679ef981d68053723ccf76ff8b67c0b8237d63c
629,923
import argparse def get_subjective_ranking_options(arguments): """ Command line arguments for the subjective.py script that can be used to obtain subjective opinion scores for image quality. """ parser = argparse.ArgumentParser( description="Command line arguments for the " "subjec...
b1ff103cd313f26d1e8e478ef9f6b0209d1f86f8
629,924
def cTA(H, DIC, BT, TP, TSi, TS, TF, Ks, mode="multi"): """ Calculate Alkalinity. H is on Total scale. Returns ------- If mode == 'multi' returns TA, CAlk, PAlk, SiAlk, OH else: returns TA """ # negative Denom = H ** 2 + Ks.K1 * H + Ks.K1 * Ks.K2 CAlk = DIC * Ks.K1 * (H + 2 * Ks...
3af5a082f2082274c43a70a224df7a999853eeb7
629,926
def unf_pb_Standing_MPaa(rsb_m3m3, gamma_oil=0.86, gamma_gas=0.6, t_K=350): """ bubble point pressure calculation according to Standing (1947) correlation :param rsb_m3m3: solution ration at bubble point, must be given, m3/m3 :param gamma_oil: specific oil density (by water) :param gamma_gas: s...
d8ac0830699cc8c85a0998c8576f32c484234152
629,927
def process_somaticsniper_vcf(job, somaticsniper_vcf, work_dir, univ_options): """ Process the SomaticSniper vcf for accepted calls. Since the calls are pre-filtered, we just obtain the file from the file store and return it. :param toil.fileStore.FileID somaticsniper_vcf: fsID for a SomaticSniper gen...
9273fbb330be8da05eb52ed281eed97528ed56f3
629,928
import typing def _find_model_index(html: str) -> typing.Tuple[int, int]: """Find start and end index of model in html :raises ValueError on missing model start :raises ValueError on missing model end :raises ValueError no None model""" if html is None: raise ValueError('...
6270c8f8913e107e444a0dda114c2bd1b4595a74
629,929
from textwrap import dedent def dedent_pairs(pairs): """Dedent the `pairs`'s `text` part """ pairs = list(pairs) # Using textwrap.dedent on this requires a few lines of hackery. types = [ty for ty, _line in pairs] dedented_lines = dedent(''.join(line + '\n' for ty, line in pairs)).splitlines(...
d18cb3676f19d411ddcdc8bf45209f6e57c1ba4b
629,930
def color_text(r, g, b, text): """构造有颜色的文本 :param r: 红色通道 :param g: 绿色通道 :param b: 蓝色通道 :param text: """ return "\033[48;2;{};{};{}m{}".format(r, g, b, text)
0e014415c05d5bba95bbf3d254beb142c83674d6
629,931
def get_gradient_norm2(m): """ Computes the L2 Norm :param m: the model :return: the total norm for the model parameters """ total_norm = 0 for p in m.parameters(): param_norm = p.grad.data.norm(2) total_norm += param_norm.item() ** 2 total_norm = total_norm ** (1. / 2) ...
cffb5f7c9fd2c54af9bb5ad6a6903c396f7ac2f4
629,932
def _split_divisible(num, num_ways, divisible_by=8): """Evenly splits num, num_ways so each piece is a multiple of divisible_by.""" assert num % divisible_by == 0 assert num / num_ways >= divisible_by # Note: want to round down, we adjust each split to match the total. base = num // num_ways // divisible_by *...
bfa7dce06054325e50ecca644ad085a3eec1e0b3
629,933
def array_split(ary,n): """ >>> data = [1,2,3,4,5] >>> array_split(data,3) [[1, 2], [3, 4], [5]] >>> grps = array_split(range(0,1121),8) >>> total_len = 0 >>> for grp in grps: total_len += len(grp) >>> assert(total_len == len(range(0,1121))) """ step = int(round(len(ary)/float(n)...
a36bb14778ba9b3ed8a2bd77990ad6baf0d14271
629,934
def NMB(obs, mod, axis=None): """ Normalized Mean Bias (%)""" return (mod - obs).sum(axis=axis) / obs.sum(axis=axis) * 100.
bc53562cc43a71424ad6e9255264b58050eff661
629,935
from pathlib import Path import os def create_relative_file_path(file_path, root_dir, root_prefix=''): """ Return a subpath of `file_path` that is relative to `root_dir` >>> file_path = '/home/test/example/foo.txt' >>> root_dir = '/home/test/' >>> create_relative_file_path(file_path, root_dir) ...
9a727ec6aff26a0438e2564effacaf1df1c1aacd
629,936
def objdict_to_dict(objdict): """ Convert an objdict structure into a dict structure Args: obj (objdict): the objdict to convert Returns: dict: the objdict as standard dictionnary """ d = {} if objdict: for k, v in objdict.items(): if type(v) == dict: ...
11e0cbe6e208e69742822fcf643a19975b431330
629,937
import argparse import typing import pathlib def _initialize_script_path(args: argparse.Namespace) -> typing.Optional[pathlib.Path]: """Initialize the output script if it exists.""" if not args.script_path: return None p = pathlib.Path(args.script_path).resolve() p.write_text('#!/bin/sh\nexpo...
bff8f812f8e7c99610ebe44c642af0cba9098222
629,939
def type_check(name, correct_type): """ decorator function for checking correctness of input type name: attribute name --> str correct_type: correct_type of name attribute --> type Procedure: 1. call type_check first,return prop setter,and convert name to private attribute. Store private_name &...
7c04f60484e63aedebec6346cb4a10e676ae5514
629,941
import string def safestring(unsafe): """Returns a 'safe' version of the given string. All non ascii chars and other chars are removed """ valid_chars = "_%s%s" % (string.ascii_letters, string.digits) return ''.join(c for c in unsafe if c in valid_chars)
332e61f27be30d7b5029d23317e5befc0c520392
629,942
import os def map_files(files): """Maps a list of files to basename -> path.""" output = {} for f in files: #pylint: disable=invalid-name basename = os.path.splitext(os.path.basename(f))[0] output[basename] = f return output
88853560ea42e35ccebb2e8767f81f24eae5cb4a
629,943
def clip_json_parameter_lists(spllo,splhi,cini,nWaves=2): """ Clip negative valus for non-negative parameters """ non_negative_state_ind = [] for i in range(nWaves): non_negative_state_ind += [1+4*i,2+4*i,3+4*i] for ind in non_negative_state_ind: spllo[ind] = max(spllo[ind]...
0df4f81279ac9ec2f85b82bcbf4a7bdba95f22d0
629,944
def _str(uni): """ Make inbound a string Encoding to utf-8 if needed """ try: return str(uni) except: return uni.encode('utf-8')
e341073a69319b8f8ffb86bd13371d7b57921714
629,945
def frames_to_get_hit(in_frame,game,player_ports,prev_frame_hits=[None,None,None,None],max_len=300): #notice that the other way around is useful to know when they land a hit """ in_frame int current frame we are analyzing game Slippi Game prev_frame_hits int array if in_frame is not 0 we will tak...
2ae3e2a0afe9e640fbf5f5f6283fcc9cced245ef
629,946
def encode_message(message): """ 命令编码 """ message = message.encode("utf-8") return message
67b61410b4e5b2d4c9bae06ae12de6e4312191f6
629,947
import os import torch def read_checkpoint(F, D, file_to_load, device): """ Loads network paramteres and training logs. """ assert os.path.isfile(file_to_load) if device == torch.device('cpu'): checkpoint = torch.load(file_to_load, map_location='cpu') else: checkpoint = torch...
d0d6035b44cdc9425cc53be08fd13f9562a64922
629,948
import os import uuid def make_upload_path(instance, filename): """ Create path for image. :param instance: :param filename: :return: """ extension = filename.split('.')[-1] return os.path.join(instance.upload_dir, u'{0}.{1}'.format(uuid.uuid4(), extension))
67c8ee7f2201d13d523f2545e0bac33d4597f86a
629,949
import re def raw_line_formatter(raw_line:str): """ Convers raw line into a tuple (name, year, location) >>> raw_line_formatter('"#15SecondScare" (2015) {Its Me Jessica (#1.5)}\tCoventry, West Midlands, England, UK') ('"#15SecondScare"', 2015, 'Coventry, West Midlands, England, UK') """ line_l...
0f1e71ded02f3bbbde0cd8e94f9a377f2f6e4e5d
629,950
from typing import List from typing import Tuple def is_location_combination_same_country( owm_locations: List[Tuple[int, str, str]] ) -> bool: """ Checks to see if the list of owm_locations is the same combination of city,country pairs only distinguishable by place_id integers """ if len(owm...
d1e90a985799f63e94f0e944c186efffc703f63c
629,951
def create_query(keyword, start_date, end_date, max_results) -> dict: """ Creates the params part in the GET request Parameters ---------- keyword : str The key word/words that you want to be included in your search start_date : str The start of the time period that you would li...
029aabdd2f972406237266edf2d7f5bad25bfc9d
629,952
def my_decorator(f): """ A simple decorator to apply timing """ def method(): f() return method
6f71245627e05778711e6b3e47b8650de75181e6
629,953
def clean_text(identifica, ementa, fulltext): """ Given a DOU article titles `identifica` and an abstract `ementa`, remove the first title in `identifica`, `ementa` and the hard-coded footnote from the full text of the DOU article `fulltext`. """ # ATTENTION: this code should reproduce the clea...
06d3b3db514dfa9a410ba22d7c5585fb42752e16
629,954
def is_basestring(s): """Return True for any string type (for str/unicode on Py2 and bytes/str on Py3).""" return isinstance(s, (str, bytes))
f1fa4f9a755a47aadda35e788ce8f511b1d1412d
629,956
def _hc2rgb1(h, c): """ Takes the hue and chroma and returns the helper rgb1. Parameters ---------- h float The hue in degrees c float The chroma in [0, 1] """ try: h = float(h) c = float(c) except ValueError: raise ValueError("h (%s) and c (%s) must be (convertible to) floats" % (str(h), str(c)...
62439e5cb6baee1673b2fb48b6f09a70bd8f894c
629,957
def all_lines(diff_filter): """Handles filters that operate by comparing inserted lines with removed lines. Args: diff_filter ([function]): [A filter that takes a list of inserted lines and a list of removed lines and returns tru...
4feefc3eec24a1163be1a1391da0d70a5c8dd4fe
629,958
def maxSubArray(self, nums): """ :type nums: List[int] :rtype: int """ max_current = nums[0] max_so_far = nums[0] for i in range(1, len(nums)): max_current = max(nums[i], max_current + nums[i]) max_so_far = max(max_current, max_so_far) return max_so_far
af3a304ff0060967de63688b23e12f7c414f12d2
629,959
def best_period(periods,pulses): """ Find the best period for these data and the summed pulse. """ imax = pulses.argmax()/pulses.shape[1] return imax,pulses[imax]
8bf2743b29180591bc8a388e5d2c02d773cfe30d
629,960
def is_segment_tokenized(segment): """Return True, iff the segment is already tokenized. Examples -------- >>> s = ('<segment id="1"><sign pos="ART">Die</sign>' ... '<sign pos="NN">Antwort</sign></segment>') >>> is_segment_tokenized(seg) True >>> seg = etree.fromstring('<segment i...
62e1dd16945fb1fc5d0fa8754dc51373bca43640
629,962
def getFixtures(method): """Return a methods fixtures""" method_name = method.__name__ inst = method.__self__ if hasattr(inst, '_' + method_name): method = getattr(inst, '_' + method_name) return getattr(method, '_fixtures', [])
8232c2363bfc48db80204af8de14e0f63a71f00e
629,963
def int_to_mask(mask_int): """ Convert int to mask Args: mask_int ('int'): prefix length is convert to mask Returns: mask value """ bin_arr = ["0" for i in range(32)] for i in range(int(mask_int)): bin_arr[i] = "1" tmpmask = ["".join(bin_arr[i * ...
fd1ae66b10552f163e9ab152c3679fb903a6ddd6
629,964
import torch def _coordinate_grid(dims, align_corners=False): """ Creates a homogenous coordinate system. Args: dims (Tuple[int*]): height / width or depth / height / width align_corners (bool): returns a grid where the left and right corners assigned to the extre...
dba819955dfce059077d1836dcf1255c8cdd5ea1
629,965
def str_to_orientation(value, reversed_horizontal=False, reversed_vertical=False): """Tries to interpret a string as an orientation value. The following basic values are understood: ``left-right``, ``bottom-top``, ``right-left``, ``top-bottom``. Possible aliases are: - ``horizontal``, ``horiz``, ``h...
359e3fb09a70027160b942a13da0fc6686f059f9
629,966
def set_even(number): """Utility method: ensures number is even by adding. Args: number - number to make even Returns: number - even number """ if number % 2 != 0: number += 1 return number
89749315578f05098e9df458cccb373dc419fedc
629,967
def is_valid_pid(value: str) -> bool: """ Return if value is a valid pid (passport id). Parameter --------- value: str a pid. Return ------ bool True if pid is valid, False othewise. """ return len(value) == 9 and all((char.isdigit()) for char in value)
acf8511922dc4efc73724f69c74edb0035066bcd
629,971
def swap_columns(df, col1, col2): """Swaps the two given columns of the DataFrame.""" col_list = list(df.columns) a, b = col_list.index(col1), col_list.index(col2) col_list[b], col_list[a] = col_list[a], col_list[b] return df[col_list]
615f43515d52e4f6ff5f1851c54f4bd9ba6cabdb
629,972
def is_value_1(for_): """check if for_["value"] == 1""" v = for_.get("value", None) return v == 1
a707f0e9490dfcd890818a193b0f4d9a401172b7
629,973
def find_first_list_element_above(a_list, value): """ Simple method to return the index of the first element of a list that is greater than a specified value. Args: a_list: List of floats value: The value that the element must be greater than """ if max(a_list) <= value: Val...
475b290bbd4b84d34528c69a6763c935af27d712
629,974
def scale(value): """Scale an value from 0-65535 (AnalogIn range) to 0-255 (RGB range)""" return int(value / 65535 * 255)
2c0601234648047b7ea28c691e5cfd8871aebea4
629,975
def date_to_iso8601(date): """Converts a date to an ISO 8601 date""" return '%s-%02d-%02d' % (date.year, date.month, date.day)
402ac680afaec9a1c9f163a737a838b61d1a9d25
629,976
def depth(data): """ Get the depth of a dictionary Args: data: data in dictionary type Returns: the depth of a dictionary """ if isinstance(data, dict): return 1 + (max(map(depth, data.values())) if data else 0) return 0
eee917ab77f35c10ca4f01cbc78f1bc8493fede7
629,977
from datetime import datetime def get_first_last_ts(data): """ Retrieves datetime objects for first and last timestamps in data structure for partitioning :param data: data structure :type data: numpy.ndarray """ first_ts = datetime(int(data['year'][0]), int(data['month'][0]), int(data['day']...
bee9f8f262598b3435ad4bc75a0293f28fd2dbfb
629,978
import pickle def load_obj(name: str): """Load object as a pickle file to a given path.""" with open(f'{name}.pkl', 'rb') as f: return pickle.load(f)
dccb41bb9afcca9bf0ec455520d47dc2ff37d987
629,979
def sst_freeze_check(insst, sst_uncertainty=0.0, freezing_point=-1.80, n_sigma=2.0): """ Compare an input SST to see if it is above freezing. :param insst: the input SST :param sst_uncertainty: the uncertainty in the SST value, defaults to zero :param freezing_point: the freezing point of the w...
c265c7de53bd9d2376a386723a81ca90c11f9b17
629,980
import time def timeit(do=True, name=""): """ Decorator to print the time that the function has taken to execute. """ def inner0(function): if not do: return function def inner(*args, **kw): start = time.time() val = function(*args, **kw) end = time....
77b44e5657d98cfb5f48c5a28025823983d7ff8f
629,981
import sys import getpass def prompt_for_password(): """Prompt user for password if not provided so the password doesn't show up in the bash history. """ if not (hasattr(sys.stdin, 'isatty') and sys.stdin.isatty()): # nothing to do return while True: try: new_p...
b974d4964e400ef1065842e609f788794346d02a
629,982
import struct def convert_from_binary(data_type, dat): """Deserialization from simple serialization""" if data_type == 0: return dat elif data_type == 1: return int.from_bytes(dat, "big") elif data_type == 2: val = int.from_bytes(dat, "little") if val == 1: ...
8148e85eaab023d47281d9b4b6da89c41bbf3532
629,983
def gmail_timestamp_to_epoch_seconds(epoch_time_ms: int) -> int: """ Convert GMail `internalDate` into epoch time in seconds. Arguments: epoch_time_ms {int} -- the GMail `internalDate` epoch time which is in milliseconds. Returns: int -- epoch time in seconds """ epoch_time_sec...
d9a3bc4ab6ea41f4c627ae606ceaa19a0d2c5433
629,984
import random import string def create_secret_key(): """ Randomly create the secret key for the settings file """ secret_key = list((string.ascii_letters + string.digits + string.punctuation).replace("\\", "") .replace("'", '"').replace("{", "_").replace("}...
babb556fe7ab78b82fcb33a677864768481b2a6b
629,985
def extract_box_types(df, gb_boxes): """Define a column reporting the mode of the boxes delivered to the customer in the specified time period, in terms of box type.""" prods_by_sub = gb_boxes['product'] mode_ratios = (prods_by_sub.value_counts()/prods_by_sub.count()).unstack().max(axis=1) fav_products = gb_boxes['...
1245064b431874232fed6b487bb178a243f27d46
629,986
def derivative_polynomial_latitude(lon_norm, lat_norm, alt_norm, coeff): """ Compute latitude derivative polynomial equation :param lon_norm: Normalized longitude position :type lon_norm: float 64 :param lat_norm: Normalized latitude position :type lat_norm: float 64 :param alt_norm: Normal...
de8c9811a882e39ce1a7d0c039d03ebead8de2a6
629,987
from io import StringIO import contextlib def format_check(file_or_dir): """Perform format and return True if changes were made (False otherwise).""" capture = StringIO() with contextlib.redirect_stderr(capture): format(file_or_dir) output = capture.getvalue() made_changes = any(["file ref...
c3e17c4c45ca05ee2a67614d444b89a1fbd4c489
629,988
def compare(lhs, rhs): """Implements cmp() for Python 2 and 3 alike""" if lhs == None: if rhs == None: return 0 else: return -1 else: if rhs == None: return 1 else: return (lhs > rhs) - (lhs < rhs)
d56c7d8b57512af657b74f56db6c5e3ea233457f
629,989
from typing import Iterable import functools import operator def _prod(vs: Iterable[float]) -> float: """Product function.""" return functools.reduce(operator.mul, vs, 1)
a5339920abe99d190579e06102e1ae6831380093
629,990
def get_bar_height(values): """Get the height of the bar, given a Numpy array of Y coordinates. By default, this is a simple mean, but feel free to modify it as needed. """ return sum(values) / len(values)
5c0c711169a39ebdd4ec43feb73f9383f54db4e5
629,991
def sizeof_fmt(size, binary=True, separator=' ', suffix='B', digits=2): """ takes a *size* (in bytes) and convert it in a human readable format. :param size: size in bytes :param digits: amount of decimals for any number :param binary: `True` for binary (:math:`2^x`) or `False` for decimal (:math:`...
e98f4783e85388a7695e5a8b5d527b1cb63cdd66
629,992
import subprocess def check_java_version(): """ Check the java (JRE) and javac (JDK) version on the system. :param: None :returns: java (JRE) and javac (JDK) version on the system. :raises: None """ java_version = subprocess.check_output(['java', '-version'], stderr=subprocess.STDOUT) ...
333c625b33d679c05a796c7be34f96d472c8e35c
629,993
def make_id(problem): """Convert problem description in to human-readable id.""" key_value_strs = [] for key, value in problem.items(): if key == "input_fn": key_value_strs.append(f"input_shape={value().shape}") else: key_value_strs.append(f"{key}={value}") retu...
58de0c3e6d3e7fccac5327419e97ae2299ae5656
629,994
def sort_numbers(nums): """ Sorts an array of numbers. :param nums: array of integers. :return: sorted array. """ if nums: return sorted(nums) return []
2c3785cddc275f8d1cf5f66e0ef95e1f8841a8cc
629,995
from typing import Optional import torch def regulate_len(durations, enc_out, pace: float = 1.0, mel_max_len: Optional[int] = None): """If target=None, then predicted durations are applied""" reps = torch.round(durations.float() / pace).long() dec_lens = reps.sum(dim=1) max_len = dec...
82b37680960e4614a9d654b9450303343e5fa010
629,996
def compute_diffs(df_dict, df_str, gridclimname1, gridclimname2, prefix1, prefix2='meanmonth', comp_dict=None): """ Compute difference between monthly means (e.g,. Temp) for two different gridded datasets (e.g., Liv, WRF) """ if isinstance(comp_dict, type(None)): comp_dict={} ...
fad821939e9ee3d3039984b5385a7fe9399d57d9
629,997
def split_array_half(array): """ Splits an array like object in half, into two arrays. If of an odd length, the first half will be larger by 1. :param array: array like object to be split in half :return: Two arrays (first_half and second_half) """ midpoint = len(array) // 2 first_half ...
8d69e738b51740966bb35b45cc502129d0e5548d
629,998
def compute_sv_offset(frequency, pulse_length): """ A correction must be made to compensate for the effects of the finite response times of both the receiving and transmitting parts of the instrument. The magnitude of the correction will depend on the length of the transmitted pulse, and the response ...
d853e546df1524c7b9fddf1a8ac6d8a7072933c3
629,999
def clean_stix_data(data): """ Clean stix data from unwanted characters """ return data.replace("\n", "")\ .replace("{", "{{")\ .replace("}", "}}")\ .replace("”","\"")\ .replace("“","\"")
0f2a73012e25b103f24292a1722f11139217657a
630,000
def contains_no_complete_reductions(reductions): """Checks whether reductions contains a reduction with the empty word.""" for reduction in reductions: if reduction[-1] == "": return False return True
7fc3b6f032762d238861839d2b10ca9873ee0884
630,001
def overrides(interface_class): """ This is a method decorator that can be used to ensure/document that a method overrides a method in a superclass.""" def overrider(method): assert(method.__name__ in dir(interface_class)) return method return overrider
ad62fc1d5628a1feab3c2c2dcfe6956bc8f8ab63
630,002
def amino_acid_collection(fn): """get the list of the amino acids from the file""" ret = {} # fn = os.path.join(os.path.dirname(os.path.abspath( __file__ )), fn) fp = open(fn) for line in fp.readlines(): line = line.rstrip() if line.startswith("#") or len(line) == 0: cont...
9472f053e48947079fb5a461658d23d18dc885bf
630,003
from numpy import cos, deg2rad, sin def earth_radius(lat): """Calculate the radius of the earth for a given latitude Args: lat (array, float): latitude value (-90 : 90) Returns: array: radius in metres """ lat = deg2rad(lat) a = 6378137 b = 6356752 r = ( ((a ...
f459109842a4b535b093d44f0c81d0e3334fd75a
630,006
from datetime import datetime def date_to_unix_time(date) : """ Convert the timestamps of powershell in unix timestamp""" if date[-2:] == "PM" : split_date = date.split(" ")[:-1] split_hour = split_date[1].split(":") if split_hour[0] != "12" : split_hour[0] = str(int(split_hour[0])...
cf832acd8b28d32a4bbc0050aaf04dcee452b074
630,007
import pandas def export_to_pandas(pipe, dst, **kwargs): """ Basic example how to export into Pandas DataFrame Custom params for "read_csv" may be passed in **kwargs """ return pandas.read_csv(pipe, skip_blank_lines=False, **kwargs)
46005414e5b3a3905e5c431841dd375c5f71ee65
630,008
def get_request_attribute(form_data, key, default=''): """ """ if key not in form_data: return '' return form_data[key]
73333fd9a13a94237f50abf0b15edd9acfed0c62
630,009