content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import re def _ls_file_and_folder_filter(file_path_list: list, parent_path: str): """ Args: file_path_list: file_name list including parent_path parent_path: filter only specified parent_path Returns: file list Examples: >>> file_path_list = [ "file1....
9ea841795b08becad4aa5c1bd16308fde5f70a55
638,447
def getDayOfMonth(date): """Extracts the day of the month from a date. The first day of the month is day 1. Args: date (Date): The date to use. Returns: int: An integer that is representative of the extracted value. """ return date.day
53d890d032be2acfea014212df6e8f0ca4eba5f9
638,448
import csv def into_dict(fIn,delimiter=","): """ Read data from file into a dictionary. By default first element of each row is assigned to the key and the second element is assigned to the value. Parameters ---------- fIn : str Path to input file delimeter : str (optional) ...
b73b5ffbf3fae1a16159f06336ff2aca22f0983e
638,449
def _parse_percent(perc): """Parse percentile""" return float(perc[:-1]) / 100
43933e8e9a64c8d43d35dd72c590c4e7fabfa455
638,450
def _escapeArg(arg): """Escape the given command line argument for the shell.""" #XXX There is a probably more that we should escape here. return arg.replace('"', r'\"')
0b1b125edfb21a95f97e6a20a33691d0ad8d16e3
638,451
def arrayPairSum(self, nums): """ :type nums: List[int] :rtype: int """ nums.sort() return sum(nums[::2])
32bf0e9cff7ee2508b3217c23033e349f89971c8
638,453
def build_tx_req(ProposalResponses): """Check the endorsements from peers :param reponses: ProposalResponse from endorsers :param ProposalResponses: :return: an instance of TXRequest """ class TXRequest(object): def __init__(self, responses, proposal, header): self._respon...
8700a3cb6ded6b3047ce47b0e921aa143c819133
638,454
from operator import contains def does_not_contain(path, data): """Return False if data is present in file path""" return not contains(path, data)
74ca9731a4ff3418bb2e1bd8618109bc5f1fb431
638,455
from typing import Tuple import math def get_tires_w(lg, wg, w_in, v) -> Tuple[float, float]: """ Calculate the number of tires needed to fit the width of the vehicle :param l: length of the vehicle(cm) :param wg: width of the vehicle(cm) :param w_in: radius of the tire :param v: speed of the ...
39bdf852b8a453cb90a77c25ef27b855327b0982
638,456
def is_valid_name(name): """Checks that GitHub user's name is valid""" return name and len(name) >= 3 and ' ' in name
7197c0d420cfcd59eb68337e0933c02f00e9f801
638,457
def adjust_df(df, tsize): """ check if df hasthe correct size, so if the value of the day were recorded every 5 seconds, otherwise adjust it """ dsize = tsize - df.size if dsize == 0: pass else: if dsize > 0: df_tail = df.tail(dsize) df = df.append(df_...
b938e5c110acb4f8fe971b589f450af22c68635e
638,459
def build_call(*args): """ Create a URL for a request to the OEC API. Args: *args (str): strings to be appended to the API call. Returns: str: url for the API request. """ call_url = 'https://legacy.oec.world/' for val in args: call_url += str(val) + '/' return ...
72e305bbb598d7d6ceec60e825363647dfc56bfb
638,460
def pack_words(raw): """3 raw bytes to 2 encoded bytes stuffing for datamatrix text modes.""" if len(raw) % 3 != 0: raise ValueError('Length of "raw" must be integer multiple of 3') enc = [] while len(raw) > 0: word = ((raw.pop(0) * 40**2) + (raw.pop(0) * 40**1) + ...
9c8812251725c3bcc519ac6a4079b315da8bbb90
638,461
def get_json(nifti_path): """ Get associated JSON of input file """ return nifti_path.replace(".nii.gz", ".json").replace(".nii", ".json")
8afa8ff9e5fcceeacfe4fadaee03589fc1edfc81
638,463
def catch(data): """ Used to skip over any encoding errors when using LC for creation of titles and selftext lists """ try: print(data) return data except UnicodeEncodeError as e: print("\n\n\nYOU'VE HIT THE CATCH!!\n") return 'trash'
a0d8221a08230552b821e49e0129808082173251
638,466
def beautifyName(person): """remove domain prefix like mydomain\\user""" person = person.lower() if '\\' in person: person = person.split('\\')[1] return person
81eaf3aa0746c2b7756547600c3502e7e0176dcb
638,467
def add_score_line(line: str, value: str) -> str: """ String formatting for scoreboard sidebar :param line: score text :param value: score :return: str - formatted score """ base_str = f"{line}{value}".center(20) return_str = '┃' + base_str[1:-1] + '┃' return return_str
7825fc206a9ca57a5c657ca182f21aaf1c4ef87d
638,468
def conjugate3(infinitive): """ >>> conjugate3('sy') ('sy', ('sy', 'syr', 'sydde', 'sytt')) """ stem = infinitive present = stem + "r" preterite = stem + "dde" supine = stem + "tt" return stem, (infinitive, present, preterite, supine)
8d6124346680fc4017df90a9833fd2043ed23cd4
638,469
def split_data(test_size, df): """ Split data into training and testing sets INPUT: test_size - size of testing data in ratio (default = 0.2) df - cleaned and processed dataframe OUTPUT: train - training data set test - testing data set """ test_size = test_size training_si...
cea724ab0d2a1808c93d8b3beae8d81e0485ebd3
638,470
def augment_segmentation_map(self, segmentation_map, hooks=None): """ Augment a single segmentation map. Parameters ---------- segmentation_map : (H,W,C) ndarray or (H,W) ndarray The segmentation map to augment. Expected dtypes are integer-likes, e.g. int32. hooks : None or ia....
af0961f56a12bab724fdb6bfee1d83dfb46176dc
638,471
def seabed2aliased(seabed, rlog, tpi, f, c=1500, rmax={18:7000, 38:2800, 70:1100, 120:850, 200:550}): """ Estimate aliased seabed range, given the true seabed range. The answer will be 'None' if true seabed occurs within the logging range or if it's beyond the detection limit of the...
1bbdcabda760fe99b7d0c8d8fa6ff9b9bfdc8af5
638,472
def unchanged_shape_with_rank_at_most(rank): """Returns a shape function for ops that constrain the rank of their input. Args: rank: An upper bound on the rank of the input and output. Returns: A shape function for ops that output a tensor of the same size as their input, with a particular rank. "...
a9386cb02e2ea45c107b60a4f2e616aad0e5bb1d
638,473
import math def lcm(a, b): """ Calculate and return lowest common multiple for a and b """ return abs(a*b) // math.gcd(a, b)
a299301b5b046ded49b069fadf315b856c630c99
638,474
def get_unique_name(obj): """ Creates a unique name (hopefully) of producer and product. """ return obj['producer'].lower() + "_" + obj['product'].lower().replace('/', ' ')
0ec40aa0f4e60eba4c1c4b0c0886352ef6ce5bfa
638,475
import json import random import copy def place_pairs_ltpFR3(pairs, cond): """ :param pairs: :param cond: :param config: :return: """ # Load all valid list compositions for 12-item lists (small lists are too restrictive to use trial and error) with open('valid12.json', 'r') as f: ...
eb4f3d2d131451f837657637b86102c1f16d4a23
638,476
import hashlib def hash_sha256(b): """ Args: b (:class:`bytes` or :class:`str`): sequence to be hashed Returns: :class:`bytes`: sha256 hash """ return hashlib.sha256( b if isinstance(b, bytes) else b.encode('utf-8') ).digest()
0a816055069971d6ea1d3f0e698e4e789861abc8
638,477
import os import pandas import numpy import math def load_UCR_dataset(path, dataset): """ Loads the UCR dataset given in input in numpy arrays. @param path Path where the UCR dataset is located. @param dataset Name of the UCR dataset. @return Quadruplet containing the training set, the correspon...
6ca991fb6381ea45145d48a0563042efec8a39fc
638,478
import time def format_localtime(fmt="%Y%m%d%H%M%S"): """ 转换当前时间为指定格式 """ t = time.strftime(fmt, time.localtime()) return t
8f134eb2388a523d757142a696ada5ed00171113
638,479
def extended_euclidean(a, b): """Extended Euclidean algorithm. Return s, t and r such that r = gcd(a, b) and s * a + t * b = r""" prev_r, r = a, b prev_s, s = 1, 0 prev_t, t = 0, 1 while r != 0: q = prev_r // r prev_r, r = r, prev_r - q * r prev_s, s = s, prev_s - q * s ...
9b4c082cf1e68d70af682bb9ff2ba5e49e3f90b1
638,480
import os def createTemporaryFileWithSequence(sequence_AA, protein_id): """ create file that is used in the domain search :param sequence_AA: id of the organism :param protein_id: id of the organism :type sequence_AA: str :type protein_id: int :return: file name :rtype str ""...
a6a511c9e404facdee12eb97dced8e845604ad20
638,481
import os def get_file_names(sub_,data_dir_,n_trunc_,hrshiftval_, verbose = False): """ Get all the participant file names Parameters ---------- data_dir_ [str]: the data root dir task_name_ [str]: the name of the task Return ---------- fnames_ [list]: file names for all...
16753376091eda4dbaa2a44b4d26ff816e117d55
638,482
def arrow(self): """length of extension arrows""" return self._arrow
bc9986605dc5eefaaa27fceeeaedc8813c347bd2
638,483
def sendController(msg, q): """Communicate with connected controller Arguments: msg {str} -- Message to be sent q {socket.socket} -- Controller's socket Returns: int -- Error Code: 0) Error 1) Success """ try: q.send(msg) ...
f0c27aff3ad54903c0a480754bc304d4bd7a5058
638,484
import os def getFileDate(fileName): """returns the date on a file or 0 if the file does not exist >>> getFileDate('xtfg.dnv') 0 >>> #getFileDate(testdrive + "\\sites/qh/qhhtml.rc") # 1072694718 (not testable, changes all the time!) """ try: return int(round(os.path.getmtime(fileN...
3a579a99cc81f2c0a5c4dffde8f99636ebd56f9f
638,485
from typing import get_origin def _is_type_alias(obj: object) -> bool: """Determines whether the given object is (likely) a type alias.""" return get_origin(obj) is not None
5b72fecd5869492feb7af7097fca184b1cc05786
638,486
def get_source_attributes(source): """ Retreives a dictionary of source attributes from the source class :param source: Seismic source as instance of :class: `openquake.hazardlib.source.base.BaseSeismicSource` :returns: Dictionary of source attributes """ return {"id": s...
78cf144f833e8ae8447545ea0608ecb2aa31bd85
638,487
import re def get_column_defaults(table): """ Extract column default value for each column. If column lacks default, set default to NULL. Returns: a map(column_name, default_value) """ defaults = dict() regex1 = re.compile(r'default\s+(\(|"|\')(.*)(?=(\)|"|\'))') regex2 = re.compi...
cd4f3b4d897d0cfec4d5af887131a7b06b0c9ab6
638,488
def flatten_dict(y, key_filter=None, seperator="."): """ flatten given dictionary, if filter is provided only given values are returned """ res = {} def flatten(x, name="", seperator=""): if isinstance(x, dict): # --- dict --- for k in x.keys(): f...
26ac5c1babd1afabecfeff2c4621067063318034
638,489
import argparse def cli(rfs): """ Process CLI args. Inputs: - rfs ([str]): the list of reciprocation functions that should be accepted as valid input Returns: Parsed arguments. """ cli = argparse.ArgumentParser() # fmt: off cli.add_argument( "--da...
20931ccf085ae762e3a71ff17e8e3fb6447bfec6
638,490
import click import os def upload_file(mwdb, file, name, parent, private, public, share_with): """Upload file object""" with click.open_file(file, 'rb') as f: content = f.read() name = name or os.path.basename(file) obj = mwdb.upload_file( name=name, content=content, pa...
cb70391c8f50c0e35bded6d814d5cb16adfc4be6
638,491
def process_one_file(k, a, filename): """Return a set of species over thresholds.""" with open(filename) as f: f.readline() species = set() for line in f: tkns = [tkn.strip() for tkn in line.split('\t')] abund, _, _, kmers, _, _, _, rank, taxa_name = tkns ...
ec00bf57d67c9fe0b1b54e9644e32415da7855fc
638,493
from typing import Callable def custom_color(x: int) -> Callable[[], str]: """Return an escape string for a color by it's number. param: x: The color code (between 0 and 255). returns: Formatted escape sequence for a color """ return lambda: "38;5;" + str(x) + "m"
a423dde11a68a317db77ab1e9f7d17464bc6b919
638,494
def get_parameters(): """ retrieve a list of parameter codes available. Reference for GSOD parameters : https://www1.ncdc.noaa.gov/pub/data/gsod/readme.txt Parameters ---------- None Returns ------- dictionary of variables with parameter codes as keys and GSOD codes as valu...
6ef24376dd5e9c29d3ea1059b5731f2778b42c4c
638,495
def get_connectors(pipe): """Get the connector elements of a pipe.""" connector_set = pipe.ConnectorManager.Connectors connectors = [connector for connector in connector_set.GetEnumerator()] assert len(connectors) == 2 return connectors
0e344844b7371d9227bf62e409d3ddee4b04e84b
638,496
import os def get_experiment_name(): """Returns experiment name.""" return os.environ['EXPERIMENT']
9588d9b14f84466e8c0432b37ff8a9562e0db29f
638,497
import os def _load_toolchain_ninja(out_dir, toolchain_label): """Load a toolchain.ninja path for a given toolchain. Args: out_dir: Root output directory (e.g. "$FUCHSIA_DIR/out/toolchains.gn") toolchain: Toolchain GN label (e.g. "//build/toolchain:host_x64"). Returns: A (content, tool...
d5ac3c7ecf4e3f8b492eda10eeae302576dfc2cb
638,498
def isControlTimestampChanged(prev, latest): """\ Checks whether a new (latest) Control Timestamp is different when compared to a old (previous) Control Timestamp. Note that this does not check equivalency (if two Control Timestamps represent the same mapping between Wall clock time and content time) ...
550166b8d8637582edb68a21704c69bc79bce0cc
638,500
def create_child(document, element_name, attributes): """Create new XML child attribute.""" newChild = document.createElement(element_name) x = document.lastChild for attr in attributes.keys(): newChild.setAttribute(attr, attributes[attr]) x.appendChild(newChild) return x.toxml()
bf14be7de0007c0aaebba77170472ff0e72076d5
638,502
def too_big(dataset, start, end, dim = 300, cutoff = 620000): """ Calculates if a batch consisting of dataset[start:end] is too big based on cutoff. This can be used for constructing dynamic batches. """ sizes = [len(x) for x in dataset[start:end]['embeddings']] max_size = max(sizes) dim = dim ...
881ec1a3376722c5a9e18384b1f46b640178c3ea
638,503
import argparse def ParseArguments(raw_args): """Parse command line arguments.""" parser = argparse.ArgumentParser() parser.add_argument('-p', '--port', type=int, default=8000, help='Port to run the http server.') parser.add_argument('-v', '--verbosity', action='count', default=0, ...
263a73e5c4004477ad1ab75ab06d558fa8d98686
638,504
def command_clone(ctx, src, dest, mirror=False, branch=None): """Produce a command-line string to clone a repository. Take in ``ctx`` to allow more configurability down the road. """ cmd = ['git', 'clone'] if mirror: cmd.append("--mirror") if branch is not None: cmd.extend(["--b...
ac20883e8009116354ddc5aab0a2304a4b2730f0
638,506
def separate_file_from_parents(full_filename): """Receives a full filename with parents (separated by dots) Returns a duple, first element is the filename and second element is the list of parents that might be empty""" splitted = full_filename.split('.') file = splitted.pop() parents = splitted...
a074e234c931fa816ca17864af1710e396a5a263
638,507
def v_sub(v, w): """Performs componentwise subtraction on two vectors. Returns a list.""" return [vi - wi for vi, wi in zip(v, w)]
8014d580553299fbd187e8c8ebe7e5670aa3aec7
638,508
def generate_filename(blob_name: str, message_index: int) -> str: """Strip the file type suffix from the blob name, and append message index.""" fname = blob_name.split("/")[-1] fname, _ = fname.rsplit(".", 1) return f"{fname}-{message_index}"
da075bec5b52c429b651ecf87b76d050fc062492
638,509
def _is_type(t): """ Factory for a type checking function of type ``t`` or tuple of types. """ return lambda x: isinstance(x.value, t)
4c2768f0a818b24227e96c705eace42550c8a4f6
638,510
def calc_diff(prev, curr): """Returns percentage difference between two values.""" return ((curr - prev) / prev * 100.0 if prev != 0 else float("inf") * abs(curr) / curr if curr != 0 else 0.0)
e9f53bca8007157208dd40c265140082817f423f
638,511
import re def normalize_url(params): """this function takes a tuple with start_url and url and removes the start_url if found inside of url otherwise return original url :return:string with url or path portion of url """ (start_url, url) = params if url is None: return ur...
aea84f654bdd6d6806d07d8e727fc056efccb2d6
638,512
def ns_id(tagname, suds_ns): """Adds namespace to tag""" return '{{{0}}}{1}'.format(suds_ns[1], tagname)
6990d241c71c48edfd1f52cd6893b6559d2c9d27
638,513
def k2e(k, E0): """ Convert from k-space to energy in eV Parameters ---------- k : float k value E0 : float Edge energy in eV Returns ------- out : float Energy value See Also -------- :func:`isstools.conversions.xray.e2k` """ return ((1...
2999eedff5135999f4a062c8eb83b0fddea6138f
638,514
def get_time(): """ Description: get_time is responsible for getting user input and verify if it is a valid time. Parameters: Takes no Parameters: None:None return: returns None or time of type String: None:None time:String """ ...
b547a46b3fb16bbd797dd5f8b54cd52073a54067
638,515
import traceback import sys def is_gsm_text(text): """Returns True if ``text`` can be encoded as gsm text""" try: tx = text.encode("gsm0338") print(tx, type(tx), len(tx)) except UnicodeError: return False except: traceback.print_exc(file=sys.stdout) return False...
05fcea25260e0866e8ef87496be30a8b7f5657cb
638,516
def get_page_info(ctx, title): """Retrieves information about a page identified by its table (with namespace prefix. This returns a lua table with fields "id", "exists", and "redirectTo". This is used for retrieving information about page titles.""" assert isinstance(title, str) page_id = 0 ...
f91aa7356b7e60b114a5b43aa303849e904af1e6
638,517
def parse_pattern(pattern:str): """ tokenize matching patter """ pattern = pattern.strip() tail = None for i in [":before",":after"]: if pattern.endswith(i): pattern = pattern[0:-len(i)].strip() tail = i ret = [] for pat in pattern.split('>'): pat = pat....
810a3cfed504cea70694dbaf67be119f77690e4f
638,518
def sdf_readOnly_object(RO_value): """ Take the read only value and convert it for sdf writable property :param RO_value: Read only value string :return: json formatted string """ if RO_value: # "readOnly" = true # "writeable" = false return "false" else: # "r...
ba87754dbc1a958cbc7398f18e8c4400bb05860b
638,519
def get_docker_python_version(params: dict) -> str: """Return the highest python version defined for the project.""" max_version = list(sorted(params["template"]["python_versions"]))[-1] version = max_version.replace(".", "") return f"py{version}"
bfd81f582741279708a296584a2d6f233a382b8c
638,520
from typing import Iterable from typing import Any from typing import List def unique_list(seq: Iterable[Any]) -> List[Any]: """ Returns a list of all the unique elements in the input list. Args: seq: input list Returns: list of unique elements As per http://stackoverflow.co...
40bc33a9e42553fbc924ecf71fb2273a382f502e
638,521
def resource_from_path(path): """Get resource name from path (first value before '.') :param path: dot-separated path :return: resource name """ index = path.find('.') if index == -1: return path return path[:index]
ae5e00cec7be8dd94e4e7083a2db6a8878dabd2f
638,522
from typing import List def valley(arr: List[int]) -> int: """Valley element is NOT larger than its neighbours.""" lo = 0 hi = len(arr) - 1 while lo <= hi: mid = int(lo / 2 + hi / 2) larger_than_left = mid - 1 >= lo and arr[mid] > arr[mid - 1] larger_than_right = mid + 1 <= hi ...
fae162f382209c059a61a3780021f2ff6f940652
638,525
def make_numeric_labels(class_set): """Generates numeric labels (to feed external tools) for a given set of strings""" return { cls : idx for idx, cls in enumerate(class_set) }
ad5a002c31bcdd2b305d40430773e918bd89f212
638,526
import sys def _ImportDeployTemplate(): """Returns the setup_script and servers objects from the deployment template specified by the first command line argument. """ deploy_template = "viewfinder.backend.prod.deploy.{0}".format(sys.argv[1]) __import__(deploy_template) servers = sys.modules[deploy_templat...
5860a80a81ae1ff4f68c68097a49f36bdfe5702c
638,528
def proj(A,B): """Returns the projection of A onto the hyper-plane defined by B""" return A - (A*B).sum()*B/(B**2).sum()
57036612b3e3307cf079c11969c54a5d8b016a05
638,529
import pandas def empty(col_keys): """ construct an empty pandas.DataFrame """ return pandas.DataFrame(columns=col_keys)
05ca12994c9f4b67e737d6600556c85a797cdec3
638,530
def getindex(header,axes,vals) : """ DEVELOPMENT : get index of requested model from input grid header """ out=[] for ax,val in zip(axes,vals) : i = (val-header['CRVAL'+str(ax)])/header['CDELT'+str(ax)] if i+1 > header['NAXIS'+str(ax)] : i=-1. out.append(int(round(i))) retur...
8e1c482ee3893cfb25dea8debaed987f74058f5f
638,531
import numpy def mix_x_and_y_and_call_binary_f_two(func, c, x, y): """Create an upper function to test `func`""" z = numpy.abs(func(c, x) + 1) z = z.astype(numpy.uint32) + y return z
46b505f3259b22a06e1c6ff091cfada5ef3685c7
638,532
from typing import Counter def create_claim(left, top, width, height): """Create a claim as it would appear on the fabric.""" claimed = Counter() for i in range(width): for j in range(height): claim = (i+left, j+top) claimed[claim] += 1 return claimed
a002b315ab7e028ab9d1885a47c4c84ea0a68579
638,534
import csv def writeCSV(file,data,cols = None): """ Write CSV file with data typically supplied as a list or np.arrays. :param file: file or name of file, :type file: file or str :param data: list of numpy.array or two dimensional numpy.array :type data: list of numpy.array or two dimensiona...
06ebb93fc019dbfad41e62a69ff772ae2b5bbfd0
638,536
def present_protocols(out_packet): """ return identifier of all protocols present in the packet as """ # top packet has no identifier, only upper layers protocols = [] out = out_packet loop = True while loop: out = out.upper_layer() if out is not None: if hasattr(out...
8b22d89b17503990293953bdd1d533e01801d6a3
638,538
from pathlib import Path import subprocess import json def _is_enterprise(build_artifact: Path, workspace_dir: Path) -> bool: """ Return whether the build artifact is an Enterprise artifact. Raises: ValueError: A space is in the build artifact path. """ if ' ' in str(build_artifact): ...
9709a447ef43358cfaf70d12708e7ea1401b22dd
638,539
def parametrized(decorator): """ Decorator for easily defining parametrized decorators. Should be used like this: @parametrized def my_decorator(func, *args, **kwargs): @wraps def _my_decorator(*args_, **kwargs_): # At this point args and kwargs are decorator parameters whil...
f9cbf0896c1c0948631bb7f7aa94ee0ce95b9f50
638,540
def left(i, heapsize=None): """ Calcula o nó filho à esquerda. """ res = i << 1 if heapsize != None and res > heapsize: return None return res
9adf618bb483bf757464aaefbbced6863d6e1697
638,541
import importlib def import_module(module_name): """ A nice namespace alias for users. """ return importlib.import_module(module_name)
8f9284aa1498bf53ef6d27363b771efb1e721251
638,542
def sum_fibonaci_minus_sum_powers_of_two(total_lambs): """ I don't remember the original formulation. Given total_lambs, an integer between 1 and 1000000000. It computes the largest sum of consecutive (modified) Fibonaci numbers which is not greater than total_lambs, the sum of powers of 2 whic...
64e0c74c7ec20ff831fb687d2f179ef6afdba46f
638,544
import sys def open_text(fname, **kwargs): """On Python 3 opens a file in text mode by using fs encoding and a proper en/decoding errors handler. On Python 2 this is just an alias for open(name, 'rt'). """ PY3 = sys.version_info[0] == 3 if PY3: # See: # https://github.com/giamp...
6b3cfa6edcd50b066907ddf444646fb55cba545d
638,545
def size_to_human(size): """Humane readable size, with 1/10 precision""" if size < 1024: return str(size) if size < 1024 * 1024: return str(round(size / 1024.0, 1)) + ' KiB' if size < 1024 * 1024 * 1024: return str(round(size / (1024.0 * 1024), 1)) + ' MiB' return str(round(...
9fd710d66925108e488e02708442bb0fccdc6870
638,546
def make_scenario_name_nice(name): """Make a scenario name nice. Args: name (str): name of the scenario Returns: nice_name (str): nice name of the scenario """ replacements = [ ("_", " "), (" with", "\n with"), ("fall", ""), ("spring", ""), ...
82d9034b5b08db05ae9a7c80797e9cd0574d410b
638,547
def lookup_by_href_or_nickname(href, nickname, find_function): """ Helper to retrieve items by href or nickname :param href (optional): String of the item href :param nickname (optional): String of the item nickname :param find_function: The function to use to find by nickname :return: String o...
9f7b36bb0c1d4c31e93fd1737fd55fc7210f6dd5
638,548
def dictify(some_named_tuple): """ Convert Named Tuple to dictionary :param some_named_tuple: collections.namedtuple() :return:dict, """ return dict((s, getattr(some_named_tuple, s)) for s in some_named_tuple._fields)
2dff7ef035ce9f7b508349cd1afb1bd12e338712
638,549
from typing import Union import yaml def clean_config(config: str, return_dict: bool = False) -> Union[str, dict]: """ Used to remove adhoc service related values from the configuration. :param config: A yaml structured string. :param return_dict: True if wishing to return config as dictionary. :r...
0d03f066499ed85a1a7aa990cdd070d885d53db2
638,550
def filter_in_attack_range_of(unit, targets): """filter targets who are in attack range of the unit""" return targets.subgroup(target for target in targets if unit.target_in_range(target))
ad4a41816988419b8efd1ff270d4556b2cbb7d3a
638,551
import re def _IsTaskKillError(stderr): """Returns whether the stderr output of taskkill indicates it failed. Args: stderr: the string error output of the taskkill command Returns: True iff the stderr is considered to represent an actual error. """ # The taskkill "reason" string indicates why it f...
9a3e0a8d4ed88b767384cb3802147b18dd37e84b
638,552
def binary_search(numbers, number): """Binary search Locates the number in the list of sorted numbers. Looks at the middle element, and proceeds recursively to the left or to the right, depending on whether the number was smaller or bigger, respectively Returns the position of the found number, or the...
b60f3709e0d5e13be4cb268c22bf86dd607141c7
638,553
def setup(): """ setup hashes elements into dictionaries (hash tables). """ h, target_values = set(), set() for x in range(-10000, 10001): target_values.add(x) with open("algo1-programming_prob-2sum.txt") as f: # Exclude the newline character, \n for line in f: ...
7a2a7e6f9cf266194eacd4999852cce9d8d5130e
638,554
def minmax_element(iterable, first=0, last=None, key=None): """ Find and return the minimum and maximum element in an iterable range. Parameters ---------- iterable: an iterable object with __get_item__ first: first element to check last: one past last element to check. None will check unti...
a5176ac552ff720fdd304c12b64a1ec9a9b9a09b
638,555
def load_field_type(value): """load field_type""" return value
77e0243bb2764c9cdb08a27ef0af769dcf309b18
638,556
def scrubPrefixes(name): """ Removes commonly seen prefixes. """ prefixes = ["Mr.", "Ms.", "Mrs.", "Dr.", "Mr", "Ms", "Mrs", "Dr", "Miss"] names = name.split() if names[0] in prefixes: names = names[1:] else: names = names[0:] return ' '.join(names)
f6a062f9c15f51e07c5250ebc503c3cc7c83bb69
638,557
def pop_attr(obj, attr, default=None): """Pops and returns value of object attribute, similar to dictionary item pops. If attribute doesn't exist, returns value of 'default'. .. Usage:: >>> pop_attr(obj, 'attribute') 'value' """ return obj.__dict__.pop(attr, default)
454bb4ea2087a8f6433f806c5a8b6f7c19af169c
638,558
def sql_from_dtype(dtype): """Returns a sql datatype given a pandas datatype Args: dtype (str): The pandas datatype to convert Returns: str: the equivalent SQL datatype Examples: >>> sql_from_dtype('bool') 'boolean' >>> sql_from_dtype('float64') 'numeri...
29873e0530fd5d0bdad027917bd6e121e7de8bb9
638,559
import re def tidy_ssh_user(url=None, user=None): """make sure a git repo ssh:// url has a user set""" if url and url.startswith('ssh://'): # is there a user already ? match = re.compile('ssh://([^@]+)@.+').match(url) if match: ssh_user = match.group(1) if user ...
a7d8c71941748df8ac3b80b2da2afb940c93bf4c
638,560
def escape_ass_tag(text: str) -> str: """Escape text so that it doesn't get treated as ASS tags. :param text: text to escape :return: escaped text """ return text.replace("\\", r"\\").replace("{", r"\[").replace("}", r"\]")
da976a528ff88fea3a36e532b6fc3b73e77ebb34
638,561
def interact(data, interaction_cols): """ add interactions to data for the columns in self.columns --- @param data: a 2D data matrix of n observations and m predictors @param interaction_cols: list of columns to interact """ # for each pair of interaction columns, create a new product column...
32114b45f2740472782d890923a0f83d98281ad9
638,562