content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import random def evolve(pop, mut_rate, mu, lambda_): """ Evolve the population *pop* using the mu + lambda evolutionary strategy :param pop: a list of individuals, whose size is mu + lambda. The first mu ones are previous parents. :param mut_rate: mutation rate :return: a new generation of indiv...
e2510d0ce92d0c5703b9166778f48581db4aca2f
15,007
import re def strip_comments(source_code): """ Strips comments from source code to increase analysis accuracy. The function is similar to strip_quotations. It removes all comments from the source_code. It is also used to prevent false positives. It uses a regex to match and remove line comments a...
7e3842940367caaae875ec6c24a1a40fdf7efbc0
15,008
def preprocess_data(data, label_encoder): """ Get input columns from raw data """ # Remove Tree Name column input_data = data """ Encode Categorical variables """ for i,item in enumerate(input_data[0,:]): if isinstance(item, str) is True: input_data[:, i] = label_encoder.fit_tra...
50f03f59a3ea98915d760f74a888780af69b1c68
15,009
def make_ratings_hash(ratings): """ Make a hashtable of ratings indexed by itemId and pointing to the vector (genres, decade) that fully characterize an item. """ rhash = {} # For every rating, check if the relevant item is already in the map. # If not, add it to the map. Key...
e105f08dbdbec544dccdcd299aaf189ef64691b7
15,012
def predecessor(self, root): """ One step left and then always right """ root = root.left while root.right: root = root.right return root.val
77b22323f4623df3002b9e7d12123d4ee9a98cad
15,013
def get_rules(rules_module): """ Get rule functions from module :param rules_module: module with rules implementations :return: rule functions """ rules = [] for item in dir(rules_module): if item.startswith("rule"): rules.append(getattr(rules_module, item)) return ru...
41b9428f0893a153700a19f4237453af8910a759
15,014
def format_pun_list(header, entries, footer, *, cnt=1): """ Generate the management list of entries. """ msg = header for ent in entries: msg += '{}) {}\n Hits: {:4d}\n\n'.format(cnt, ent.text, ent.hits) cnt += 1 msg = msg.rstrip() msg += footer return msg
3393c0f01fba1cef412a5b68e1ca180af86b3693
15,015
import requests def _download_chunk(args): """Download a single chunk. :param args: Tuple consisting of (url, start, finish) with start and finish being byte offsets. :return: Tuple of chunk id and chunk data """ idx, args = args url, start, finish = args range_string = '{}-'.format(start...
eb88e1200fff8d336908d2247e12c46576bb4422
15,017
import torch def discounted_cumsum(rewards, discount): """Calculates the cummulative sum of discounted rewards Arguments: rewards {torch.Tensor} -- rewards discount {float} -- discount factor Returns: [type] -- cummulative sum of discounted rewards """ discount **= torch.a...
b0e2cd45c4cb6882a84784c64a20ae64995f26a6
15,019
def histogram(content): """ Takes a source_text contents of the file as a string and return a histogram data structure that stores each unique word along with the number of times the word appears in the source text.""" words = content.split() # Dictionary histogram_dic = {'one': 1, 'fi...
28af6161b05472fef9632bfb0df7e0672ed9359c
15,020
def _StripPC(addr, cpu_arch): """Strips the Thumb bit a program counter address when appropriate. Args: addr: the program counter address cpu_arch: Target CPU architecture. Returns: The stripped program counter address. """ if cpu_arch == "arm": return addr & ~1 return addr
9127f10cbbeb71814f6c9f30e7446d5f8233bb67
15,021
from pathlib import Path import pickle def fetch_data(name): """Fetches data with the given name. Data is stored in a file namemed name.pickle in the current directory. """ filename = Path(__file__).parent / (name + ".pickle") with open(filename, 'rb') as f: return pickle.load(f)
2bc908ec29555f3d7dd4263b816cb9727c7f8f85
15,022
import random def get_random_replicates(well_df, replicate_cardinality): """This function return a list of random replicates that are not of the same compounds or found in the current cpd's size list """ while (True): # Randomly sample replicate names random_replicates = random.sample(...
294d7c431d9e80baca25cc8cb6022558874c3674
15,023
import curses def set_window_parameters(): """ Function to set all the window sizes and placements on the screen. Returns a dictionary of all curses windows where key is a string that is the title of the window (eg 'twitter'), and the value is the curses window object. """ max_y, max_x =...
9be542c065665ab22afdb692a635fa31adfa9a32
15,024
def compute_weighted_profile_average(profile, attribute): """ :param profile: :param attribute: """ return sum([getattr(entry, attribute) * weight for entry, weight in profile]) / \ sum([weight for entry, weight in profile])
9bed1ff173c9cda9a88458ff1484d903a5ee2696
15,025
def prune(set_list): """ Prunes combinations that are not identical in symbols. :param set_list: the list of sets containing nodes. :return the pruned list """ symbol_set_list = [{symbol for _, _, symbol in current_set} for current_set in set_list] return [sl for _, sl in list(filter(lambda...
530c6be1df860bed87540ba2080096f2c318e9bf
15,027
def domains_to_xyt(xyt, domains): """ This function takes in xyt data and a list of domains and converts the list of domains into a list of xyt points within those domains. This list can then be used to graph the domains onto the entire worm path, for visualization. :param xyt: A list of xyt points....
56bb2614d3f612913b19c550ed042e6a635ae4fa
15,028
def replicaset_status(client, module): """ Return the replicaset status document from MongoDB # https://docs.mongodb.com/manual/reference/command/replSetGetStatus/ """ rs = client.admin.command('replSetGetStatus') return rs
eb46cd1e28ecb1f2c6c5a222d176438677bd8e8c
15,029
def new_user_form(): """Display an HTML form for user creation.""" return """ <form action='/users' method='POST'> Username: <input name='username' type='text'/> Password: <input name='password' type='password'/> Bio: <textarea name='bio'></textarea> <button type='submit'>Su...
1aeb4ba99ec5aa91bdc9c064da020e3eebb6b9ed
15,032
from textwrap import dedent def minimal_html_page( body: str, css: str = "", title: str = "Standalone HTML", lang: str = "en" ): """Return a template for a minimal HTML page.""" return dedent( """\ <!DOCTYPE html> <html lang="{lang}"> <head> <meta charset="utf-8"> <title>{title...
71397e60fefab240dbd0b173e437ef90be4b8493
15,033
def _common_strategies(choices): """Generate some common strategies to deal with multiple references.""" return {'min': min(choices), 'max': max(choices), 'avg': sum(choices) * 1. / len(choices) }
ffe0070667aabe2ab8072bb39a6e452341780c41
15,034
import struct def doubleToRawLongBits(value): """ :param value: A float value :return: The IEEE 754 biit representation of the given double-precision floating-point value. """ return struct.unpack('Q', struct.pack('d', value))[0]
8c5c525e481a50225a6bd99fffbd7fb0555aba79
15,035
import re def tokenize(text, regex=r'[a-zA-z]+'): """Split text into tokens using a regular expression :param text: text to be tokenized :param regex: regular expression used to match tokens using re.findall :return: a list of resulting tokens >>> tokenize('the rain in spain') ['the', 'rain', 'in', 'sp...
c7daee14ec14ff4a22d42883f3b3e3827924389e
15,036
def cover_phone_number(no): """ >>> cover_phone_number('01234 567 890') '01234 *** *** **' """ result = '' for order, digit in enumerate(no): if order < 5: result = result + digit else: if order in (5, 8, 11): result = result + ' ' ...
d33d98e915135644119a66d39ac8f9fc80770d62
15,040
from typing import Iterable def concatenate_lists(*list_of_lists: Iterable) -> list: """Combines the Iterables provided as arguments into one list. Examples -------- Normal usage:: concatenate_lists([1, 2], [3, 4], [5]) # returns [1, 2, 3, 4, 5] """ return [item for lst in li...
e630fd31888753814e3f486c02b0fc1e67f269ef
15,041
import os def getPathList(folderFullName: str) -> list: """ 특정 폴더의 전체 파일을 리스트 형태로 반환합니다. :param folderFullName:파일명을 가져올 대상 경로. 절대경로 :return: 대상 경로 안에 들어있는 모든 경로들을 절대 경로로 반환(list) """ fullNameList = [] for dirName, subDirList, fnames in os.walk(folderFullName): for fname in fnames: ...
ff4ee0f6a49922acd5e7cbdb5db709489e2c1454
15,042
def getAria2SpinSystems(ariaRestraint): """Descrn: Get the pairs of ARIA spin systems that correspond to the contributions to an ARIA restraint Inputs: Aria2 restraint object Output: List of 2-List of ARIA SpinSystem objects """ spinSystemPairs = [] for contribution in ariaRestraint.getC...
22a6d717787ec74144457451b78a4651577f9619
15,043
def is_attr_pattern(text): """Attribute patters are like '[title=Version \d.*]' """ return text.startswith('[')
05978edb1d6589f47a96ab6cb2da4b7f0e3f2569
15,044
def test_input_data(): """A set of fields required to validate the company form""" return { 'DUNS Number': '123456789', 'Business Name': 'Widgets Pty', 'Secondary Name': 'Lots-a-widgets', 'National Identification System Code': '12', 'National Identification Number': '123...
34f1826119882a9fb1a8fadc40845a435bcdfb98
15,045
import os import random def generate_meta(images_dir, output_file, n_images): """ Helper method for generating metadata from a folder of images. Generated metadata is compatible with the task specification. """ images_dir = images_dir.resolve(strict=True) img_names = os.listdir(images_dir) ...
7045ce168af0db2a894183eca72fac53c92fea46
15,046
def determine_feature_dtype(X, features): """ Determine if any features are categorical. """ feature_names = list(X.columns) non_cat_features = [] cat_features = [] for f in features: if f not in feature_names: raise KeyError(f"'{f}' is not a valid feature.") if ...
39368183612f214e9b1385be0d3bc716f7eaa950
15,047
def strip_nondigits(string): """ Return a string containing only the digits of the input string. """ return ''.join([c for c in string if c.isdigit()])
564a05de12c61a09a6d07e13b13279908128389a
15,049
def get_top_card_symbol(hand): """ :param hand: rankbit of a given hand without any repetition :return: the rankbit rep of the top card in the current hand """ i = 0 while hand >> i != 0: i += 1 return 1 << i
578f69f9c1b00f367670bf7d4bb95becb412cee1
15,050
def parse_begins(msg): """Parse the guard ID out of the "begins his shift" message.""" words = msg.split() return int(words[1][1:])
b07e3d741038365dddbacfdb70d219ef1bf007d8
15,052
import pickle def load_pickle(file_name): """ load a pickle object from the given pickle file :param file_name: path to the pickle file :return: obj => read pickle object """ with open(file_name, "rb") as pick: obj = pickle.load(pick) return obj
e50ae7ccd4b72700e5079774c45ec91b240bc88a
15,055
def find_extremes(content_list): """Calculates the smallest and highest values of every position's column of the positions of features of a wortverbund. Args: content_list: list with features of a wortverbund and their positions of occurrence. Returns: ...
75fccb7cd483bfe9e2de0440a93c77a380aef9ad
15,057
import glob import os def get_track_ids(annot_dir): """Obtains the track ids of all the files contained in the experiment. Parameters ---------- annot_dir: str Path to the annotations directory where all the jams file reside. Retutns ------- track_ids: list List containin...
39293496c792bcb429f46aab93c694e231b0d8a4
15,058
def get_t_epoch(jd): """ Get the JD in julian centuries """ t = (jd - 2451545.0) / 36525. return t
6605018efc72e37b635240180575e31fb08352b1
15,059
from typing import List from typing import Dict from typing import Union def format_resources(resources: List[str], resource_param: List[str], kwargs: Dict[str, Union[List[str], str]]): """ >>> resources=['hello/{user_name}'] >>> resource_param=['user_name'] >>> kwargs={'user_name': "bob"} >>> x =...
9a50c0ee34b07cb228dda781668dd61b94ebaa67
15,060
import glob import os def get_present_scene_ids(dp_split): """Returns ID's of scenes present in the specified dataset split. :param dp_split: Path to a folder with datasets. :return: List with scene ID's. """ scene_dirs = [d for d in glob.glob(os.path.join(dp_split['split_path'], '*')) if o...
fd3661db7d80aae15635782bedcdd2ca508fbc8a
15,061
import os def _readme(): """Find the README.*. Prefer README.rst Returns: str: Name of README """ for which in 'README.rst', 'README.md', 'README.txt': if os.path.exists(which): return which raise ValueError('You need to create a README.rst')
1fa683974bd542e51de344ab28db027730b47c97
15,062
def baits(path_to_file, created_baitset_id=None, build='GRCh37'): """Reads the bed-file and returns a list of dictionaries Args: path_to_file(): path tp temp file Returns: bait_dict_list(list): a list of dictionaries with the keys: chromosome, chr_start, chr_stop """ bait_dict_list...
8f05b295a233bd42d1baf40d3ad03477e192e425
15,064
def prepend_domain(link): """ Urls are directly combined as given in *args """ top_level_domain ='https://www.proff.no' return top_level_domain + link
25e599d2744100aeea71556751906dc1a9166428
15,066
def ref_str_to_tuple(ref): """String like ' a : b ' to tuple like ('a', 'b').""" return tuple(x.strip() for x in ref.split(':'))
fc2e467f054d2b53a580f1d0917d01eda9ba1727
15,067
def bin_append(a, b, length=None): """ Appends number a to the left of b bin_append(0b1, 0b10) = 0b110 """ length = length or b.bit_length() return (a << length) | b
c2d3132532b1d9311d5b6eef94289c0763422665
15,069
def levenshtein_distance(word_1, word_2): """ Calculates the levenshtein distance (= the number of letters to add/ substitute/interchange in order to pass from word_1 to word_2) """ array = [[0 for i in range(len(word_2)+1)] for y in range(len(word_1)+1)] for i in range(len(word_1)+1): ...
ce43e60454b59c3c1323656636f457bc192a2c67
15,070
import inspect def get_source_link(obj, page_info): """ Returns the link to the source code of an object on GitHub. """ package_name = page_info["package_name"] version = page_info.get("version", "master") base_link = f"https://github.com/huggingface/{package_name}/blob/{version}/src/" mod...
86748f179e44cec37efd88e1b8dc5de0c6268631
15,071
def concat_environment(env1, env2): """ Concatenate two environments. 1 - Check duplicated keys and concatenate their values. 2 - Update the concatenated environment. Parameters ---------- env1: dict (mandatory) First environment. env2: dict (mandatory) Second environment. ...
25f7aee5a9316ab0604f2e38538a1f67a5333b08
15,072
import re def is_path(source): """ check if the supplied source is a valid path (this does not appear to be part of moments.path module, but could be relocated there) ** this will not match relative paths ** """ if re.match('/', source): return True else: return False
405ff439b2785c54b30877574408e65a4f36e3de
15,073
import argparse def parse_cmdargs(): """ Using argparse module, get commandline arguments :return: """ parser = argparse.ArgumentParser(description='Parse Covid19 dataset from JHU-CSSE, add ' 'population data and dump combined data to ' ...
dbe753a45e2c7fdb4c882167825635ec5e1f30b6
15,074
import itertools def get_emin_emax(self): """ Finds how much the Ek_grid has to be expanded above the bandwidth D of the leads. Parameters ---------- self : Approach2vN Approach2vN object. self.funcp.emin : float (Modifies) Minimal energy in the updated Ek_grid. self....
102198b413f190264e231c80f896045fc2eb3f58
15,076
import re def substitute_pattern_with_char(s, pattern, repl_char='x'): """ This is a little different than re.sub(). It replaces all the characters that match the pattern with an equal number of `repl_char` characters. The resulting string should be the same length as the starting string. >>> su...
98d7f3d642430a5211aa7396a3454d979057ebef
15,077
def extract_table_name(file_name: str) -> str: """Extract the table name name from the filename Assumes the name of the bigquery table the data is being inserted to is the first word of the filename Examples: extract_file_extension(properties/properties_09.csv) >>> "properties" """ re...
1cac0a58325651abff1399974df52aaefa93585f
15,079
def calculate_block_ranges(scan, block_size): """ :param scans :type a scan object :param block_size: :type block_size: target block size in degrees""" image_ranges = [] nimages = scan.get_num_images() osc_range = scan.get_oscillation_range(deg=True) osc_width = abs(osc_range[1] - ...
1ea1f8ecb6b7a3a5713a7169effcf0db2d9eac06
15,080
import random def _randbytes(n: int) -> bytes: """Polyfill for random.randbytes in Python < 3.9""" return bytes(random.choices(range(256), k=n))
5d6b0a734774dc28d45d53cc2dfeedc8a986a8a5
15,082
def duel(Player, CPU): """ flag = 0 --> HAI PERSO flag = 1 --> PAREGGIO flag = 2 --> HAI VINTO """ flag = 0 # Initialize the flag if(CPU.cpu == Player.p_value): flag = 1 else: if(CPU.cpu == "sasso"): if(Player.p_value == "carta"): flag = 2 if(Pla...
9248d86e14ae0783f87dcee42e0fd9a8299f0150
15,083
def avg(arr): """Count average.""" return sum(arr) / float(len(arr))
0da964cdb1d14154b4569d010b4caa710a30fd84
15,084
import numpy as np def get_time_course_for_columns( time_course_data_set, col_indices=None ): """ Pick out a set of columns :param time_course_data_set: :param col_indices: :return: """ if col_indices is None or None in col_indices: return None data = np.ndarray( shape=(len...
1ec4570f37ad7eff10e201a934e05accea7aecbc
15,086
from typing import Any def get_full_name(obj: Any) -> str: """Returns identifier name for the given callable. Should be equal to the import path: obj == import_object(get_full_name(obj)) Parameters ---------- obj : object The object to find the classpath for. Returns ---...
6f83f808f8c4d226b1d26365adc75f5cb6c4e28f
15,087
from statistics import mean from collections import namedtuple def infer_user_based_cf(model, train, test): """ Infer user CF Vanilla """ # Users' mean ratings - (user, mean_rating) mean_user_ratings = train.map(lambda x: (x['user_id'],x['stars']))\ .groupByKey()\ ...
15185905fb86dcb40dfc29f0d1c58e142bb8bd42
15,088
def estimate_microturbulence(effective_temperature, surface_gravity): """ Estimate microtubulence from relations between effective temperature and surface gravity. For giants (logg < 3.5) the relationship employed is from Kirby et al. (2008, ) and for dwarfs (logg >= 3.5) the Reddy et al. (2003) rel...
bf54342e00fc61f042f183c8bbebc01005eb6b4c
15,089
from platform import python_version def pl_python_version() -> str: # pragma: no cover """ Stored procedure that returns databases python interpreter version @return: semantic python version X.X.X """ return python_version()
4c46818a35bf5b793fdfb58f0e8648efe59a777e
15,090
import yaml from typing import OrderedDict def ordered_dump(data, stream, Dumper=yaml.Dumper, representer=OrderedDict, **kwds): """ write data dict into a yaml file. :param: data: input dict :param stream: output yaml file :param Dumper: yaml.Dumper :param representer: =OrderedDict to write in...
77fd33e7726a75d7e2f93955e96118f6ff14e1a4
15,092
def search_the_word(word_dict, search_word): """word_dict => a list of words to search from. search_word => a word to search for in the provided list. USAGE: This function is used to search for a word in a list of provided list of other words. It proviides a mathch according to ...
311f63fb903e63e75a99b5ebbd09de5aba3a899c
15,093
def fO2(celsius, bars=1., buffer_curve='QFM'): """ Input: Temperature in Celcius Pressure in bars (default is 1) Buffer curve. Options are QFM (default), NNO, and IW QFM = quartz - fayalite - magnetite buffer (default) NNO = Ni-NiO IW = iron-wustite; ...
a3bf160d4e0a51aed168e1aac783b90e5278c953
15,094
def compute_graph(local, rules): """ Obtain a DAG given an STA """ graph = {} for l in local: graph[l] = [r['to'] for r in rules if r['from'] == l and r['to'] != r['from']] return graph
94bde12c64a461a3bcb296568deccf3bc7624bd0
15,095
import os def energy_from_log(): """Get the total energy from the GROMACS log file""" if not os.path.exists('energy.log'): exit('energy.log did not exist - cannot obtain the energy') energy_filelines = open('energy.log', 'r').readlines() try: total_energy_idx = next(i for i, line in...
2e1c11655e6a3b3df7a966a7066a3a2126164374
15,097
import re def messagestat_formatting(messageBody): """ Formats the message body for messagestat functions. This mostly involves replacing spaces with underscores and doubling up on quotations so that SQL server ignores them """ messageBody = re.sub(' ', '_', messageBody) messageBody = ...
f91a8fe73b336f97be8322c6b5034013090e0807
15,099
def change_pals_col_names(pals_df): """ :param pals_df: A dataframe returned fromm the PALS package :return: The pals_df with columns removed and headings changed for use on the website """ pals_df.reset_index(inplace=True) columns = pals_df.columns # Drop the columns that are not required ...
ff81ca9f200bc80e2037b14779d674c98e2f155d
15,100
def get_sol_ud_model_columns(df_columns): """Get experimental condition features.""" sol_ud_model_columns = list(filter(lambda column_name: column_name.startswith('_rxn_') and not column_name.startswith('_rxn_v0'), df_columns)) sol_ud_model_columns.remove('_rxn_organic-inchikey') return sol_ud_model_col...
ab05433a6cb05af82c4642c27fb5cb85851e88e7
15,102
def _ngrams_from_tokens(tokens, n, join=True, join_str=' '): """ Helper function to produce ngrams of length `n` from a list of string tokens `tokens`. :param tokens: list of string tokens :param n: size of ngrams :param join: if True, join each ngram by `join_str`, i.e. return list of ngram string...
39afd35a4e715ea3e358a81d3a557eb1f0f0310a
15,103
def parse_prior_params(bt_config, code_config, key, default, prior='pre'): """ Parse parameters with priority. Args: bt_config(dict): bt config code_config(dict): code config key(string): parameter name default(default): default value prior(string): use bt_config in ...
beee29f04562173d18cc95b2b49683dee02fbca8
15,104
def map_merge_cubes(process): """ """ # intentionally empty, just for clarity # the only thing needed for this process is to create a new pickled object from the input ones, already mapped by other functions in map_processes.py return []
26d247c6ddb0ae217edd58666126ebb94bda0c7a
15,105
def entity_tostring(entity): """Converts one GNL (Google Natural Language) entity to a readable string.""" metadata = ", ".join(['"%s": "%s"' % (key, value) for key, value in entity.metadata.items()]) mentions = ", ".join(['"%s"' % mention for mention in entity.mentions]) re...
dd3e30247e36186e6eccfe1e32f8f31bf3577660
15,108
import sys import select def has_data_from_stdin(): """ Check if any data comes from stdin. :return: True if there are data from stdin, otherwise False """ if select.select([sys.stdin, ], [], [], 0.0)[0]: return True else: return False
005928784fc121877cfe9f4857b95427556c8b79
15,109
import networkx def graph_from_dict(d): """ Creates a NetworkX Graph from a dictionary Parameters ---------- d : dict Returns ------- Graph: NetworkX Graph Examples -------- >>> g = graph_from_dict({'a':['b'], 'b':['c', 'd'], 'c':[], 'd':[], 'e':['d']}) """ g = netw...
e0029b6018ff840bd2f314038c25f41e025600a7
15,110
def dectobin(dec_string): """Convert a decimal string to binary string""" bin_string = bin(int(dec_string)) return bin_string[2:]
5f02507ae5e7ab855eceb7a5908347060b46a400
15,111
def underscorize(camelcased): """ Takes a CamelCase string and returns a separated_with_underscores version of that name in all lower case. If the name is already all in lower case and/or separated with underscores, then the returned string is identical to the original. This function is used to ta...
b0f2622c105c09502aa984e15cf1b61ac12a608b
15,112
def best_validation_rows(log_df, valid_col='valid_accuracy', second_criterion='iterations_done'): """ Takes a dataframe created by scripts/logs_to_dataframe.py and returns a dataframe containing the best-validation row for each log. """ return log_df.sort_values([valid_col,second_criterion],ascendin...
9541adb6653a93bfe0385bd24beedf80b065dde7
15,114
def get_kwargs(names, defaults, kwargs): """Return wanted parameters, check remaining. 1. Extracts parameters `names` from `kwargs`, filling them with the `defaults`-value if it is not in `kwargs`. 2. Check remaining kwargs; - Raise an error if it is an unknown keyword; - Print warnin...
20720215c9d1e2849b519c9f6ce2d8eb074752c3
15,115
def n_mask_items(request): """Percentage of items to mask on init""" return request.param
10c1214b8dca81fde59428835302abe35fc72d23
15,118
def align(source): """Return a string containing the same program but aligned to the start of a transaction or command (in that order). This function does not run a complete syntax check, but raises an ValueError, if the source is commented incorrectly. Examples: >>> align("+67; O=0, O+66;...
228a1fe4bbc94e20b08828fb03e9714ca8acd6f9
15,119
import os def mkdir_even_if_exists(path,name): """creates a directory ubder path with a given name. If exists, adds integer number to directory name. returns directory full path""" directory = os.path.join(path,name) if os.path.exists(directory): i = 0 while True: directory...
141be84f9a0aa8fb40f5044aa6607cd2eec01c73
15,120
def getMsgTime(line): """Parse the timestamp off the 978 message and return as a float. Args: line (str): Line containing a 978 message with a timestamp at the end. Returns: float: Timestamp of the message. Raises: Exception: If the timestamp can't be f...
860a02a28d154357d6fcc61de182fee1f4875aaa
15,121
import os def get_student_id(username): """ Obtain a user's Student ID number from the server (if tied into the WPI network). :param username: The user's username (WPI network username) :return: Student ID number """ try: uid = os.popen('id -u ' + username).read().replace('\n', '') ...
1c0d99473b773a1d76ef5dec69762c660e060f17
15,122
def _counting_sort(a, max_value): """ sorting positive integers less than or equal to max_value """ result = [] counter = [0] * (max_value + 1) for i in a: counter[i] += 1 for i, count in enumerate(counter): result.extend([i]* count) return result
8d81ec58e851eab73011ee180c1fe60c36b46675
15,123
import os def auto_delete_photo_on_update(sender, instance, **kwargs): """ Deletes old photo from filesystem when Profile object is updated with new photo. """ if not instance.pk: return False try: old_photo = sender.objects.get(pk=instance.pk).photo except sender.DoesNot...
f6aaf0c9b35a775d14f42e696a25d06dddd7f4e0
15,124
def GetAllFields(fielddefs): """Extract L{objects.QueryFieldDefinition} from field definitions. @rtype: list of L{objects.QueryFieldDefinition} """ return [fdef for (fdef, _, _, _) in fielddefs]
0a831dc1eadad01a91bfb131feae4ecc0e5cb1f2
15,125
def ordinalize(given_number: int) -> str: """Ordinalize the number from the given number Args: given_number (int): integer number Example: >>> ordinalize(34) '34th' Returns: str: string in ordinal form """ suffix = ["th", "st", "nd", "rd"] thenum = int(given_number...
e0b43b3b8353e9e79d2f13a36198782a2a5dcd73
15,126
def get_filenames(hda_dict): """ Generates a list of filenames taken from the results dictionary, retrieved with the function request_results_list. Parameters: hda_dict: dictionary initied with the function init, that stores all required information to be able to ...
c14911b14fa2b31f061b4420875c603d8acce5c1
15,127
def get_fibonacci_ints(ints, length): """f(n) = f(n-1) + f(n-2)""" first = ints[0] second = ints[1] if length == 1: return [first] if length == 2: return [first, second] ints = get_fibonacci_ints(ints, length=length - 1) ints.append(ints[-1] + ints[-2]) return ints
ff9e1691183560f12cb844af0e0a9b9f9579efd6
15,130
import numpy import pandas def metrics_to_pandas(metrics): """ Place holder for an attempt to make a generic Pandas object for the metrics service. However, for this to work well, you need to know all the possible year keys, and so currently as it is written it won't result in necessarily all the ...
af1ae73f2b94680adb838682d97ac926a34ec36e
15,131
def is_copula_relation(token1, token2): """Return True if `token1` is a copula dependent of `token2`. We don't want to capture cases where `token2` is an adjective, because we capture those in `is_predicated_adjective_relation()`. """ return ( (token1.deprel == "cop") and (token2.u...
35e7b19c3cf1662c09a8fd80c8099073de11bc51
15,133
def get_glass_spec_category(glass_spec_name): """ガラスの仕様の区分はガラスの仕様に応じて返す Args: glass_spec_name(str): ガラスの仕様 Returns: int: ガラスの仕様の区分はガラスの仕様に応じて返す """ # 表3 ガラスの仕様の区分 table_3 = { '2枚以上のガラス表面にLow-E膜を使用したLow-E三層複層ガラス(日射取得型)': 6, '2枚以上のガラス表面にLow-E膜を使用したLow-E三層複層ガラス(日射遮蔽型)...
e5fbd29c438384931102744a97e7cd94c96a8478
15,134
import math def calculate_coordinates(valid_dict: list) -> list: """ Calculate the coordinates using trigonometry This takes a list of dictionaries of the format `[{'testuser':[6, 4, 3, 10, 5]}, {'testuser2':[1, 5, 17, 20, 6]}]` and then returns a list of coordinates. These coordinates can be used to...
b648a965c83df841778fe4030e2b9729cbac2c59
15,135
import os def get_file(filename=None): """ Returns either imported.expt or imported_experiments.json as filename Parameters ---------- filename: str, optional user can provide which of the imported file to use or program does the searching for you Returns ------- str ...
3f66b4635ee20c37fc65ff02cc670682226ba901
15,136
def _safe_decr(line_num): """ Return @line_num decremented by 1, if @line_num is non None, else None. """ if line_num is not None: return line_num - 1
ad6092b68240f39ccba13fda44bbf8af22d126f4
15,137
def zfun(p,B,pv0,f): """ Steady state solution for z without CRISPR """ return p*(B-1/pv0)/(1+p*(B-1/pv0))
aaddce7a41e0ad9e909e6f5f2bf86354f66c5be8
15,139
def _build_verbose_results(ret, show_success): """ Helper function that builds the results to be returned when the verbose parameter is set """ verbose_results = {'Failure': []} for tag_data in ret.get('Failure', []): tag = tag_data['tag'] verbose_results['Failure'].append({tag: tag...
53f5ad2525893e7277014664555894f51c601d4d
15,143
def _parse_year(cover_display_date): """ :param cover_display_date: :return: entry year """ return cover_display_date[-4:]
c722973f8663aabe15207cc995cff5ec9aece575
15,144