content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def obstruction(info_dict): """ Obstruction due to M2 """ # Multiply by 1.05 to take the arms into account info_dict["obstruction"] = ( info_dict["M2_factor"] * info_dict["D_M2"] ) ** 2.0 / info_dict["D_M1"] ** 2.0 return info_dict
b67cc8b87d68dbd386d75fdb869f999072085607
701,632
def parse_response(response): """ :param response: output of boto3 rds client describe_db_instances :return: an array, each element is an 3-element array with DBInstanceIdentifier, Engine, and Endpoint Address Example: [ ['devdb-ldn-test1', 'mysql', 'devdb-ldn-test.cjjimtutptto.eu-we...
edaa4abbb695adb06c43dc93d70178bc10a82445
701,633
def format_csv(factor_name, entry): """Format a data entry as a csv line.""" return "%s, %s, %s" % (entry[factor_name], entry['quarter'], entry['count'])
8d3f4f794f58f6aa0c6d259fcda124340df8d4da
701,634
def _remove_quotes(values): """Remove any quotes from quoted values.""" removed = [] for value in values: if value.startswith('"') and value.endswith('"'): value = value[1:-1] removed.append(value) return removed
a75bd25198a56a28748af059647e62c26df74232
701,635
def consolidate(voice, length): """ Join notes of the same pitch together, and increase their duration. No attempt is made to handle ties between bars, They are just treated as separate notes. :param voice: :param length: :return: """ out = list() try: for bars in range(0, ...
6e6a60be0a6438b6f7c5fb23a1be720d5486e693
701,637
import json def get_dimensions(cube_id): """ For this test data we will use a predefined dimension object matching cube-420 in the acceptance environment, but this could be read from the TAP service. """ dims = json.loads( '{"axes": [{"name": "RA", "numPixels": "4096", "pixelSize": "5.555...
aab639236510785649fd02ff80c795d7941007fd
701,638
from pathlib import Path import yaml def load_yaml_config(file_path: str | Path) -> dict: """ Parameters ---------- file_path : str or Path Yaml config file name. The file is assumed to be in the repo's config directory. Returns ------- config : dict Configuration...
88a137807d6d1caabd3b8f7f7a03a3be3f04bdfe
701,639
def split_in_words(text, num_letters): """ Split a long text (without space) into words of num_letters letters. For instance if text is niijighkqj and num_letters is 4, will return ["niij", "iiji", "ijig", "jigh", "ighk", "ghkg", "hkgj"] :param text: Text to split into words :param num_letters: ...
334be65a1592b13056dede738fb5cabb67e79236
701,640
import re def get_specified_file(file_names, *args): """Get specified filename extension from a list of file names.""" specified_filename = [] if args is (): raise Exception('get_specified_file() missing at least 1 required specified argument') for name in file_names: for extension i...
195e6d1556afb46fd98972c6c7f5a4b897efbdc2
701,641
import re def has_sh_placeholders(message): """Returns true if the message has placeholders.""" return re.search(r'\$\{(\w+)\}', message) is not None
9bd5b4a22c89cfa1d45ea28bf7121cd4171828ee
701,642
import re def _find_char(input_char): """ find english char in input string """ result = re.findall(r'[a-zA-Z=_/0-9.]+', str(input_char)) return result
b89bc97e0b73c71ec6a1a875414b73e16c9d6036
701,643
import functools def verifyrun(func): """Prints whether the decorated function ran.""" @functools.wraps(func) def wrapper_verifyrun(*args, **kwargs): print(f'Ran {func.__name__!r} from {func.__module__}.') value = func(*args, **kwargs) return value return wrapper_verifyrun
5f2d1289573a9069f283e508b1ce133eccfe3529
701,644
def bold_viewed(val, viewed_pages): """ Takes a scalar and returns a string with the css property `'color: red'` for negative strings, black otherwise. """ weight = 'bold' if val in viewed_pages else 'normal' return 'font-weight: %s' % weight
f7cbe6b3d3736926841941dfbc8cc4595a1eda62
701,645
def get_can_reach_set(n, reach_dic, max_trip_duration=150): """Return the set of all nodes whose trip to node n takes less than "max_trip_duration" seconds. Arguments: n {int} -- target node id reach_dic {dict[int][dict[int][set]]} -- Stores the node ids whose distance to n is w...
f422db246ac926c8d0e2144ef42c09ba06b8a488
701,646
def create_empty_gid_matrix(width, height): """Creates a matrix of the given size initialized with all zeroes.""" return [[0] * width for row_index in range(height)]
8f1a0adf9e45bb6fc267a5cec3079657dbace51d
701,647
def value_to_none_low_medium_high(confidence_value): """ This method will transform an integer value into the None / Low / Med / High scale string representation. The scale for this confidence representation is the following: .. list-table:: STIX Confidence to None, Low, Med, High :header-...
ac3b39ae12591408fca2f8b4e844b535e7b1aaa3
701,648
def process_detail(hvr_client, hub_name, channel, source, target): """ Get all process details """ rt = {} jobs = hvr_client.get_hubs_jobs(hub=hub_name) for job_name in jobs: if ( job_name == f"{channel}-activate" or job_name == f"{channel}-refr-{source}-{targ...
0a8e2f1bc0f45c1e4854421497bb809c7d8ef457
701,649
from typing import Iterable def iterify(x): """Return an iterable form of a given value.""" if isinstance(x, Iterable): return x else: return (x,)
85373e5ac0e03caf2115096088ce92ca27b65b4a
701,650
import os def get_subfolder(path, subfolder, init=True): """ Check if subfolder already exists in given directory, if not, create one. :param path: Path in which subfolder should be located (String) :param subfolder: Name of the subfolder that must be created (String) :param init: Initialize ...
2109aa0c8e8d402f6ced8437e5399b754d9cbfa9
701,651
import binascii import os def choose_boundary() -> str: """Random boundary name.""" return binascii.hexlify(os.urandom(16)).decode("ascii")
6335e14abc34652141e7c77989d60fcb40ec3d17
701,652
def load_ignore(fname): """Loads patterns signalling lines to ignore Args: fname: File name containing patterns Returns: A list of patterns """ values = [] with open(fname, 'r') as f: lines = f.readlines() for line in lines: values.append(line.rstrip('\n')) return values
6a2b4aad3bb4f2747e91a0b1a9a58b70187d1d1e
701,653
def _parse_xtekct_file(file_path): """Parse a X-tec-CT file into a dictionary Only = is considered valid separators Parameters ---------- file_path : string The path to the file to be parsed Returns ------- string A dictionary containing ...
744f67638c50573cfa7d568238b488f12e59217b
701,654
def removeObstacle(numRows, numColumns, lot): """ See shortestMazePath for more info. This is similar to shortestMazePath with slightly different conditions. 1 <= numRows, numColumns <= 1000 """ possible_paths = { 'left': [-1, 0], 'right': [1, 0], 'up': [0, 1], 'd...
2a1d541742b478f1132b01e018a7aed1b9e7493c
701,655
def _read_stimtime_AFNI(stimtime_files, n_C, n_S, scan_onoff): """ Utility called by gen_design. It reads in one or more stimulus timing file comforming to AFNI style, and return a list (size of ``[number of runs \\* number of conditions]``) of dictionary including onsets, durations and weig...
5fcda88f9d29606ee2e13e005d9523d58ef88e9c
701,656
def isok(num: int): """주어진 인수가 0과 1로만 이루어져 있을 경우 참 반환""" cnv = set(int(n) for n in str(num)) return all(e in {0, 1} for e in cnv)
bb47608695029ef9450b29b7c69c16a00f1032f5
701,657
def heapsort(values): """Heapsorts a list of values in nondecreasing order.""" length = len(values) def pick_child(parent): left = parent * 2 + 1 if left >= length: return None right = left + 1 if right == length or values[left] >= values[right]: ret...
74e1afaf33e474611e842e97032a60a28fe5664d
701,658
def get_array_info(subs, dictofsubs): """ Returns information needed to create and access members of the numpy array based upon the string names given to them in the model file. Parameters ---------- subs : Array of strings of subscripts These should be all of the subscript names that a...
ad97545278eddd12e8098dc623024beb797baebc
701,659
import click def validate_nonempty(ctx, param, value): """Validate parameter is not an empty string.""" if not value.strip(): raise click.BadParameter('value cannot be empty') return value
a8dd9a81c7fc7b0d0064fe34e849d35c0ce52a04
701,660
import re def get_genres_from_soup(soup): """Get the genres of a book. Parameters ---------- soup : BeautifulSoup BeautifulSoup object created from a book page. Returns ------- list Book genres. """ genres_elements = soup.find_all('a', {'href': re.compile('/genres...
16db0fc8cb58cdcf19aa89ea8fef27078d33a390
701,661
def truncate(string, length, extra=0, add_whitespace=True): """ Add whitespace to strings shorter than the length, truncate strings longer than the length, replace the last few characters with ellipsis """ # Strip whitespace base = string.strip() difference = length-(len(base)) if diffe...
228612cc4591122085ca358513eac7d025b19e77
701,662
import torch def accuracy(predictions, labels): """ Evaluate accuracy from model predictions against ground truth labels. """ ind = torch.argmax(predictions, 1) # provide labels only for samples, where prediction is available (during the training, not every samples prediction is returned for effic...
484ba64b2239363daddd206e747f6c1456e236c9
701,663
def inet_ntoa(i): """Convert an int to dotted quad.""" return '.'.join(map(str, [(i >> (3-j)*8) & 0xff for j in range(4)]))
b83a6b08118bcd7858cb588f53b71daaf31d358e
701,664
def cleanup_string(string): """ >>> cleanup_string(u', Road - ') u'road' >>> cleanup_string(u',Lighting - ') u'lighting' >>> cleanup_string(u', Length - ') u'length' >>> cleanup_string(None) '' >>> cleanup_string(' LIT ..') 'lit' >>> cleanup_string('poor.') 'poor' ...
5f9a369a52b798ff8c26bea56fbfe585b3612db0
701,665
def is_field_allowed(name, field_filter=None): """ Check is field name is eligible for being split. For example, '__str__' is not, but 'related__field' is. """ if field_filter in ["year", "month", "week", "day", "hour", "minute", "second"]: return False return isinstance(name, s...
8be38b79bab3aeb49219155db0159cc143c38111
701,666
def merge_user_settings(settings): """Return the default linter settings merged with the user's settings.""" user = settings.get('user', {}) default = settings.get('default', {}) if user: tooltip_styles = default.get('tooltip_styles', {}) user_tooltip_styles = user.get('tooltip_styles',...
969457f907d8431c9af6ef8a1b587575cb3ba681
701,667
from typing import Optional from typing import Dict import os def true_color_supported(env: Optional[Dict[str, str]] = None) -> bool: """Check if truecolor is supported by the current tty. Note: this currently only checks to see if COLORTERM contains one of the following enumerated case-sensitive v...
dc69282c90b57bec6ad2eb348ca6c327aacb5426
701,669
def strip_outer_matching_chars(s, outer_char): """ If a string has the same characters wrapped around it, remove them. Make sure the pair match. """ s = s.strip() if (s[0] == s[-1]) and s.startswith(outer_char): return s[1:-1] return s
b55d1f966a8b216dce2d4817117f350f639b9b83
701,671
import sys def get_sentence(lower=True): """Simple function to prompt user for input and return it w/o newline. Frequently used in chat sessions, of course. """ sys.stdout.write("Human: ") sys.stdout.flush() sentence = input() if lower: return sentence.lower() return sentence
8e0ae0591bace7da27dc0d044272793fd397276a
701,672
def mclag_ka_session_dep_check(ka, session_tmout): """Check if the MCLAG Keepalive timer and session timeout values are multiples of each other and keepalive is < session timeout value """ if not session_tmout >= ( 3 * ka): return False, "MCLAG Keepalive:{} Session_timeout:{} values not satisfying ...
3f3fd6a12711c0c290cdb0fbd68cfd1c743ef515
701,673
def lucas(n): """ compute the nth Lucas number """ a, b = 2, 1 # notice that all I had to change from fib were these values? if n == 0: return a for _ in range(n - 1): a, b = b, a + b return b
9d9404edf59690cafc49ba70d7dc776376d1f020
701,674
def _get_edge_attrs(edge_attrs, concat_qualifiers): """ get edge attrs, returns for qualifiers always a list """ attrs = dict() if "qualifiers" not in edge_attrs: attrs["qualifiers"] = [] elif edge_attrs["qualifiers"] is None: attrs["qualifiers"] = edge_attrs["qualifiers"] if at...
8500ae7c606041071264d980155fbada98ba870e
701,675
def pair_align(a, b): """ Accurate Registration. :param a: Point cloud for previous frame. :param b: Point cloud for current frame. :return: The matrix. """ x = 0 return x
033515d87b900a7790c4a461409138d420aa164d
701,678
from typing import Tuple from typing import Union def _verify_data_shape(data, shape, path=None) -> Tuple[bool, Union[str, None]]: """ _verify_data_shape( {'data': []}, {'data': list} ) == (True, None) _verify_data_shape( {'data': ''}, {'data': list} ) == (False, '.data') ...
3e76362938146972d96e34a22373b43dca23381b
701,680
import tempfile import os import tarfile def get_tarinfo(path): """Gets the `TarInfo` object for the file at the specified path. This contains useful information such as the owner and the group. @param path: The path. @type path: str @return: The info for that path @rtype: tarfile.TarInfo ...
365d978083c494bf76c518eeb0fecc8f06d32a0a
701,681
from datetime import datetime def _prepare_transactions(response, telegram_id, mcc_codes): """Parse response from monobank API and return formatted transaction.""" transactions = [] costs_converter = 100.0 for transaction in response: transactions.append(( transaction["id"], ...
0794c0761e7232bf517dd867f4d8bab252b2c708
701,684
def create_dict_playlists_playlistids(p_list, pid_list): """ Create a dictionary of playlists and playlist ids """ playlists_and_playlist_ids = {} for i in range(len(p_list)): playlists_and_playlist_ids[p_list[i]] = pid_list[i] return playlists_and_playlist_ids
173850ed85b3dc774ddea14674e22e701991c807
701,685
def required_input(message, method=input): """ Collect input from user and repeat until they answer. """ result = method(message) while len(result) < 1: result = method(message) return result
c9a21d6e63ab6bdde081db471cf0d2420f9047ea
701,686
def get_first_char(value): """ Returns the first char of the given string :param value: :return: """ return value[:1]
98207e7269371f0177f45a2c85f874e1d9bbb756
701,687
import json def load_instructions(ufilename): """ Expand this, maybe in the readme/docs because it's pretty much the heart and soul of the program. Loads a json file that describes the titlecard. In general, it'll be pairings of json keys and values. There are two keys that are handled specially...
e6b0d5ed81f5bc5c3a1837455f3815b282533e80
701,688
def dfs_search_recursive(G, src): """Entry to recursive Depth First Search.""" marked = {} node_from = {} def dfs(v): """Recursive DFS.""" marked[v] = True for w in G[v]: if not w in marked: node_from[w] = v dfs(w) dfs(src) re...
b433aba6a0d397c355ce578a867cfdebcccd980d
701,689
def is_cat(filename: str) -> bool: """ Returns true if filename is an image of a cat. In the dataset we are using this is indicated by the first letter of the filename; cats are labeled with uppercase letters, dogs with lowercase ones. """ result = filename[0].isupper() # print(f"File: {fil...
ad56c7c3ae28951fc31bcf70fece29bf934e4cec
701,690
def analyze_text(filename): """ Calculate the number of lines and characters in a file :param filename: the name of the file to analyze :raises: IOError: if ``filename`` does not exist or can't be read :return: a tuple where the first element is the number of lines in the file and the second...
1670d3bff0402482e9e33be401e8914eea117f6c
701,691
def auto_adapt_batch(train_size, val_size, batch_count_multiple=1, max_size=256): """ returns a suitable batch size according to train and val dataset size, say max_size = 128, and val_size is smaller than train_size, if val_size < 128, the batch_size1 to be returned is val_size if 128 < val...
d0a6fa9e6bde3d563bd7fad5e2bbcf7068f9ff65
701,692
from typing import Tuple def pascals_triangle(rows: int) -> Tuple[Tuple[int, ...], ...]: """Return tuple containing pascals triangle up to specified length.""" result = [] next_numbers = [1] for _ in range(0, rows): # move row current_numbers = next_numbers next_numbers = [] ...
80c46657d413ff67bf3fc94091fd8a81bdb5a148
701,693
import os def list_results_files(path, instanceid, omittedfiles): """ lists the files associated with an instanceid leavuing out the omittedfiles and in ascending age. :param path: :param instanceid: :param omittedfiles: :return: """ files = sorted(os.listdir(os.path.join(path, instanc...
c7e1d5e62ef1e4dc87a321cf0c391397fad8bc7c
701,694
def two_fer(name="you"): """Returns a string in the two-fer format.""" return "One for " + name + ", one for me."
a7f10a45b214ea1ea79a6956148b3c6677f27e21
701,695
import math def create_pagination(page, results_per_page, total_results): """Create pagination to filter results to manageable amounts.""" pagination = {} # For UI pagination['page'] = page pagination['total_results'] = total_results pagination['total_pages'] = math.ceil(total_results / resul...
d58bf2adee3e090e88aa82a5a91560e8fb1631e0
701,697
def conv_len(a, l): """ Function that converts a number into a bit string of given length :param a: number to convert :param l: length of bit string :return: padded bit string """ b = bin(a)[2:] padding = l - len(b) b = '0' * padding + b return b
b3c28e82c759e3a433ca9b52d7e7726f786e76ff
701,700
import math def a_raininess_oracle(timestep): """Mimics an external data source for raininess Arguments ========= timestep : int Requires a year between 2010 and 2050 Returns ======= raininess : int """ msg = "timestep {} is outside of the range [2010, 2050]".format(time...
e1b4f32f62fe19f95ac876a0acf03fe533858366
701,701
import torch def matrix_to_homogeneous(batch: torch.Tensor) -> torch.Tensor: """ Transforms a given transformation matrix to a homogeneous transformation matrix. Args: batch: the batch of matrices to convert [N, dim, dim] Returns: torch.Tensor: the converted batch of matrices ...
ab3bf1acf1e8fab2d4a4fcdcfd062821bc891b9d
701,702
import struct def readHeader(fd): """read protocol header""" data = fd.recv(6) value = struct.unpack(">bib", data) return value
6f1ac379f9eb1f5862754dd10fced9a817bb664a
701,703
def get_RSI(df, column='Close', time_window=14): """Function to make the RSI values for a given stock dataframe""" # Differential between the Column diff = df[column].diff(1) # Integrity of the difference values up_chg = 0 * diff down_chg = 0 * diff # We consider the upchange as positive...
dca6f44062b8dbc04444f033d2e3b54075ad2ca6
701,704
def find_ch_interest_dict(show_channel_dict : dict, usr_pref_dict : dict): """Pass in show_channel_dict {show:channels} and usr_pref_dict {show: rating}. Returns dictionary {channel : total rating}""" ch_interest_dict = {} for show in usr_pref_dict: if show in show_channel_dict: if show_...
9928b03c0ceea3ea38c3808a5fd4053553f4e5c4
701,706
def is_valid_int(s: str) -> bool: """ Return true if s can be converted into a valid integer, and false otherwise. :param s: value to check if can be converted into a valid integer :return: true if s can be converted into a valid integer, false otherwise >>> is_valid_int("hello") False >>> ...
9d2c849839f6fdcf729a7c1503a3eac3daa5f000
701,707
def clean_software_config(config): """Take an individual `config` data structure (as specified by config_validation.SoftwareSchema) and return a 'clean' version suitable for internal use. This allows for a simplified schema to be available to users whilst preserving consistent internal data structures b...
c89ad5a4b61e4214d4b79ce6782e4fe5a86311bf
701,708
def miller_rabin_d(n: int) -> bool: """Check if n is a prime number via deterministic Miller-Rabin test. Miller showed that it is possible to make the algorithm deterministic by only checking all bases ≤ O(lg(n)^2). Bach later gave a concrete bound, it is only necessary to test all bases a ≤ 2lg(n)^...
ac668cb55e417a6784ba52d1c5da1dc26d3693ad
701,709
from typing import List from typing import Callable def evaluate_predictions(preds: List[List[float]], targets: List[List[float]], metric_func: Callable) -> List[float]: """ Evaluates predictions using a metric function and filtering out invalid targets. ...
7b7f550a0983cbb8af90f13b214a195cdb8cbfe3
701,711
def recommend_size(args, img): """ Recommend size (in pixels) for populated image to reach 300 dpi""" current_ppi = 72.0/img.scale target_ppi = args.normal_ppi scale = target_ppi/current_ppi return (int(img.image.width*scale), int(img.image.height*scale))
b32a0520586984124ba2134dc99ecc0b71cd01df
701,712
from typing import Union def flatten(x: Union[list, tuple]) -> list: """ Flattening function for nested lists and tuples Args: x: List or tuple Returns: object (list): Flat list """ if not isinstance(x, list) and isinstance(x, tuple): raise TypeError("input must be a ...
36c35dfbef4214ccf0f6d355f36865996fd6d88e
701,713
from typing import Mapping def update_nested(original_dict, update_dict): """Update a nested dictionary with another nested dictionary. Has equivalent behaviour to :obj:`dict.update(self, update_dict)`. Args: original_dict (dict): The original dictionary to update. update_dict (dict): The...
a1a372ac4d26066c3fe32cd4ee1a49fff6972cd9
701,714
import argparse def process_command_line_args(): """ Returns: tuple(str, str): Command line args for (config, output) files """ ap = argparse.ArgumentParser() ap.add_argument("-d", "--directory", required=True, help="Path to dot file directory") args = vars(ap.pars...
505e7fc47c06162fb2f1328882a59caa3b0539a2
701,715
def remove_comment(line): """Remove trailing comments from one line.""" start = 0 while True: loc = line.find('#', start) if loc == -1: return line.replace('\\#', '#') elif not (loc and line[loc - 1] == '\\'): return line[:loc].replace('\\#', '#') star...
e2ab53813efd17e00240f747709330c44c875235
701,716
def augment(cls): """Add `time` to kwargs list.""" class New(cls): @staticmethod def _myfun(x, *args, time=0, **kwargs): return super(New,New)._myfun(x) return New
cf08f753ba3af3ff2d2c11ca24c5796d2b0a4c12
701,717
def handle_none(func): """A decorator function to handle cases where partition values are `None` or "__HIVE_DEFAULT_PARTITION__" Args: func (Callable): A function registered to the singledispatch function `partition_to_py` """ def wrapper(primitive_type, value_str): if value_str is Non...
23db0c46a35f2e433735c4a863d5619bf4c3cc55
701,718
from typing import List from typing import Tuple import os import csv def get_location_replacements() -> List[Tuple[str,str]]: """Gets a list of location replacement tuples from csv""" replacements = [] with open(os.path.join(os.path.dirname(__file__), '../config/location.replacements.csv'), 'r') as infile: read...
c1e2a67ed64df8e3610ffd3150b5a5dd1982f61c
701,719
def asInteger(epsg): """ convert EPSG code to integer """ return int(epsg)
18a14944f5f29ec09585757f0edc912b896a12ba
701,720
def monitor_cb(ud, msg): """Callback for the MonitorStates, listening to /click/start_button""" # Return False when you want the MonitorState to terminate return False
34f5065aadf8ec96bbe0fb54b791f7a4385a55b5
701,721
def mag(initial, current): """ Calculates the magnification of a specified value **Parameters** intial: *float* initial value (magnificiation of 1) current: *float* current value **Returns** magnification: *float* the magnification of the current value """ ...
abc8d3603f11e62f57a62c47dc372b4b9ea19b0c
701,722
import re def capitalize(word): """Only capitalize the first letter of a word, even when written in CamlCase. Args: word (str): Input string. Returns: str: Input string with first letter capitalized. """ return re.sub('([a-zA-Z])', lambda x: x.groups()[0].upper(), word, 1)
4f254696e00c24a85a20ea74fc66a32fceb541c6
701,723
import re def cassandra_ddl_repr(data): """Generate a string representation of a map suitable for use in Cassandra DDL.""" if isinstance(data, str): return "'" + re.sub(r"(?<!\\)'", "\\'", data) + "'" elif isinstance(data, dict): pairs = [] for k, v in data.items(): if ...
c81ad24c0185ef10646644b82399c202c2261a1a
701,724
import tempfile def build_dir(): """Test build dir for the sphinx compiled docs.""" return tempfile.mkdtemp()
aef168b1031a9ebc15d502a3aedb89da004caffa
701,725
import csv def read_csv_file(file_name): """ Given a CSV file, read the data into a nested list Input: String corresponding to comma-separated CSV file Output: Nested list consisting of the fields in the CSV file """ with open(file_name, newline='') as csv_file: # don't need to ...
65f9d2edb9ecf020d773a8d8516f31247fa680ed
701,726
def get_all_entries(df, pdbid, cdr): """ Get all entries of a given PDBID and CDR. :param df: dataframe.DataFrame :rtype: pandas.DataFrame """ return df[(df['input_tag'].str.contains(pdbid)) & (df['CDR'] == cdr)]
414eca4481bde0ccc5cdd6e143f7d4b06216a102
701,728
import argparse def process_create_experiment_arguments(): """ Processing command line arguments for 01_create_experiment script """ # defining command line arguments parser = argparse.ArgumentParser() # general arguments parser.add_argument("-d", "--exp_directory", help="Directory where...
e6830a43ad215f03ad59a1b496140d4247aa124d
701,729
def merge_result(res): """ Merges all items in `res` into a list. This command is used when sending a command to multiple nodes and they result from each node should be merged into a single list. """ if not isinstance(res, dict): raise ValueError("Value should be of dict type") re...
28d21ca00316303c0e2fc0400599921154253236
701,730
def get_file_section_name(section_key, section_label=None): """Build a section name as in the config file, given section key and label.""" return section_key + (" {0}".format(section_label) if section_label else "")
01e1f46d2a949315ba2e927ddfab610064539e3b
701,731
import os def FindSrcDirPath(): """Returns the abs path to the src/ dir of the project.""" src_dir = os.path.dirname(os.path.abspath(__file__)) while os.path.basename(src_dir) != 'src': src_dir = os.path.normpath(os.path.join(src_dir, os.pardir)) return src_dir
d41d225fd65b3a6e934abd42bcbbe5c25a064a31
701,732
import re import os def _parse_rptfiles_from_log(log_filename): """Parses Red stdout log and returns a list with the names of output files with repeat coordinates""" rpt_files = [] try: logfile = open(log_filename) except OSError as error: print("# ERROR: cannot open/read file:",...
4607ba7005dfacf747f8dfe36b520737092d1747
701,733
import torch import math def positionalencoding2d(pos_embed_dim, height, width): """ :param pos_embed_dim: dimension of the model embeddings :param height: height of the positions :param width: width of the positions :return: height * width * pos_embed_dim matrix """ if pos_embed_dim % 4 !...
685396742b965df3b409203656707f1868e30c45
701,734
import random def shades_of_jop(): """Return a pretty colour.""" c1 = random.randint(127, 255) c2 = random.randint(0, 127) c3 = random.randint(0, 255) return tuple(random.sample([c1, c2, c3], 3))
366bc5bada332b6de3561d6c906a1880119b02f2
701,735
def _final_frame_length(header, final_frame_bytes): """Calculates the length of a final ciphertext frame, given a complete header and the number of bytes of ciphertext in the final frame. :param header: Complete message header object :type header: aws_encryption_sdk.structures.MessageHeader :param ...
b7029e3b705194ee7daa02b4400d124ffe6efc2a
701,736
def real2complex(input_data): """ Parameters ---------- input_data : row x col x 2 Returns ------- output : row x col """ return input_data[..., 0] + 1j * input_data[..., 1]
9e359903f9653e8ea799a2baedcc9c274471f34f
701,737
def check_is_paired(df, subject, group): """ Check if samples are paired. :param df: pandas dataframe with samples as rows and protein identifiers as columns (with additional columns 'group', 'sample' and 'subject'). :param str subject: column with subject identifiers :param str group: column with ...
38f9b0722e77edb88ff44a7bc73eb24a8f1aa097
701,738
def ascii(object: object) -> str: """ascii.""" return repr(object)
44dc1a77ebd46215aa25a2fea91f9c7c41bd4e7a
701,740
import subprocess import sys import json def collect_clusteroperator_relatedobjects(): """ Returns a list of every namespace listed as a relatedObject by every clusterOperator. This captures managed namespaces that aren't defined in the OCP manifests. """ co_namespaces = [] try: result...
94324dbca3457d76f50d80020f560dad6f97798c
701,742
def specific_heat(mat): """Calculate specifc heat""" cw = 4183 mr = mat['m_heat'] mw = mat['m_w'] Tr = mat['Tr'] Tw = mat['Tw'] Te = mat['Te'] return (mw * cw * (Te - Tw)) / (mr * (Tr - Te))
7d3fbe3f67b3df593c94c93ab7d8523242d17b46
701,743
def _flatten(suitable_for_isinstance): """ isinstance() can accept a bunch of really annoying different types: * a single type * a tuple of types * an arbitrary nested tree of tuples Return a flattened tuple of the given argument. """ types = set() if not isinstance(sui...
5ba63f39b2d22da78f5a362ce6821239714a9e6a
701,745
def attach_tasks(queryset, as_field="tasks_attr"): """Attach tasks as json column to each object of the queryset. :param queryset: A Django user stories queryset object. :param as_field: Attach tasks as an attribute with this name. :return: Queryset object with the additional `as_field` field. """...
02a7e189226f9fb5809d7b4d18f3055e5fbc5462
701,746
import string def PrintableString(s): """For pretty-printing in tests.""" if all(c in string.printable for c in s): return s return repr(s)
4f22a5ed8152039a21e045ea2e04b4cff3dbec85
701,747
import six def bitcast_to_bytes(s): """ Take a string and return a string(PY2) or a bytes(PY3) object. The returned object contains the exact same bytes as the input string. (latin1 <-> unicode transformation is an identity operation for the first 256 code points). """ return s if six.PY2 ...
b902550be03f447a286490653a2a1361257ac88c
701,748