content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
def remove_full_rowspans(rows): """Remove rows in which all cells have the same text.""" return [row for row in rows if len(set(row)) > 1]
af1e4ccbd7e88e79e0f2bd01bf6dfaba4315bea3
103,416
from typing import Tuple import getpass def ask_creds() -> Tuple[str, str]: """manually ask for credentials Returns: Tuple[str, str]: username and password """ username = input("Enter your ProQuest username: ") password = getpass.getpass("Enter your ProQuest password: ") return (username, password)
951ff3ef88c3e6d52fe2b16dbce723bda5c9fea3
516,591
from datetime import datetime def midnight(d): # noqa """Given a datetime.date, return a datetime.datetime of midnight.""" if d is None: return None return datetime(d.year, d.month, d.day)
93c257d21722e8f31feec49fe2be193a833e75c2
263,909
def cwE(nc, w, adj, *args): """ Create column width _profile for cmds.rowColumnlayout command :param nc: number of columns :param w: total width of whole layout :param adj: adjustment number to fit all columns to layout :return: column width """ width = (w - adj) / nc cw = [] for i in range(nc): columnID = i + 1 cw.append((columnID, width)) return cw
6fa0ece3c7661a917c2f6595ab453be6852899b4
456,433
import re def split_hname(hname): """split a hierarchical name (hname) into parts. double '/' is used to escape the '/'. and is transformed into a into single '/' e.g. hname = "network/network-fd02:://64" => ["network", "network-fd02::/64"] :param str hname: hierarchical name :returns: a list with the splitted parts of the hname :rtype: list """ lst = [] cat = None for part in re.split(r"/(?=[^/])", hname): if cat: part = cat + part cat = None if part[-1] == '/': cat = part else: lst.append(part) return lst
bb88dd2164a37c42a109332f6d62a85d2d009198
643,787
def plato_to_gravity(degrees_plato: float) -> float: """ Convert degrees plato to gravity. """ return 259.0 / (259.0 - degrees_plato)
61edbccd590e9344ab69df7af3cc03895426c4c7
230,009
def catwalk(text): """ Replace multiple spaces in a string with a single space. :type text: string :param text: The text to fix. >>> catwalk("this is a long sentence") 'this is a long sentence' """ # Return the fixed version return ' '.join(text.split())
49f00d6e7d584ecaa31454e8cf2d214b937f5002
582,320
def bool_or_none(b): """Return bool(b), but preserve None.""" if b is None: return None else: return bool(b)
14627043e5fd67f11a72be916144269e658b26b1
477,732
def cropImage(image, crop_bottom, crop_top, crop_left, crop_right): """Crop an image. Parameters ---------- image : numpy array The image that is to be cropped crop_bottom, crop_top, crop_left, crop : int How many pixels to crop in each of these directions Returns ------- image: array The image that has been cropped """ if crop_bottom == 0: image = image[crop_top:] else: image = image[crop_top:-crop_bottom] if crop_right == 0: image = image[:, crop_left:] else: image = image[:, crop_left:-crop_right] return image
8ecbeec91e213e8db192bb05e0f5032511608aa4
152,607
def abbr_status(value): """ Converts RFC Status to a short abbreviation """ d = {'Proposed Standard':'PS', 'Draft Standard':'DS', 'Standard':'S', 'Historic':'H', 'Informational':'I', 'Experimental':'E', 'Best Current Practice':'BCP', 'Internet Standard':'IS'} return d.get(value,value)
08025ed44e9c8ea725755f9a07b6a5a04834f896
32,490
def nodes_iter(topology): """Get an iterator for all nodes in the topology""" return topology.nodes_iter()
66613676ae76d1705c9a45eeb336862d99df2ebe
635,902
def last_delta(x): """difference between 2 last elements""" return x[-1]-x[-2]
e7a979b1b2a328b85e413e9c5817efa31d275d61
472,323
def c2f(t): """ Converts Celsius Temperature to Fahrenheit Temperature. """ return t * float(1.8000) + float(32.00)
c7c2fd30d257a0a09aaaa546445e80ef9553e93c
522,546
def get_tri_from_course(course, courses): """ Given a courses dict, return the trimester of the :param course """ for tri in courses: for _course in courses[tri]: if course == _course: return tri
14970e0c7e72d9ef79a717d75a798f35a62aa09c
367,106
import importlib def find_dataset_using_name(dataset_name): """Import the module "data/[dataset_name]_dataset.py". In the file, the class called DatasetNameDataset() will be instantiated. It has to be a subclass of BaseDataset, and it is case-insensitive. """ dataset_filename = "datasets." + dataset_name + "_dataset" datasetlib = importlib.import_module(dataset_filename) dataset = None target_dataset_name = dataset_name.replace('_', '') + 'dataset' for name, cls in datasetlib.__dict__.items(): # print(f"name = {name}, class = {cls}") if name.lower() == target_dataset_name.lower(): # and issubclass(cls, BaseDataset): dataset = cls if dataset is None: raise NotImplementedError( "In %s.py, there should be a subclass of BaseDataset with class name that matches %s in lowercase." % ( dataset_filename, target_dataset_name)) return dataset
961b38ac33b08b08d0be5d7c85c1c6c38ee0fe13
499,304
def _pseudo_alpha(rgb, opacity): """ Given an RGB value in [0, 1], return a new RGB value which blends in a certain amount of white to create a fake alpha effect. This allosws us to produce an alpha-like effect in EPS, which doesn't support transparency. """ return tuple((value * opacity - opacity + 1 for value in rgb))
0326d306c8846b46a7b9225ee5b969ff88e4e47d
687,647
def image_scale(img): """Retrieves the image cell size (e.g., spatial resolution) Args: img (object): ee.Image Returns: float: The nominal scale in meters. """ # bands = img.bandNames() # scales = bands.map(lambda b: img.select([b]).projection().nominalScale()) # scale = ee.Algorithms.If(scales.distinct().size().gt(1), ee.Dictionary.fromLists(bands.getInfo(), scales), scales.get(0)) return img.select(0).projection().nominalScale()
038c14412c7a53dbc77915e99b162f2534361589
187,593
from typing import Union from typing import Dict from typing import List import json def dict_to_formatted_string(dictionary: Union[Dict, List]) -> str: """ Return dictionary as clean string for war room output. Parameters ---------- dictionary : dict | list The dictionary or list to format as a string. Returns ------- str Clean string version of a dictionary Examples -------- >>> example_dict = {'again': 'FsoD', ... 'church': {'go': 'pArcB', 'month': '2009-08-11 16:42:51'}, ... 'production': 5507, ... 'so': [9350, 'awzn', 7105, 'mMRxc']} >>> dict_to_formatted_string(example_dict) 'again: FsoD, church: {go: pArcB, month: 2009-08-11 16:42:51}, production: 5507, so: [9350, awzn, 7105, mMRxc]' """ return json.dumps(dictionary).lstrip('{').rstrip('}').replace('\'', '').replace('\"', '')
2ecc473e68253c14260976cf77f459d67d5b6ef3
457,489
def get_title(soup): """ Get a topic title. Examples -------- >>> title_tag = '<title>title</title>' >>> soup = make_soup(title_tag) >>> get_title(soup) 'title' """ return soup.find('title').text.split('|')[0].strip()
d5ae3581338940f7ac7ddc4949fc294ed16d197e
647,836
def convert_hours_to_days(hours): """ (int or float) -> float Takes time in hours and returns time in days. """ return hours / 24.0
81e3e8a7060aa71b16a8eb4fdc0bac7af996febd
164,914
import re def truncate(text, words=25): """Remove tags and truncate text to the specified number of words.""" return ' '.join(re.sub('(?s)<.*?>', ' ', text).split()[:words])
42cc1f0520a92a6bcbc46501e37dcb6832d8f93f
625,070
def Dictionary_to_XmlTupleString(python_dictionary): """transforms a python dictionary into a xml line in the form <Tuple key1="value1" key2="value2"..keyN="valueN" />""" prefix="<Tuple " postfix=" />" inner="" xml_out="" for key,value in python_dictionary.items(): inner=inner+'{0}="{1}" ' .format(key,value) xml_out=prefix+inner+postfix return xml_out
fe6a52b10dccc4e836bb12ec1c5b26017d075dcf
671,285
import math def calculate_entropy(positives, negatives): """ Given a column, calculate entropy for it Parameters ---------- positives: int Number of positive attributes negatives: int Number of negative attributes Returns ------- float """ # since the calculations are reused, doesn't make sense to do every single time total = positives + negatives # no entropy if we have no elements if total == 0: return 0.0 positive_ratio = positives / total negative_ratio = negatives / total # need to handle case of 0 separately, as that throws error if positive_ratio == 0: positive_entropy = 0 else: positive_entropy = positive_ratio * math.log(positive_ratio, 2) if negative_ratio == 0: negative_entropy = 0 else: negative_entropy = negative_ratio * math.log(negative_ratio, 2) return round(-1 * (positive_entropy + negative_entropy), 5)
424e2d0f9173eab0dd6d8ac9202057ea3f3bd61b
465,444
def arg1(*args): """Returs args[0]. Helpful in making lambdas do more than one thing.""" return args[0]
c4254f3c16d001661088723e093ca4086d483e89
362,109
def background_subtract(meas_area, back_area, meas_time, back_time): """ Background_Subtract will subtract a measured Background peak net area from a sample peak net area. The background peak is converted to the same time scale as the measurement and the subtraction is performed. All inputs are scalar numbers, where Meas_Area and Back_Area represent the net area of a sample net area and background net area respectively. Meas_Time and Back_Time are the livetimes of the measurement and background respectively. """ time_ratio = meas_time / back_time back_to_meas = back_area[0] * time_ratio meas_sub_back = meas_area[0] - back_to_meas meas_uncertainty = meas_area[1] back_uncertainty = back_area[1] * time_ratio meas_sub_back_uncertainty = (meas_uncertainty**2 + back_uncertainty**2)**0.5 sub_peak = [meas_sub_back, meas_sub_back_uncertainty] return sub_peak
36aa96743b396daccb571c6c59c0a0f592f25c29
391,443
def complete_matrix(X): """ input: X: sparse matrix output: Y: same matrix with zeros completed """ Y={} row=0 column=0 for k in X.keys(): row=max(row,k[0]) column=max(column,k[1]) for i in range(1,row+1): for j in range(1,column+1): if (i,j) in X.keys(): Y[i,j]=X[i,j] else: Y[i,j]=0 return Y
c3ceab63ba8282c7d67f562f27baa58481c5e3cd
417,920
import collections import math def shannon_entropy(sequence, log_base=2): """ Calculates the shannon entropy over a sequence of values. Args: sequence: An iterable of values. log_base: What base to use for the logarithm. Common values are: 2 (bits), e (nats), and 10 (bans). Returns: The shannon entropy over the sequence. """ counter = collections.Counter(sequence) n = sum(counter.values()) sequence_sum = 0 for _, count in counter.items(): sequence_sum += (count/n) * math.log(count/n, log_base) return -sequence_sum
5e1760ae666cda2faf477ccb218a3e1faf0b4da2
190,186
def distinct_powers(a, b): """ Finds and returns the number of distinct powers of a and b Example: >>> distinct_powers(5, 5) 15 :param a: Limit of a :type a int :param b: limit of b :type b int :return: number of distinct powers :rtype: int """ # sanity checks if a is None or b is None: raise ValueError("Expected a or b to be an integer") if not isinstance(a, int) or not isinstance(b, int): raise ValueError("Expected a or b to be a integer") powers = set(m ** n for m in range(2, a + 1) for n in range(2, b + 1)) return len(powers)
4f77b03087bc0c0e0b0a8fc90bfc16941e2c1bd0
342,200
def mouse_coll_func(arbiter, space, data): """Simple callback that increases the radius of circles touching the mouse""" s1, s2 = arbiter.shapes s2.unsafe_set_radius(s2.radius + 0.15) return False
0127da96630136e2e058d7e46bb2a3099f673412
380,648
import random def sim_detections(gt, tpr, fpr): """Simulates detection data for a set of ground truth cluster labels and an annotator with a specified TPR and FPR. Returns an array of with same length as input gt, where 1 indicates the simulated annotator detected a cluster and 0 indicates an undetected cluster. Args: gt (array): Array of ground truth cluster labels. 1 indicates a true detection and 0 indicates a false detection. tpr (float): The true positive rate of the annotator. For a ground truth value of 1, it is the probability that the function will output 1, indicating that the simulated annotator detected the true cluster. fpr (float): The false positive rate of the annotator. For a ground truth value of 0, it is the probability that the funciton will output 1, indicating that the simulated annotator falsely detected the cluster. Returns: array: Array of detected cluster labels. A value of 1 indicates that a cluster was detected by the annotator, and 0 indicates that the cluster was not detected by the annotator. """ assert tpr >= 0 and tpr <= 1, "TPR must be between 0 and 1" assert fpr >= 0 and fpr <= 1, "FPR must be between 0 and 1" det_list = [] for item in gt: rand = random.random() if item == 1: if rand < tpr: det_list.append(1) else: det_list.append(0) elif item == 0: if rand < fpr: det_list.append(1) else: det_list.append(0) return det_list
ad8d0ac4423333c64ab1db8b838cba4ed7da4291
27,357
from typing import List from typing import Any def deduplicate(a_list: List[Any]) -> List[Any]: """ deduplicate a list :param a_list: a list of possibly repeating items :returns: a list of unique items """ new_list = [] for item in a_list: if item not in new_list: new_list.append(item) return new_list
d3f9181bcb196a8f518eb208ec615fdbd4f0be04
165,990
def read_sym_table(sym_table_path: str) -> dict: """Read in a kaldi style symbol table. Each line in the symbol table file is "sym index", separated by a whitespace. Args: sym_table_path: Path to the symbol table file. Returns: sym_table: A dictionary whose keys are symbols and values are indices. """ sym_table = {} with open(sym_table_path, 'r') as reader: for each_line in reader: key, val = each_line.split() val = int(val) if key not in sym_table: sym_table[key] = val else: raise ValueError("Duplicated key: %s", key) return sym_table
02b8811fe125358ec60ca98ba8eb15074b5be826
527,515
import math def latlon2equirectangular(lat, lon, phi_er=0, lambda_er=0): """Naive equirectangular projection. This is the same as considering (lat,lon) == (y,x). This is a lot faster but only works if you are far enough from the poles and the dateline. :param lat: :param lon: :param phi_er: The standard parallels (north and south of the equator) where the scale of the projection is true :param lambda_er: The central meridian of the map """ x = (lon - lambda_er) * math.cos(phi_er) y = lat - phi_er return y, x
84b423595df0c1036246d3ac0ee68627575ecfcc
146,301
def money_with_currency(money): """A filter function that returns a number formatted with currency info.""" return f"$ {money / 100.0:.2f} USD"
b35569883abc855c6b633e7d91d93c87f86834bf
529,215
def check_is_iterable(py_obj): """ Check whether a python object is a built-in iterable. Note: this treats unicode and string as NON ITERABLE Args: py_obj: python object to test Returns: iter_ok (bool): True if item is iterable, False is item is not """ # Check if py_obj is an accepted iterable and return return(isinstance(py_obj, (tuple, list, set)))
9d5c912a94237f71f6f85a479720dcbcc06144f8
415,898
def get_simple_split(branchfile): """Splits the branchfile argument and assuming branch is the first path component in branchfile, will return branch and file else None.""" index = branchfile.find('/') if index == -1: return None, None branch, file = branchfile.split('/', 1) return branch, file
2dc4dd86add1ee90937ee36d873c255b9ed1cd01
487,448
from collections.abc import Sequence def is_list_like(obj): """ This function checks if the given `obj` is a list-like (list, tuple, Series...) type or not. Parameters ---------- obj : object of any type which needs to be validated. Returns ------- Boolean: True or False depending on whether the input `obj` is like-like or not. """ if isinstance(obj, (Sequence,)) and not isinstance(obj, (str, bytes)): return True else: return False
993ef0b572302ac24fe61e4a41fd2c845b35a7b6
553,915
from typing import Iterable def const_col(dims: Iterable[int]) -> str: """ Name of an constant columns. Parameters ---------- dims Dimensions, that describe the column content. Returns ------- name: str Column name. Example ------- >>> from rle_array.testing import const_col >>> const_col([1, 2]) 'const_1_2' >>> const_col([2, 1]) 'const_1_2' """ dims = sorted(dims) dims_str = [str(d) for d in dims] return f"const_{'_'.join(dims_str)}"
52aecf5872f6444bf0155f0556ce39b2250ce758
40,847
import attr def struct(*args, **kw): """ Wrapper around ``attr.s``. Sets ``slots=True`` and ``auto_attribs=True``. All other arguments are forwared to ``attr.s``. """ return attr.s(*args, slots=True, auto_attribs=True, **kw)
1eee1044ee340b2fe9387773304751d4efca209f
31,222
import time def _create_etag() -> str: """Generate the current timestamp to use as etag.""" return str(time.time())
b96eaf2409aab3d5ecc33eb93f2facbefaf874fd
236,522
def AA2n(s): """ >>> AA2n('AA') 27 >>> AA2n('A') 1 >>> AA2n('BC') 55 """ v = 0 for i in s: v *= 26 n = ord(i) - ord('A') n += 1 v += n return v
48706143526bab792c043b4cb224a464fefb6208
508,899
def construct_return_tuple(original_ctypes_sequence): """Generate a return value for queryf(), scanf(), and sscanf() out of the list of ctypes objects. :param original_ctypes_sequence: a sequence of ctypes objects, i.e. c_long, c_double, and ctypes strings. :returns: The pythonic variants of the ctypes objects, in a form suitable to be returned by a function: None if empty, single value, or tuple of all values. """ length = len(original_ctypes_sequence) if length == 0: return None elif length == 1: return original_ctypes_sequence[0].value else: return tuple([argument.value for argument in original_ctypes_sequence])
2183cb0266873184cdbc9dccbb1494e6999ee93c
227,409
def checkanswer(possible, guess): """ Case insensitive check of answer. Assume inputs are in the correct format, since takeQuiz() accounts for Args: possible (list): List of possible answers for question. guess (string): User's guess for question. Returns: bool: True if guess is in possible, False otherwise. """ #In order to be user friendly, check for strings that are lowercased for answer in possible: if guess.lower() == answer.lower(): return True return False
efd7d81b83d23f62f85f65b6b000c1c4dd9ff98a
455,113
def read_log_file(file_path): """ reads the values from a log_file :param file_path: path to the log file :return: indices, values => indices and values for them """ indices, values = [], [] # initialize these to empty lists with open(file_path, "r") as filer: for line in filer: ind, val = line.strip().split("\t") ind, val = int(ind), float(val) indices.append(ind) values.append(val) return indices, values
546fa9c9ff39763bd045ad9c36898d3c62cdf8f3
481,104
from typing import Union def num_format(num: Union[int,float], precision: int = 3) -> str: """Return a properly formated string for a number at some precision. Formats a number to some precesion with trailing 0 and . removed. Args: num (Union[int,float]): Number to be formatted. precision (int, optional): Precision to use. Defaults to 3. Returns: str: String representation of the number.""" return ('%.*f' % (precision, num)).rstrip('0').rstrip('.')
91ae5f2dadfed57a24a6f3e9a14a81e2e35f770d
545,098
import time def getMDY(t): """Return MMM DD, YYYY.""" tm = time.strptime(t, "%Y-%m-%d %H:%M:%S") return time.strftime("%b %d, %Y", tm)
631de3ca3eb1ca753c8e523c81d4d81f086a71f2
516,869
from typing import Tuple import math def calc_differential_steering_angle_x_y(b: int, dl: float, dr: float, o: float) -> Tuple[float, float, float]: """ Calculate the next orientation, x and y values of a two-wheel propelled object based on the differential steering principle. :param b: the distance between the two wheels. :param dl: linear displacement of the left motor in pixels. :param dr: linear displacement of the right motor in pixels. :param o: current orientation of the object in radians. :return: the new orientation in degrees and the new x and y values in pixels. """ dc = (dr + dl) / 2 diff_angle = (dr - dl) / b diff_x = dc * math.cos(diff_angle + o) diff_y = dc * math.sin(diff_angle + o) return diff_angle, diff_x, diff_y
bd9c2bac7296e188930b51b7d5c1775f6af2ad9f
593,958
def is_my_argument_a_string(maybe_string): """In this challenge you need check to see what type of object the variable 'maybe_string' is. If it is a string type please return a true if it is not a string object please return false. """ return isinstance(maybe_string, str)
154e50b645c0c14e84940c3ebff0bd71bb10f598
225,767
def _get_mc_host(host=None): """Gets the host of the ModelCatalog""" if host is None: return "model-catalog"
9e656f31d7c5949000347d3d1d8c06840d99539c
535,484
def gethHfieldop(hx, hy, hz, l=2): """ Return magnetic field operator for one l-shell. Returns ------- hHfieldOperator : dict Elements of the form: ((sorb1,'c'), (sorb2,'a') : h_value where sorb1 is a superindex of (l, s, m). """ hHfieldOperator = {} for m in range(-l, l + 1): hHfieldOperator[(((l, 1, m), "c"), ((l, 0, m), "a"))] = hx / 2 hHfieldOperator[(((l, 0, m), "c"), ((l, 1, m), "a"))] = hx / 2 hHfieldOperator[(((l, 1, m), "c"), ((l, 0, m), "a"))] += -hy * 1j / 2 hHfieldOperator[(((l, 0, m), "c"), ((l, 1, m), "a"))] += hy * 1j / 2 for s in range(2): hHfieldOperator[(((l, s, m), "c"), ((l, s, m), "a"))] = hz / 2 if s == 1 else -hz / 2 return hHfieldOperator
4d9f7e343de40fe68d8b4b2ee49ca894c5e063fb
599,087
def _interp_fit(y0, y1, y_mid, f0, f1, dt): """Fit coefficients for 4th order polynomial interpolation. Args: y0: function value at the start of the interval. y1: function value at the end of the interval. y_mid: function value at the mid-point of the interval. f0: derivative value at the start of the interval. f1: derivative value at the end of the interval. dt: width of the interval. Returns: List of coefficients `[a, b, c, d, e]` for interpolating with the polynomial `p = a * x ** 4 + b * x ** 3 + c * x ** 2 + d * x + e` for values of `x` between 0 (start of interval) and 1 (end of interval). """ a = 2 * dt * (f1 - f0) - 8 * (y1 + y0) + 16 * y_mid b = dt * (5 * f0 - 3 * f1) + 18 * y0 + 14 * y1 - 32 * y_mid c = dt * (f1 - 4 * f0) - 11 * y0 - 5 * y1 + 16 * y_mid d = dt * f0 e = y0 return [e, d, c, b, a]
0884c0980dba3b819e62df1b36055d5b21670104
526,283
import math def guessDistanceTrig(targetHeight, ownHeight, angleOffset, angle): """ Uses the difference between two heights and an angle to construct a right triangle and tangent to determine the horizontal distance. """ return (targetHeight - ownHeight) / math.tan(math.radians(angle + angleOffset))
a7228673c84d0e37a69d3340ae0d2dfe6acf02dc
237,628
import asyncio async def wait_for_event(evt, timeout): # pylint: disable=invalid-name """Wait for an event with a timeout""" try: await asyncio.wait_for(evt.wait(), timeout) except asyncio.TimeoutError: pass return evt.is_set()
b8b2616f36f12db092c8f12a402115df863dff6f
663,043
import re def try_include(line): """ Checks to see if the given line is an include. If so return the included filename, otherwise None. """ match = re.match('^#include\s*[<"]?(.*)[>"]?$', line) return match.group(1) if match else None
f30c885ffa783f78f5a71dc1906ac6e158226361
27,775
def triggered_telescopes(array, trigger_threshold): """ Return the list of telescopes that triggered in the array Parameters ---------- array: list of telescope Class trigger_threshold: float Returns ------- list of telescope Class """ trig_tel = [tel for tel in array if tel.signal_hist.sum() > trigger_threshold] return trig_tel
39f0ff7a1d042af3c4fbe09698ac6dc07df305e4
359,382
def clean_data(df): """ This function cleans data from the provided dataframe Parameters: df is the dataframe with the messages and categories Return: df is the dataframe already clean with no duplicates """ print("df shape=",df.shape) duplicate = df[df.duplicated()] print("df shape of duplicates=",duplicate.shape ) # drop duplicates df.drop_duplicates(inplace=True) # check number of duplicates duplicate = df[df.duplicated()] print("df shape with no duplicates=",duplicate.shape ) print("Dataframes columns = ", df.columns) print("Dataframe head=",df.head()) df['related'] = df['related'].astype('str').str.replace('2', '1') df['related'] = df['related'].astype('int') return df
7becbeb82c79ac0319b1dbacc65afcca0a1f7359
647,239
def underline(line, underline='~'): """Return an underline string for ``line``. Intended for use with level 3 and lower headings. Note that the default for ``underline`` assumes that the level 1 and 2 underlines are the standard ``=`` and ``-``. You can pass a different underline character to this function if needed. """ if line.endswith('\n'): line = line[:-1] return "{}\n".format(underline * len(line))
27d898f92d15fbe50be133b61887c1211173979c
179,604
def backslash_remove(text): """Return text without backslashes""" return text.replace('\\', '')
43771acac84fd57bfa0f21223b2f82735e42c7d8
256,637
def quick_sort(seq): """Quicksort method.""" if isinstance(seq, list): if len(seq) <= 1: return seq piv, seq = seq[0], seq[1:] low, high = [x for x in seq if x <= piv], [x for x in seq if x > piv] return quick_sort(low) + [piv] + quick_sort(high) else: raise TypeError('Input type must be a list.')
47e5691b6808993d8e4387f1f10f03ab656be443
609,109
import random import math def randCoord(cLat=38.889484, cLong=-77.035278, radius=10000): """ Generate a random lat/long within a radius of a central location :param cLat: central points latitude, in degrees :param cLong: central points longitude, in degrees :param radius: radius to generate points, in degrees :return: tuple - lat, long """ rad = radius/111300 rand_1 = float(random.uniform(0.0, 1.0)) rand_2 = float(random.uniform(0.0, 1.0)) w = rad * math.sqrt(rand_1) t = 2 * math.pi * rand_2 deltaLat = w * math.cos(t) deltaLong = w * math.sin(t) return f'{deltaLat+cLat:.6f}', f'{deltaLong+cLong:.6f}'
a86f1e13c56d66e898d557e73c5aa05b09e6455e
452,403
import shlex def get_flexbar_options_string(args): """ Extract the flags and options specified for flexbar added with add_flexbar_options. Parameters --------- args: argparse.Namespace The parsed arguments Returns ------- flexbar_options: string a string containing flexbar options suitable to pass to another command """ args_dict = vars(args) s = "" if args_dict['flexbar_options']: flexbar_option_str = "--flexbar-options {}".format( ' '.join(shlex.quote(flx_op) for flx_op in args_dict['flexbar_options'])) s = "{}".format(' '.join([s, flexbar_option_str])) return s
72ba73bd51d037c3d6ad3f523913b1de93e5a729
401,601
import base64 def decode(b64): """ Decode given attribute encoded by using Base64 encoding. The result is returned as regular Python string. Note that TypeError might be thrown when the input data are not encoded properly. """ barray = base64.b64decode(b64) return barray.decode('ascii')
5c04c43247d1415ca8f1398c3b8206c50a7e0fa4
14,282
from typing import List def _clean_names_refstate(names: List[str]) -> List[str]: """Uniformization of refstate profile names.""" to_clean = { 'Tref': 'T', 'rhoref': 'rho', 'tcond': 'Tcond', } return [to_clean.get(n, n) for n in names]
29b3618bbe0b8f8e9922d91681d4761f769815c8
54,274
from typing import Callable from typing import Any import importlib def get_function_by_name(func_str: str) -> Callable[..., Any]: """Get a function by its name. Args: func_str (str): Name of function including module, like 'tensorflow.nn.softplus'. Returns: Callable[Any]: the function. Raises: KeyError: Function does not exists. """ module_name, _, func_name = func_str.rpartition(".") if module_name: module = importlib.import_module(module_name) return getattr(module, func_name) return globals()[func_name]
f7a0fb35ab49b15b10668a16561609e6bd3f2355
355,683
def get_root_id(org_client): """ Query deployed AWS Organization for its Root ID. """ roots = org_client.list_roots()['Roots'] if len(roots) >1: raise RuntimeError("org_client.list_roots returned multiple roots.") return roots[0]['Id']
58c27ddf61e2a4d892eb90b3d64c7766fb1c0010
262,310
def _to_http_url(url: str) -> str: """Git over SSH -> GitHub https URL.""" if url.startswith("git@github.com:"): _, repo_slug = url.split(':') return f"https://github.com/{repo_slug}" return url
7bb6f5477dbf2e62cc480a78cf12cfee9ec7c1f6
512,009
from typing import Tuple def _s2_face_uv_to_xyz( # pylint: disable=invalid-name face: int, uv: Tuple[float, float] ) -> Tuple[float, float, float]: """ Convert face + UV to S2Point XYZ. See s2geometry/blob/c59d0ca01ae3976db7f8abdc83fcc871a3a95186/src/s2/s2coords.h#L348-L357 Args: face: The S2 face for the input point. uv: The S2 face UV coordinates. Returns: The unnormalised S2Point XYZ. Raises: ValueError: If the face is not valid in range 0-5. """ # Face -> XYZ components -> indices with negation: # 0 -> ( 1, u, v) -> ( /, 0, 1) # 1 -> (-u, 1, v) -> (-0, /, 1) # 2 -> (-u, -v, 1) -> (-0, -1, /) # 3 -> (-1, -v, -u) -> (-/, -1, -0) <- -1 here means -1 times the value in index 1, # 4 -> ( v, -1, -u) -> ( 1, -/, -0) not index -1 # 5 -> ( v, u, -1) -> ( 1, 0, -/) if face == 0: s2_point = (1, uv[0], uv[1]) elif face == 1: s2_point = (-uv[0], 1, uv[1]) elif face == 2: s2_point = (-uv[0], -uv[1], 1) elif face == 3: s2_point = (-1, -uv[1], -uv[0]) elif face == 4: s2_point = (uv[1], -1, -uv[0]) elif face == 5: s2_point = (uv[1], uv[0], -1) else: raise ValueError('Cannot convert UV to XYZ with invalid face: {}'.format(face)) return s2_point
2df5372e6bb3d304e386dcf2abdbd72dc75397aa
556,517
import torch def get_device(gpus: int) -> torch.device: """ Return the device type to use. If the system has GPUs available and the user didn't explicitly specify 0 GPUs, the device type will be 'cuda'. Otherwise, the device type will be 'cpu' which will be significantly slower. Parameters ---------- gpus : int An ``int`` of the number of GPUs to use during training. Returns ------- torch.device Returns the specific type of device to use for computations where applicable. """ if gpus > 0: return torch.device('cuda') else: return torch.device('cpu')
3fa7bbf5a39914428f215bce2b7dab9a06b6a4ba
113,797
def _get_jira_label(gh_label): """ Reformat a github API label item as something suitable for JIRA """ return gh_label["name"].replace(" ", "-")
0e734c64198b6ccab6515317d60b6fa799ae8870
128,051
import requests import json def send_request( url, authKey ): """Send a request Send a request using the provided url and authentication key. Raise an exception if the request fails. When successful, return the json data replied by the server """ try: headers = {'Accept' : 'application/json', 'X-Auth-AccessKey' :authKey } r = requests.get(url, headers=headers) r.raise_for_status() return json.loads(r.text) except Exception as e: raise Exception("send_request failed : \n\t- {} \n\t- {}".format(type(e), e))
6253aacef6addefe9f795252f91bc094d19d6fc7
524,569
def get_filename(disposition): """Parse Content-Disposition header to pull out the filename bit. See: http://tools.ietf.org/html/rfc2616#section-19.5.1 """ if disposition: params = [param.strip() for param in disposition.split(';')[1:]] for param in params: if '=' in param: name, value = param.split('=', 1) if name == 'filename': return value.strip('"')
b24907fa6820d5d80f53cbd2e1c14a9578b959d6
558,169
import six def _objectToDict(obj): """ Convert an object to a dictionary. Any non-private attribute that is an integer, float, or string is returned in the dictionary. :param obj: a python object or class. :returns: a dictionary of values for the object. """ return {key: getattr(obj, key) for key in dir(obj) if not key.startswith('_') and isinstance(getattr(obj, key), tuple([float, tuple] + list(six.string_types) + list(six.integer_types)))}
b65303a667b36ee0bab9110556392a85ec902c3c
57,422
def theta_map(mat, z): """ Evaluates the conformal map "theta" defined by a matrix [a,b],[c,d] theta = (a*z + b)/(c*z + d). """ [a, b], [c, d] = mat return (a*z + b)/(c*z + d)
ab7fae009d93c8de0c4c8935600ce19588ed8a40
588,975
def pad(tokens, length, pad_value=0): """add padding 1s to a sequence to that it has the desired length""" return tokens + [pad_value] * (length - len(tokens))
43ddf4229856d630f464aaaee21ebdeb8edc1980
562,406
def closestMatch(value, _set): """Returns an element of the set that is closest to the supplied value""" a = 0 element = _set[0] while(a<len(_set)): if((_set[a]-value)*(_set[a]-value)<(element-value)*(element-value)): element=_set[a] a = a + 1 return element
204709e6e1305a23fec39c64c851c2487d5bc753
251,063
def get_filter_name(filter_obj): """ Get filter name Args: filter_obj: Returns: str """ sql_expression = filter_obj.get("sqlExpression") if sql_expression: return sql_expression clause = filter_obj.get("clause") column = filter_obj.get("subject") operator = filter_obj.get("operator") comparator = filter_obj.get("comparator") return f"{clause} {column} {operator} {comparator}"
e3094eca8186e1edc957a1531bf5bd274e697ad5
476,562
def divide(dividend, divisor): """ :param dividend: a numerical value :param divisor: a numerical :return: a numerical value if division is possible. Otherwise, None """ quotient = None if divisor is not None : if divisor != 0: quotient = dividend / divisor return quotient
e5e6678f7de33524444b3bcd40fa45c21f42c77d
38,811
import math def circle(center_pt, radius): """ Creates a polygon with the given center point and radius center_pt: center of circle, as tuple (x, y) radius: radius of circle return: list of tuples representing points on circle boundary. first and last point should be the same. """ circle_points = [(radius*math.cos(i)+center_pt[0],radius*math.sin(i)+center_pt[0]) for i in range(0,360)] return circle_points
d87c8cfa268fd3f7ae11540f96e220ee951ad20d
232,056
def get_color_name(color_int): """Gets a human readable name for a traffic sign color. Args: color_int: ID of traffic light color (specified in styx_msgs/TrafficLight). Returns: A string corresponding to the color name. """ color_int_map = { 0: "RED", 1: "YELLOW", 2: "GREEN", 4: "UNKNOWN", } return color_int_map.get(color_int, "UNKNOWN")
2f73c6f5e8a70110ded2ade1ce5d6f7320db2f4f
553,491
def cat2axis(cat): """ Axis is the dimension to sum (the pythonic way). Cat is the dimension that remains at the end (the Keops way). :param cat: 0 or 1 :return: axis: 1 or 0 """ if cat in [0, 1]: return (cat + 1) % 2 else: raise ValueError("Category should be Vi or Vj.")
ad33bf7a70d468c5eb9a98529b751ab8254ae24c
53,536
def format_time(msec): """Converts msec to correct unit. Returns it as formatted string.""" if msec < 10**3: #ms return str(msec)+"ms" else: return str(msec//1000)+"s"
fcf34cc6c5c7c74424b6d9ac7f0609a3ab515300
474,682
from typing import List import re def extract_jira_references(text: str) -> List[str]: """ Extract identifiers that point to Jira tickets """ return [result.group(0) for result in re.finditer(r"\w+-\d+", text)]
a9f428d9ed30119908a96c9bd8aac360ec177c46
222,836
def lagrange(x_data, y_data): """ Compute the interpolant polynomial corresponding to the points given in (x_data, y_data) Parameters ---------- x_data : list List with x coordinates for the interpolation. y_data : list List with y coordinates for the interpolation. Returns ------- fun_poly : Python function Interpolant polynomial as evaluable function. """ def fun_poly(x): num = len(x_data) acu = 0 for i in range(num): prod = 1 for j in range(num): if i == j: continue prod = prod * (x - x_data[j])/(x_data[i] - x_data[j]) acu = acu + prod * y_data[i] return acu return fun_poly
ae2ba231948d61327830ffe2cb255c0575b3a52e
386,268
import collections def find_consensus(sequences, threshold=0.7): """ Given aligned sequences, return a string where each position i is the consensus value at position i if at least threshold fraction of strings have the same character that position i, and "." otherwise. """ if len(sequences) == 0: return "" num_needed = len(sequences) * threshold max_len = max(len(s) for s in sequences) sequences = [s.ljust(max_len, ".") for s in sequences] result = [] for i in range(max_len): chars = collections.Counter(s[i] for s in sequences) (char, count) = chars.most_common()[0] if char == "." and count >= num_needed: # most strings have terminated break result.append(char if count >= num_needed else ".") return "".join(result).strip(".")
3994f417977b2c89ea49b87452513481914e4697
404,434
import hmac import hashlib def gen_sign(key, data): """Compute RFC 2104-compliant HMAC signature.""" return hmac.new(key, data.encode('utf-8'), hashlib.sha256).digest()
d25ba278581e49f7197a0ac8524a00fef68ac36b
325,748
def Moffat2D(x, y, amplitude=1.0, x_0=512.0, y_0=512.0, x_gamma=6.0, y_gamma=6.0, alpha=1.0): """Two dimensional Moffat function with different scale parameters for both axes""" rr_gg = (x - x_0) ** 2 / x_gamma**2 + (y - y_0) ** 2 / y_gamma ** 2 return amplitude * (1 + rr_gg) ** (-alpha)
1451a83d8e9f6a1fc49132b1b4a244f92a5dcdfe
561,090
def get_sequence_name_from(seq_name_and_family): """Get sequence name from concatenated sequence name and family string. Args: seq_name_and_family: string. Of the form `sequence_name`_`family_accession`, like OLF1_CHICK/41-290_PF00001.20. Output would be OLF1_CHICK/41-290. Returns: string. Sequence name. """ return '_'.join(seq_name_and_family.split('_')[0:2])
25377994f92353efdae25deb42a315beb4c345a9
234,142
def color_to_hex(name): """Convert a named ReportLab color (Color class) to a hexadecimal string""" _tuple = (int(name.red*255), int(name.green*255), int(name.blue*255)) _string = '#%02x%02x%02x' % _tuple return _string.upper()
e1eba5f284ef90dfcb6bde8ef75739c58a62f89c
345,556
def tokens_from_module(module): """ Helper method; takes a module and returns a list of all token classes specified in module.__all__. Useful when custom tokens are defined in single module. """ return [getattr(module, name) for name in module.__all__]
da1c53f9f1c56784c81000f98a3be9e675956e2a
92,934
def xpath_lower_case(context, values): """Return lower cased values in XPath.""" return [v.lower() for v in values]
f9048bc16ea717ec6f0538ab8217a0e1e2223c0d
96,059
def get_chunks(sequence, chunk_size): """Split sequence into chunks. :param list sequence: :param int chunk_size: """ return [ sequence[idx:idx + chunk_size] for idx in range(0, len(sequence), chunk_size) ]
b7abdf160e6eacc635372d7fb07d09330cea292c
510,256
from typing import Dict from typing import List def convert_spin_to_list(spins: Dict) -> List: """Convert the Spin dictionary from the ssoCard into a list. Add the spin index as parameter to the Spin entries. Parameters ---------- spin : dict The dictionary located at parameters.physical.spin in the ssoCard. Returns ------- list A list of dictionaries, with one dictionary for each entry in parameters.physical.spin after removing the index layer. """ spin_dicts = [] for spin_id, spin_dict in spins.items(): spin_dict["id_"] = spin_id spin_dicts.append(spin_dict) return spin_dicts
0d06523abe118305bbef13d681cb1d811628edda
43,947
def enact_interventions(background_inmate_turnover, background_release_number, time, infected_list, release_number, social_distance, social_distance_tau, stop_inflow_at_intervention, tau): """Enacts specified interventions.""" # Print intervention info print(f'Release intervention condition met:\n\tTime: {time}\n\t# of infected: {len(infected_list)}') # Release intervention r_n = background_release_number if release_number: print(f'\tReleasing {release_number} inmates.') r_n += release_number # Stopping-inmate-inflow intervention if stop_inflow_at_intervention: print('\tStopping inmate inflow.') background_inmate_turnover = 0 # Social distancing intervention if social_distance: print('\tEnacting social distancing.') tau = social_distance_tau return background_inmate_turnover, r_n, tau
2816a9670d25c281642461256d2e464c9d4274c1
623,745
from typing import List def generate_pairs(number: int) -> List[List[int]]: """Generate all pairs of number sequence. Args: number: <int> the number Returns: <list> a sequence Examples: >>> assert generate_pairs(1) == [[0, 0], [0, 1], [1, 1]] """ return [ [top, inner] for top in range(number + 1) for inner in range(top, number + 1) ]
1f711fca8774ce06dc291d45aff1d4ac3b1388e1
636,538
def synchronous_events_intersection(sse1, sse2, intersection='linkwise'): """ Given two sequences of synchronous events (SSEs) `sse1` and `sse2`, each consisting of a pool of positions `(iK, jK)` of matrix entries and associated synchronous events `SK`, finds the intersection among them. The intersection can be performed 'pixelwise' or 'linkwise'. * if 'pixelwise', it yields a new SSE which retains only events in `sse1` whose pixel position matches a pixel position in `sse2`. This operation is not symmetric: `intersection(sse1, sse2) != intersection(sse2, sse1)`. * if 'linkwise', an additional step is performed where each retained synchronous event `SK` in `sse1` is intersected with the corresponding event in `sse2`. This yields a symmetric operation: `intersection(sse1, sse2) = intersection(sse2, sse1)`. Both `sse1` and `sse2` must be provided as dictionaries of the type .. centered:: {(i1, j1): S1, (i2, j2): S2, ..., (iK, jK): SK}, where each `i`, `j` is an integer and each `S` is a set of neuron IDs. Parameters ---------- sse1, sse2 : dict Each is a dictionary of pixel positions `(i, j)` as keys and sets `S` of synchronous events as values (see above). intersection : {'pixelwise', 'linkwise'}, optional The type of intersection to perform among the two SSEs (see above). Default: 'linkwise'. Returns ------- sse_new : dict A new SSE (same structure as `sse1` and `sse2`) which retains only the events of `sse1` associated to keys present both in `sse1` and `sse2`. If `intersection = 'linkwise'`, such events are additionally intersected with the associated events in `sse2`. See Also -------- ASSET.extract_synchronous_events : extract SSEs from given spike trains """ sse_new = sse1.copy() for pixel1 in sse1.keys(): if pixel1 not in sse2.keys(): del sse_new[pixel1] if intersection == 'linkwise': for pixel1, link1 in sse_new.items(): sse_new[pixel1] = link1.intersection(sse2[pixel1]) if len(sse_new[pixel1]) == 0: del sse_new[pixel1] elif intersection == 'pixelwise': pass else: raise ValueError( "intersection (=%s) can only be" % intersection + " 'pixelwise' or 'linkwise'") return sse_new
3335f84433f8a82c020689a185d04538fc9660b8
401,203
def rgb2mpl(rgb): """ convert 8 bit RGB data to 0 to 1 range for mpl """ if len(rgb) == 3: return [rgb[0]/255., rgb[1]/255., rgb[2]/255., 1.0] elif len(rgb) == 4: return [rgb[0]/255., rgb[1]/255., rgb[2]/255., rgb[3]/255.]
02a74d00fe43763d69597960359bcc7912b2cf6c
543,876
def get_signed_polygon_area(points): """ Get area 2d polygon :param points: list[DB.UV] :type points: list[DB.UV] :return: Area :rtype: float """ area = 0 j = points[len(points) - 1] for i in points: area += (j.U + i.U) * (j.V - i.V) j = i return area / 2
960d5a3e5bff125fb560580f81b5103fa8147789
20,174
def hash_employee_data(employee_data): """ Hashes employee data by email for quick lookup. This is necessary for efficient comparison of remote and local data. Returns ------- Dictionary - employee email to employee_data """ email_to_employee = {} for employee in employee_data: email_to_employee[employee['email']] = employee return email_to_employee
a62e862e78171f5c98ad7d233fe944419e103b07
303,599
import re def parse_id_name(one_string): """Parses b"500(guest)" (bytes) and returns (500, "guest") (str)""" mtch = re.match(br"^([0-9]*)\(([^)]*)\)$", one_string) if mtch: return mtch.group(1), mtch.group(2).decode("utf-8") return -1, ""
2142c7196565b6166513be1b76273a0f3e6ab62b
158,153
from typing import List import torch import collections def get_balanced_sample_indices(target_classes: List, num_classes, n_per_digit=2) -> List[int]: """Given `target_classes` randomly sample `n_per_digit` for each of the `num_classes` classes.""" permed_indices = torch.randperm(len(target_classes)) if n_per_digit == 0: return [] num_samples_by_class = collections.defaultdict(int) initial_samples = [] for i in range(len(permed_indices)): permed_index = int(permed_indices[i]) index, target = permed_index, int(target_classes[permed_index]) num_target_samples = num_samples_by_class[target] if num_target_samples == n_per_digit: continue initial_samples.append(index) num_samples_by_class[target] += 1 if len(initial_samples) == num_classes * n_per_digit: break return initial_samples
90df01021555ec54a0f3ad5caf36494edd8ae200
204,059