content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def entity_emiss_o(x, n_lbs, tp, exp_term=2): """ The function that calculates the emission prior of entity labels to the non-entity label 'O' according to the diagonal values of the emission prior Parameters ---------- x: diagonal values n_lbs: number of entity labels (2e+1) tp: turning point exp_term: the exponential term that controls the slope of the function Returns ------- non-diagonal emission priors """ # separating piecewise function low = x < tp high = x >= tp # parameters for the first piece a = (2 - n_lbs) / ((exp_term - 1) * tp ** exp_term - exp_term * tp ** (exp_term - 1)) b = 1 - n_lbs # parameter for the second piece f_tp = a * tp ** exp_term + b * tp + 1 c = f_tp / (tp - 1) # piecewise result y = low * (a * x ** exp_term + b * x + 1) + high * (c * x - c) return y
34b9473e5799d7beddd20bea81a6fe926b8fde3f
37,759
def mssql_sql_utcnow(element, compiler, **kw): """MS SQL provides a function for the UTC datetime.""" return 'GETUTCDATE()'
5f3fed9f95de23069bd13b6a26cdf21f916a15b7
37,764
import re def validate_fs_path(path): """Checks if the specified file system path is valid Arguments: path {string} -- the file system path to check Returns: True if the specified path matches the regex (is a valid path), False if otherwise """ is_valid_path = re.search(r"(\w:)?([\\\/]{1}[a-zA-Z-_ ]*)*", path) return bool(is_valid_path)
c34f451fd3e74167fc6aa1b72862378878da7b6e
37,769
import copy def get_added_dicts(a, b): """Add two dictionaries together, return new dictionary. if key in B already exists in A, do not override. None destructive. Args: a (dict): dictionary you want to ADD to b (dict): dict you want to add from, the new keys Returns: dict: copied from a, with b keys added """ tmp = copy.deepcopy(a) for key, val in b.iteritems(): if key not in tmp: tmp[key] = val return tmp
f2a015dddcd1442ec556a71cb13e9da6b2950805
37,772
def format_uuid(uuid: str): """ Returns UUID formatted according to https://tools.ietf.org/html/rfc4122#section-3 (8-4-4-4-12) Parameters ---------- module_name : str unformatted UUID """ return f'{uuid[0:8]:s}-{uuid[8:12]:s}-{uuid[12:16]:s}-{uuid[16:20]:s}-{uuid[20:32]:s}'
c3383cab2bbcafb9d67c4535c6369f3646faafea
37,781
from typing import List import re def extract_cve_references(text: str) -> List[str]: """ Extract CVE identifiers """ return [result.group(0) for result in re.finditer(r"CVE-\d{4}-\d{4,8}", text)]
8d32525bc04077a418e3f9fd334ab4e8dd905376
37,789
import math def ordinal(n): """Output the ordinal representation ("1st", "2nd", "3rd", etc.) of any number.""" # https://stackoverflow.com/a/20007730/404321 suffix = "tsnrhtdd"[(math.floor(n / 10) % 10 != 1) * (n % 10 < 4) * n % 10::4] return f'{n}{suffix}'
fa7f5cadd1c684e048a1bf1557014e37ad69c930
37,790
def parse_string(string, *, remove): """ Return a parsed string Args: :string: (str) string to parse :remove: (list) characters to remove Returns: :parsed_string: (str) parsed string """ parsed_string = string for char in remove: parsed_string = parsed_string.replace(char, '') return parsed_string
641feb61ff5ad918fefe14b618863e4b5164ddbf
37,791
def build_message(history_record, game): """Builds the endpoint message from the game and current history record""" msg = "" if history_record[0].result == 'Good guess': msg += "Good guess! | " else: msg += "Wrong guess... | " msg += game.current_game + " | " msg += "Strike(s) left: " + str(game.strikes_left) + " | " if game.game_over is False: msg += "Carry on!" if game.game_over is True: if game.game_won is True: msg += "YOU WON!" else: msg += "YOU LOST!" return msg
ff3c9dd193de67f1879a4ffe3e9f859993bdef6f
37,794
def decompose_two(p): """Decomposes p into p - 1 = q * 2^s Args: p: an integer representing a prime number Results: p: an integer representing q above k: an integer representing the exponent of 2 """ k = 0 while p % 2 == 0: k += 1 p //= 2 return p, k
19934989b53707c836c1fb6864365c1828800229
37,795
def create_node(id, shape, size, label): """Auxiliary function that creates a Node in Vis.js format :return: Dict with Node attributes """ node = { "id": id, "shape": shape, "size": size, "label": label, "color": {"background": "#FBD20B"}, } return node
007c3d1d42e981aa378664683903caecc898c7c6
37,801
from typing import Union import torch from typing import Tuple from typing import Any from typing import Optional from typing import Dict from typing import List def split_non_tensors( mixed: Union[torch.Tensor, Tuple[Any, ...]] ) -> Tuple[Tuple[torch.Tensor, ...], Optional[Dict[str, List[Any]]]]: """ Split a tuple into a list of tensors and the rest with information for later reconstruction. Usage:: x = torch.Tensor([1]) y = torch.Tensor([2]) tensors, packed_non_tensors = split_non_tensors((x, y, None, 3)) assert tensors == (x, y) assert packed_non_tensors == { "is_tensor": [True, True, False, False], "objects": [None, 3], } recon = unpack_non_tensors(tensors, packed_non_tensors) assert recon == (x, y, None, 3) """ if isinstance(mixed, torch.Tensor): return (mixed,), None tensors: List[torch.Tensor] = [] packed_non_tensors: Dict[str, List[Any]] = {"is_tensor": [], "objects": []} for o in mixed: if isinstance(o, torch.Tensor): packed_non_tensors["is_tensor"].append(True) tensors.append(o) else: packed_non_tensors["is_tensor"].append(False) packed_non_tensors["objects"].append(o) return tuple(tensors), packed_non_tensors
9b63e940bccd4e0bfabe618d2986d11f3b16ef93
37,804
def split_url(url): """Splits the given URL into a tuple of (protocol, host, uri)""" proto, rest = url.split(':', 1) rest = rest[2:].split('/', 1) host, uri = (rest[0], rest[1]) if len(rest) == 2 else (rest[0], "") return (proto, host, uri)
67b09e52d2e3e321d5f1d1effb7f2ac5163e3d29
37,808
def underscorify(name): """Replace ``-`` and ``/`` with ``_``.""" return name.replace("-", "_").replace("/", "_")
a5dcddb62119ea5863522cdffcbc44dc7381a0d6
37,809
import re def is_date_index(index): """ Checks whether the index is of the agreed upon date format. In this case YYYY.MM.DD. This is a very 'EU' centric date. Would have preferred YYYY-MM-DD which is more ISO, however there are dates which exist in the 'EU' format already (topbeat). Note that match is very fast. It is faster than doing search and pulling groups. Using this method helps decouple using a single regex pattern for all things. While using this method along with get_date_from_index() below is 2n, we can ensure cognitive load is low - which is a secondary goal of this repo. :param index: :return: """ date_pattern = '.*?-\d{4}[-/:.]\d{2}[-/:.]\d{2}' match = re.match(date_pattern, index) if match is not None: return True return False
b53bb6a58350d6ada8e5fce91c6191296bb93c15
37,811
from typing import TextIO from typing import Dict def parse_percepta_txt_output( result_file: TextIO, offset: int = 0 ) -> Dict[str, Dict[str, str]]: """ Parses text output file from perceptabat_cv. Returns a nested dictionary {compound ID: {property name: value}}. """ parsed_output = {} for line in result_file: if line.split()[0].isdigit() and line.split()[1] != "ID:": cp_id = str(int(line.split()[0]) + offset) col_name = line.split()[1].rstrip(":").lower() value = line.split(": ")[1].rstrip("\n") if not cp_id in parsed_output: parsed_output[cp_id] = {} parsed_output[cp_id][col_name] = value else: continue return parsed_output
030af92661e38c7f8e84164639c2bb82da71485c
37,813
def mapValue(value, minValue, maxValue, minResultValue, maxResultValue): """ Maps value from a given source range, i.e., (minValue, maxValue), to a new destination range, i.e., (minResultValue, maxResultValue). The result will be converted to the result data type (int, or float). """ # check if value is within the specified range if value < minValue or value > maxValue: raise ValueError("value, " + str(value) + ", is outside the specified range, " \ + str(minValue) + " to " + str(maxValue) + ".") # we are OK, so let's map value = float(value) # ensure we are using float (for accuracy) normal = (value - minValue) / (maxValue - minValue) # normalize source value # map to destination range result = normal * (maxResultValue - minResultValue) + minResultValue destinationType = type(minResultValue) # find expected result data type result = destinationType(result) # and apply it return result
339268c09e99db9294dc1c30871b6c03f9fca776
37,814
def opt_bool(opt): """ Convert bool ini strings to actual boolean values """ return opt.lower() in ['yes', 'y', 'true', '1']
9f321363cb96b08a122c9437c028cbe142de5881
37,815
def read_length(data): """Read length from a list of bytes, starting at the first byte. Returns the length, plus the number of bytes read from the list. EMV 4.3 Book 3 Annex B2 """ i = 0 length = data[i] i += 1 if length & 0x80: length_bytes_count = length & 0x7F length = 0 for j in range(length_bytes_count): length = (length << 8) + data[i + j] i += length_bytes_count return length, i
79ebf734ff863a567727ef0469e37f74327ee6e0
37,825
def parse_range(s): """Parse a string "a-b" describing a range of integers a <= x <= b, returning the bounds a, b.""" return tuple(map(int, s.split("-")))
b17314dc729bec8130384a71ee10cf32e60da9c1
37,828
def get_page_id(title, query_results): """ Extracts the title's pageid from the query results. Assumes queries of the form query:pages:id, and properly handle the normalized method. Returns -1 if it cannot find the page id """ if 'normalized' in query_results['query'].keys(): for normalized in query_results['query']['normalized']: if title == normalized['from']: title = normalized['to'] for page in query_results['query']['pages']: if title == query_results['query']['pages'][page]['title']: return str(query_results['query']['pages'][page]['pageid']) return str(-1)
8ddce8c95b4a312b7478dc53d5b3a7fb53bba39e
37,830
def get_gt(variant_call): """Returns the genotypes of the VariantCall. Args: variant_call: VariantCall proto. The VariantCall for which to return GTs. Returns: A list of ints representing the genotype indices of this call. """ return variant_call.genotype
865c1954d24c43ee5545dc0f477e66eba8c22a46
37,831
def find_video_attachments(document_attachments): """This function identifies any attached videos in a collection of document attachments. :param document_attachments: Attachments associated with a document :type document_attachments: list, dict :returns: A list of dictionaries containing info on any video attachments """ if isinstance(document_attachments, dict): document_attachments = [document_attachments] video_info_list = [] for collection in document_attachments: if "video" in collection['contentType']: size = round(collection['size']/1048576, 2) video_info_list.append({"download_url": collection['url'], "size": size}) return video_info_list
471e0366279711784d0b628cbd38527e5f15c836
37,839
def getBytesSize(bytesIn=0, suffix="B"): """ Scale bytes to its proper format e.g: 1253656 => '1.20MB' 1253656678 => '1.17GB' """ bytesValue = bytesIn if bytesValue is None or 0: return int(0) elif (isinstance(bytesValue, int) or isinstance(bytesValue, float)) and (int(bytesValue) > 0): factor = 1024 for unit in ["", "K", "M", "G", "T", "P"]: if bytesValue < factor: return f"{bytesValue:.2f}{unit}{suffix}" bytesValue /= factor return bytesValue return int(0)
1e6e2ad83a13ddc0cd35f82925f7617c09e229dc
37,841
def _CreateChartStats(loss_stats): """Creates the Chart object to interface with Google Charts drawChart method. https://developers.google.com/chart/interactive/docs/reference#google.visualization.drawchart Args: loss_stats: A dictionary of years paired to square meters. Returns: A Python dictionary with all of the parameters required to draw a Chart. """ chart_data = { 'type': 'area', 'options': {}, } columns = [ {'id': 'name', 'label': 'Year', 'type': 'string'}, {'id': 'year', 'label': 'Loss (sq. km)', 'type': 'number'}] rows = [] for loss_year in sorted(loss_stats.keys()): entry = { # The loss stats are in m2; convert them to km2. 'c': [{'v': loss_year}, {'v': loss_stats[loss_year]/1000/1000}] } rows.append(entry) chart_data['data'] = {'cols': columns, 'rows': rows} return chart_data
384623ad5cd3c3ee81cf25c00402bd8d65396f59
37,842
def extract_channel_platform(url): """Returns last two elements in URL: (channel/platform-arch) """ parts = [x for x in url.split('/')] result = '/'.join(parts[-2:]) return result
73c71ed879f07e8eedf2730db174e1cb81177276
37,844
def is_same_class(obj, a_class): """return true if obj is the exact class a_class, otherwise false""" return (type(obj) == a_class)
029b12b101b53cc960f72994ae082df5f0fd9d0e
37,845
import hashlib import six import base64 def CalculateMd5Hash(file_path): """Calculate base64 encoded md5hash for a local file. Args: file_path: the local file path Returns: md5hash of the file. """ m = hashlib.md5() with open(file_path, 'rb') as f: m.update(f.read()) return six.ensure_text(base64.b64encode(m.digest()))
2a24ce3dd4f6e5f9d9a5d9be5632e6d481fd690b
37,851
def read_connection_data_from_external_file(filepath, separator="="): """Reads SQL server connection information from an external file. Keeping this information external is potentially important for security reasons. The format of this file should be: server = [server_name] database = [database_name] Arguments: filepath -- the location of the connection file (e.g. "C:/connection_data/server_connection_data.txt") separator -- the delimiter (default "=") Returns: The server, database as strings """ with open(filepath, 'r') as f: connection_data = f.readlines() connection_data_dict = dict() # clean strings and split on delimiter for entry in connection_data: entry_cleaned = entry.replace(" ", "").strip("\n") # strip whitespace and trailing new lines split_string = entry_cleaned.split(separator) connection_data_dict[ split_string[0] ] = split_string[1] if "server" not in connection_data_dict or "database" not in connection_data_dict: raise ValueError( """Connection data file must contain server and database_name, formated like: server = server_name database = database_name\n""") exit(0) server = connection_data_dict["server"] database = connection_data_dict["database"] print("Server={}\nDatabase={}".format(server, database)) return server, database
f12a659f302f7a8252f29673fa916b6ac997663f
37,852
import json def load_filename(loc: str) -> dict: """Open a filename, parse it as JSON.""" with open(loc) as fh: return json.load(fh)
9b8984926573dbcbff16a7fcee4b20e5e85fe6e0
37,853
def lin_poly_solve(L, M): """ Return the point defined as the intersection of two lines (given as degree-one polynomials in some field). """ x0,x1,x2 = M.parent().gens() a0 = L.coefficient(x0) a1 = L.coefficient(x1) a2 = L.coefficient(x2) b0 = M.coefficient(x0) b1 = M.coefficient(x1) b2 = M.coefficient(x2) # a0 a1 a2 # b0 b1 b2 return [a1*b2-a2*b1, -a0*b2+a2*b0, a0*b1-a1*b0]
5ebacff94b80dd4b1b54ac7742d0c9a37db596c8
37,854
def toRGB(hex_color_str): """ transform hex color string to integer tuple. e.g. r,g,b = toRGB('0xFFFFFF') """ return int(hex_color_str[2:4],16)/255., int(hex_color_str[4:6],16)/255., int(hex_color_str[6:8],16)/255.
5821d5f0d42d1a53982eb81739fe81e47d75fa23
37,855
def lookup_object(spec): """ Looks up a module or object from a some.module:func_name specification. To just look up a module, omit the colon and everything after it. """ parts, target = spec.split(':') if ':' in spec else (spec, None) module = __import__(parts) for part in parts.split('.')[1:] + ([target] if target else []): module = getattr(module, part) return module
e09c30d1cf3f523b790208dec60ec9fc1a309b1d
37,856
def default(d, k, i, default=None): """Returns d[k][i], defaults to default if KeyError or IndexError is raised.""" try: return d[k][i] except (KeyError, IndexError): return default
c48c57b7698f23e075d45043917e2427e1b39c2d
37,858
def line_1d(x, slope, offset): """Return the value of a line with given slope and offset. Parameters ---------- x : float or iterable of floats The x-value to calculate the value of the line at. slope : float The slope of the line. Must be finite. offset : float The y-offset of the line. Returns ------- float or iterable of floats The value at the given `x`, or values if len(x) > 1, in which case it will be an array with length = len(x). """ return slope * x + offset
9befd9fdd13db12e27be4e000501c09a51c231e8
37,860
def decimal_all_finite(x_dec_list): """Check if all elements in list of decimals are finite. Parameters ---------- x_dec_list : iterable of Decimal List of decimal objects. Returns ------- y : bool True if all elements are finite. """ y = all(x.is_finite() for x in x_dec_list) return y
610f95d7022047a8b020d5af48ceb3923d168e5d
37,877
def coord_shift180(lon): """Enforce coordinate longiude to range from -180 to 180. Sometimes longitudes are 0-360. This simple function will subtract 360 from those that are above 180 to get the more user-friendly [-180, 180], since slicing is a lot easier. Parameters ---------- lon: numpy.ndarray Array of longitudes with values in range [0, 360]. Returns ------- numpy.ndarray with longitudes in range [-180, 180]. """ # noqa nlon = len(lon) # change those above 180.0 to negative for i in range(nlon): x = lon[i] if x > 180: lon[i] = x - 360 return lon
cdf4ccbfc0e0dbb0201012826b88720934231d32
37,881
def temperature_over_total_temperature( mach, gamma=1.4 ): """ Gives T/T_t, the ratio of static temperature to total temperature. Args: mach: Mach number [-] gamma: The ratio of specific heats. 1.4 for air across most temperature ranges of interest. """ return (1 + (gamma - 1) / 2 * mach ** 2) ** -1
a1fea37f80df9eff21716f273b6270cfa7fcd302
37,882
from functools import reduce def words_in_chapters(chapters: list) -> list: """ Returns all words in the given chapters, without any special characters (no punctuation or quotation characters) :param chapters: Chapter objects :return: all words in the given Chapters as a list of words """ return reduce(lambda c1, c2: c1 + c2, map(lambda c: c.words(), chapters))
ef30472d3096f7b5cf58cab2ab7bdeed41c9fa85
37,885
import json def htmlsafe_json_dumps(obj, dumper=None, **kwargs): """Works exactly like :func:`dumps` but is safe for use in ``<script>`` tags. It accepts the same arguments and returns a JSON string. Note that this is available in templates through the ``|tojson`` filter which will also mark the result as safe. Due to how this function escapes certain characters this is safe even if used outside of ``<script>`` tags. The following characters are escaped in strings: - ``<`` - ``>`` - ``&`` - ``'`` This makes it safe to embed such strings in any place in HTML with the notable exception of double quoted attributes. In that case single quote your attributes or HTML escape it in addition. """ if dumper is None: dumper = json.dumps rv = dumper(obj, **kwargs) \ .replace(u'<', u'\\u003c') \ .replace(u'>', u'\\u003e') \ .replace(u'&', u'\\u0026') \ .replace(u"'", u'\\u0027') return rv
d3cdff425da3a7a01369ae89890d1d00ab7fe000
37,888
def slices_overlap(slice_a, slice_b): """Test if the ranges covered by a pair of slices overlap.""" assert slice_a.step is None assert slice_b.step is None return max(slice_a.start, slice_b.start) \ < min(slice_a.stop, slice_b.stop)
db9cfc0dcfa64f6c7c52f2410a140088f9d03b13
37,890
def get_requirements(fname): """ Extracts requirements from requirements-file <fname> """ reqs = open(fname, "rt").read().strip("\r").split("\n") requirements = [ req for req in reqs if req and not req.startswith("#") and not req.startswith("--") ] return requirements
1b091b89cf6835f544560eb8e2235d9bb02f2952
37,892
def camelcase(name): """Converts a string to CamelCase. Args: name (str): String to convert. Returns: str: `name` in CamelCase. """ return ''.join(x.capitalize() for x in name.split('_'))
2a0052d52faf1aabb45ae9909f76482c927ba395
37,901
def completed(lines): """ Check if the output file shows successful completion """ return lines[-1][:14] == 'TOTAL RUN TIME'
2dcb9ff850086f4e7496a46a82c510297f0488d6
37,905
import torch import random def create_sample_batch(speaker_data, batch_size, vector_dim): """ Return torch tensors ((input1, input2), target) for siamese network training (for mutual information). Constructs each batch to have roughly equal amount of target and non-target samples to keep training balanced """ input1_tensor = torch.zeros(batch_size, vector_dim).float() input2_tensor = torch.zeros(batch_size, vector_dim).float() target_tensor = torch.zeros(batch_size, 1).float() speaker_ids = list(speaker_data.keys()) for i in range(batch_size): # Throw a coin if we add target or non-target sample input1 = None input2 = None target = None if random.random() < 0.5: # Target sample: # Pick speaker, and then pick two separate vectors # from that speaker random_speaker_id = random.choice(speaker_ids) speaker_vectors = speaker_data[random_speaker_id] # random.sample takes two unique vectors input1, input2 = random.sample(speaker_vectors, 2) target = 1 else: # Non-target sample # Pick two different speakers and one vector from # each speaker1, speaker2 = random.sample(speaker_ids, 2) input1 = random.choice(speaker_data[speaker1]) input2 = random.choice(speaker_data[speaker2]) target = 0 # Put sampled vectors to batch input1_tensor[i] = torch.from_numpy(input1).float() input2_tensor[i] = torch.from_numpy(input2).float() target_tensor[i, 0] = target input1_tensor = input1_tensor.cuda() input2_tensor = input2_tensor.cuda() target_tensor = target_tensor.cuda() return ((input1_tensor, input2_tensor), target_tensor)
71edfa9f239b84a8414a645d391330f929cd2e2d
37,909
import six def safe_shadow(text): """ Shadow string to first and last char :param text: :return: >>> safe_shadow(None) 'None' >>>safe_shadow("s") '******' >>>safe_shadow("sssssss") 's******s' >>> safe_shadow(1) '******' >>> safe_shadow([1, 2]) '******' """ if not text: return "None" elif not isinstance(text, six.string_types): return "******" elif len(text) > 2: return "%s******%s" % (text[0], text[-1]) else: return "******"
46d63b4a598bbc45ae32335e105539f7c43f1c9e
37,910
def _merge_notebooks_feedback(notebook_ids, checksums): """ Returns a list of dictionaries with 'notebook_id' and 'feedback_checksum'. ``notebook_ids`` - A list of notebook IDs. ``checksum`` - A dictionary mapping notebook IDs to checksums. """ merged = [] for nb_id in notebook_ids: if nb_id not in checksums.keys(): checksum = None else: checksum = checksums[nb_id] merged.append({'notebook_id': nb_id, 'feedback_checksum': checksum}) return merged
6e45fa2f5889b94b9dd6e0164ab7554e284fa3b9
37,912
import random def generate_random(power: int) -> list: """ Generate list with 2 ** power random elemnts. """ array = [random.random() for i in range(2 ** power)] return array
b822277c6f4ca0a28339ef2feddfcec485e4d686
37,918
def findmax(L): """ >>> L1 = [ 1, 4, 5, 10 ] >>> findmax(L1) 10 >>> L2 = [ 1, 3, 9, 33, 81 ] >>> findmax(L2) 81 """ return max(L)
3fbb99b5189ee8a4a4867642ec4ebc73f06c04f0
37,920
def dayOfWeek(julian): """Get day of week from a julian day :param `julian`: the julian day :returns: the day of week as an integer and Monday = 1 """ return int((julian + 1) % 7)
0aa478cb8d597097a73f998cb6d4de128a06611c
37,922
def recall(tp_count, targets_count): """Calculates recall. :param tp_count: Number of true positives. :param targets_count: Number of targets. :return: The recall rate. """ if targets_count == 0: return 0.0 else: return tp_count / float(targets_count)
985c5c4567c9be12e4bd248d2a3054a2def1f29f
37,926
def intersect_interval(interval1, interval2): """Computes the intersection of two intervals. Parameters ---------- interval1: tuple[int] Should be `(x1_min, x1_max)` interval2: tuple[int] Should be `(x2_min, x2_max)` Returns ------- x_intersect: tuple[int] Should be the intersection. If the intersection is empty returns `(0, 0)` to represent the empty set. Otherwise is `(max(x1_min, x2_min), min(x1_max, x2_max))`. """ x1_min, x1_max = interval1 x2_min, x2_max = interval2 if x1_max < x2_min: # If interval1 < interval2 entirely return (0, 0) elif x2_max < x1_min: # If interval2 < interval1 entirely return (0, 0) x_min = max(x1_min, x2_min) x_max = min(x1_max, x2_max) return (x_min, x_max)
5db8daefa083b680c89a970224e2fc67a07beb5e
37,928
def get_order_by_from_request(request): """ Retrieve field used for sorting a queryset :param request: HTTP request :return: the sorted field name, prefixed with "-" if ordering is descending """ sort_direction = request.GET.get("dir") field_name = (request.GET.get("sort") or "") if sort_direction else "" sort_sign = "-" if sort_direction == "desc" else "" return f"{sort_sign}{field_name}"
9324e8e03bb8b5a48cd37f3daf6807712b57ad97
37,933
def turn_strat_into_label(stratum): """ Convert age stratification string into a string that describes it more clearly. Args: stratum: String used in the model Returns: label: String that can be used in plotting """ if 'up' in stratum: return stratum[4: -2] + ' and up' elif 'to' in stratum: to_index = stratum.find('to') return stratum[4: to_index] + ' to ' + stratum[to_index+2:] elif stratum == '': return 'All ages' else: return ''
fb2ce3810359a150948905913ba48e7627875769
37,934
def diff(prev_snapshot, next_snapshot): """Return a dict containing changes between two snapshots.""" snapshot_diff = { 'left_only': [], 'right_only': [], 'changed': [], 'common': [], } for path in set(prev_snapshot.keys()) | set(next_snapshot.keys()): if path in prev_snapshot and path not in next_snapshot: snapshot_diff['left_only'].append(path) elif path not in prev_snapshot and path in next_snapshot: snapshot_diff['right_only'].append(path) elif next_snapshot[path].mtime != prev_snapshot[path].mtime: if next_snapshot[path].isfile: snapshot_diff['changed'].append(path) else: snapshot_diff['common'].append(path) return snapshot_diff
040be0018e4b517cfc884a1e4a0f9cc030032fa9
37,936
def make_table_row(contents, tag="td"): """Given an iterable of string contents, make a table row. Args: contents: An iterable yielding strings. tag: The tag to place contents in. Defaults to 'td', you might want 'th'. Returns: A string containing the content strings, organized into a table row. Example: make_table_row(['one', 'two', 'three']) == ''' <tr> <td>one</td> <td>two</td> <td>three</td> </tr>''' """ columns = ("<%s>%s</%s>\n" % (tag, s, tag) for s in contents) return "<tr>\n" + "".join(columns) + "</tr>\n"
346301a77954829f6869a47ace6c1de52d787ffa
37,938
def typical_price(data, high_col='High', low_col='Low', close_col='Close'): """ Typical Price Source: https://en.wikipedia.org/wiki/Typical_price Params: data: pandas DataFrame high_col: the name of the HIGH values column low_col: the name of the LOW values column close_col: the name of the CLOSE values column Returns: copy of 'data' DataFrame with 'typical_price' column added """ data['typical_price'] = ( data[high_col] + data[low_col] + data[close_col]) / 3 return data
3c47cb01d4bd02351269f00c394d73abca862bc8
37,940
def get_family_name_from(seq_name_and_family): """Get family accession 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. Assumes the family does not have an underscore. Returns: string. PFam family accession. """ return seq_name_and_family.split('_')[-1]
d75d48c72ebee14ef43edf9d0ab42b2f85999713
37,943
from bs4 import BeautifulSoup def extract_html_links(text): """ Grab any GOV.UK domain-specific links from page text. :param text: Text within a details sub-section, refer to filtered for keys. :return: list of links """ links = [] try: soup = BeautifulSoup(text, "html5lib") links = [link.get('href') for link in soup.findAll('a', href=True)] except Exception: print("error") return [l.replace("https://www.gov.uk/", "/") for l in links if l.startswith("/") or l.startswith("https://www.gov.uk/")]
c7debea7ef2b3c8d239cde39b40913d9f141d3fb
37,946
def pow(a, b): """ Finds a^b using recursion. Params: a (float) - Base b (int) - Exponent Returns: Value of a^b (float) """ if(type(b) != int): print("ERROR: pow() not callable with doubles!") return 0 if(b == 0): return 1 else: return a * pow(a, b-1)
e903a8a430453cc57460a124a2485b7de57473e2
37,948
def twr(rors): """The Time-Weighted Return (also called the Geometric Average Return) is a way of calculating the rate of return for an investment when there are deposits and withdrawals (cash flows) during the period. You often want to exclude these cash flows so that we can find out how well the underlying investment has performed. Args: rors: List of all rors over multiple time periods Returns: The time-weighted return of a given investment Example: By providing a list of rate of returns you can calculate the time-weighted return based on that list: >>> import malee >>> malee.aar([.10, -.05, .12]) 0.056666666666666664 """ Rtw = 1 for ror in rors: Rtw *= 1 + ror return Rtw - 1
d9346efca7f8db311643818a8f13f30ab0ee12f5
37,951
def NoEmbedding(X): """Return X without changes.""" return X
c33dd4175999dab4eb3568753f8d4980c809b294
37,952
def bytes_split(bytes_, length): """Split bytes into pieces of equal size.""" n_pieces, excess = divmod(len(bytes_), length) if excess: raise ValueError('Bytes of length {} cannot be equally divided into ' 'pieces of length {}'.format(len(bytes_), length)) return [bytes_[i * length : (i + 1) * length] for i in range(n_pieces)]
7c70146e4ebbef70371e7cfb3ce3a1abe6df3c97
37,955
def diamag_correction(H, H0, Mp, Mpp, m_sample, M_sample, Xd_sample, constant_terms=[], paired_terms=[]): """ Calculates a diamagnetic correction of the data in Mp and Mpp and calculates the corresponding values of Xp and Xpp Input H: amplitude of AC field (unit: Oe) H0: strength of applied DC field (unit: Oe) Mp: in-phase magnetization (unit: emu) Mpp: out-of-phase magnetization (unit: emu) m_sample: sample mass in (unit: mg) M_sample: sample molar mass (unit: g/mol) Xd_sample: sample diamagnetic susceptibility in emu/(Oe*mol) from DOI: 10.1021/ed085p532 constant_terms: terms to be subtracted directly from magnetization (unit: emu/Oe) paired_terms: list of tuples (tup) to be subtracted pairwise from magnetization The terms must pairwise have the unit emu/Oe when multiplied, fx. unit of tup[0] is emu/(Oe*<amount>) and unit of tup[1] is <amount> Output Mp_molar: molar in-phase magnetization, corrected for diamagnetic contribution (unit: emu/mol) Mpp_molar: molar out-of-phase magnetization, corrected for diamagnetic contribution (unit: emu/mol) Xp_molar: molar in-phase susceptibility, corrected for diamagnetic contribution (unit: emu/(Oe*mol)) Xpp_molar: molar out-of-phase susceptibility, corrected for diamagnetic contribution (unit: emu/(Oe*mol)) """ # Old #Xp = (Mp - self.Xd_capsule*H - self.Xd_film*film_mass*H)*molar_mass/(sample_mass*H) - Xd_sample*molar_mass #Xpp = Mpp/(sample_mass*H)*molar_mass # NEW (documentation in docs with eklahn@chem.au.dk) # --------------------------- # Recalculate sample mass into g m_sample *= 10**-3 # Calculate the molar amount of the sample n_sample = m_sample/M_sample sum_of_constants = sum(constant_terms) sum_of_pairwise = sum([tup[0]*tup[1] for tup in paired_terms]) Mp_molar = (Mp - (sum_of_constants + sum_of_pairwise)*H - Xd_sample*H*n_sample)/n_sample Mpp_molar = Mpp/n_sample Xp_molar = Mp_molar/H Xpp_molar = Mpp_molar/H return Mp_molar, Mpp_molar, Xp_molar, Xpp_molar
6b29fd46ff6fd2457b6b3572efc544c3d84956c1
37,956
def rearange_base_link_list(table, base_link_index): """Rarange base link to beginning of table""" value = table[base_link_index] del table[base_link_index] table.insert(0, value) return table
08d94b515d6c1e1fcaf47fecdda7816d7fcb6470
37,963
import html def decode_html_entities(v): """Decodes HTML entities from a value, converting them to the respective Unicode characters/strings.""" if isinstance(v, int): v = str(v) return html.unescape(v)
852fa968ab99e0618eb1d845b6ef74322e137a42
37,964
def exe_success(return_code: int) -> bool: """Check if **return_code** is 0 Args: return_code (int): Return code of a process. Returns: bool: True if return code is equal to 0 """ return return_code == 0
cfea5a87f750c3629714832cb0758fcd3c18ad9a
37,966
def extract_pairs_from_lines(lines): """Extract pairs from raw lines.""" collected_pairs = [] for i in range(len(lines) - 1): first_line = lines[i].strip() second_line = lines[i+1].strip() if first_line and second_line: collected_pairs.append([first_line, second_line]) return collected_pairs
071d75bf422fa2ef61daff301837c85c0e0f3af6
37,967
def _replace_nan_with_none( plot_data, plot_keys): """Replaces all instances of nan with None in plot data. This is necessary for Colab integration where we serializes the data into json string as NaN is not supported by json standard. Turning nan into None will make the value null once parsed. The visualization already handles falsy values by setting them to zero. Args: plot_data: The original plot data plot_keys: A dictionary containing field names of plot data. Returns: Transformed plot data where all nan has been replaced with None. """ output_metrics = {} for plot_type in plot_keys: metric_name = plot_keys[plot_type]['metricName'] if metric_name in plot_data: data_series_name = plot_keys[plot_type]['dataSeries'] if data_series_name in plot_data[metric_name]: data_series = plot_data[metric_name][data_series_name] outputs = [] for entry in data_series: output = {} for key in entry: value = entry[key] # When converting protocol buffer into dict, float value nan is # automatically converted into the string 'NaN'. output[key] = None if value == 'NaN' else value outputs.append(output) output_metrics[metric_name] = {data_series_name: outputs} return output_metrics
887fff7f110945f8444f5ffec205828edf63f1f6
37,968
def bytearray_to_long(byte_array): """ Converts a byte array to long. :param byte_array: The byte array. :returns: Long. """ total = 0 multiplier = 1 for count in range(len(byte_array) - 1, -1, -1): byte_val = byte_array[count] total += multiplier * byte_val multiplier *= 256 return total
7dee1685dacd7e693a6cc50bf0ac704f78aa42bd
37,974
def identity(*args): """ Return whatever is passed in """ return args if len(args) > 1 else args[0]
f0f1276beb43a13c49311974013caa330588e734
37,975
def WordStartWithUppercase(word): """Return whether a word starts with uppercase letter""" if len(word) == 0: return False firstChar = word[0] return firstChar == firstChar.upper()
71b775fa9168abac586470e2a454194ce9103efe
37,976
def heading_level(line): """Return heading level of line (1, 2, 3, or 0 for normal)""" for i in range(4): if line[i] != '#': return i return 3
47a21dd52d827b33dc467c02a31ce16c85b2b41b
37,980
def validate_sequence_length(sequence): """ Validates that the sequence passed into it has a minimum length of 100 n.t. """ try: assert len(sequence) >= 100 return True except AssertionError: return False
3f9aecbd050e52a6d264a4753acc4215e6227c9e
37,985
def obtain_valid_painter(painter_class, **kwargs): """Returns a valid painter whose class is <painter_class>. You can try any argument you want ; only arguments existing in painter's __init__ method will be used. """ try: painter = painter_class(**kwargs) except TypeError: painter = painter_class() args_okay = {} for arg in kwargs: if hasattr(painter, arg): args_okay[arg] = kwargs[arg] painter = painter_class(**args_okay) return painter
259f36dc3f75de608dfb53c3db23cf018df07adb
37,997
def percent_diff(value1: float, value2: float, frac: bool = False) -> float: """ Return the percentage difference between two values. The denominator is the average of value1 and value2. value1: float, first value value2: float, second value frac: bool, Default is False. Set to True returns a fraction instead of percentages. This is useful for performing calculations on spreadsheets. return: float, absolute value of the difference in percentages Usage ----- >>> percent_diff(5, 7) 33.33333333333333 >>> percent_diff(5, 7, frac=True) 0.3333333333333333 """ assert value1 >= 0 and value2 >= 0, 'Values must not be negative' perdiff = abs(value1 - value2)/((value1 + value2)/2.0) if frac is False: perdiff *= 100 return perdiff
cffe298fb4218adc60bf75ff659090c41ae86922
37,999
def scheduler(epoch): """ Learning rate scheduler """ lr = 0.0001 if epoch > 25: lr = 0.00001 elif epoch > 60: lr = 0.000001 print('Using learning rate', lr) return lr
c65e57cc31926c4eb911c312e709f3209102e92a
38,002
def occurs_once_in_sets(set_sequence): """Returns the elements that occur only once in the sequence of sets set_sequence. The elements are returned as a set.""" occuronce = set() deleted = set() for setx in set_sequence: for sety in setx: if (sety in occuronce): deleted.add(sety) occuronce.remove(sety) elif (sety not in deleted): occuronce.add(sety) return occuronce
21344df038bf3af83584a9a1ef2dda1d6642af72
38,003
def allow_guess(number): """ Input: Takes in the number which the user is to guess Gets user input and tells the user whether the number is too high or too low Returns false if the guess is wrong and True if correct """ print('Guess a number') guess = input() guess = int(guess) if guess < number: print('Your guess is too low.') return False elif guess > number: print('Your guess is too high.') return False else: # If guess is equal to number return True
be3f97b8118c6a80bf0cc907fcc946bf89f0e9a0
38,009
def check_def_file(universe, res_name, atoms_name): """Check if atoms from the definition file are present in the structure in `universe`. This function return false if there is one missing in the structure. Print also an error message. Parameters ---------- universe : MDAnalysis universe instance res_name : str lipid residue name atoms_name : list of str list of atom names Returns ------- Bool True if all atoms are found in the structure. False otherwise. """ # get all atom names of the res_name in the system all_names = set(universe.select_atoms(f"resname {res_name}").names) if not set(atoms_name).issubset(all_names): miss_atoms = ",".join(set(atoms_name) - all_names) print(f"Some atoms ({miss_atoms}) of residue {res_name} from definition " "file are not found in your system.") return False return True
f2cff1286aca9a3be7e71b1d2f2d5cd810a93838
38,010
import re import logging def GetChromeosVersion(str_obj): """Helper method to parse output for CHROMEOS_VERSION_STRING. Args: str_obj: a string, which may contain Chrome OS version info. Returns: A string, value of CHROMEOS_VERSION_STRING environment variable set by chromeos_version.sh. Or None if not found. """ if str_obj is not None: match = re.search(r'CHROMEOS_VERSION_STRING=([0-9_.]+)', str_obj) if match and match.group(1): logging.info('CHROMEOS_VERSION_STRING = %s' % match.group(1)) return match.group(1) logging.info('CHROMEOS_VERSION_STRING NOT found') return None
d0dc48eb6c5f9c501024f155535e6e9adb1061c0
38,011
def JavaFileForUnitTest(test): """Returns the Java file name for a unit test.""" return 'UT_{}.java'.format(test)
6a524204c50084188b5144ba10434b586f2bc735
38,012
def get_descendant(node, desc_id): """Search the descendants of the given node in a scipy tree. Parameters ---------- node : scipy.cluster.hierarchy.ClusterNode The ancestor node to search from. desc_id : int The ID of the node to search for. Returns ------- desc : scipy.cluster.hierarchy.ClusterNode If a node with the given ID is not found, returns None. """ if node.id == desc_id: return node if node.is_leaf(): return None if node.left.id == desc_id: return node.left if node.right.id == desc_id: return node.right # search left l = get_descendant(node.left, desc_id) if l is not None: return l # search right r = get_descendant(node.right, desc_id) return r
99e081b2ee8dce513aad8fccbadb6cd94a017365
38,014
def length(x): """Calculate the length of a vector. This function is equivalent to the `length` function in GLSL. Args: x (:class:`~taichi.Matrix`): The vector of which to calculate the length. Returns: The Euclidean norm of the vector. Example:: >>> x = ti.Vector([1, 1, 1]) >>> length(x) 1.732051 """ return x.norm()
bab7dfde88c3cb7d9dc4a2f697dfe2443e9acabd
38,017
import hashlib def hash_csv(csv_path): """Calculates a SHA-256 hash of the CSV file for data integrity checking. Args: csv_path (path-like) : Path the CSV file to hash. Returns: str: the hexdigest of the hash, with a 'sha256:' prefix. """ # how big of a bit should I take? blocksize = 65536 # sha256 is the fastest relatively secure hashing algorith. hasher = hashlib.sha256() # opening the file and eat it for lunch with open(csv_path, 'rb') as afile: buf = afile.read(blocksize) while len(buf) > 0: hasher.update(buf) buf = afile.read(blocksize) # returns the hash return f"sha256:{hasher.hexdigest()}"
690c7c281d6c2f74c37195462f89dc75bf227fc1
38,018
import requests def retrieve_info(url, apidata): """ Return a dictionary from the HTSworkflow API """ web = requests.get(url, params=apidata) if web.status_code != 200: raise requests.HTTPError( "Failed to access {} error {}".format(url, web.status_code)) result = web.json() if "result" in result: result = result["result"] return result
c30cdc0bc8b556062195da0dc43d836446652a6b
38,020
def pvct(pv: float, compr_total: float): """ Pore Volume times Total Compressibility Parameters --- pv : float pore volume compr_total : float total compressibility Return pvct : float pore volume total compressibility """ return pv*compr_total
31c84e4dc94cb2f1c78c9e26ba02cec4c81f0800
38,022
def format_datestr(v): """ Formats a datetime or date object into the string format shared by xml and notation serializations.""" if hasattr(v, 'microsecond'): return v.isoformat() + 'Z' else: return v.strftime('%Y-%m-%dT%H:%M:%SZ')
3f149e3babf7703281583d5b31b56e2b1d261fcb
38,024
def betterFib(n): """ Better implementation of nth Fibonacci number generator Time complexity - O(n) Space complexity - O(n) :param n: The nth term :return: The nth fibonnaci number """ fib = [None] * n #print fib if n == 0: return 0 elif n == 1: return 1 elif fib[n-1] is not None: return fib[n-1] else : fib[n-1] = betterFib(n-1) + betterFib(n-2) return fib[n-1]
9374446b2f63943862b5b07c24d087c0083b319f
38,025
def top_level(symbol): """A rule that matches top-level symbols.""" return (symbol and ('.' not in symbol)) or None
71a80314e80e2242d7b505a19939e26eb060dded
38,026
def _seq_id_filter(id: str) -> str: """ Replaces underscores and semicolons with dashes in the sequence IDs. This is needed to have nice output filename templates with underscore as a delimiter for parameters """ result = id.replace("_", "-") return result.replace(";", "-")
e6355b1f94e76d255a1052072706619299ea4b51
38,028
import hashlib def _md5_hash_as_long(input_value): """Return the hash of the input value converted to a long.""" hex_hash = hashlib.md5(str(input_value).encode('utf-8')).hexdigest() return int(hex_hash, 16)
748cf6d783a17f07c3ea25280b9faae3d76211be
38,032
def _get_name(f): """Gets the name of underlying objects.""" if hasattr(f, '__name__'): return f.__name__ # Next clause handles functools.partial objects. if hasattr(f, 'func') and hasattr(f.func, '__name__'): return f.func.__name__ return repr(f)
c6f5c35b004afea321d981b5db9dd7be52b5efa6
38,036
def if_none(obj, default): """ Returns `obj`, unless it's `None`, in which case returns `default`. >>> if_none(42, "Hello!") 42 >>> if_none(None, "Hello!") 'Hello!' """ return default if obj is None else obj
fd851c9eb1eaa0048e3a0ac2d45b15fb208080a3
38,043
def _swiftmodule_for_cpu(swiftmodule_files, cpu): """Select the cpu specific swiftmodule.""" # The paths will be of the following format: # ABC.framework/Modules/ABC.swiftmodule/<arch>.swiftmodule # Where <arch> will be a common arch like x86_64, arm64, etc. named_files = {f.basename: f for f in swiftmodule_files} module = named_files.get("{}.swiftmodule".format(cpu)) if not module and cpu == "armv7": module = named_files.get("arm.swiftmodule") return module
59e978f22f4b1959ef32b0f2d68b0d92ec7fabe0
38,046
from typing import Dict def get_bags_inside(color: str, dependency_dict: Dict[str, Dict[str, int]]) -> int: """Recursively count the bags stored wthin color, including itself""" count = 1 inner_bags = dependency_dict[color] for bag_color, bag_count in inner_bags.items(): count += bag_count * get_bags_inside(bag_color, dependency_dict) return count
b97da4a194d3aba89f7eec9ac684812e139d116b
38,052
def pick(seq, func, maxobj=None): """Picks the object obj where func(obj) has the highest value.""" maxscore = None for obj in seq: score = func(obj) if maxscore is None or maxscore < score: (maxscore, maxobj) = (score, obj) return maxobj
707f9534fdec3b66bd311238689e2fe8e3456fbd
38,060
from typing import BinaryIO from typing import List def _create_test_file(tfile: BinaryIO, nlines=10) -> List[str]: """Helper function for populating a testing temp file with numbered example lines for comparison""" lines = [f"This is an example line {i}\n".encode('utf-8') for i in range(1, nlines+1)] tfile.writelines(lines) tfile.flush() return [l.decode().strip("\n") for l in lines]
4eac8c5e351c415ddc5734fa93e7e2aed0e61e2e
38,061
import ntpath import base64 def send_file(path, filename=None, mime_type=None): """ Convert a file into the format expected by the Download component. :param path: path to the file to be sent :param filename: name of the file, if not provided the original filename is used :param mime_type: mime type of the file (optional, passed to Blob in the javascript layer) :return: dict of file content (base64 encoded) and meta data used by the Download component """ # If filename is not set, read it from the path. if filename is None: filename = ntpath.basename(path) # Read the file into a base64 string. with open(path, 'rb') as f: content = base64.b64encode(f.read()).decode() # Wrap in dict. return dict(content=content, filename=filename, mime_type=mime_type, base64=True)
efd32f249f292ec5e15924b6e30f5b107029e90b
38,062
import re def extract_bibtex_items(latex_source): """Extract all bibtex items in a LaTeX file which are not commented out.""" bibtex_item_regex = re.compile(r"""(?<!%) # Lookbehind to check that the bibtex item is not commented out. (\\bibitem{.*?}.+?) # Match the entire bibtex item. (?=\\bibitem{|\\end{thebibliography}|$) # Match only until the next bibtex item, end of bibliography or end of line. """, re.DOTALL | re.VERBOSE) return bibtex_item_regex.findall(latex_source)
995a9d9559a6da564af010254fd466a8b729beb2
38,065