content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def deny_all(*args, **kwargs): """Return permission that always deny an access. :returns: A object instance with a ``can()`` method. """ return type('Deny', (), {'can': lambda self: False})()
74898e52aba03a57267c6209b434a1c8843a39b7
20,728
def get_chosen_df(processed_cycler_run, diag_pos): """ This function narrows your data down to a dataframe that contains only the diagnostic cycle number you are interested in. Args: processed_cycler_run (beep.structure.ProcessedCyclerRun) diag_pos (int): diagnostic cycle occurence for ...
b09abfdc3a9b1fa7836f548d6c40ca7845321418
20,729
def hms_to_sec(hms): """ Converts a given half-min-sec iterable to a unique second value. Parameters ---------- hms : Iterable (tuple, list, array, ...) A pack of half-min-sec values. This may be a tuple (10, 5, 2), list [10, 5, 2], ndarray, and so on Returns ------- ou...
9da83a9487bfe855890d5ffd4429914439f4b28b
20,733
import os def get_path_to_file_from_here(filename, subdirs=None): """ Returns the whole path to a file that is in the same directory or subdirectory as the file this function is called from. Parameters ---------- filename : str The name of the file subdirs : list of strs, optiona...
f6f89355986c3ca42749f5a3c982aad0f79e1e39
20,734
def tag_clusters(docs, cluster_assignment, cluster_name="cluster_covid"): """Tag clusters with an assignment""" docs_copy = docs.copy() docs_copy[cluster_name] = docs_copy["project_id"].map(cluster_assignment) docs_copy[cluster_name] = docs_copy[cluster_name].fillna("non_covid") return docs_copy
dd48b43dc54483e248cbc149de7e3e968c943836
20,735
def easeInOutQuad(t, b, c, d): """Robert Penner easing function examples at: http://gizma.com/easing/ t = current time in frames or whatever unit b = beginning/start value c = change in value d = duration """ t /= d/2 if t < 1: return c/2*t*t + b t-=1 return -c/2 * (t*(t...
a4ae2cc0b2c03a499bee456a08bdada023570361
20,736
def defaultToSelfText(fn): """ A fun little decorator that makes it so we can default to the text stored on a class instance, but also let people just instantiate and re-use calls while supplying new text. Whee. """ def wrapper(self, text = None): if text is None: ...
add3fbc6247b6959a2acc9e33580acc2e3d07a8b
20,739
def to_str(data, **kwargs): """ Reference Name ``to_str`` Function to transform Python structure to string without applying any formatting :param data: (structure) Python structure to transform :param kwargs: (dict) ignored :return: string """ return str(data)
e1972d06e5f3328ad63d880b5e71cd5fc5c17005
20,740
def a_1d_worse_less_corr(a_1d): """similar but not perfectly correlated a_1d.""" a_1d_worse = a_1d.copy() step = 3 a_1d_worse[::step] = a_1d[::step].values + 0.1 return a_1d_worse
f7c0120968f0772095a63b3497b5fdf08d67ce74
20,741
def higlight_row(string): """ When hovering hover label, highlight corresponding row in table, using label column. """ index = string["points"][0]["customdata"] return [ { "if": {"filter_query": "{label} eq %d" % index}, "backgroundColor": "#3D9970", "...
c4473cf2d41b4ef7df6d08048dd6f9fe8f5d4099
20,742
def enforce_order(fmt: bytes) -> bytes: """Enforce consistent ordering in a ``struct`` format""" if fmt[:1] == b'>': return fmt elif fmt[:1] not in b'@=<!': return b'>' + fmt else: return b'>' + fmt[1:]
d1b74bcf9641f232c0aea10f9bea77456dbc1637
20,743
def get_dict_value(key, data): """Return data[key] with improved KeyError.""" try: return data[key] except (KeyError, TypeError): raise KeyError("No key [%s] in [%s]" % (key, data))
166656c226bb7a846c7c63f6d8d07ab7ee1a81f9
20,744
from typing import Union import re def _expand_deb_query_value(key: str, value: str) -> Union[str, list]: """Expands a value gained from deb-query --status if necessary. Some keys like 'Depends' are a list of other packages, which might contain package version information too. For further ease of...
d5af88395912ad098ddaab07bf44c93d19af44a3
20,745
def list_to_string(s, separator='-'): """ Convert a list of numeric types to a string with the same information. Arguments --------- s : list of integers separator : a placeholder between strings Returns ------- string Example ------- >>> list_to_string( [0,1], "-" ) ...
bf926cbc87895fe820d5de8c206f499f9558eefd
20,746
import functools def cached_method(cache_size=100): """ Decorator to cache the output of class method by its positional arguments Up tp 'cache_size' values are cached per method and entries are remvoed in a FIFO order """ def decorator(fn): @functools.wraps(fn) def wrapper(self, *...
3e580dc984373d3a19fd37a7c195ee3c4842d8b3
20,748
def portion_dedusted(total, fraction): """ Compute the amount of an asset to use, given that you have total and you don't want to leave behind dust. """ if total - (fraction * total) <= 1: return total else: return fraction * total
473ee713986b869d6dc193410ef76f54a04f6499
20,749
def line_is_heading(line): """Check whether a line of output generated by :func:`report_metrics()` should be highlighted as a heading.""" return line.endswith(':')
e0696c15188de89cd81caf84caf854aa2f15e11e
20,751
def stringify_json_data(data): """Convert each leaf value of a JSON object to string.""" if isinstance(data, list): for i, entry in enumerate(data): data[i] = stringify_json_data(entry) elif isinstance(data, dict): for key in data: data[key] = stringify_json_data(data...
fb40ba20b0c7fc66f7f7c3c4fd9daa1a2f7a3428
20,752
def sort_to_buckets(buclist, data_iter, keyfunc=None): """Sorts items in data_iter into len(buclist)+1 buckets, with the buclist (presumably sorted) providing the dividing points. Items are put into a bucket if they are <= the corresponding buclist item, with items greater than buclist[-1] put into the ...
73c6545ed8ed11758a7e7828d20eec1945e5ae12
20,753
import re def __unzip_labels(label): """unzips a string with more than one word Parameters ---------- label : tuple tuple or list of the text labels from the folder name Returns ------- list splited labels as list of strings """ labels = re.split('(?=[A-Z])', labe...
c442eaadf18c51fdb7d9519bc00658b97657a225
20,754
import pathlib def get_requirements(): """Read requirements.txt and return a list of requirements.""" here = pathlib.Path(__file__).absolute().parent requirements = [] filename = here.joinpath('requirements.txt') with open(filename, 'r') as fileh: for lines in fileh: requiremen...
70cae7cba123f0bf738c5ca1c36315bb5534cb02
20,755
def check_user(user, event): """ Checks whether the ``ReactionAddEvent``, ``ReactionDeleteEvent``'s user is same as the given one. Parameters ---------- user : ``ClientUserBase`` The user who should be matched. event : ``ReactionAddEvent``, ``ReactionDeleteEvent`` The reacti...
37c5e280ced5a3470ac9691e6cb0dcadf3e3c550
20,756
def _encode_to_utf8(s): """ Required because h5py does not support python3 strings converts byte type to string """ return s.encode('utf-8')
05be6da8d53dd8c29527d5822c27623a9eb49d18
20,757
from typing import List def countValidArrangements(adapters: List[int]) -> int: """ Counts valid arrangements of the adapters (sorted list) """ paths: List[int] = [0] * (adapters[-1] + 1) paths[0] = 1 for index in range(1, adapters[-1] + 1): for i in range(1, 4): if index - i in adap...
fe296424a31a3e59c0af2516c67c284f463d2747
20,760
import time def sync_zones(conn, namespace, network, zones): """Synchronize a local set of zones with one in broadstreet. `namespace` should be something very unique. A UUID or identifer of a product. it will be pre-pended to the alias of all zones with a dot (.). `zones` is a dictionary keyed by th...
9e9d896216f73c038760420c1fad0158b53be036
20,761
def action_description(text): """Decorator for adding a description to command action. To display help text on action call instead of common category help text action function can be decorated. command <category> <action> -h will show description and arguments. """ def _decorator(func): ...
633f2f840a49b4239248dd48e32e58ae6b749f10
20,762
def unsquish(selected, unadapted_data): """Transform our selected squished text back to the original text selected: the selected sentences unadapted_data: the list of original unadapted sentences returns: the selected sentences, with clear text """ for i, line in enumerate(selected): i...
3853a24d1644fd68a7635cc9400cbc5354e99ace
20,763
import torch def sample_idxs_from_loader(idxs, data_loader, label): """Returns data id's from a dataloader.""" if label == 1: dataset = data_loader.dataset.dataset else: dataset = data_loader.dataset.dataset return torch.stack([dataset[idx.item()][0] for idx in idxs])
bef007d08b4dd2efe94a19525c166ffe859e67bd
20,764
def change_root(devices_map, new_root_border_id): """This function sets the specified device as a root and corrects all hierarchy taking new root in account """ def go_down_and_increase_depth(board_id, initial_depth): """This subfunction walks down the tree and increases the "depths" values for children...
a34414b288f95756ff5b14f320b056f4a6b902ac
20,765
def test_cards(): """ Discover test cards """ return [ # Auth.Net test cards "6011000000000012", # Braintree test cards, "6011111111111117", "6011000990139424", # Stripe test cards "6011111111111117", "6011000990139424", # WorldPay ...
6d781b413ed4f7288274b78605ac77b454ca5b1f
20,766
import math def _close_descent(a, b, rtol, atol, equal_nan, flatten=True): """ Returns a boolean or sequence comparing to inputs element-wise within a tolerance. This is a recursive function intended to implement `allclose` and `isclose` Which one it implements depends on the value of `flatten`. ...
d26f23110bea7261f0d7fda1cb20356da670a42e
20,767
def to_r_camel(s): """ Turns fields from python snake_case to the PCR frontend's rCamelCase. """ return "r" + "".join([x.title() for x in s.split("_")])
2380807ba449c65962657721842ef910d569aa03
20,769
def load_events(filename): """ load all events from a text file (W,E,X,Y,Z,WX,WY,WZ) """ events = [] with open(filename) as f: for line in f: #if line.find("G4W") != -1: # continue #if line.find("GGG") != -1: # continue ...
c64c28ba050cbf06508e600ea92bf3ab1a00d825
20,770
import os def read_EMCEE_options(config, check_files=True): """ parses EMCEE options Parameters: config - configparser.ConfigParser instance check_files - *bool* - should we check if files exist? Returns: starting - dict - specifies PDFs for starting values of parameters ...
56ca3d26c2a78d3f54edd729425d3de3a12ec0dd
20,771
def is_theme(labels, zen_issue): """Check If Issue Is a Release Theme. Use the input Github Issue object and Zenhub Issue object to check: * if issue is an Epic (Zenhub) * if issue contains a `theme` label """ if zen_issue['is_epic']: if 'theme' in labels: return True
380dbe8d4c9105a49a8ae211f55dcbfd35c38d3c
20,775
from typing import Dict from typing import Any import pprint def describe_item(data: Dict[str, Any], name: str) -> str: """ Function that takes in a data set (e.g. CREATURES, EQUIPMENT, etc.) and the name of an item in that data set and returns detailed information about that item in the form of a str...
4df9e99f713effc00714342f54e2bd135b580675
20,777
def mini(a,b): """ Minimal value >>> mini(3,4) 3 """ if a < b: return a return b
2d49ce51bd239dd5ceb57396d7ed107f1309c203
20,778
def measures_to_notes(measures): """ measures: List[List[List[str, float, float]]] -> List[List[str, float, float]] Breaks up a list of measures of notes into a list of notes. """ notes = [] for i in range(len(measures)): notes.extend(measures[i]) return(notes)
56e33cd543d5d503b0894c5d6f9e84a61f358313
20,780
def prod(iterable): """Computes the product of all items in iterable.""" prod = 1 for item in iterable: prod *= item return prod
f5ddea44c14a6d1dc77a3049723609358c1e8525
20,781
def areinstance(tokens, classes): """ >>> tokens = (TimeToken(15), TimeToken(16)) >>> areinstance(tokens, TimeToken) True >>> tokens = (TimeToken(15), DayToken(7, 5, 2018)) >>> areinstance(tokens, TimeToken) False >>> areinstance(tokens, (TimeToken, DayToken)) True """ assert...
27cf41a668dfcd52975becd0ae96c81d2c9ab385
20,782
import json def aws_credentials_from_file(path): """ Get the AWS S3 Id and Secret credentials, from a json file in the format: {"AWS_ID": "AWS_SECRET"} """ with open(path, 'r') as f: key_dict = json.load(f) for key in key_dict: aws_id = key aws_secret = key_dict[key...
68d04f3cdb223a9ccaa497981a8a0e3bc9a23378
20,783
def do_decomposition(gene_trail, selection): """Given a list of lists gene_trail and indexes for every item to be selected in every list in gene_trail, returns a list representing the corresponding decomposition. For example, if gene_trail is [['a', 'b'], ['c'], ['d','e']] and the index for the fir...
cbe3a942db5fb447f9e7ffe8f0866419b04f81f1
20,784
def processEnum(enum, tableExists=True, join=True): """ Take an Enum object generated by the PyDBML library and use it to generate SQLite DDL for creating an enum table for "full" enum emulation mode only. Parameters: enum (Enum): Enum object generated by PyDBML library representing an SQL enum....
832ca77c1287790ea33b26baacdeee5b3f611785
20,785
from typing import OrderedDict def _get_file_metadata(help_topic_dict): """ Parse a dictionary of help topics from the help index and return back an ordered dictionary associating help file names with their titles. Assumes the help dictionary has already been validated. """ retVal = OrderedDi...
6e03564f28ebc9ab8dc8ce12d314d18c35cf3518
20,786
def teens_to_text(num): """ >>> teens_to_text(11) 'eleven' >>> teens_to_text(15) 'fifteen' """ if num == 10: return 'ten' elif num == 11: return 'eleven' elif num == 12: return 'twelve' elif num == 13: return 'thirteen' elif num == 14: ...
1c3288b9a152fe5b341c77b4bac66797b1aaf616
20,789
def is_no_overlap(*set_list): """ Test if there's no common item in several set. """ return sum([len(s) for s in set_list]) == len(set.union(*[set(s) for s in set_list]))
300253d499c22bb398837c9766a9f5d8f7b5c720
20,790
from warnings import warn def _format_1(raw): """ Format data with protocol 1. :param raw: returned by _load_raw :return: formatted data """ data, metadata = raw[0]['data'], raw[0]['metadata'] # Check for more content if len(raw) > 1: base_key = 'extra' key = base_key...
0939ffb4242828a7857f0f145e4adeb90ec6cff1
20,791
def get_abyss_rank_mi18n(rank: int, tier: int) -> str: """Turn the rank returned by the API into the respective rank name displayed in-game.""" if tier == 4: mod = ("1", "2_1", "2_2", "2_3", "3_1", "3_2", "3_3", "4", "5")[rank - 1] else: mod = str(rank) return f"bbs/level{mod}"
869946e701918c4d43af88bcca693ab9361b9608
20,792
import requests def post_request(headers, json_data, url): """ Posts request to given url with the given payload args ---------- headers : dict Holds authentication data for the request json_data : json The request payload url :...
6a8a69ca7b5d13be02e037e8e283f9a44d69b54b
20,793
def first(iterable): """ Gets the first element from an iterable. If there are no items or there are not enough items, then None will be returned. :param iterable: Iterable :return: First element from the iterable """ if iterable is None or len(iterable) == 0: return None return ...
246ca69493a601343e1b1da201c68e2d8a3adc55
20,794
def distribute_conc_by_cover(data, total_conc): """ Divides the total concentration of the primers proportionally to the number of sequences detected by each primer. Arguments: -data: a pandas dataframe with sequences detected by the oligo as returned by remove_redundant_after_inosine_addition ...
e08f8168f6019689b717769264cc8a02c1444917
20,795
import re def allsplitext(path): """Split all the pathname extensions, so that "a/b.c.d" -> "a/b", ".c.d" """ match = re.search(r'((.*/)*[^.]*)([^/]*)',path) if not match: return path,"" else: return match.group(1),match.group(3)
06baf4d1a58c9f550bd2351171db57a8fc7620d2
20,796
def update_static_alloc_plan_and_get_size(self): """update static memory allocation plan without actual allocation :return: a dict that maps from comp node to size of allocation in bytes """ return {k: v for k, v in self._update_static_alloc_plan_and_get_size()}
7b6838d4272b3a5f631f2220c537a7f805548bce
20,797
def is_prepositional_tag(nltk_pos_tag): """ Returns True iff the given nltk tag is a preposition """ return nltk_pos_tag == "IN"
746a1439613a2203e6247924fe480792e171eb7b
20,798
import re def clean_data(d): """Replace newline, tab, and whitespace with single space.""" return re.sub("\s{2}", " ", re.sub(r"(\t|\n|\s)+", " ", d.strip()))
3c6b9032588d0cb2ca359ff27d727ade7011048a
20,801
def sample_to_sum(N, df, col, weights): """Sample a number of records from a dataset, then return the smallest set of rows at the front of the dataset where the weight sums to more than N""" t = df.sample(n=N, weights=weights, replace=True) # Get the number of records that sum to N. arg = t[col].c...
bd4ac2d5885c6de02d61fc0acb03f6f314d1c3d4
20,803
def calc_alpha_init(alpha, decay): """ Calculate the numerator such that at t=0, a/(decay+t)=alpha """ if not decay or decay <= 0: return alpha else: return float(alpha * decay)
41725753868a01b89f0a1ba0bc0b37b0ac2499c2
20,807
import requests def get_geolocation(all_the_ip_address): """ Given a list of lists from `get_addresses()`, this function returns an updated lists of lists containing the geolocation. """ print("Getting geo information...") updated_addresses = [] counter = 1 # update header header_r...
8c4d92a5a19caf663f635760c1c490abbe40868f
20,808
def tuple_to_list(t): """ Convert a markup tuple: (text,[(color,pos),...]) To a markup list: [(color,textpart),...] This is the opposite to urwid.util.decompose_tagmarkup """ (text,attrs) = t pc = 0 l = [] for (attr,pos) in attrs: if attr == None: l.append(text[pc:pc+pos]) else: l.append((at...
466767cd7d1d43665141908661ca75b291b4db50
20,811
def getMPlugs(mFn, mPlugList): """ get MPlugs from a list :param mFn: mFn :param mPlugList: list :return: list """ if type(mPlugList) == list: returnList = list() for plug in mPlugList: mPlug = mFn.findPlug(plug, False) if mPlug.isArray or plug == "wo...
195cfd07e8771eaa4707e722742de68c0feed9df
20,812
from typing import Iterable from typing import Tuple import networkx def build_graph(data: Iterable[Tuple[dict, str, dict]]): """ Builds a NetworkX DiGraph object from (Child, Edge, Parent) triples. Each triple is represented as a directed edge from Child to Parent in the DiGraph. Child and Paren...
6d43f3d2b9698eaac54cfcee38fd005e6762eaf6
20,813
from xml.sax.saxutils import escape def esc(str): """XML escape, but forward slashes are also converted to entity references and whitespace control characters are converted to spaces""" return escape( str, {"\n": " ", "\t": " ", "\b": " ", "\r": " ", "\f": " ", "/": "&#47;"} )
0a235e21f0bd911da0bfe62d7cf70b5b2e8b63e7
20,814
def macthing_templates(templates_peptide, templates_minipept): """ The function searching atoms of peptide bonds in small peptide pattern. Parameters ---------- templates_peptide : list List of atoms of peptide bonds. templates_minipept : list List of atoms of part of peptide bo...
a5f42305ab57648e4243c3f4cac51aa347dd8c60
20,815
def divides(a, b): """ Return True if a goes into b. >>> divides(3, 6) # Tests! True >> divides(3, 7) False """ return b % a == 0
c80223323997d940e35b1b05f16d031d1ae769aa
20,816
def compare_versions(actual, expected): """Compare Python versions, return the exit code.""" if actual < expected: print("Unsupported version {}.{}".format(actual[0], actual[1])) return 1 else: m = "OK: actual Python version {}.{} conforms to expected version {}.{}" print(m.f...
1ad44078c13f8710df5681ac2c1bd10f8f547990
20,817
import torch def to_gpu(x, on_cpu=False, gpu_id=None): """Tensor => Variable""" if torch.cuda.is_available() and not on_cpu: x = x.cuda(gpu_id) return x
49c8c91535f4ba93f682f6f28ed32c976eb56211
20,818
def find_first_feature(tree): """Finds the first feature in a tree, we then use this in the split condition It doesn't matter which feature we use, as both of the leaves will add the same value Parameters ---------- tree : dict parsed model """ if 'split' in t...
d57d29c3aadb0269d39fa73d27cd56416cc3e456
20,819
def sum_product(array: list) -> dict: """ BIG-O Notation: This will take O(N) time. The fact that we iterate through the array twice doesn't matter. :param array: list of numbers :return: """ total_sum = 0 total_product = 1 for i in array: total_sum += i for i in array: ...
53a8ac6000f9c6f722ef7159e31d1dc5f069fa9b
20,821
import six import ipaddress def IPv4ToID(x): """ Convert IPv4 dotted-quad address to INT. """ # try: # if six.PY2: # id = int(ipaddress.IPv4Address(x.decode('utf-8'))) # else: # id = int(ipaddress.IPv4Address(x)) # except ipaddress.AddressValueError as err:...
f73feab66969ed8adc683a1ebf36cef4de5d5825
20,823
from pathlib import Path def get_file_extension(filepath: str) -> str: """ Returns the extension for a given filepath Examples: get_file_extension("myfile.txt") == "txt" get_file_extension("myfile.tar.gz") == "tar.gz" get_file_extension("myfile") == "" """ extension_with_d...
d90dd071298c1ee429d913abd831030a60086b1b
20,826
def unescape(s): """The inverse of cgi.escape().""" s = s.replace('&quot;', '"').replace('&gt;', '>').replace('&lt;', '<') return s.replace('&amp;', '&')
3bad6bc3679405dd0d223ea8ab6362a996067ea5
20,827
from itertools import accumulate from collections import Counter def ZeroSumRange(a, unhashable = False): """ 総和が零元になるような空でない連続する部分列の数 """ *a, = accumulate(a) e = a[0] - a[0] if unhashable: a = [tuple(b) for b in a] e = tuple(e) C = Counter(a) C[e] += 1 return sum(v...
463789ce4938ac4b05eec0c850e1adab588d9480
20,828
def pick_inputs(workspace): """ Figure out which inputs don't yet have fragments. This is useful when some of your fragment generation jobs fail and you need to rerun them. """ frags_present = set() frags_absent = set() for path in workspace.input_paths: if workspace.fra...
35e9ca4a83fdc25f870cdb8e4f094881569787c1
20,830
import json def load_entity_uri_to_name(path): """ :param path: :return: json with uri, label """ return json.load(open(path))
37454284fa07da204dc4fc59029d470fd66e4b26
20,831
import random def seq_permutation(seq: str, k: int = 1) -> str: """Shuffle a genomic sequence Args: seq (str): Sequence to be shuffled. k (int): For `k==1`, we shuffle individual characters. For `k>1`, we shuffle k-mers. Returns: Shuffled sequence. """ if k == 1: ...
a789c2a5cb00e2e5fd140ba889510e6b7fd556d3
20,832
import math def get_normalized_meter_value(t): """ Expects a value between 0 and 1 (0 -> 00:00:00 || 1 -> 24:00:00) and returns the normalized simulated household consumption at that time, according to this Graph: http://blog.abodit.com/images/uploads/2010/05/HomeEnergyConsumption.png The formula...
03f40967f05de4d23d7600286bfc2927fea544d6
20,835
def is_quality_snv(var_to_test, AC_cutoff=None): """ high quality variants will have FILTER == None AND we are ignoring insertions and deltions here """ if AC_cutoff is not None: try: AC_cutoff = int(AC_cutoff) return var_to_test.FILTER is None and var_to_test.INFO.ge...
d474583126df19deb03b607f85880f79f31fdd1d
20,836
def delete_nth(order, max_e): """create a new list that contains each number of lst at most N times without reordering. """ answer_dict = {} answer_list = [] for number in order: if number not in answer_dict: answer_dict[number] = 1 else: answer_dict[numb...
8f057438b6778bc00563ca2d9752cd2f7c8bfff7
20,837
def squared_dist(x1, x2): """Computes squared Euclidean distance between coordinate x1 and coordinate x2""" return sum([(i1 - i2)**2 for i1, i2 in zip(x1, x2)])
c4ae86e54eb1630c20546a5f0563d9db24eebd3a
20,838
def S_find_square_floors_values(_data_list): """ Returns locations of values which do not change """ s_data = [] ds = len(_data_list) pd = _data_list[0] start = end = -1 for i in range(1, ds): if pd == _data_list[i]: if start == -1: start = i - 1...
09f875bdcbd05dcc889dfc1b39f186812f2cd27c
20,839
def itensity_rescaling_one_volume(volume): """ Rescaling the itensity of an nd volume based on max and min value inputs: volume: the input nd volume outputs: out: the normalized nd volume """ out = (volume + 100) / 340 return out
58ee7f00c54b063fac23eeb166df5f6d6adb2941
20,840
import os import stat def make_job_file(job_dir,job_name,cores,mem,gpus,gpu_mem,low_prio,requirements,rank,name=None,venv=None,\ conda=None,conda_name=None,commands_fn=None,command=None,queue_count=1,job_num=0,interactive=False): """ Creates the condor_submit file and shell script wrapper for the job. ...
fcdc416a0db825da633921ae1a8f7e920728ef1c
20,841
def kniferism(words): """Convert a list of words formatted with the kniferism technique. :param words (list) - The list of words to operate on :rtype words (list) - The updated list of words >>> kniferism(['foo', 'bar']) >>> ['fao', 'bor'] """ "Mid: f[o]o b[a]r => fao bor" if len(words...
b36f5eda1f0df44c7d2f772505fbd83af6d69913
20,842
def bed2gtf(infile, outfile): """Convert BED to GTF chrom chromStart chromEnd name score strand """ with open(infile) as r, open(outfile, 'wt') as w: for line in r: fields = line.strip().split('\t') start = int(fields[1]) + 1 w.write('\t'.join([ ...
92892e73e56851d3cb4054d3bdf42f029223e0a6
20,843
import math def ucb(board, tree): """Given board, return the move with the optimal UCB depending on player""" t = tree[str(board)][1] # node's total visits best_ucb = None best_move = None ucb = 0 is_white = board.turn if is_white: best_ucb = -float('inf') else: best_uc...
274f1bbfe069ab31a008384715a18e2cad0bf986
20,844
import time def timetostr(timestamp, format="%Y-%m-%d %H:%M:%S"): """把时间戳转换成时间字符串 :param timestamp: 时间戳 :param format: 格式 """ timestr = time.strftime(format, time.localtime(timestamp)) return timestr
16a7e6d6bed3b7cfb15827d0a8472982d6451c46
20,845
import re def strip_quotes(text): """ the pipeline we use does really weird stuff to quotes. just going to remove them for now or forever """ text = re.sub(r"``", r"''", text) text = re.sub(r'"', r"'", text) return text
0d30cf02026c75471a48692920718faf45866172
20,846
def convert_to_interval(id_array): """ Convert some consecutive timestamps' id to some intervals for easier retrieval :param id_array: a list containing all the camera ids of outliers :return: a list of strings representing the abnormal camera id ranges """ interval = [] current_interval = [...
dd9f25ecee49d0b7dc41015bd9ee2ebb3475a879
20,847
import re def addhead(re_check, head): """ 添加文件头 :param re_check: :param head: :return: """ re_check_o = re.compile(re_check) def _(file, code, config): if not re_check_o.match(file) is None: return file, head + code return file, code return _
a513aac065a389811410d1bf600d350218668ef4
20,848
def de_bruijn_strings(k: int, n: int): """ De Bruijn sequence for alphabet size k (0,1,2...k-1) and subsequences of length n. Modifed wikipedia Sep 22 2013 to use strips """ global sequence global a a = "0" * k * n sequence = "" def db(t, p): global sequence glob...
af52574fc89f215cec4918405b0099e616f565bb
20,849
def AU(): """ The `AU` function returns the Astronomical unit according to the IERS numerical standards (2010). """ return 1.49597870700e11
602f1528f896a948c07b970640cc43dc08e84f18
20,850
import re def clean_str(text, language='english'): """ Method to pre-process an text for training word embeddings. This is post by Sebastian Ruder: https://s3.amazonaws.com/aylien-main/data/multilingual-embeddings/preprocess.py and is used at this paper: https://arxiv.org/pdf/1609.02745.pdf """ ...
292626f6feafbf408ff04f763300cb288c135cee
20,851
def default_func(entity, attribute, value): """ Look in the entity for an attribute with the provided value. First proper attributes are checked, then extended fields. If neither of these are present, return False. """ try: return getattr(entity, attribute) == value except Attrib...
0ec6636c20d3f5eedb7a7c1f2457f72ecddb7545
20,852
def get_last_file(paths): """Returns last modified file from list of paths""" if paths: return sorted(paths, key=lambda f: f.stat().st_mtime)[-1] return ""
51978ae6dbb3686de40eebda156825904895a854
20,853
from inspect import signature def check_callable(input_func, min_num_args=2): """Ensures the input func 1) is callable, and 2) can accept a min # of args""" if not callable(input_func): raise TypeError('Input function must be callable!') # would not work for C/builtin functions such as numpy.dot...
7358d0685fd6f04f6a2ecf75aee66288a25a5e08
20,854
def _sql_gen_intermediate_pi_aggregate(model, table_name="df_e"): """ This intermediate step is calculated for efficiency purposes. In the maximisation step, to compute the new pi probability distributions, we need to perform a variety of calculations that can all be derived from this intermediate ...
fc6c812dbf0eee9bc5a78590125e547c24f8cc9b
20,857
def evaluate_svm(test_data, train_data, classifier, logfile=None): """ Evaluates svm, writes output to logfile in tsv format with columns: - svm description - accuracy on test set - accuracy on train set """ train_x, train_y = train_data classifier.fit(train_x, train_y) test_x, tes...
21550a91227eca49a05db2f3216bc72c50a74d1e
20,861
def flatten_results(results: dict, derivation_config: dict) -> dict: """Flatten and simplify the results dict into <metric>:<result> format. Args: results (dict): The benchmark results dict, containing all info duch as reduction types too derivation_config (dict): The configuration ...
045c1e1d856c20b37d2d78d8dd6c3fd76cb91777
20,862
def path_string(obj, **kwargs): """return physical path as a string""" return "/".join(obj.getPhysicalPath())
bae683d392b519f8c43f5e9d1415abb8cf8de636
20,865
def mock_list_tags_response(): """Create mock for lambda list tags""" response = { "Tags": { "SvcOwner": "Cyber", "name": "lambda-function", "Environment": "test", "Service": "cyber-service", "SvcCodeURL": "https://github.com/alphagov/my-madeu...
ade45167fe2c96ba99aa80fc3381e7ddd7290c53
20,866