content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
def interval_union(a, b): """Returns a 2-tuple representing the union of two intervals. Args: a: 2-tuple containing integer coordinates representing a half-open interval. b: 2-tuple containing integer coordinates representing the other half-open interval. Returns: 2-tuple containing integer coordinates representing the union(a, b) as a half-open interval. """ return min(a[0], b[0]), max(a[1], b[1])
d7fb8f7cb1e626f99aaa91ee56b3b23a73a92880
259,117
import re def is_valid_coordinates(coordinates): """Test coordinates for validity.""" if re.match('^-?\d+\.?\d*\,{1}\s-?\d+\.?\d*$', coordinates): lat, lon = coordinates.split(', ') return -90 <= float(lat) <= 90 and -180 <= float(lon) <= 180 else: return False
63b9b6d0bb7fd7794e3b75735ebdf72b4f4b4029
390,550
def _use_constant_crc_table(opt): """ Return True is the CRC table is constant. """ if opt.width is not None and opt.poly is not None and opt.reflect_in is not None: return True else: return False
72c6861f80b4e3f81fe9ac97bff4985cd7c18245
444,625
def remove_features(df, drop_list): """ Remove features from dataframe with columns containing substrings in drop_list. Return a new dataframe. """ keep = [] for column_name in list(df.columns.values): keepQ = True for substring in list(drop_list): if substring in column_name: keepQ = False break if keepQ: keep.append(column_name) return df[keep]
084e84d3d7cb6b2c5557c9a91e6ac7077e21f1a0
537,932
import base64 def embed_png2html(figdata_png): """ Convert the data to base64 format before the PNG data can be embedded in HTML Parameters: plt_fig: matplotlib figure Return: figdata_png: base64 encoding images """ figdata_png = base64.b64encode(figdata_png) figdata_png = figdata_png.decode('utf-8') # base64.b64encode return byte return figdata_png
280f429f55d71baeb004aa0b7be41b7bbe2cfbc9
295,021
def get_synchrony(sequences): """ Computes the normalised synchrony between a two or more sequences. Synchrony here refers to positions with identical elements, e.g. two identical sequences have a synchrony of 1, two completely different sequences have a synchrony of 0. The value is normalised by dividing by the number of positions compared. This computation is defined in Cornwell's 2015 book on social sequence analysis, page 230. Example -------- >>> s1 = [1,1,2,2,3] >>> s2 = [1,2,2,3,3] >>> sequences = [s1,s2] >>> ps.get_synchrony(sequences) 0.6 """ shortest_sequence = min([len(s) for s in sequences]) same_elements = [] for position in range(shortest_sequence): elements_at_this_position = [] for sequence in sequences: elements_at_this_position.append(sequence[position]) same_elements.append(elements_at_this_position.count(elements_at_this_position[0]) == len(elements_at_this_position)) return same_elements.count(True) / shortest_sequence
92d48ebbf43869e9ff41a6c81d458b0ae7861016
335,962
def dict_to_kwds(dct, kwdstr): """ convert a dictionary to a string of keywords Parameters ---------- dct : dict kwdstr: str additional keyword strings Examples -------- >>> dict_to_kwds({"a":1,"c":3},'a=1,b=2') 'a=1,c=3,b=2,' """ string = '' for key in sorted(dct.keys()): string += '{0}={1},'.format(key, dct[key]) for kwd in kwdstr.split(","): if not kwd.split('=')[0] + '=' in string: string += kwd + ',' return string
c646c68cb9205d00d55dfda210ed41a7743df0b4
343,311
def add_one(value: int) -> int: """Add one to a number.""" return value + 1
a7230ac288192fc75edebbfb281043b1cf7025b2
434,695
import re def getTimeElementsFromString(dtStr): """Return tuple of (year,month,day,hour,minute,second) from date time string.""" match = re.match(r'^(\d{4})[/-](\d{2})[/-](\d{2})[\s*T](\d{2}):(\d{2}):(\d{2})(?:\.\d+)?Z?$',dtStr) if match: (year,month,day,hour,minute,second) = map(int,match.groups()) else: match = re.match(r'^(\d{4})[/-](\d{2})[/-](\d{2})$',dtStr) if match: (year,month,day) = map(int,match.groups()) (hour,minute,second) = (0,0,0) else: raise(RuntimeError("Failed to recognize date format: %s" % dtStr)) return (year,month,day,hour,minute,second)
e1a2ef030e6041d256cad85a18baf4f3784377d8
125,159
def parseText(text1, nlp): """Run the Spacy parser on the input text that is converted to unicode.""" doc = nlp(text1) return doc
99d6a585358a700f8fc48c5dc4fc761a03ab42a7
705,984
def parse_coordinates(result): """ Function purpose: parse coordinates from console result into a list Input: string Output: list """ bboxStr = result[result.find("[") + 1:result.find("]")] bboxList = [float(i) for i in bboxStr.split(',')] return bboxList
2fb1ee98219618381994960d14aacb0b21abdba3
457,777
def patches2image(patches): """ Return patches obtained from a 2D image into the original image. Args: patches: Tiles to return into the 2D image. Shape = (N_patch_x, N_patch_y, Patch_size_x, Patch_size_y) Return: image: 2D image reconstructed from patches """ assert len(patches.shape) == 4, "patches2image is compatible with image2patches, input patches should be in the shape (N_patch_x, N_patch_y, Patch_size_x, Patch_size_y)" n_h,n_w,p0,p1 = patches.shape return patches.reshape(n_h, n_w, p0,p1).swapaxes(1,2).reshape(n_h*p0,n_w*p1)
e9f78cdf4fa356fce42df01890f0f618f01d732d
317,425
import hashlib def hex_sha1_of_stream(input_stream, content_length): """ Returns the 40-character hex SHA1 checksum of the first content_length bytes in the input stream. :param input_stream: stream object, which exposes read() method :param content_length: expected length of the stream :type content_length: int :rtype: str """ remaining = content_length block_size = 1024 * 1024 digest = hashlib.sha1() while remaining != 0: to_read = min(remaining, block_size) data = input_stream.read(to_read) if len(data) != to_read: raise ValueError( 'content_length(%s) is more than the size of the file' % content_length ) digest.update(data) remaining -= to_read return digest.hexdigest()
fb4666f89a20fe0112840c58600d96915a66510a
283,146
import math def printXYZDegrees(self): """Print X, Y, and Z components in degrees.""" return ("[%f, %f, %f]" % (math.degrees(self.x), math.degrees(self.y), math.degrees(self.z)))
8f48563c13e170a18b1c9a9e6385a842e307d177
649,555
import itertools def _Powerset(input_list): """Create powerset iterator from the elements in a list. Note: Based on example in official Python itertools documentation. Example: [p for p in Powerset(['a', 'b')] == [(), ('a',), ('b'), ('a', 'b')] Args: input_list: A sequence of Python objects Returns: An iterator which loops through all (tuple) elements in the powerset of the input_list. """ return ( itertools.chain.from_iterable( itertools.combinations(input_list, r) for r in range(len(input_list) + 1)))
0218cc5f6b4a5905c0563332d8229c49fd0e8dd2
548,816
import math def calc_heading(currentLat, currentLong, targetLat, targetLong): """ Calculates target heading from coordinates Args: currentLat: Current latitude of the player currentLong: Current longitude of the player targetLat: Target latitude targetLong: Target longitude Returns: Target heading in degrees """ currentLat = math.radians(currentLat) currentLong = math.radians(currentLong) targetLat = math.radians(targetLat) targetLong = math.radians(targetLong) dLat = math.log(math.tan(math.pi/4 + targetLat/2) / math.tan(math.pi/4 + currentLat/2)) dLong = targetLong - currentLong heading = math.degrees(math.atan2(dLong, dLat)) if heading < 0: heading = heading + 360 return int(round(heading))
51392f6a533f7c02c2d392af5ca5fe08188476bb
341,895
def formatDateTime(raw: str) -> str: """ Helper function. Converts Image exif datetime into Python datetime Args: raw (str): exif datetime string Returns: str - python compatible datetime string """ datePieces = raw.split(" ") if len(datePieces) == 2: return datePieces[0].replace(":","-") + " " + datePieces[1].replace("-",":") else: return ""
d9c0ec43e42e1d24223eb8f640d8790ec48b82fc
64,543
def _chi2_ls(f): """Sum of the squares of the residuals. Assumes that f returns residuals. Minimizing this will maximize the likelihood for a data model with gaussian deviates. """ return 0.5 * (f ** 2).sum(0)
af223f48bc0beffa9a99fba872c769a94fbe3235
19,200
from pathlib import Path import inspect def here(frames_back: int = 0) -> Path: """ Get the current directory from which this function is called. Args: frames_back: the number of extra frames to look back. Returns: the directory as a Path instance. """ stack = inspect.stack() previous_frame = stack[1 + frames_back] return Path(previous_frame.filename).parent
a261aeac42b8fe4143783e41a74c1025e937e17d
87,668
def sum_period_review_request_stats(raw_aggregation): """Compute statistics from aggregated review request data for one aggregation point.""" state_dict, late_state_dict, result_dict, assignment_to_closure_days_list, assignment_to_closure_days_count = raw_aggregation res = {} res["state"] = state_dict res["result"] = result_dict res["open"] = sum(state_dict.get(s, 0) for s in ("requested", "accepted")) res["completed"] = sum(state_dict.get(s, 0) for s in ("completed", "part-completed")) res["not_completed"] = sum(state_dict.get(s, 0) for s in state_dict if s in ("rejected", "withdrawn", "overtaken", "no-response")) res["open_late"] = sum(late_state_dict.get(s, 0) for s in ("requested", "accepted")) res["open_in_time"] = res["open"] - res["open_late"] res["completed_late"] = sum(late_state_dict.get(s, 0) for s in ("completed", "part-completed")) res["completed_in_time"] = res["completed"] - res["completed_late"] res["average_assignment_to_closure_days"] = float(sum(assignment_to_closure_days_list)) / (assignment_to_closure_days_count or 1) if assignment_to_closure_days_list else None return res
68a46d89bbe773668ea27a1ac8a04c8f62e45292
466,446
def format_headers(unformatted_dict): """ Utility method for formatting a dictionary of headers. Params: unformatted_dict (dict): Unformatted dictionary being submitted for formatting. Returns: formatted_headers (dict): Dictionary that has been camel cased with spaces replacing underscores("_") """ # Split and title the headers_dicionary for better display. formatted_headers = list() for field in unformatted_dict['ModelBase']: formatted_headers.append(field.replace('_', " ").title()) return formatted_headers
10d09985a811ef3e6cf4d5cf43cf7c998f50548c
387,317
def pass_through_formatter(value): """No op update function.""" return value
202ea761db9e1fa858718c61df3a7fd18f02826c
706,015
def guess_content_type(name): """Return the content type by the extension of the filename.""" if name.endswith(".jpg"): return "image/jpg" elif name.endswith(".jpeg"): return "image/jpeg" elif name.endswith(".png"): return "image/png" elif name.endswith(".gif"): return "image/gif" elif name.endswith(".bmp"): return "image/bmp" return "image/jpg"
3f6681e1df2384e3fcba58eda436cb31c3e8d18c
665,613
import pickle def distance_histogram_dict(f): """Parses distance histogram dict pickle. Distance histograms are stored as pickles of dicts. Write one of these with contacts/write_rr_file.write_pickle_file() Args: f: File-like handle to distance histogram dict pickle. Returns: Dict with fields: probs: (an L x L x num_bins) histogram. num_bins: number of bins for each residue pair min_range: left hand edge of the distance histogram max_range: the extent of the histogram NOT the right hand edge. """ contact_dict = pickle.load(f, encoding='latin1') num_res = len(contact_dict['sequence']) if not all(key in contact_dict.keys() for key in ['probs', 'num_bins', 'min_range', 'max_range']): raise ValueError('The pickled contact dict doesn\'t contain all required ' 'keys: probs, num_bins, min_range, max_range but %s.' % contact_dict.keys()) if contact_dict['probs'].ndim != 3: raise ValueError( 'Probs is not rank 3 but %d' % contact_dict['probs'].ndim) if contact_dict['num_bins'] != contact_dict['probs'].shape[2]: raise ValueError( 'The probs shape doesn\'t match num_bins in the third dimension. ' 'Expected %d got %d.' % (contact_dict['num_bins'], contact_dict['probs'].shape[2])) if contact_dict['probs'].shape[:2] != (num_res, num_res): raise ValueError( 'The first two probs dims (%i, %i) aren\'t equal to len(sequence) %i' % (contact_dict['probs'].shape[0], contact_dict['probs'].shape[1], num_res)) return contact_dict
dcd3a1eca88327a47e4c16b27463d3f0b6c475e4
298,663
from typing import Sequence from typing import List from typing import Tuple def search_sub_seq(s1: Sequence, s2: Sequence) -> List[Tuple[int, int]]: """ Searches all occurrences of sequence s1 in s2, :param s1: First sequence. :type s1: Sequence :param s2: Second sequence. :type s2: Sequence :return: List of searched spans. Span is a tuple [start, end). Empty list maybe return in case when there are no spans found. :rtype: List[Tuple[int, int]] :raise ValueError: When one of input sequences haves zero len. """ if len(s1) == 0 or len(s2) == 0: raise ValueError("Both sequences must have non zero length.") if len(s1) <= len(s2): res = [] for offset in range(0, len(s2) - len(s1) + 1): end_offset = offset + len(s1) if s1 == s2[offset:end_offset]: res.append((offset, end_offset)) return res return []
ef29454bed263dbb7456623f0e5d4254010a6a8e
571,419
import turtle def make_window(color, title): """ Set up the window with the given background color and title. Returns the new window. """ window = turtle.Screen() window.bgcolor(color) window.title(title) return window
e3a23fddbbffd0f4851a28c327b37cebf1bcda5d
599,196
def is_mode_correct(mode_no): """The function checks the correctness of the game mode (number range from 1 to 3).""" try: num = int(mode_no) if num < 1 or num > 3: return False except ValueError: return False return True
4b9218abdc4f66a692bc423fbb2fb6323175e5f2
530,207
def violate_safety_requirement(complete_solution): """Checks whether a complete_solution violates a safety requirement. In case of violation, the function returns `True`, otherwise it returns `False`. Since the definition of fitness function is based on the safety requirement and it is defined in a way that its positive sign indicates a violation and vice versa. :param complete_solution: a complete solution that has a fitness value. """ assert complete_solution is not None, \ "complete_solution cannot be None." assert complete_solution.fitness.values is not None, \ "complete_solution must have a real value." if complete_solution.fitness.values[0] > 0: return True else: return False
c1ee4e79948a68f75893a89270cf807b9f6ef844
365,556
def extract_gp_layer_kwargs(kwargs): """Extracts Gaussian process layer configs from a given kwarg.""" return dict( num_inducing=kwargs.pop("num_inducing", 1024), normalize_input=kwargs.pop("normalize_input", True), gp_cov_momentum=kwargs.pop("gp_cov_momentum", 0.999), gp_cov_ridge_penalty=kwargs.pop("gp_cov_ridge_penalty", 1e-6), scale_random_features=kwargs.pop("scale_random_features", False), l2_regularization=kwargs.pop("l2_regularization", 0.), gp_cov_likelihood=kwargs.pop("gp_cov_likelihood", "gaussian"), return_gp_cov=kwargs.pop("return_gp_cov", True), return_random_features=kwargs.pop("return_random_features", False), use_custom_random_features=kwargs.pop("use_custom_random_features", True), custom_random_features_initializer=kwargs.pop( "custom_random_features_initializer", "random_normal"), custom_random_features_activation=kwargs.pop( "custom_random_features_activation", None))
416097ab3ebe7f8980177862d18e2b0b24005918
575,789
def line_to_int_list(line): """ Args: line: A string of integers. Ex: '1 3 5\n' Returns: A list of integers. Ex: [1, 3, 5] """ data = line.split(' ') data = filter(None, data) data = [int(x.strip('\n')) for x in data] return data
0ba3f984704219f134185a80d7858e176679e8bf
566,560
def frame_to_midi(frame, ignore_graces=True): """ :param list frame: Frame of data from :obj:`~decitala.utils.get_object_indices`. :return: A numpy array holding the pitches within the frame. :rtype: numpy.array >>> from music21 import note >>> my_frame = [ ... (note.Note("B-", quarterLength=0.125), (4.125, 4.25)), ... (note.Note("A", quarterLength=0.25), (4.25, 4.5)), ... (note.Note("B", quarterLength=0.125), (4.5, 4.625)), ... (note.Note("B-", quarterLength=0.125), (4.625, 4.75)), ... (note.Note("A", quarterLength=0.25), (4.75, 5.0)), ... (note.Note("G", quarterLength=0.25), (5.0, 5.25)), ... (note.Note("G", quarterLength=0.25), (5.25, 5.5)), ... ] >>> frame_to_midi(my_frame) [(70,), (69,), (71,), (70,), (69,), (67,), (67,)] """ midi_out = [] for this_obj, this_range in frame: if not(ignore_graces): fpitches = this_obj.pitches midi_out.append(tuple([x.midi for x in fpitches])) else: if this_obj.quarterLength == 0.0: pass else: fpitches = this_obj.pitches midi_out.append(tuple([x.midi for x in fpitches])) return midi_out
b567d7358b4a1a3ccd0a828c7f67ec318ba82a27
135,619
def getmorphology(word, tagmap): """Get morphological features FEATS for a given word.""" if tagmap and word.tag_ in tagmap: # NB: replace '|' to fix invalid value 'PronType=int|rel' in which # 'rel' is not in the required 'attribute=value' format for FEATS. # val may be an int: Person=3 feats = ['%s=%s' % (prop, str(val).replace('|', '/')) for prop, val in tagmap[word.tag_].items() if isinstance(prop, str)] if feats: return '|'.join(feats) return '_'
572499db5e104041900c13d238862739afd1039e
229,655
def indicator_bollinger(df_t, lookback=20): """Creates columns for bollinger channel. Requires columns "high" and "low" in intraday_df Args: df (pd.DataFrame): OHLCV intraday dataframe, only needs close lookback (:obj:int, optional): rolling window. Default is 20 Returns: pd.DataFrame: columns are: - bollinger_high - bollinger_low """ df = df_t[["close"]].copy() df["bb_ma"] = df.close.rolling(window=lookback).mean() df["bb_std"] = df.close.rolling(window=lookback).std() df["bollinger_high"] = df.bb_ma + df.bb_std df["bollinger_low"] = df.bb_ma - df.bb_std df = df.drop(["close", "bb_ma", "bb_std"], axis=1) return df
42e188968eb69dae138906a467ee5eaff5c93a7e
326,608
import toml import yaml import json def mock_settings_file(request, monkeypatch, tmpdir, file_extension): """Temporarily write a settings file and return the filepath and the expected settings outcome.""" ext = file_extension p = tmpdir.mkdir("sub").join("settings" + ext) expected_result = {"testgroup": {"testvar": 123}, "othergroup": {"blabla": 555}} if ext == ".toml": p.write(toml.dumps(expected_result)) elif ext in [".yml", ".yaml"]: p.write("---\n" + yaml.dump(expected_result)) elif ext == ".json": p.write(json.dumps(expected_result)) else: # pragma: nocover raise NotImplementedError("Invalid file extension :{}.".format(ext)) return str(p), expected_result
4899ebbc9efbe31a931387d4a09dcb8c727eaf8d
698,303
def get_mac_address(path): """ input: path to the file with the location of the mac address output: A string containing a mac address Possible exceptions: FileNotFoundError - when the file is not found PermissionError - in the absence of access rights to the file TypeError - If the function argument is not a string. """ if type(path) is not str: raise TypeError("The path must be a string value") try: file = open(path) except FileNotFoundError as e: raise e except PermissionError as e: raise e return file.readline().strip().upper()
814a530b63896103adcb8fbc84d17939644b9bbe
709,477
def get_next_free_ind(d:dict): """ given a dictionary of indices, get the next free index """ return max(d.values()) + 1
96a7c95fd65cd1b4f3db1fc731a3d227340326fb
464,543
def convert(k: str) -> str: """Convert key of dictionary to valid BQ key. :param k: Key :return: The converted key """ if len(k.split(":")) > 1: k = k.split(":")[1] if k.startswith("@") or k.startswith("#"): k = k[1:] k = k.replace("-", "_") return k
06eaa83cbc0ebdde02c498123cb48662936eba01
579,226
def _prev_rosdistro(index, rosdistro_name): """Given current rosdistro name, return the previous.""" valid_rosdistro_names = list(index.distributions.keys()) valid_rosdistro_names.sort() # skip distributions with a different type if the information is available distro_type = index.distributions[rosdistro_name].get('distribution_type') if distro_type is not None: valid_rosdistro_names = [ n for n in valid_rosdistro_names if distro_type == index.distributions[n].get('distribution_type')] try: i = valid_rosdistro_names.index(rosdistro_name) except ValueError: raise ValueError('Distribution key not found in list of valid distributions.') if i == 0: raise ValueError('No previous distribution found.') return valid_rosdistro_names[i - 1]
6d6c1e8e5d9ca02115c7e0a4ee6006ba4af98c13
495,467
import re def re_search(regex, string): """Try matching a regular expression.""" return re.search(regex, string)
4cd9cfadfda9fdf875c6c4a96a589d038afcfd30
522,593
def getOrderedTeamGames(teamGames): """ input: team games output: map team -> ordered list of games (by time) """ orderedTeamGames = {} for team in teamGames: orderedTeamGames[team] = [] currentTeamGames = teamGames[team] keylist = list(currentTeamGames) keylist.sort() for key in keylist: orderedTeamGames[team].append(currentTeamGames[key]) return orderedTeamGames
87b29b9f9a392a7d813b0ddd9be0be0be4c28c10
501,186
def get_probability(sample, cond): """Find the probability that the sample fullfills conditions. Example ------- >>> y = np.array([-1., 0., 1., 2.]) >>> print get_probability(y, y<=0) 0.5 Arguments --------- sample : ndarray A sample to check the condition on. cond : ndarray An array of bools with equal size to sample which decides wether or not the sample point fulfills the conditions or not. """ return float(sample[cond].size) / float(sample.size)
5e993081fd9ee14d386bce9229c61d2835adb6ad
163,580
import re def intcomma(value): """ Converts an integer to a string containing commas every three digits. For example, 3000 becomes '3,000' and 45000 becomes '45,000'. """ value = str(value) new = re.sub("^(-?\d+)(\d{3})", '\g<1>,\g<2>', value) if value == new: return new else: return intcomma(new)
fca5cbbff83cf23e052308cec0d88a2a49d85387
609,584
def read_file(path): # type: (str) -> list """Loads a text file from ``path`` into a list of str and returns it. """ with open(path, "rU") as text: return text.readlines()
396341e9a46fbcfebd473cc2fb171d56dd2cc41c
384,146
def make_constant(match): """Returns a Constant JSON Object""" return { 'type': 'c', #c for constant, f for function 'name': match.group('name'), 'value': match.group('value') #is this necessary? }
75d3781aaefec29570c06e1c672409de9c71974d
286,126
def tidy_participation_url(url: str) -> str: """ >>> tidy_participation_url( ... "https://test.connpass.com/event/123456/participation/") 'https://test.connpass.com/event/123456/participation/' >>> tidy_participation_url( ... "https://test.connpass.com/event/123456/participation") 'https://test.connpass.com/event/123456/participation/' >>> tidy_participation_url("https://test.connpass.com/event/123456/") 'https://test.connpass.com/event/123456/participation/' >>> tidy_participation_url("https://test.connpass.com/event/123456") 'https://test.connpass.com/event/123456/participation/' """ if not url.endswith("/"): url += "/" if not url.endswith("participation/"): url += "participation/" return url
bda0b6c69eff84f959de35f223c6c23602612f2e
235,748
def get_attribute_values(elements,name): """ returns a list of attributes 'name' from a list of elements """ attribute_values = [] for element in elements: attributes = element.attributes for n in range(attributes.length): attribute = attributes.item(n) if attribute.name == name: attribute_values.append(attribute.value) return attribute_values
953ae221b0dd88812fc9b59e5dc86add9d9ededb
649,022
def count_items(alist): """ Count number of items in alist. """ count = 0 for item in alist: count = count + 1 return count
69675913ffbcc1e6021c2c1002d4fa039ecc63b4
52,148
def _gen_param_excluder(added_kwargs): """ Pass through all the original keys, but exclude any kwargs that we added manually through prep_scalar Parameters ---------- added_kwargs : list of str Returns ------- excluder : callable """ def excluder(params, except_=None): """ Parameters ---------- params : dict except : str """ return {k: v for k, v in params.items() if k not in added_kwargs or k == except_} return excluder
99b7db0cd064a3afc9997e8c0e82adea991a836d
506,151
def to_string(val): """Convert a value to a string.""" return str(val)
0f3d4a4d74c10f1e37f95d9e23b6b04e6c10d3be
202,692
def maplist2dict(dlist): """ Convert a list of tuples into a dictionary """ return {k[0]: k[1] for k in dlist}
2d6c03d09ad8cdb9c9d7878c5038b99a28992dde
68,510
def parse_vertex_and_square_ids( data: str, start_string: str = "Square ID", end_string: str = "# Edges", ) -> dict: """Return a dictionary of vertex ID & square ID pairs. This function will parse through the read-in input data between ''start_string'' and ''end_string'' to return the filtered text in-between. This text is then converted to a dictionary mapping vertex IDs to square IDs. :param data: read-in input file :type data: str :param start_string: starting string to search from, defaults to 'Square ID' :type start_string: str :param end_string: ending string to search until, defaults to '# Edges' :type end_string: str :return: a dictionary of vertex IDs & corresponding square IDs :rtype: dict """ # split the data on the two strings list_of_ids = data.split(start_string)[-1].split(end_string)[0] # split the data on newline character list_of_ids = list_of_ids.split("\n") # remove empty strings that arose due to whitespace by using filter list_of_ids = list(filter(lambda x: x != "", list_of_ids)) # create a dictionary of key-value pairs by splitting on the comma character ids_map = {} for i in list_of_ids: splitted_string = i.split(",") vertex_id = splitted_string[0] square_id = int(splitted_string[1]) # create a mapping ids_map[vertex_id] = square_id return ids_map
168ec7a785a89508c60061a6ac85b2f8a62c001b
561,130
def exoption(self, ldtype="", option="", value="", **kwargs): """Specifies the EXPROFILE options for the Mechanical APDL to ANSYS CFX profile file transfer. APDL Command: EXOPTION Parameters ---------- ldtype Load type: * ``"SURF"`` : Surface load * ``"VOLU"`` : Volume load option Surface options: * ``"Precision"`` : Number of significant digits for the fractional part of real data * ``"Connectivity"`` : Key to include face connectivity in the exported profile file * ``"Precision"`` : Number of significant digits after the decimal for real data value Specify the value for either Precision or Connectivity. For Precision, specify the number of significant digits. Can be any value between 1 to 20, default 8. When 0 or an invalid value is specified, the program will use the default value of 8 and issue a warning message. For Connectivity, specify the key to include the element face connectivity data for surface loads (does not support volume loads): * ``"OFF"`` : Do not include the connectivity data in the exported file (default) * ``"ON"`` : Include the connectivity data in the exported file Notes ----- This command is not supported in Distributed ANSYS. """ return self.run(f"EXOPTION,{ldtype},{option},{value}", **kwargs)
82a3d62b5d9d079e8a5c3f2ca457e133e329030b
136,693
def format_month_interval(val): """ Format a MonthInterval value. """ return f"{int(val)}M"
28ac3d457dab6c4c877d15b137a26930180c389e
62,977
def strip_namespace(obj): """ Returns the given object name after striping the namespace :param obj: str, object to strip namespace from :return: str """ return obj.split(':')[-1]
1c34576458df1a90b6c0d075d7e54bbd7c350125
46,564
def classify(model, dataframe): """Classifies a dataframe using a trained random forest model Args: model: trained RandomForestClassifier dataframe: A features dataframe Returns: dataframe of raw predictions """ return model.transform(dataframe)\ .select(['cx', 'cy', 'px', 'py', 'sday', 'eday', 'rawPrediction'])\ .withColumnRenamed('rawPrediction', 'rfrawp')
c0331c2767772c386fd7a8eac7f2d30d974841dc
593,683
import json def dict_to_json(json_dict: dict, sort_keys=True, indent=None) -> str: """ Transforms a tree made up of dictionaries and list into json string. :param json_dict: the dict to transform :return: the json string """ return json.dumps(json_dict, sort_keys=sort_keys, indent=indent)
b5004f8913eebfdfa6876dd269693dc5d56bd46d
501,260
from datetime import datetime def year(date): """ Returns the year Accepted format: %m/%d/%Y """ try: fmt = '%m/%d/%Y' return datetime.strptime(date, fmt).timetuple().tm_year except ValueError: return 0
bb4a0e942967cf70ffc45c0ffcdf1df1fecd1910
142,541
def get_mappings(params): """ Create a mapping between attributes and their associated IDs. """ if not hasattr(params, 'mappings'): mappings = [] k = 0 for (_, n_cat) in params.attr: assert n_cat >= 2 mappings.append((k, k + n_cat)) k += n_cat assert k == params.n_attr params.mappings = mappings return params.mappings
d75ffb85f1a5ccb1705866b16de65275347c1865
285,660
import struct def parse_sch(l2cap_data): """ Parse the signaling channel data. The signaling channel is a L2CAP packet with channel id 0x0001 (L2CAP CID_SCH) or 0x0005 (L2CAP_CID_LE_SCH) 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 ----------------------------------------------------------------- | code | id | length | ----------------------------------------------------------------- References can be found here: * https://www.bluetooth.org/en-us/specification/adopted-specifications - Core specification 4.1 ** [vol 3] Part A (Section 4) - Signaling Packet Formats Returns a tuple of (code, id, length, data) """ code, id, length = struct.unpack("<BBH", l2cap_data[:4]) return (code, id, length, l2cap_data[4:])
93acbe97cdcbd2a961c13e5adede037941a44abe
254,949
def get_numeric_ratio(s): """ gets the ratio of numeric characters to the total alphanumerics :type s: str :rtype: float or NoneType """ num_numeric = 0 num_alphabetic = 0 if len(s) == 0: return None else: for character in s: if character.isnumeric(): num_numeric += 1 elif character.isalpha(): num_alphabetic += 1 return num_numeric / (num_numeric + num_alphabetic)
2a7fa2cd97bd2044cced18efa68530e366e0f179
488,987
def get_magnetic_galaxy_dir(galaxy: str, data_directory: str) -> str: """ Get the full path to a specific galaxy directory Args: galaxy (str): Name of the galaxy data_directory (str): dr2 data directory Returns: str: Path to galaxy directory """ return data_directory + "/magnetic/" + galaxy
29c4266bac4bb3b133baf23c3fb1381ffb4a6349
139,643
import math def format_pace(pace): """formats a pace in s/km as a nice mm:ss/km""" rem, inte = math.modf(pace/60) return f"{int(inte)}:{int(rem*100):02d}/km"
c8d14fe4bd67a3bf5daf7cd623a65eb84cfd452f
265,923
import hashlib def get_fingerprint(file_path: str) -> str: """ Calculate a fingerprint for a given file. :param file_path: path to the file that should be fingerprinted :return: the file fingerprint, or an empty string """ try: block_size = 65536 hash_method = hashlib.md5() with open(file_path, 'rb') as input_file: buf = input_file.read(block_size) while buf: hash_method.update(buf) buf = input_file.read(block_size) return hash_method.hexdigest() except Exception: # if the file cannot be hashed for any reason, return an empty fingerprint return ''
b0ee4d592b890194241aaafb43ccba927d13662a
3,511
def strip_tuple(tuple_list, tuple_index = 0): """Given a list of tuples, creates a list of elements at tuple_index""" elem_list = [] for i in range(0, len(tuple_list)): elem_list.append(tuple_list[i][tuple_index]) return elem_list
0540b1f85987f5bce1a42ee6e72460faecd6a31c
205,171
import time def timestamp(d=True, t=True, tz=True, utc=False, winsafe=False): """Simple utility to print out a time, date, or time+date stamp for the time at which the function is called. Parameters ----------: d : bool Include date (default: True) t : bool Include time (default: True) tz : bool Include timezone offset from UTC (default: True) utc : bool Include UTC time/date (as opposed to local time/date) (default: False) winsafe : bool Omit colons between hours/minutes (default: False) """ if utc: time_tuple = time.gmtime() else: time_tuple = time.localtime() dts = '' if d: dts += time.strftime('%Y-%m-%d', time_tuple) if t: dts += 'T' if t: if winsafe: dts += time.strftime('%H%M%S', time_tuple) else: dts += time.strftime('%H:%M:%S', time_tuple) if tz: if utc: if winsafe: dts += time.strftime('+0000') else: dts += time.strftime('+0000') else: offset = time.strftime('%z') if not winsafe: offset = offset[:-2:] + '' + offset[-2::] dts += offset return dts
a2d74db673993a9a22822062b962fbc161dfe59d
241,495
import re def parse_speaker(path): """ Get speaker id from a BAS partitur file Parameters ---------- path : str a path to the file Returns ------- str or None the speaker id """ speaker = '' with open(path, 'r', encoding='utf8') as f: lines = f.readlines() for line in lines: splitline = re.split("\s", line) if splitline[0] == 'SPN:': return splitline[1].strip() return None
31f65b13903324b1b941b2beb6c28edde430ffa1
67,391
def dp(n): """Returns the n-th number of fib with DP""" f = [0] * (n + 1) for i in range(n + 1): if i <= 1: f[i] = i else: f[i] = f[i - 1] + f[i - 2] return f[n]
d421689bbb3b51d6745a92eefbf41800761dcd68
387,855
def es_parentesis(caracter): """ (str of len == 1) -> str >>> es_parentesis('(') 'Es parentesis' >>> es_parentesis('x') 'No es parentesis' >>> es_parentesis('xa') Traceback (most recent call last): .. TypeError: xa no es un parentesis :param caracter: str el caracter a evaluar :return: str el mensaje de la validacion """ if len(caracter) != 1: raise TypeError(str(caracter) + ' no es un parentesis') elif caracter in '()': # caracter == '(' or caracter == ')': return 'Es parentesis' return 'No es parentesis'
bdace083e11eadbbf3f2d679bf9fffad4a1313c0
358,183
import time def date_passed(date): """Check if the date has already passed.""" return date <= int(time.time())
9f3499bf6fbef190b21131f40b4b5d2c42acda53
319,971
def get_sentence_at_index(index, resolved_list): """Returns the sentence beginning at the index """ end_of_sentence_punctuation = ['.', '!', '?'] begin_index = index end_index = index while begin_index >= 0: val = resolved_list[begin_index].strip() if val in end_of_sentence_punctuation: break else: begin_index -= 1 while end_index <= len(resolved_list) - 1: val = resolved_list[end_index].strip() if val in end_of_sentence_punctuation: break else: end_index += 1 return resolved_list[begin_index + 1:end_index + 1], begin_index + 1
5f081086e227689c1aa6d774c8f83e79d62e344f
468,072
import binascii def hex_decode(string): """ Hex decode string Parameters ---------- string : str String to be decoded from hexadecimal Returns ------- str Text string with ASCII / unicode representation of hexadecimal input string """ return binascii.a2b_hex(string.encode()).decode()
5513101514bded4b28f1a6b0038ce9a6f2dfac87
652,350
import click def geojson_type_feature_opt(default=False): """GeoJSON Feature or Feature sequence output mode""" return click.option( '--feature', 'geojson_type', flag_value='feature', default=default, help="Output as GeoJSON feature(s).")
d9705fcb28d70f92d94803850652231ccff1b77e
494,726
def model_eval(model, b_gen, metric_str, workers=4): """ Evaluate model on data generator. Prints and returns scores for specified metrics. Parameters ---------- model : Keras model The model to evaluate. b_gen : DataGenerator object DataGenerator object to use for loading the data. metric_str : list of str List of names of the metrics to evaluate. For printing. workers : int, optional Number of workers for the multiprocessing functionalities of the Keras model methods. Defauts to 4. Returns ------- score : ndarray Array containing results of the evaluated metrics as returned by Keras model.evaluate() methods. """ print('\nModel Evaluation: \n') score = model.evaluate_generator(b_gen, verbose=1, use_multiprocessing=True, workers=workers) for i, m in enumerate(metric_str): print('Test '+m+':', score[i]) return score
0055da84a8c790bf414930f40f65400d1b441820
406,266
def find_value(dic, key): """return the value of dictionary dic given the key""" return dic[key]
c1bbc2da7c1cb35659be9bfd76904daeac46e870
297,734
def _list_to_hash(lst): """Convert a flat list of key value pairs to a hash""" return {lst[i]: lst[i+1] for i in range(0, len(lst), 2)};
6848b7681d79c6e6609dbc98b12d763cd5e5fdbb
197,841
def k12_enrollment(parcels): """ Enrollment for grades kinder through 12th. """ return parcels['k6_enrollment'] + parcels['g7_8_enrollment'] + parcels['g9_12_enrollment']
e1b8eca67d9e6f35883a2a15ed6f73f511ac4aba
608,050
def str_to_bool(s): """ String to bool used to read config file Parameters ---------- s : str String to convert Returns ------- s : bool Boolean value of input string """ if s == 'True': return True elif s == 'False': return False else: raise ValueError
1ccfd2b39ef298fb7b02925fe667cc6d38398614
50,698
def trim_taxon(taxon: str, int_level: int) -> str: """ taxon_hierarchy: '1|2|3|4|5|6|7' level: 5 output: '1|2|3|4|5' """ return '|'.join(taxon.split('|')[:int_level])
0b9fe0b01633d81964f7d2a245ccb7621b8c10ed
205,769
def get_right_slices(var, right_ndims, fixed_val=0): """Return an indexing tuple where the left dimensions are held to a fixed value and the right dimensions are set to slice objects. For example, if *var* is a 5D variable, and the desired indexing sequence for a numpy array is (0,0,0,:,:), then *right_ndims* should be set to 2 and *fixed_val* set to 0. Args: var (:class:`numpy.ndarray`): A numpy array. right_ndims (:obj:`int`): The number of right dimensions to be sliced. fixed_val (:obj:`int`): The value to hold the left dimensions to. Returns: :obj:`tuple`: An indexing tuple that can be used to index a :class:`numpy.ndarray`. """ extra_dim_num = var.ndim - right_ndims if extra_dim_num == 0: return [slice(None)] * right_ndims return tuple([fixed_val]*extra_dim_num + [slice(None)]*right_ndims)
1665eb5077bf14c6fa5b5617c6b3285317e8f29a
152,414
def sanity_check_iob(naive_tokens, tag_texts): """ Check if the IOB tags are valid. * Args: naive_tokens: tokens split by .split() tag_texts: list of tags in IOB format """ def prefix(tag): if tag == "O": return tag return tag.split("-")[0] def body(tag): if tag == "O": return None return tag.split("-")[1] # same number check assert len(naive_tokens) == len(tag_texts), \ f"""Number of tokens and tags doest not match. original tokens: {naive_tokens} tags: {tag_texts}""" # IOB format check prev_tag = None for tag_text in tag_texts: curr_tag = tag_text if prev_tag is None: # first tag assert prefix(curr_tag) in ["B", "O"], \ f"""Wrong tag: first tag starts with I. tag: {curr_tag}""""" else: # following tags if prefix(prev_tag) in ["B", "I"]: assert ( (prefix(curr_tag) == "I" and body(curr_tag) == body(prev_tag)) or (prefix(curr_tag) == "B") or (prefix(curr_tag) == "O") ), f"""Wrong tag: following tag mismatch. previous tag: {prev_tag} current tag: {curr_tag}""" elif prefix(prev_tag) in ["O"]: assert prefix(curr_tag) in ["B", "O"], \ f"""Wrong tag: following tag mismatch. previous tag: {prev_tag} current tag: {curr_tag}""" else: raise RuntimeError(f"Encountered unknown tag: {prev_tag}.") prev_tag = curr_tag
4fb16ed2bd7a623a7dad331d8b7c8a5033a382ea
35,148
import six def is_string(value): """Returns whether value has a string type.""" return isinstance(value, six.string_types)
bbdc9602b2317fc2d8ed183af69ec60f9fce12ee
511,639
def construct_filter_based_on_destination(reimbursable_destination_type: str): """ Construct Filter Based on Destination :param reimbursable_destination_type: Reimbusable Destination Type :return: Filter """ filters = {} if reimbursable_destination_type == 'EXPENSE_CATEGORY': filters['destination_expense_head__isnull'] = True elif reimbursable_destination_type == 'ACCOUNT': filters['destination_account__isnull'] = True return filters
73116ce3e6398e98c1540380094e70cc1620867b
27,221
def adjacency_to_edges(nodes, adjacency, node_source): """ Construct edges for nodes based on adjacency. Edges are created for every node in `nodes` based on the neighbors of the node in adjacency if the neighbor node is also in `node_source`. The source of adjacency information would normally be self.graph and self.nodes for `node_source`. However, `node_source may` also equal `nodes` to return edges for the isolated graph. :param nodes: nodes to return edges for :type nodes: list :param adjacency: node adjacency (self.graph) :type adjacency: dict :param node_source: other nodes to consider when creating edges :type node_source: list """ edges = [] for node in nodes: edges.extend([tuple([node, e]) for e in adjacency[node] if e in node_source]) return edges
d593b4acd2b6f7553d6b9677209422ee665bc2d0
651,274
def getattritem(o,a): """ Get either attribute or item `a` from a given object `o`. Supports multiple evaluations, for example `getattritem(o,'one.two')` would get `o.one.two`, `o['one']['two']`, etc. :param o: Object :param a: Attribute or Item index. Can contain `.`, in which case the final value is obtained. :return: Value """ flds = a.split('.') for x in flds: if x in dir(o): o = getattr(o,x) else: o = o[x] return o
7b928b2405691dcb5fac26b7a3d7ebfcfa642f6d
13,807
def format_geo(geography_id): """ Format geography id for use within an SDF :param geography_id: string; corresponds to DV360 geography id :return: string; formatted for SDF usage """ return '{};'.format(geography_id)
63d56fd91419ce150452acb2b35dc0f6b53388b7
106,038
def convert_dcc_translation(translation): """ Converts given tpDcc translation into a translation that DCC can manage NOTE: tpDcc uses Y up coordinate axes as the base reference axis :param translation: list(float, float, float) :return: list(float, float, float) """ return translation[0], translation[2], -translation[1]
a0376cb496af36693a6119640ef985e7853a8eff
465,608
import re def parse_port_name(name): """ Parses a port name. Returns the base name, cell index and bit index. >>> parse_port_name("A_PORT") ('A_PORT', None, None) >>> parse_port_name("A_PORT_0") ('A_PORT', 0, None) >>> parse_port_name("A_PORT_b31") ('A_PORT', None, 31) >>> parse_port_name("A_PORT_0_b15") ('A_PORT', 0, 15) """ # A multi-bit port m = re.match(r"(?P<name>.*)(_b(?P<bit>[0-9]+))$", name) if m is not None: port = m.group("name") bit = int(m.group("bit")) else: port = name bit = None # A port of a sub-cell m = re.match(r"(?P<name>.*)(_(?P<cell>[0-9]+))$", port) if m is not None: return m.group("name"), int(m.group("cell")), bit return port, None, bit
643dbcad09f890419d36b47123a6478387944548
87,809
def _insert_single_package_eups_version(c, eups_version): """Insert version information into the configuration namespace. Parameters ---------- eups_version The EUPS version string (as opposed to tag). This comes from the ``__version__`` attribute of individual modules and is only set for single package documentation builds that use the `build_package_configs` configuration entrypoint. Notes ----- The variables are: ``release_eups_tag`` Always ``current``. ``version``, ``release`` Equal to ``eups_version``. ``release_git_ref`` Always ``master``. ``scipipe_conda_ref`` Always ``master``. ``newinstall_ref`` Always ``master``. ``pipelines_demo_ref`` Always ``master``. """ c["release_eups_tag"] = "current" c["release_git_ref"] = "master" c["version"] = eups_version c["release"] = eups_version c["scipipe_conda_ref"] = "master" c["pipelines_demo_ref"] = "master" c["newinstall_ref"] = "master" return c
5fb78d55952466d454f911cead259948407c6e92
585,300
import torch def decoder_padding_mask( ys_pad: torch.Tensor, ignore_id: int = -1 ) -> torch.Tensor: """Generate a length mask for input. The masked position are filled with True, Unmasked positions are filled with False. Args: ys_pad: padded tensor of dimension (batch_size, input_length). ignore_id: the ignored number (the padding number) in ys_pad Returns: Tensor: a bool tensor of the same shape as the input tensor. """ ys_mask = ys_pad == ignore_id return ys_mask
5c494ed2c4f18118a708b3fa4c50b05599e93b3f
556,830
def place_piece(piece, x, y, board): """ Utility function that places the piece at a given (x,y) coordinate on the given board if possible Will overwrite the current value at (x,y), no matter what that piece is Returns True if the piece is placed successfully and False otherwise Arg piece: string - represents a piece on the board ('*' is an empty piece, '2' '8' etc. represent filled spots) Arg x: integer - x coordinate Arg y: integer - y coordinate Arg board: board - the board you wish to place the piece on """ #Ensure that x and y are both integers (use assert) assert type(x) == int and type(y) == int, "Error: not an integer" #What are the dimensions of the board? N = len(board) #Checking that the (x,y) coordinates given are valid for the board if not (x >= 0 and x < N and y >= 0 and y < N): return False #Placing the piece on the board board[y][x] = piece return True
271e5b553cc21f826dda644f0c486ee329191af1
467,899
def deserialize_yesno(value): """ Deserialize a boolean (yes or no) value. """ return value.lower() == 'yes'
c3c92966302d1865763a7106ea7905c00cae9f2c
442,562
from typing import List def subtotals_for_deltas(deltas) -> List[int]: """ Given a list of deltas corresponding to input coins, create the "subtotals" list needed in solutions spending those coins. """ subtotals = [] subtotal = 0 for delta in deltas: subtotals.append(subtotal) subtotal += delta # tweak the subtotals so the smallest value is 0 subtotal_offset = min(subtotals) subtotals = [_ - subtotal_offset for _ in subtotals] return subtotals
88111337b07328d56d63eb8c5e3ad76b0e6d84ea
169,770
def is_palindrome(string: str) -> bool: """Return whether string is a palindrome or not.""" if "".join(reversed(string)).lower() == string.lower(): return True return False
b40bdaa54b9807ff0d1f88cef08dd232d8b26cb9
350,608
def is_tuple(value): """is value a tuple""" return isinstance(value, tuple)
08f51cba93b07620a93b531dd9ea380ae7dd1118
336,695
import warnings def deduplicate(S): """deduplicate pd.Series by removing rows with same index and values""" dedup = S.groupby(S.index).first() diff = len(S) - len(dedup) if diff: warnings.warn(f"found {diff} duplicates in S, removing them") return dedup return S
743d2429ffc5e3fad435fa30e63f2c19a1fa2e09
552,776
def triple(n): """ (number) -> number Returns triple a given number. >>> triple(9) 27 >>> triple(-5) -15 >>> triple(1.1) 3.3 """ one = n * 3 return (one)
0f10a8026aba22ce9a1905c5d445984c7310763d
636,956
def parse_clusters(cluster_file): """ expects one line per cluster, tab separated: cluster_1_rep member_1_1 member 1_2 ... cluster_2_rep member_2_1 member_2_2 ... """ cluster_dict = {} with open(cluster_file) as LINES: for line in LINES: genes = line.strip().split("\t") rep = genes[0] for gene in genes: cluster_dict[gene] = rep return cluster_dict
88243b7a142224e755eb2046c11a90b352d5835d
685,017
def sniff_params(read): """ Given a read dict parsed from JSON, compute a mapping parameter dict for the read. The read will have param_XXX annotations. Turn those into a dict from XXX to value. These should be the same for every read. """ # This is the annotation dict from the read annot = read.get('annotation', {}) # This is the params dict to fill in params = {} for annot_name in annot.keys(): if annot_name.startswith('param_'): # Split the param annotations on underscore (_, param_name) = annot_name.split('_') # Save the values under the name params[param_name] = annot[annot_name] return params
312e792d58ff4a5c6b5c7a05086f4356f5fcda43
422,386
def get_summary(html_text): """Returns the summary part of the raw html text string of the wikipedia article. :param html_text: The html content of an article. :type html_text: str :return: The summary of the input wikipedia article. :rtype: str """ # The summary ends before the first h tag. end_summary_index = html_text.find('<h') summary = html_text[:end_summary_index] return summary
762085d15826ee1ca3bb6a9d63ee5e6700500029
432,392
from typing import List from typing import Union def average(values: List[Union[int, float]]) -> float: """Return the average.""" return sum(values) / len(values)
4e63aa9055c1251f240465440b79aec2241f07d7
413,423