content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
import pickle def read_analysis_files(pathnames): """Reads in simulation analysis files (as produced by pathsim_analysis.py). Returns list of start times, end times, and statistics.""" start_time = None end_time = None compromise_stats = [] for pathname in pathnames: with open(pat...
ba3529a3b45bd20c0d3dc7e4243620a7f2c510ab
646,645
import socket def _canonicalize_hostname(hostname): """Canonicalize hostname following MIT-krb5 behavior.""" # https://github.com/krb5/krb5/blob/d406afa363554097ac48646a29249c04f498c88e/src/util/k5test.py#L505-L520 af, socktype, proto, canonname, sockaddr = socket.getaddrinfo( hostname, None, 0, 0...
3d8bf992e820292112e07aa03b1d1c98dc85c93b
646,646
def drop_na_rows_from_datum(datum): """Drops rows from the pandas dataframe where all values are NA.""" datum_size = len(datum) datum_type = datum['Type'][0] dropped_datum = datum.dropna(axis=0, how='all') dropped_datum_size = len(dropped_datum) print(str(datum_size - dropped_datum_size) + " ro...
a82cc5a43a3e6e7ea5ef8b467e1601ea281386b9
646,647
import time def timeit(callback, message): """Measure the time taken to execute a function. This function measures the amount of time it takes to execute the specified callback and prints a message afterwards regarding the time taken. The `message` parameter provides part of the message, e.g. if ...
093e53859132651113830733d034ee69be736488
646,649
import yaml def read_config_file(file_name): """Setup config parameters Read and store configuration parameters from given config file """ with open(file_name) as config_file: config_values = {} config = yaml.safe_load(config_file) # get values from yaml config_va...
f242fbfce7e2b59d3fa9a8129ca73bb56bde170e
646,654
import re def build_filter(pattern): """Function to return a filter function for scan_directories Parameters ---------- pattern : str Regex pattern to match Returns ------- function : a filter which returns true when a file matching the pattern is present ...
7d0543276f0bbadba15441f4dfe2c8363f664b65
646,655
def rearrange_pandasdf_columns(df): """ Takes a pandas Dataframe with columns 'DateTime' and 'WorkerIndex' amongst others and places them at the front :param df: The pandas Dataframe :return: The column rearranged df """ new_columns = ['DateTime', 'WorkerIndex'] for c in df.columns: ...
799f65fa8cdc0285e285865d9ed1823d0f802321
646,657
def compare_flavors(flavor_item): """ Helper function for sorting flavors. Sorting order: Flavors with lower resources first. Resource importance order: GPUs, CPUs, RAM, Disk, Ephemeral. :param flavor_item: :return: """ return ( flavor_item.get("Properties", {}).get("Accelerato...
a0e167ee1c7a4f93cc3533064a801b1a29211b7d
646,658
import json def process_config(json_file): """Load configuration as a python dictionary. Args: json_file (str): Path to the JSON file. Returns: dict: """ # parse the configurations from the config json file provided with open(json_file, 'r') as config_file: co...
2190525330bb319547fa143ea9e78bbddf052ffa
646,660
import inspect def _filter_class_attributes(path, parent, children): """Filter out class attirubtes that are part of the PTransform API.""" del path skip_class_attributes = { "expand", "label", "from_runner_api", "register_urn", "side_inputs" } if inspect.isclass(parent): children = [(name, child)...
b9911c076dc7aafcfbda0f7dcf197982ed8067a3
646,662
def make_list(arg): """Return a list with arg as its member or arg if arg is already a list. Returns an empty list if arg is None""" return (arg if isinstance(arg, list) else ([arg] if arg is not None else []))
d3663fb45d6dbf1b82508eaebac04afc48b7a6f4
646,665
from datetime import datetime import pytz def ns_to_datetime(ns): """ Converts nanoseconds to a datetime object (UTC) Parameters ---------- ns : int nanoseconds since epoch Returns ------- nanoseconds since epoch as a datetime object : datetime """ dt = datetime.utcf...
8e70e06b01add515147e267c2490b552567afb09
646,667
def get_total_ramp_rate_violation(model): """Total ramp rate violation""" ramp_up = sum(v.value for v in model.V_CV_TRADER_RAMP_UP.values()) ramp_dn = sum(v.value for v in model.V_CV_TRADER_RAMP_DOWN.values()) return ramp_up + ramp_dn
d0b7a7df22534f9a18f164a7c4ab27de7d7af577
646,669
def single_byte_xor(hex_string, single_byte: int) -> str: """XOR the hex_string with a single byte.""" return "".join((chr(letter ^ single_byte) for letter in bytes.fromhex(hex_string)))
5c0d6d7128e6d38d19515d45bdc02877bcddd0df
646,672
def _readSPARQLQuery(filename): """Read a SPARQL query from file and return the content as a string.""" content = "" with open(filename, 'r') as reader: content = reader.read() return content
6af37a844b1839c851fb686793e8b5ba2b0b12ae
646,673
import itertools def split_escaped_whitespace(text): """ Split `text` on escaped whitespace (null+space or null+newline). Return a list of strings. """ strings = text.split('\x00 ') strings = [string.split('\x00\n') for string in strings] # flatten list of lists of strings to list of strin...
32976934ae41b927ac9c5ed3b202881f0d2bc9e7
646,675
import re def axes_from_cmd(cmd, alt_names=None): """ Get axes name from command string :param cmd: str :param alt_names: dict {name_in_cmd: name_in_file} :return: str """ alt_names = {} if alt_names is None else alt_names cmd = cmd.split() axes = cmd[1] if axes in alt_names: ...
443acce54aaec1f9bf1fda3031464bcc1566399e
646,684
def level_states_full_space(level, dimension): """ Creates a list of all states in ``level``. Parameters ---------- level : int Level of the state space. dimension : int Number of clonotypes. Returns ------- state_list : list List of all states in level. ...
2796b6f00c9a1ffd5ffa4f42cf49f5b1cc7c1053
646,687
import re def Extract_Numbers(string): """Function to extract the individual numbers form within a string """ List = [int(s) for s in re.findall(r'\d+', string)] # Pythonic language for obtaining the integers that may appear in a string return List # Return the list of integers. Remianin...
c15b7374bc6f0655df503f461bc8af2477949bfc
646,688
def read_group_string(experiment_sample): """ Generate a SAM header string for the read group. Passed to bwa with escaped tabs. """ read_group_fields = [ '@RG', 'ID:'+experiment_sample.uid, 'PL:illumina', 'PU:'+experiment_sample.uid, 'LB:'+...
2c51e599ade513990a834d701b606cf7b444daba
646,690
def guess_n_initial_points(params): #96 (line num in coconut source) """Guess a good value for n_initial_points given params.""" #97 (line num in coconut source) return max(len(params), min(len(params) * 2, 10))
bceea596c4793a1f87cf5ac01398fe051b98b5e7
646,691
import logging def ping(reply, cfg) -> str: """ Replies to the !ping command, and is used as a keep alive check :param reply: Message object :param cfg: See reply param :return: The ping string, which in turn is given to Reddit's reply.reply() """ logging.info(f"Received ping from {reply.a...
fdd8a2f92f9059a40d351993ab9d718ef20fbfe7
646,692
import base64 import json def serialize(obj: object) -> str: """ Serializes a given object. It will find all the attributes of the class that don't start with '__' and returns a base64 encoded json string. """ final_dict = {} for attr in dir(obj): if not attr.startswith("__") and n...
eecc7016daca6b7f37bd16aa81b4d23bdff34abb
646,700
import pickle def loadData(file_model): """ Load object from (pk) dump file :param file_model: object file :return: reconstructed object file """ object_file = None try: object_file = open(file_model, 'rb') object_model = pickle.load(object_file) object_file.close()...
5715e6343b0ab12370ce3821089d3dc9f4b150a1
646,701
def dataset_len(tf_dataset, verbose=False): """ Compute the length of a TF dataset. """ tot = 0 for data, _ in tf_dataset.batch(128): tot += data.shape[0] if verbose: print('.', end='') if verbose: print(flush=True) return tot
1db2b4d474716633530bebecd6eeb450b3aa6b87
646,702
from typing import List def argmax(array: List[float]) -> int: """Simple argmax implementation for lists of floats.""" index, value = max(enumerate(array), key=lambda x: x[1]) return index
30ac274ff31c8e0da83d07cca9d48c17a1d08b2c
646,704
def check_exists(connection, path): """Check the file path in the SQL filepaths table. :param connection: :param path: :return: path id""" exists = '''SELECT EXISTS(SELECT 1 FROM filepaths WHERE filepath = ?);''' cursor = connection.cursor() cursor.execute(exists, (path,)) return cursor.fetchone()
2a7aab7ab36b644db9a5efbe2aa847a8f7fd7487
646,705
def _round_to_interval(time, interval): """ :param time: in us :return: time in us rounded to the earliest interval """ return time - time % interval
62bdd9a1ea5e7466c8effca9443c004c5c8423f9
646,706
def BMI_calculator(weight, height): """ Function to calculate the BMI of an individual given their respective weight (lb) and height (in)""" # Calculate BMI using lb / inches equation bmi = ((weight)/(height * height)) * 703 return bmi
610af23be46bb16ad28a1ba6bec4048ad67e9083
646,707
import uuid def create_id() -> str: # pragma: no cover """Creates an uuid.""" return str(uuid.uuid4())
a22df1382bc2da7d730aed6e9131301749720919
646,710
def ReadFileAsLines(filename): """Reads a file, removing blank lines and lines that start with #""" file = open(filename, "r") raw_lines = file.readlines() file.close() lines = [] for line in raw_lines: line = line.strip() if len(line) > 0 and not line.startswith("#"): lines.append(line) ret...
ff4ed7f4a380e0b80d8c1353483a509906dfd47e
646,713
def _formula_str(formula, sep='&'): """Returns a representation of 'formula' for prettyprinting""" next_sep = '|' if sep == '&' else '&' items = [item if (type(item) == str) else _formula_str(item, next_sep) for item in formula] return '({0})'.format(' {0} '.format(sep).join(items))
2cd33343ef16172f898da130cd59deaffcd0e76a
646,715
from typing import List def as_list(ans: str, sep: str = ",") -> List[str]: """ Spits answer into list according to separator """ items = ans.strip().split(sep) items = map(str.strip, items) return list(items)
c9607856762064fbeeaea668e05cff51d7684d61
646,716
def empty(level): """ To generate empty space needed for shaping the tree""" s = "" for x in range(level): s += " " return s
a312865a038d51fa3a9885f94b1f9c1926b172fc
646,720
def is_python_file(filename): """ Return whether a file is a Python file or not """ return filename.endswith('.py')
6f4b64a0c71afa3afe610f0aa014e526c6db77c7
646,723
def partition(message): """ Takes in a decoded message (presumably passed through prepare()) and returns a list of all contained messages. The messages are strings Example: >>> partition("5 Hello6 World!") ['Hello', 'World!'] """ messages = [] while len(message) > 0: ...
1d6c6b32052924b7862d579f5baae8bf8285c03c
646,724
def _date_long_form(date): """ Displays a date in long form, eg 'Monday 29th April 2019'. """ second_last = (date.day // 10) % 10 last = date.day % 10 if second_last != 1 and last == 1: ordinal = "st" elif second_last != 1 and last == 2: ordinal = "nd" elif second_last != 1 and l...
248cdaaba72e6252d6fdcec6499a4332e50a85c9
646,725
def _seconds_and_microseconds(timestamp): """ Split a floating point timestamp into an integer number of seconds since the epoch, and an integer number of microseconds (having rounded to the nearest microsecond). If `_seconds_and_microseconds(x) = (y, z)` then the following holds (up to the err...
5776932c2c2eb1e155c47cb7ca07c34933439f15
646,729
def _is_external(p): """Checks if the string starts with ../""" return p[0:3] == '../'
4e80683d6e84c2ada4d32e69aa6513df680a1616
646,732
def cli(ctx, tool_id, io_details=False, link_details=False): """Get details of a given tool. Output: Information about the tool's interface """ return ctx.gi.tools.show_tool(tool_id, io_details=io_details, link_details=link_details)
c56943a42517d2fa5ebd6654e7af45a59fe26018
646,734
def get_centroids(vertices, entities, dim=2): """Calculate the centroids of all the entities. :param vertex: vertex coordinates of mesh :type vertex: numpy.ndarray[float64 x dim] :param entities: mesh connectivity :type entities: numpy.ndarray[int x (dim+1)] :param dim: dimension of mesh :t...
8a3dc3c64b791698d90c3de1857f6d54bbc3a697
646,735
import itertools import fnmatch def ignore_rules_for_url(spider, url): """ Returns a list of ignore rules from the given spider, that are relevant to the given URL. """ ignore_rules = getattr(spider, "pa11y_ignore_rules", {}) or {} return itertools.chain.from_iterable( rule_list ...
1f225b175cf412df063e161ef5f4c824a93e65fc
646,736
def remove_resource(admin_mc, request): """Remove a resource after a test finishes even if the test fails.""" client = admin_mc.client def _cleanup(resource): request.addfinalizer(lambda: client.delete(resource)) return _cleanup
6fd635e0906bbad96094cdba3d4cdb2dc4b97a2c
646,739
def fixture_make_queue(request, make_unique_name): """ Return a factory function that can be used to make a queue for testing. :param request: The Pytest request object that contains configuration data. :param make_unique_name: A fixture that returns a unique name. :return: The factory function to ...
90d3259e19c5a3ab828841d01d219df8c3f89a56
646,740
import torch def points_to_cartesian(batch: torch.Tensor) -> torch.Tensor: """ Transforms a batch of points in homogeneous coordinates back to cartesian coordinates. Args: batch: batch of points in homogeneous coordinates. Should be of shape BATCHSIZE x NUMPOINTS x NDIM+1 Ret...
d2acca1df5deac28c4cb415a471e1eecadc2d2a9
646,749
def dnsamp2(x): """Downsamples by a factor 2 a 2D numpy array""" return x[::2,::2]
53faf6dd9992808b83059efeace7d3e74d69d88a
646,752
def get_view_predicates(view): """Returns the given view's predicates as list with (predicate's class name, predicate's value) pairs as items. Assumes the predicate's value is stored an attribute ``val``. """ predicates = [] for predicate in getattr(view, "__predicates__", []): if hasatt...
105881bc64a5238d6e67946f9d99f97c5b6902f8
646,753
def get_nth_line(file_name: str, line_no: int) -> str: """Return the given line of an input file. :param line_no: Which line of the input file to return? Starts at 1! :raises ValueError: line_no is too large for a small file or < 1. """ if line_no < 1: raise ValueError(""""line_no" starts ...
bab9579a05f994d40e0b9ac32d8d9293936b4f86
646,755
def __tuples(a): """map an array or list of lists to a tuple of tuples""" return tuple(map(tuple, a))
092c5b760e22f8b568668e27433a9733fbe6d85e
646,757
def scale_filters(filters, multiplier, base): """Scale `filters` by `factor`and round to the nearest multiple of `base`. Args: filters: Positive integer. The original filter size. multiplier: Positive float. The factor by which to scale the filters. base: Positive integer. The number of filters will be...
6b5b63ab78e6b592526cca85c6b9134acb850086
646,759
def map_values(function, dictionary): """ Transform each value using the given function. Return a new dict with transformed values. :param function: keys map function :param dictionary: dictionary to mapping :return: dict with changed values """ return {key: function(value) for key, value ...
7073f63e98f3b5e2a44bf76d74a40d08293f1a1d
646,760
import math def interpolate(low, high, n, method): """ Interpolates between two numeric values. The *n* parameter specifies the number of values to interpoluate. Specifically the number of classes that will result from the interpolated values. The *method* parameter specifies the interpolation method....
9405c308abd59d54dff77abef49094fc53f16879
646,764
def nearest_neighbor_interpolation(points): """ Input: list of points (x, y). Returns a function f(x) which returns y value of nearest neighbor for given x. At the midpoints (when distances to 2 closest points are the same) value of point with lower x value is returned. """ points.sort(key=l...
992e385d91a722989aef6c8f962863ddc46d6d25
646,768
def cache_get_langs(sql): """Get the list of languages from tooltip database.""" return [row[0] for row in sql.execute( "SELECT DISTINCT lang FROM vars").fetchall()]
160e61c15c5141ac9a590a0993361ab6548796b5
646,770
def trigger_reactions(polymer: str) -> str: """ Triggers the polymer reactions and returns the polymer with all the reactions applied. The algorithm works by iterating through the polymer and comparing the current unit against the next unit. If the next unit is the same as the current one but d...
28eb37247b75243f662f0d3e2959a37bd6cdd3c9
646,772
def pep8_module_name(name): """Convert a module name to a PEP8 compliant module name. * lowercase * whitespace -> underscore * dash -> underscore """ if name[0].isnumeric(): name = '_'+name valid_module_name = name.lower().replace('-', '_').replace(' ', '_') ...
ae9399663626321b040c52a598b2cd37e4421753
646,779
def put_list_to(path_to_file: str, lines: list): """ Write a list to a file in lines. :param str path_to_file: /path/to/file :param list lines: source list :return: str """ with open(path_to_file, 'w') as fp: content = list() for line in lines: content.append('{}...
74d57c76e8303467441d6035d85b62e677a4db55
646,782
def get_geotag(post_content): """Gets latitude and longitude from post's HTML content.""" post_map = post_content.find("div", {"id": "map"}) geotag = {"lat": "", "lon": ""} if post_map is not None: geotag["lat"] = post_map.attrs["data-latitude"] geotag["lon"] = post_map.attrs["data-longi...
a61c3742e6a0cdc23ef28fa8ec03631a20e1e352
646,783
def get_hosted_zone_id(session, hosted_zone): """Look up Hosted Zone ID by DNS Name Args: session (Session|None) : Boto3 session used to lookup information in AWS If session is None no lookup is performed hosted_zone (string) : DNS Name of the Hosted Zone to loo...
98f0a54d9a440b44c2c266adc8f698090bde50de
646,785
def assert_variable_type(variable, expected_type, raise_exception=True): """Return True if a variable is of a certain type or types. Otherwise raise a ValueError exception. Positional arguments: variable -- the variable to be checked expected_type -- the expected type or types of the variable r...
9610b5013aeb15a692a8b8f5c12a556f766a86fc
646,786
import sqlite3 def get_all_assembled_contigs(cxn, bit_score=0, length=0): """Get all assembled contigs.""" sql = """ SELECT iteration, contig_id, seq, description, bit_score, len, query_from, query_to, query_strand, hit_from, hit_to, hit_strand FROM aux.assemble...
0780d6087dd40dd30d258716c108f647491811ed
646,791
def convert_from_CAL_to_k(data): """ Transforms from CAL to k using k = (1 - CAL) """ return 1 - data
ea3a3a7a73a13662e07417206cb5725fc6b02575
646,796
def word_count(text): """ Count number word in text Args: text (str): string text Returns: (int): number of word in text """ if isinstance(text, str): tokens = text.split(" ") else: tokens = [] return len(tokens)
fa35beb4187eab1245f16e355193e66256d6f460
646,798
def cast_str_to_int_float_bool_or_str(str_, fmt='{:.3f}'): """ Convert string into the following data types (return the first successful): int, float, bool, or str. :param str_: str; :param fmt: str; formatter for float :return: int, float, bool, or str; """ value = str(str_).strip() f...
50edf0028c5d6194947c426275437d4dc75c9a3b
646,799
def exists(env): """ Check if `gtags` module has been loaded in the environment """ return env['GTAGS'] if 'GTAGS' in env else None
8feb1b08e24cd77c8f954c113f9fa6241496318d
646,801
def filter_matching_fields(fields, other_fields): """return fields which are same as in other_fields list, ignoring the case""" other_fields_lowercase = set([f.lower() for f in other_fields]) return [f for f in fields if f.lower() in other_fields_lowercase]
f8b0909e4872c0bc6b1212b8bd658debb38da922
646,802
def get_file_attachment(res_client, incident_id, artifact_id=None, task_id=None, attachment_id=None): """ call the Resilient REST API to get the attachment or artifact data :param res_client: required for communication back to resilient :param incident_id: required :param artifact_id: optional :...
8dcf887f2773addbbf8a29791157f9be833ab9e9
646,803
import textwrap def literal(text: str) -> str: """ Quick way of 'quoting' the text https://orgmode.org/manual/Literal-Examples.html """ return textwrap.indent(text, ': ', lambda line: True)
af821c624581cd9dd55b27d4a8937c7cd57c679a
646,805
def concatenate_dirs(dir1, dir2): """ Appends dir2 to dir1. It is possible that either/both dir1 or/and dir2 is/are None """ result_dir = dir1 if dir1 is not None and len(dir1) > 0 else '' if dir2 is not None and len(dir2) > 0: if len(result_dir) == 0: result_dir = dir2 e...
576f2f0df6d7f54c659a1a315920e748d784f4be
646,808
def intersection_lists(lst1, lst2): """ Return the intersection between two lists """ return list(set(lst1) & set(lst2))
9ab488c7658ff8a09b9210d6c778391030533bd0
646,810
from typing import List def find_mine_pythonic_alt(field: List) -> List[int]: """Finds mine location (pythonic alternative). Examples: >>> assert find_mine([[0, 0, 0], [0, 1, 0], [0, 0, 0]]) == [1, 1] """ return next( [field.index(sub_field), sub_field.index(1)] for sub_field ...
7ec65ae9698dd901cd07f3a2cf12a8fb9c27d65b
646,811
def specieset(structure): """ Returns ordered set of species. Especially usefull with VASP since we are sure what the list of species is always ordered the same way. """ tmp = [a.type for a in structure] species = sorted(set(tmp), key=tmp.index) return species
23d38b5e1052a6010e48794c2f2978b9fd753311
646,814
async def get_db_name(pool): """Gets the name of the current database.""" return await pool.fetchval("SELECT current_database()")
d81f486de7b2e0a45101b7d8badf6b3b855591ae
646,815
def extract_prime_power(a, p): """ Return s, t such that a = p**s * t, t % p = 0 """ s = 0 if p > 2: while a and a % p == 0: s += 1 a //= p elif p == 2: while a and a & 1 == 0: s += 1 a >>= 1 else: raise ValueError("Nu...
39e39b7911ad71d6c15600cc52e61e5e819b05e4
646,816
def get_K(jfdb): """ Infer K from jellyfish db. """ j = jfdb.rsplit('_', 1)[0].rsplit('-', 1)[-1] assert j[0] == 'K' return int(j[1:])
82b649e09a57108e22006dc7baaef01b40570166
646,820
def load_file_list(filename): """ Load a text file containing a list of filenames (or other strings) as a Python list. To obtain a list of DataFile objects, the result can easily be converted as in the example: >>> raw_biases = DataFileList(load_file_list('list_of_biases.txt')) If the lis...
bbb49943b9d5ea6869be35d343ce0f7452d1f6d5
646,821
def create_choice(klass, choices, subsets, kwargs): """Create an instance of a ``Choices`` object. Parameters ---------- klass : type The class to use to recreate the object. choices : list(tuple) A list of choices as expected by the ``__init__`` method of ``klass``. subsets : l...
948d6e1ba8082c82ff6a7e7dea643b4a39ee6a60
646,822
import torch def try_gpu(x): """Try to put a Variable/Tensor/Module on GPU.""" if torch.cuda.is_available(): return x.cuda() return x
2db7675874cfa50f4472fcaab4708d218d028fe3
646,824
def methods(attrdict): """Return all public methods and __init__ for some class.""" return { name: method for name, method in attrdict.items() if callable(method) and (not name.startswith("_") or name == "__init__") }
81d77e191475431124fa4fe1b1ccc74ef7f016d3
646,825
import time def chop_midnight( tsecs ): """ Returns the epoch time at midnight for the given day. """ tup = time.localtime( tsecs ) tup = ( tup[0], tup[1], tup[2], 0, 0, 0, tup[6], tup[7], tup[8] ) return int( time.mktime( tup ) + 0.5 )
267b6c576288f0bffc831104e208582a783eef8f
646,826
def difference_with(f, xs, ys): """Finds the set (i.e. no duplicates) of all elements in the first list not contained in the second list. Duplication is determined according to the value returned by applying the supplied predicate to two list elements""" out = [] for x in xs: if x in out: ...
13304fc3b0a7335c5c30b7c16d35bec1e37ae7bd
646,829
import math def roundup(x, n=10): """Round up x to multiple of n.""" return int(math.ceil(x / n)) * n
6cd0fcddf7488a3aecd13a255dabaa3a775c125e
646,830
def site(coord, size, xperiodic): """ numbering the square lattice sites Parameters -------------- site : (x, y) (x, y) coordinate of the site size : (int, int) -> (nx, ny) linear size of the square lattice xperiodic : boolean indicates PBC along x """ nx, ny...
f0344d7663c45054968ab44a793b7c651dbb608a
646,831
import requests import logging def get_news_from_steamNetAPI(game_id): """ This is the function that gets the latest news of a game from the Steam API. Params: game_id - Integer Returns: List - Contains 3 dictionaries with the 'actual' news. """ try: game_news_api...
e9f13957d076a17cfd767ef4d383fd55be0c9c57
646,841
def compute_overlap(bound1, bound2): """ Get the bound of the overlapping section between two bounds :param bound1: bound where overlap is to be checked :param bound2: bound where overlap is to be checked :return: bound tuple of overlap between ``bound1`` and ``bound2`` if there is no overl...
9e6853aa13f4395bb2a151c0f24a5aec766ab78f
646,843
def calculate_check_digit(number): """ Given a number without the check-digit, calculate the check digit and return it. See: https://www.gs1.org/services/how-calculate-check-digit-manually """ # Step 2: Multiply alternate position by 3 and 1 # and get the sum step_2 = sum( [int(...
7c219600ae96672344d14cbce997ce1c0a1f7ff7
646,858
def b64max(char_length): """ Maximum number of raw bits that can be stored in a b64 of length x """ # Four byte increments only, discard extra length return (char_length // 4) * (3 * 8)
fc5adc579bf8a250b161723a7e31fc7a71c06aee
646,862
def get_age_df(df, age_list): """Gets a DataFrame and filters it for the purpose of putting specific ages on the Concordia plots. Note the DataFrame must have a column named 'age'. Parameters ---------- df : DataFrame A dataframe with a column 'age'. age_list : list A list o...
4c007f23fed55d808b2c6bb426b7f66f788a8d68
646,863
def rm_duplicates(lis): """ Takes a list, removes duplicates and returns it sorted. """ a_set = set(lis) return sorted(a_set)
c3571f5002a0c02cfe404b7613d1db5e685e56bc
646,867
def researched_before(technology, timestamp, player): """Check if a technology was researched before a given time.""" for item in player['research']: if item['technology'] == technology and item['timestamp'] < timestamp: return True return False
dc13485aa0be40fa2cb2c25fe0926e8e97f32c9d
646,869
def average(lst): """Averages a list, tuple, or set of numeric values""" return sum(lst) / len(lst)
4c29af810ebd80de38cf8fad2622e1d2c701f5e4
646,873
def hasHandlers(self): """ See if this logger has any handlers configured. Loop through all handlers for this logger and its parents in the logger hierarchy. Return True if a handler was found, else False. Stop searching up the hierarchy whenever a logger with the "propagate" attribute set to ze...
3a2586bd34513be12c6170edab127315c8be0d08
646,875
def cmp_column_indices(x,y): """Comparision function for column indices x and y are XLS-style column indices e.g. 'A', 'B', 'AA' etc. Returns -1 if x is a column index less than y, 1 if it is greater than y, and 0 if it's equal. """ # Do string comparision on reverse of column indices ret...
7ce7305eadd32a0b756dd6bdf2cabd20bfe0b2ff
646,877
def color_rgb(red, green, blue): """ Given three intensities red, green, blue, all from 0 to 255, returns the corresponding CSS color string e.g. '#ff00cc' """ return f"#{red*256**2 + green*256 + blue:06x}"
be02aea5a0fc04f7bbedce4b3fc18fb5cdfff862
646,878
import builtins def _parse_warning(warn_str): """Reverse-engineer a warning string Parameters ---------- warn_str : string Returns ------- (str, Warning, str, int) message, category, filename, lineno """ tokens = warn_str.rstrip('\n').split(" ") # The first token is ...
803826059f3bd2cfdd84d2ec7bdf0ef9c97b5eaa
646,879
import functools def expected_failure(exptn, msg=None): """ Wrapper for a test function, which expects a certain Exception. Example:: @expected_failure(ValueError, "point must be an instance of lib.Point") def test_result_error(self): Result([1., 1.], 1.1) @param Excepti...
8270662bc767ba37895ff31d06e0da0b9d59dee4
646,880
def elements_to_str(l): """ Convert each element in an iterator to a string representation Args: l (:obj:`list`): an iterator Returns: :obj:`list`: a list containing each element of the iterator converted to a string """ return [str(e) for e in l]
fe38143e0c9f839750a3118e4bc397e6a6fba360
646,883
def fence_native_format(source, language, css_class, options, md): """Format source as div.""" return '<div class="%s">%s</div>' % (css_class, source)
b0ebf41d59b63952d6e2cccb3c89aa64cdfc420c
646,884
def add_inplace(X, varX, Y, varY): """In-place addition with error propagation""" # Z = X + Y # varZ = varX + varY X += Y varX += varY return X, varX
37648a0a42cc6578320f20ee771d885172170ee9
646,890
from typing import get_origin from typing import Union from typing import get_args def is_type_SpecificOptional(f_type) -> bool: """ Returns true for types such as Optional[T], but not Optional, or T. """ return get_origin(f_type) is not None and f_type.__origin__ == Union and get_args(f_type)[1]() is...
e4259a94ac0c6a7e2913271a2711ec30b659f11d
646,893