content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
from typing import MutableMapping from typing import Callable from typing import Any def _create_before_send_filter(tags: MutableMapping[str, str]) -> Callable[[Any, Any], Any]: """Create a filter that adds tags to every events.""" def do_filter(event: Any, hint: Any) -> Any: event.setdefault("tags", {}).update(tags) return event return do_filter
84f0ba6757cef10e39f447baeefb305b00e976bc
219,118
def tpc_h17(con, BRAND="Brand#23", CONTAINER="MED BOX"): """Small-Quantity-Order Revenue Query (Q17) This query determines how much average yearly revenue would be lost if orders were no longer filled for small quantities of certain parts. This may reduce overhead expenses by concentrating sales on larger shipments.""" lineitem = con.table("lineitem") part = con.table("part") q = lineitem.join(part, part.p_partkey == lineitem.l_partkey) innerq = lineitem innerq = innerq.filter([innerq.l_partkey == q.p_partkey]) q = q.filter( [ q.p_brand == BRAND, q.p_container == CONTAINER, q.l_quantity < (0.2 * innerq.l_quantity.mean()), ] ) q = q.aggregate(avg_yearly=q.l_extendedprice.sum() / 7.0) return q
4f2214192ea084c05a257dd9dac7785fc54ad8ec
66,674
def string_list(s): """Convert a string to a list of strings using .split().""" return s.split()
7a1882fc3ca6264929e80f14d3d88f156fe9143d
507,725
def sanitize(extracted_df): """ Drops all rows that have invalid values :param extracted_df: The dataframe generated from the data extracted from the loaded file :return: A dataframe with no invalid values """ columns = extracted_df.columns cleaned_df = extracted_df.copy() print('Removing invalid values') print(f'Total values before invalid value removal: {len(extracted_df.index)}') for column in columns: cleaned_df = cleaned_df[cleaned_df[column] != -1] print('Invalid values removed') print(f'Total values after invalid value removal: {len(cleaned_df.index)}') return cleaned_df
ecdbe067b94e3836421e51df823383d9566e0bcf
403,526
def get_dimentions_factors(strides_schedule): """ Method calculates how much height and width will be increased/decreased basen on given stride schedule Args: strides_schedule: A list of stride tuples(heigh, width) Returns: Two numbers that tells how many times height and width will be increased/decreased """ width_d = 1 height_d = 1 for s in strides_schedule: width_d = width_d * s[1] height_d = height_d * s[0] return height_d, width_d
9905936f6c06dc243009dc5af2d8191c8ee6a9e7
537,547
import itertools def _group_by_key(in_file, sep='\t'): """Turn this: ['x\ta', 'x\tb', 'y\tc'] into this: [('x', ['a', 'b']), ('y', ['c'])] """ group_key = lambda line: line.split(sep, 1)[0] return itertools.groupby(in_file, key=group_key)
94ad37296e356993257808382f7a16123d0e2c90
157,926
import copy import collections def stringify_keys(dictionary: dict): """ This helper function will stringify all keys in the given dictionary. For example: > from apps.authentication.models.user import Jobs > data = { Jobs.PTA: True } > stringify_keys(data) { "PTA": True } """ origin_dict = copy.deepcopy(dictionary) return_dict = collections.defaultdict() for key in origin_dict.keys(): # Check if the value is a dict if isinstance(origin_dict[key], dict) and origin_dict[key]: value = stringify_keys(copy.deepcopy(origin_dict[key])) else: value = copy.deepcopy(origin_dict[key]) if not isinstance(key, str): new_key = str(key) if hasattr(key, "json_repr") and callable(key.json_repr): new_key = key.json_repr() return_dict[new_key] = value else: return_dict[key] = value return return_dict
db5a08fc106ce01ef90d37e896a24db2d143ce13
635,207
import secrets def generate_token_urlsafe(unique=False, nbytes=32): """Generate an URL-safe random token.""" return secrets.token_urlsafe(nbytes=nbytes)
5bdab6879f241a7459653e5ec363110263f0c171
702,380
import zipfile def unzipper(zip_file, outdir): """ Unzip a given 'zip_file' into the output directory 'outdir'. Return the names of files in the archive. """ zf = zipfile.ZipFile(zip_file, "r", allowZip64=True) filenames = zf.namelist() zf.extractall(outdir) return filenames
515224a3f1880977979a27c0e9aef199c12abe64
350,816
import re def get_table_dividers(table): """ Receives a results table Returns a list of divider rows (------) """ return [len(re.findall(r"^-{3,}$", line)) for line in table.split("\n")]
da3f971fd81207ab8d1a78605c31affb105ad968
669,514
import re def findExtendedCode(message): """get extended codes, which give more information than standard 3 digit codes Args: message: message from email server Returns: Extended code if found, None otherwise """ #references: #https://www.iana.org/assignments/smtp-enhanced-status-codes/smtp-enhanced-status-codes.xhtml #https://www.usps.org/info/smtp_status.html #https://docs.microsoft.com/en-us/exchange/mail-flow-best-practices/non-delivery-reports-in-exchange-online/non-delivery-reports-in-exchange-online #the first digit can be 2-5. Second digit can be 0-7. Third digit varies between servers. regex = '[2-5]\.[0-7]\.[0-9](([0-9])?)(([0-9])?)' #find such a pattern in the message x = re.search(regex, message) if x is not None: #return the first match return x.group(0) else: return None
751390084521234412fa313c5e2bc1e985a7f812
435,157
def as_snake_case_prefix(name): """ Convert PascalCase name into snake_case name""" outname = "" for c in name: if c.isupper() and len(outname) > 0: outname += '_' outname += c.lower() return outname + ('_' if name else '')
6a06dcc0b1cc4423c026f880005f2e3f9827ae46
151,561
import math def gc_distance(point1, point2): """returns distance between point1 and point2 using great circle equation""" lon1, lat1 = point1[0], point1[1] lon2, lat2 = point2[0], point2[1] lat1, lat2, lon1, lon2 = map(math.radians, [lat1, lat2, lon1, lon2]) radius = 6378 # WGS84 equatorial radius in km trig = math.sin(lat1) * math.sin(lat2) + math.cos(lat1)\ * math.cos(lat2) * math.cos(lon1 - lon2) if trig >= 1: distance = 0 else: distance = radius * math.acos(trig) return distance
0e6afd485f9150e673a618657b8ac486e4146647
169,001
from typing import Any from typing import Optional def parse_int(string: Any, base: int = 10) -> Optional[int]: """ safely convert an object to int if possible, else return None """ if isinstance(string, int): return string try: return int(string, base=base) except Exception: pass try: return int(string) except Exception: pass return None
3078a2ea8c259ca72706dbef4d223559e01f557a
232,270
import re def extract_redundancy_factor(oclass): """Extract the redundancy factor from an object class. Args: oclass (str): the object class. Returns: int: the redundancy factor. """ match = re.search("EC_[0-9]+P([0-9])+", oclass) if match: return int(match.group(1)) match = re.search("RP_([0-9]+)", oclass) if match: return int(match.group(1)) - 1 return 0
5b619d9d9d4194f5926b9ec65861053c1152ae48
87,604
def make_alignment_line(strand, kmer, prob, event): """Convert strand, kmer, probability and event to a correctly formatted alignment file line :param strand: 't' or 'c' representing template or complement strand of read :param kmer: nucleotide kmer :param prob: probability of kmer coming from certain event :param event: mean of the corresponding event :return: correctly formatted alignment line """ assert strand in ['c', 't'], "Strand must be either 'c' or 't'. strand: {}".format(strand) assert isinstance(prob, float), "probability must be a float: prob {}".format(prob) assert isinstance(kmer, str), "kmer must be a string: kmer {}".format(kmer) assert isinstance(event, float), "event must be a float: event {}".format(event) entry_line = "blank\t0\tblank\tblank\t{strand}\t0\t0.0\t0.0\t0.0\t{kmer}\t0.0\t0.0\t{prob}\t{event}\t0.0\n" return entry_line.format(strand=strand, kmer=kmer, prob=prob, event=event)
551f3739bc46aae88d266605604ec12a0f5a1e4f
443,757
def get_domain_label(domain): """ "." is not a valid character in a prometheus label and the recommended practice is to replace it with an "_". """ return domain.replace('.', '_')
7ca6d78852294c9c2d35e250114f647bbac3829e
307,839
def sanitize(str, strip=[" "], remove=["\r", "\n"]): """Return a whitespace-stripped, newline-stripped string. Args: str (str): The string to be sanitized. strip (str[], optional) Additional things to be stripped. remove (str[], optional) Additional things to be removed. Returns: (str) The sanitized string. """ for stripme in strip: str = str.strip(stripme) for removeme in remove: str = str.replace(removeme, "") return str
d84d0f021cbaa283ee0cfe4128c362188e4dbef2
616,041
def fetchone(cursor): """ Fetch one row from the given cursor Params: cursor (Cursor) : Cursor of previously executed statement Returns: dict : Dict representing the records selected indexed by column name """ if cursor: return dict(zip((d.name for d in cursor.description), cursor.fetchone())) else: return {}
1bff5e467c25db6f1d3a3d63af456812b93db676
237,019
from typing import List def read_files(file_paths: List[str]) -> List[str]: """Read all of the files in the list of files provided, returning a list of strings. Args: file_paths List[str]: List of files to be read. Returns: List[str]: List of documents as strings. """ documents = [] for file in file_paths: with open(file, "r") as f: documents.append(f.read()) return documents
073e2976736ceed988c503d2347db5528392713c
346,929
import inspect def _wrap_asgi_coroutine_func(asgi_impl): """Wrap an ASGI application in another coroutine. This utility is used to wrap the cythonized ``App.__call__`` in order to masquerade it as a pure-Python coroutine function. Conversely, if the ASGI callable is not detected as a coroutine function, the application server might incorrectly assume an ASGI 2.0 application (i.e., the double-callable style). In case the app class is not cythonized, this function is a simple passthrough of the original implementation. Args: asgi_impl(callable): An ASGI application class method. Returns: A pure-Python ``__call__`` implementation. """ # NOTE(vytas): We are wrapping unbound class methods, hence the first # "self" parameter. # NOTE(vytas): Intentionally not using functools.wraps as it erroneously # inherits the cythonized method's traits. async def __call__(self, scope, receive, send): await asgi_impl(self, scope, receive, send) if inspect.iscoroutinefunction(asgi_impl): return asgi_impl return __call__
fe54d656ba65615fbbb090666b29d63e5c70bc28
247,525
def get_genres(anilist): """ Get the genres for the search. :param anilist: The anilist search result. :return: the genres for the search. """ lst = anilist.get('genres', []) if not lst: return return [s for s in lst if s]
18bb3a9643e38ec3b34f709bc8c08950991e3112
550,364
import torch def log_interpolate(log_a, log_b, alpha_logit): """Numerically stable implementation of log(alpha * a + (1-alpha) * b).""" log_alpha = -torch.nn.functional.softplus(torch.tensor(-alpha_logit)) log_1_minus_alpha = -torch.nn.functional.softplus(torch.tensor(alpha_logit)) y = torch.logsumexp(torch.stack((log_alpha + log_a, log_1_minus_alpha + log_b),0), dim=0) return y
b07d8e9fdfc6a002d46dd84551408aef863c3867
618,012
def train_matrix_info_from_model_id(db_engine, model_id): """Get original train matrix information from model_id Args: db_engine (sqlalchemy.db.engine) model_id (int) The id of a given model in the database Returns: (str, dict) matrix uuid and matrix metadata """ get_train_matrix_query = """ select matrix_uuid, matrices.matrix_metadata from triage_metadata.matrices join triage_metadata.models on (models.train_matrix_uuid = matrices.matrix_uuid) where model_id = %s """ return db_engine.execute(get_train_matrix_query, model_id).first()
0b5aab871c84a0af769c11ec5981e850bd14fb22
528,613
import re def trim_whitespaces(string: str) -> str: """Replaces all multiple whitespaces with one and calls default strip function on a result Example: >>> trim_whitespaces('hello friend') hello friend >>> trim_whitespaces(' hello old friend ') hello old friend Args: string: A string to be trimmed. Returns: Trimmed string. """ return re.sub(r"\s+", " ", string).strip()
cc57741b498951d80191c2920942df519d0cb521
608,855
def _cast_safe(self, value, cast_type = str, default_value = None): """ Casts the given value to the given type. The cast is made in safe mode, if an exception occurs the default value is returned. :type value: Object :param value: The value to be casted. :type cast_type: Type :param cast_type: The type to be used to cast the retrieved value (this should be a valid type, with constructor). :type default_value: Object :param default_value: The default value to be used when something wrong (exception raised) occurs. :rtype: Object :return: The value casted to the defined type. """ # in case the value is none it's a considered special case # and the value should be returned immediately to caller if value == None: return value try: # retrieves the value type value_type = type(value) # in case the value type is the same # as the cast type if value_type == cast_type: # sets the value as the value casted value_casted = value # otherwise else: # casts the value using the type value_casted = cast_type(value) # returns the value casted return value_casted except Exception: # returns the default value return default_value
f89300e21a1758c892eb42ad35696a56f77313b5
71,584
def compute_f1(precision, recall): """ Compute F1 score. F1 = 2 * P * R / (P + R) """ try: f1 = 2 * precision * recall / (precision + recall) except ZeroDivisionError: f1 = 0. return f1
08531e4a98f052c3fe57587edf4823b864f1780e
496,209
def add_token_to_headers(token, headers=None): """Add bearer token to header dict.""" if headers is None: headers = {} return {**headers, **{"Authorization": "Bearer " + token["access_token"]}}
fbf122618881f5235551eaefd47c14c78092394b
144,555
def getTranslation(m): """ get the translation vector of a homogeneous 4x4 row-major transformation matrix """ return [m[3], m[7], m[11]]
6aba45f7c922a2b3be45b043e1b6c83095564feb
228,048
def _is_string_or_bytes(s): """Returns True if input argument is string (unicode or not) or bytes. """ return isinstance(s, str) or isinstance(s, bytes)
d7b098424d695d3c510fd859b9bf354a262527e3
299,497
import shutil def get_program_path(aliases): """Get programs path given a list of program names. Parameters: aliases (list): Program aliases, e.g. ["diamond", "diamond-aligner"] Raises: ValueError: Could not find any of the given aliases on system $PATH. Returns: Path to program executable. """ for alias in aliases: which = shutil.which(alias) if which: return which raise ValueError(f"Failed to find {aliases} on system $PATH!")
270a572928b3e95a6c6b46277659f86441f542a4
432,686
def map_element(element): """Convert an XML element to a map""" # if sys.version_info >= (2, 7): # return {e.tag: e.text.strip() for e in list(element)} # return dict((e.tag, e.text and e.text.strip() or "") # for e in list(element)) return dict((e.tag, e.text) for e in list(element))
b8a84be91f28757f28622a5909a569d35e38282f
35,627
def truncate(message, from_start, from_end=None): """ Truncate the string *message* until at max *from_start* characters and insert an ellipsis (`...`) in place of the additional content. If *from_end* is specified, the same will be applied to the end of the string. """ if len(message) <= (from_start + (from_end or 0) + 3): return message part1, part2 = message[:from_start], '' if from_end and len(message) > from_end: if len(message) - from_start < from_end: from_end -= len(message) - from_start part2 = message[-from_end:] return part1 + '...' + part2
44e37164aff5912d37a3dc27217e498b1c14efff
20,112
def full_model_name(model, sep='.'): """Returns the "full name" of the given model, e.g. "contacts.Person" etc. """ return model._meta.app_label + sep + model._meta.object_name
508ba659124a50d7b0c2e7a4c976e2091cb50974
157,769
import requests from bs4 import BeautifulSoup def get_holdings(base_url, mms_id, api_key): """ Get the holdings id(s) for the bib record via the Alma API. """ holdings_list = [] query = 'bibs/{}/holdings?apikey={}' r = requests.get(''.join([base_url, query.format(mms_id, api_key)])) soup = BeautifulSoup(r.text, 'xml') holdings = soup.find_all('holding_id') for id in holdings: holdings_list.append(id.text) return holdings_list
8ff8790043b9fc9ea50c7521bc27a8314e8033be
346,954
from typing import Dict from typing import Any def recursive_merge_dict(dict1: Dict[str, Any], dict2: Dict[str, Any]) -> Dict[str, Any]: """Merge two dictionaries into a third dictionary recursively. Args: dict1: First dictionary to be merged. dict2: Second dictionary to be merged. Returns: A dictionary by merging the two dictionaries. If any of the values are dicts, they will be merged recursively. """ res = dict1.copy() for k, v in dict2.items(): if k in res and isinstance(res[k], dict): res[k].update(recursive_merge_dict(res[k], dict2[k])) else: res[k] = v return res
ce659569baa270a577e190d7572f5758e62e45cd
364,368
def date_index(start_year, date): """Returns the number of months that have passed since January of start_year""" return (date.year - start_year) * 12 + (date.month - 1)
1dafa11fff2e696e0bd293e880df2f02cca38460
587,935
from typing import List def load_tokens(path: str) -> List[str]: """Loads the current tokens from file""" with open(path, 'r') as f: res = [x.strip() for x in f.readlines()] return res
13f1ffb5e462d2360ea6dbea4354141d7e21db64
546,852
import ipaddress def ip_version(value): """ Returns version of passed IP address. """ return ipaddress.ip_address(value).version
15e2a32b477918d6722ddd65d574d71236d34699
458,348
import math def example_function(x): """Compute the square root of x and return it.""" return math.sqrt(x)
0c9fa02b3ef478dd6493b5ebb6a47f68477a10f8
563,891
def get_report_from_trajectory(traject_path, report_base): """ The format is usually <name>_<number>.pdb """ name_number = traject_path.split(".") _, number = name_number[0].split("_") return report_base+"_"+number
0fa1218740de8567d3cdfc09beb1b551941944e2
98,383
def parse_config_list(s): """util to convert X = A,B,C config entry into ['A', 'B', 'C']""" return [x.strip() for x in s.split(',') if x.strip()]
7286a6038d28a52cb870b22195a958be09e031cd
492,483
def toint2(i): """ Convert a number to a binary string of length 8 """ return f'{i:08b}'
6b5abb4409349db3ec13b26f64a3c27fc4e4c470
584,804
def motp(df, num_detections): """Multiple object tracker precision.""" return df['D'].sum() / num_detections
51d1f0ef3b2353ff8a008642eeacbe0d6fe5a0ff
204,835
def get_message(tweet): """ Get the message attribute on a Tweet object. The attribute available depends on the parameters on the query to Twitter. """ try: message = tweet.full_text except AttributeError: message = tweet.text return message
7cffb76ee7795095857a48c7780f4362d37869e3
649,631
def calc_tcv(signal, threshold=2.0): """ Calculate the count of threshold crossings for positive and negative threshold. :param signal: input signal :param threshold: threshold used for counting :return: number of times the threshold was crossed """ tcv = 0 prev = 0.0 tm = -threshold for x in signal: if (x < threshold and prev > threshold) or ( x > threshold and prev <= threshold ): prev = x tcv += 1 elif (x < tm and prev > tm) or (x > tm and prev <= tm): prev = x tcv += 1 return float(tcv)
cc2c46b114d43321349098a663fe7d0328879672
242,901
def InstanceOverlap_OLD(instance1,instance2): """Returns True if given instances share a vertex.""" for vertex1 in instance1.vertices: if vertex1 in instance2.vertices: return True return False
0bbc42cc09ea0f67b8a04772eb0581b081dbb6dd
689,653
def add_offset_to_target(example_strings, targets, offset): """Adds offset to the targets. This function is intented to be passed to tf.data.Dataset.map. Args: example_strings: 1-D Tensor of dtype str, Example protocol buffers. targets: 1-D Tensor of dtype int, targets representing the absolute class IDs. offset: int, optional, number to add to class IDs to get targets. Returns: example_strings, labels: Tensors, a batch of examples and labels. """ labels = targets + offset return (example_strings, labels)
e6659a2c22bf5e9a4d73e614ce3b67d859047a39
236,135
import re def safe_name(name): """ Converts IAM user names to UNIX user names 1) Illegal IAM username characters are removed 2) +/=/,/@ are converted to plus/equals/comma/at """ # IAM users only allow [\w+=,.@-] name = re.sub(r'[^\w+=,.@-]+', '', name) name = re.sub(r'[+]', 'plus', name) name = re.sub(r'[=]', 'equals', name) name = re.sub(r'[,]', 'comma', name) name = re.sub(r'[@]', 'at', name) return name
077cb576f3c8cb6b4da905ba9c6f6410fbf691fe
59,456
def _sortValue_weightValue(font): """ Returns font.info.openTypeOS2WeightClass. """ value = font.info.openTypeOS2WeightClass if value is None: value = -1 return value
7cb5d9d44f1ee434e7da09d8c5503f48b822ef3a
276,575
import hashlib def hash_zipfile_contents(zf): """Returns a hash of a zipfile's file contents. Ignores things like file mode, modtime """ h = hashlib.blake2b() for name in zf.namelist(): h.update(name.encode("utf-8")) h.update(zf.read(name)) return h.hexdigest()
9530f28abbff3ffc88cf3e097c474836e42f067c
546,641
def flatten_sub(sub, game_id): """Flatten the schema of a sub""" sub_id = sub[0] sub_data = sub[1] return {'game_id': game_id, 'sub_id': sub_id, 'sub_type': sub_data['type'], 'time_of_event(min)': (sub_data['t']['m'] + (sub_data['t']['s'] / 60 )), 'team_id': sub_data['team'], 'player_off': float(sub_data['offId']), 'player_on': float(sub_data['inId']) }
d6557b01f6f2f11c829e1094b318bf2587c74977
687,257
import jinja2 def create_main_protocol_hoc( template_path, protocol_definitions, rin_exp_voltage_base, mtype ): """Create main_protocol.hoc file. Args: template_path (str): path to the template to fill in protocol_definitions (dict): dictionary defining the protocols rin_exp_voltage_base (float): experimental value for the voltage_base feature for Rin protocol mtype (str): mtype of the cell. prefix to use in the output files names Returns: str: hoc script containing the main protocol functions """ with open(template_path, "r", encoding="utf-8") as template_file: template = template_file.read() template = jinja2.Template(template) rmp_stim = protocol_definitions["RMP"]["stimuli"] rin_stim = protocol_definitions["Rin"]["stimuli"] thresh_stim = protocol_definitions["ThresholdDetection"]["step_template"]["stimuli"] # edit template return template.render( rmp_stimulus_dur=rmp_stim["step"]["duration"], rmp_stimulus_del=rmp_stim["step"]["delay"], rmp_stimulus_amp=rmp_stim["step"]["amp"], rmp_stimulus_totduration=rmp_stim["step"]["totduration"], rmp_output_path=f"hoc_recordings/{mtype}.RMP.soma.v.dat", rin_stimulus_dur=rin_stim["step"]["duration"], rin_stimulus_del=rin_stim["step"]["delay"], rin_stimulus_amp=rin_stim["step"]["amp"], rin_stimulus_totduration=rin_stim["step"]["totduration"], rin_holding_dur=rin_stim["holding"]["duration"], rin_holding_del=rin_stim["holding"]["delay"], holdi_precision=protocol_definitions["RinHoldcurrent"]["holdi_precision"], holdi_max_depth=protocol_definitions["RinHoldcurrent"]["holdi_max_depth"], voltagebase_exp_mean=rin_exp_voltage_base, rin_output_path=f"hoc_recordings/{mtype}.Rin.soma.v.dat", holding_current_output_path=f"hoc_recordings/{mtype}.bpo_holding_current.dat", thdetect_stimulus_del=thresh_stim["step"]["delay"], thdetect_stimulus_dur=thresh_stim["step"]["duration"], thdetect_stimulus_totduration=thresh_stim["step"]["totduration"], thdetect_holding_dur=thresh_stim["holding"]["duration"], thdetect_holding_del=thresh_stim["holding"]["delay"], threshold_current_output_path=f"hoc_recordings/{mtype}.bpo_threshold_current.dat", )
8374b01151f8e624f10f4ad2f2e9db7266e88bf1
604,415
import requests def search_onda_catalog(search, fmt='json') -> dict: """Search on ONDA Catalog.""" base_uri = 'https://catalogue.onda-dias.eu/dias-catalogue/Products' query = { '$search': search, '$format': fmt } req = requests.get(base_uri, params=query, timeout=90) req.raise_for_status() content = req.json() return content
f3a50006ddaff236b2f989f5b41834ff41cb448a
388,693
def default_func(entity, attribute, value): """ Look in the entity for an attribute with the provided value. First proper attributes are checked, then extended fields. If neither of these are present, return False. """ try: return getattr(entity, attribute) == value except AttributeError: try: return entity.fields[attribute] == value except (AttributeError, KeyError): return False
0ec6636c20d3f5eedb7a7c1f2457f72ecddb7545
20,852
def get_handcrafted_feature_names(platform): """ Returns a set of feature names to be calculated. Output: - names: A set of strings, corresponding to the features to be calculated. """ names = set() #################################################################################################################### # Add basic discussion tree features. #################################################################################################################### names.update(["comment_count", "max_depth", "avg_depth", "max_width", "avg_width", "max_depth_over_max_width", "avg_depth_over_width"]) #################################################################################################################### # Add branching discussion tree features. #################################################################################################################### names.update(["comment_tree_hirsch", "comment_tree_wiener", "comment_tree_randic"]) #################################################################################################################### # Add user graph features. #################################################################################################################### names.update(["user_count", "user_graph_hirsch", "user_graph_randic", "outdegree_entropy", "norm_outdegree_entropy", "indegree_entropy", "norm_indegree_entropy"]) #################################################################################################################### # Add temporal features. #################################################################################################################### names.update(["avg_time_differences_1st_half", "avg_time_differences_2nd_half", "time_differences_std"]) #################################################################################################################### # Add YouTube channel features. #################################################################################################################### # if platform == "YouTube": # names.update(["author_privacy_status_youtube", # "author_is_linked_youtube", # "author_long_uploads_status_youtube", # "author_comment_count_youtube", # "author_comment_rate_youtube", # "author_view_count_youtube", # "author_view_rate_youtube", # "author_video_upload_count_youtube", # "author_video_upload_rate_youtube", # "author_subscriber_count_youtube", # "author_subscriber_rate_youtube", # "author_hidden_subscriber_count_youtube", # "author_channel_lifetime_youtube"]) #################################################################################################################### # Add Reddit author features. #################################################################################################################### # elif platform == "Reddit": # names.update(["author_has_verified_mail_reddit", # "author_account_lifetime_reddit", # "author_hide_from_robots_reddit", # "author_is_mod_reddit", # "author_link_karma_reddit", # "author_link_karma_rate_reddit", # "author_comment_karma_reddit", # "author_comment_karma_rate_reddit", # "author_is_gold_reddit"]) # else: # print("Invalid platform name.") # raise RuntimeError return names
ccdf430b0403c1152f40c9c0bdf5fbb380d8f0c1
681,137
def eCF(i): """ Returns the first i terms of the (aperiodic) continued fraction representation of e. """ return [2] + [int((a+1) / 3 * 2) if a % 3 == 2 else 1 for a in range(1, i)]
4a16c01332ccb72923c8062440f928269a0e8dda
176,194
def path_to_image_name(path, class_name): """ for paths of the following structure: E:\ILSVRC2017\images\original\n01531178\n01531178_2421.JPEG returns the image name, e.g. n01531178_2421 """ t1 = path.split(class_name, 1)[1] t2 = t1.split('.', 1)[0] t3 = t2.split('\\', 1)[1] return t3
b5e306b7d2a2c516b5f304375f793fd966843e5c
58,651
def convert_8_int_to_tuple(int_date): """ Converts an 8-digit integer date (e.g. 20161231) to a date tuple (Y,M,D). """ return (int(str(int_date)[0:4]), int(str(int_date)[4:6]), int(str(int_date)[6:8]))
733982c2de2c74c5116c15a1a91adf03c3bd6871
21,325
def normalize_data_raw(data_tbl): """Return the data table without normalization.""" return data_tbl
18fc7f93cf41d671e5fcb61d3f5be44c85c6161c
166,216
def lane_lead(csd10: float, xpd10: float, total_cs: float, total_xp: float, team_prox: float) -> float: """ Returns the lead a player has in lane in terms of cs and xp relative to total cs and xp between the two laners Formula: (team_prox * (csd10 + xpd10)) / (total_xp + total_cs) :param csd10: Difference in cs at 10 minutes :param xpd10: Difference in xp at 10 minutes :param total_cs: Total cs of player and opponent :param total_xp: Total xp of player and opponent :param team_prox: How often a teammate is within 2000px after minute 2 :return: A float of lane lead metric """ ll_metric = (team_prox * (csd10 + xpd10)) / (total_cs + total_xp) return ll_metric
639e9c0e2cde9a24662e581fc842fb3f5a6006ff
200,390
def arg_name(name): """Get the name an argument should have based on its Python name.""" return name.rstrip('_').replace('_', '-')
b0f2ff12efa2685f914be95b816a7109d75df173
351,992
from datetime import datetime def find_age_band(birth_date: str, end_date: datetime) -> str: """Given the birth date, finds the age_band for PEPFAR disaggregation.""" birth = datetime.strptime(birth_date, '%Y-%m-%d') age = int((end_date - birth).days / 365.25) if age < 1: return '0-1' if age <= 4: return '1-4' if age <= 9: return '5-9' if age <= 14: return '10-14' if age <= 19: return '15-19' if age <= 24: return '20-24' if age <= 49: return '25-49' return '50+'
92e8e37b898b873f5b254de5dc1c9ff2d2909420
196,566
import pickle def load_class_ids(class_info_file_path): """ Load class ids from class_info.pickle file """ with open(class_info_file_path, 'rb') as f: class_ids = pickle.load(f, encoding='latin1') return class_ids
65025910226a2d0391108e5dde8cee5c67f4ef39
487,820
def binary_dominates(a, b): """Returns whether a binary dominates b""" for ai, bi in zip(a, b): if bi > ai: return False if a == b: return False return True
c48e0b4712d958b52cb3a4c53232a131ceefc986
592,160
def central_credible_interval(samples, alpha=0.05): """The equal-tailed interval containing a (1-alpha) fraction of the posterior samples. Parameter samples: The posterior samples (array like) Parameter alpha: The total size of the tails (Float between 0 and 1) Returns: Left and right interval bounds (tuple) """ tail_size = int(round(len(samples) * (alpha / 2))) samples_sorted = sorted(samples) return samples_sorted[tail_size], samples_sorted[-tail_size - 1]
cb9d9379234d5cb2db8a3015ef66ef7d4a384e90
613,395
def findFront(start): """ start: a Frob that is part of a doubly linked list returns: the Frob at the beginning of the linked list """ if start.getBefore() == None: return start return findFront(start.getBefore())
c91ce2b4ee1ec638bb8e0b9db3ad7075ce436f35
486,257
def parse_sections(lines): """Parse the input document into sections, separated by blank lines. A list of lists is returned. Each item is the list of lines for a section. """ secid = 0 section = [] for line in lines: if not line.strip(): secid += 1 continue if len(section) == secid: section.append([line]) else: section[secid].append(line) return [v for v in section if v]
6127f8bfbec56e77e475684d626e44cb75ac8daa
39,386
from pathlib import Path import base64 def pdf_preprocess(pdf): """ Load pdfs from local filepath if not already b64 encoded """ path = Path(pdf) if path.exists(): # a filepath is provided, read and encode with path.open("rb") as f: return base64.b64encode(f.read()).decode("utf-8") else: # assume pdf is already b64 encoded return pdf
17b2642bc90b4e7da01246a2f94c3c5f029e05d7
386,507
def numToLetter(N, ABC=u'ABCDEFGHIJKLMNOPQRSTUVWXYZ' ): """ Converts a number in to a letter, or set of letters, based on the contents of ABC. If ABC contains the alphabet (which is the default behaviour) then for a number n this will result in the same string as the name of the nth column in a normal spreadsheet. INPUTS N - integer - any number. OPTIONAL INPUTS ABC - string - any string of characters (or any other symbols I believe). OUTPUTS L - string - the number converted to a string. EXAMPLES numToLetter(1) u'A' numToLetter(26) u'Z' numToLetter(27) u'AA' numToLetter(345) u'MG' numToLetter(345, ABC='1234567890') u'345' """ L = '' sA = len(ABC) div = int(N) while div > 0: R = int((div-1)%sA) L = ABC[R] + L div = int((div-R)/sA) return L
9737918897606ef642a1747016f07a4e72cb5157
376,198
def _safe_divide(a: int, b: int): """Divides a and b as a/b if 0 < a <= b. Otherwise, raises ValueError. Args: a: Numerator. b: Denominator. Returns: Float of division result. """ if a < 0: raise ValueError('a ({}) < 0'.format(a)) elif a > b: raise ValueError('a ({}) > b ({})'.format(a, b)) return a / b
5747ebf93e33c9e09141f4512ab2e1192230d0e0
343,474
def get_lock_name(file_path): """ Returns lock file of the given file :param file_path: str :return: str """ return '{}.lock'.format(file_path)
5796f5ecab4570355f8985ebb7e41b14d0d46ac0
284,176
import math def directions(o, t): """Compute a list of directions o -> t unit length.""" assert len(o) == len(t) result = [] for j in range(len(o)): dx = t[j][0] - o[j][0] dy = t[j][1] - o[j][1] l = math.sqrt(dx * dx + dy * dy) result.append((dx / l, dy / l)) return result
4a85f552197668948864d58ca1fab8563d957a00
315,153
def device_properties() -> dict: """ Fixture that returns device_properties to be provided to the device under test. This is a default implementation that provides no properties. :return: properties of the device under test """ return {}
6e400fcce6efc7ef850ab7db57de9fb034480321
381,192
def fuel_name_matching(name, blacks, browns, petcoke): """ Harmonize fuel names :param name: Original name :param blacks: Hard coal name map :param browns: Lignite and brown coal name map :param petcoke: Other fuels map :return: Harmonized name """ if name in blacks: return "Hard Coal" elif name in browns: return "Lignite" elif name in petcoke: return "Petcoke" elif name == "natural_gas": return "Natural Gas"
72a49b2a17d58ff76d24672eb6eba09de235ebb5
316,042
from pathlib import Path def data_files(data_dir, data_types): """Recursively return a list of data files.""" data_dir = Path(data_dir) data_files = [] for d in data_types: files = [p.relative_to(Path("embers")) for p in data_dir.rglob(d)] data_files.extend(files) return [p.as_posix() for p in data_files]
ec12921efa84266013b46176bc79cc35b7f0f400
268,276
def GetColor(status): """Given a job status string, returns appropriate color string.""" if status.strip() == 'pass': color = 'green ' elif status.strip() == 'fail': color = ' red ' elif status.strip() == 'warning': color = 'orange' else: color = ' ' return color
168e1015a8b2cc17fd3f5fb60d1da7951746d0fa
187,453
def n_params(model): """Return the number of parameters in a pytorch model. Args: model (nn.Module): The model to analyze. Returns: int: The number of parameters in the model. """ pp = 0 for p in list(model.parameters()): nn = 1 for s in list(p.size()): nn = nn * s pp += nn return pp
02bf6c5cf4c3a8cbbfce2bdf1525bcdc73aac686
644,754
def get_formatted_name(first, last, middle=''): """Return a full name, neatly formatted.""" if middle: return first.title() + ' ' + middle.title() + ' ' + last.title() return first.title() + ' ' + last.title()
0ba3adc54bf71067c0cc66ec74d34fa40a29c799
537,983
import random def generate_random_integers(number_values, min_val, max_val): """Generate a list with `n` random integers between a `minimum` and a `maximum`. Args: number_values (int): Number of values to generate. min_val (int): Minimum value. max_val (int): Maximum value. Returns: result_list (list): A list with random values. Examples: >>> result_list = generate_random_integers(number_values=5, min_val=0, max_val=10) >>> len(result_list) 5 >>> min(result_list)>=0 and max(result_list)<=10 True """ l = random.sample(range(min_val, max_val), number_values) return l
c1eb1482b559d5e9a38c38b07cb4b868ca902d9a
457,857
def square_a_list(a_list): """Return a list with every item squared.""" return [item * item for item in a_list]
2f8ea43549909e90ef8f2873987371c20bd67fa9
130,058
import re def no_to_be(f, e): """ Removes 'to' or 'be' or both of those tokens in the beginning of phrases For example: be known -> known to drink -> drink :param f: :param e: :return: """ e_ = re.sub('^(to\s)?(be\s)?', '', e) if e != e_: print('> NO_TO_BE: %s -> %s' % (e, e_)) return [(f, e_)] if e_ else []
4e71510b0643e478c9d973458f19b98803d6ba02
360,589
def get_max_message_size(form): """Get max message size (in bytes).""" size = form.get('max_message_size') try: size = int(size) except: size = 0 return size
413eeaacf91ff9ea7b3082fcc2f9986fa940f9a3
181,244
def tb(tb): """Transform the tb dataset according to what was found in the explaratory analyses, available on sp_np.ipynb 1. Select only 'journal' and 'year' columns 2. Rename these two columns to 'Journal' and 'Year', with capitalization 3. Add a column named 'Source', with all rows = 'TreatmentBank' Args: tb (pandas.DataFrame): Unchanged dataframe from TreatmentBank processor Returns: pandas.DataFrame: Transformed tb dataframe """ # Selecting only the columns 'journal' and 'year' tb = tb[['journal', 'year']] # Renaming columns tb.rename(columns={'journal': 'Journal', 'year': 'Year'}, inplace=True) # Adding column 'Source', filling all rows = 'TreatmentBank' tb['Source'] = 'TreatmentBank' return tb
dcb4f6a69033e4ef779129d7c0b58715a254536d
576,148
from typing import Iterable def to_abs_coord(v, mat): """ Change the local vertices coordinate to absolute coordinate :param v: vector or a list of vertices :param mat: matrix_world :return: the Absolute vertices """ if isinstance(v, Iterable): list_verts = [] for i in v: list_verts.append(mat * i) return type(v)(list_verts) else: return mat * v
dea20a5e0e980beb41c5b4efc358958895336b20
623,120
def array_ufunc_errmsg_formatter(dummy, ufunc, method, *inputs, **kwargs): """ Format the error message for when __array_ufunc__ gives up. """ args_string = ', '.join(['{!r}'.format(arg) for arg in inputs] + ['{}={!r}'.format(k, v) for k, v in kwargs.items()]) args = inputs + kwargs.get('out', ()) types_string = ', '.join(repr(type(arg).__name__) for arg in args) return ('operand type(s) all returned NotImplemented from ' '__array_ufunc__({!r}, {!r}, {}): {}' .format(ufunc, method, args_string, types_string))
4620772f4521325e66798c57e501ffd88ab991d1
692,705
def get_es_master(es_algorithm, logger, log_dir, stubs, bucket, experiment_name, credential): """Instantiate an evolution strategic algorithm master. Return an ES algorithm master from the algorithms package. Args: es_algorithm: algorithms.*. ES algorithm. logger: logging.Logger. Logger. log_dir: str. Log directory. stubs: list. grpc stubs. bucket: str. GCS bucket name. experiment_name: str. Experiment name. credential: str. Credential JSON file path. Returns: algorithms.*Master. """ return es_algorithm( logger=logger, log_dir=log_dir, workers=stubs, bucket_name=bucket, experiment_name=experiment_name, credential_json=credential, )
9191ec1a6433206c93091423d32af35081ac7e39
309,184
def conseq(cond, true, false): """ Behaves like the tenary operator. """ if cond: return true else: return false
9ed23d6d9aa6cc93c902247dd7842f4a86675b23
692,196
import time def compose_query_sql(measurement, limit, start_date, end_date, condition=None): """ 根据条件构建查询metric db的sql语句 :param measurement: 表 :param limit: 条数限制 :param start_date: 查询起始日期 :param end_date: 查询结束日期 :param condition: 查询附带条件 :return: 查询的sql语句 """ # 将年月日转换为时间戳,便于查询 start = int(time.mktime(time.strptime(f"{start_date}", "%Y%m%d"))) end = int(time.mktime(time.strptime(f"{end_date}", "%Y%m%d"))) if condition: sql = ( f"SELECT * FROM {measurement} WHERE {condition} AND time >= {start}s AND time < {end}s " f"ORDER BY time DESC LIMIT {limit}" ) else: sql = f"SELECT * FROM {measurement} WHERE time >= {start}s AND time < {end}s ORDER BY time DESC LIMIT {limit}" return sql
a8e8f87e90e86be4eff55dc013ad7bbad97250de
135,759
def _remove_addtl_whtspace(text: str) -> str: """Removes addtl. whitespace, newlines, etc. from a string.""" return " ".join(text.split())
d201114d55700108037c4760a7fdf4f2a8faaf73
512,531
def check_nmap_file(file_path): """ Checks if file is oX xml output nmap file """ with open(file_path,'r') as check: data = check.readlines() if r"<?xml" in data[0] and r"<!DOCTYPE nmaprun" in data[1]: return True else: return False
7272e31032339ac8a11047e8e47873ff76d782e9
174,932
import torch def get_mask(tensor, lengths): """ Generates the masks for batches of sequences. Time should be the first axis. input: tensor: the tensor for which to generate the mask [N x T x ...] lengths: lengths of the seq. [N] """ mask = torch.zeros_like(tensor) for i in range(len(lengths)): mask[i, :lengths[i]] = 1. return mask
75b82fe3554eb838c0ab041e258f0a1b973d3dd9
183,875
def _count_worker(cluster_spec): """Counts the number of workers in cluster_spec. Workers with TaskType.WORKER and TaskType.MASTER are included in the return value. Args: cluster_spec: a ClusterSpec instance that describes current deployment. Returns: The total number of eligible workers. If 'cluster_spec' was None, then 0 is returned. """ return (len(cluster_spec.as_dict().get('worker', [])) + len(cluster_spec.as_dict().get('master', []))) if cluster_spec else 0
bb31ea27c624ba93c3d6c33795fea1ca59d5256a
382,208
def __randomize(items, random_state): """Returns a List containing a random permutation of items""" randomized_items = list(items) random_state.shuffle(randomized_items) return randomized_items
4671d051c29fabc0cd36bfbddacdd02e6f7a4056
293,960
def _hand_copy_line_to_line(original_object, new_object): """Copies one class object attributes to another class object""" new_object.action_amount = original_object.action_amount new_object.action_from_player = original_object.action_from_player new_object.all_in = original_object.all_in new_object.current_chips = original_object.current_chips new_object.current_round = original_object.current_round new_object.game_id = original_object.game_id new_object.player_index = original_object.player_index new_object.player_name = original_object.player_name new_object.position = original_object.position new_object.pot_size = original_object.pot_size new_object.previous_time = original_object.previous_time new_object.remaining_players = original_object.remaining_players new_object.stack = original_object.stack new_object.starting_chips = original_object.starting_chips new_object.text = original_object.text new_object.time = original_object.time new_object.win_stack = original_object.win_stack new_object.winner = original_object.winner new_object.winning_hand = original_object.winning_hand new_object.start_time = original_object.start_time new_object.end_time = original_object.end_time return new_object
485249f04243051e3607c94728b9b84318f242ab
576,128
def get_dictvals(mydict): """This function recursively gets all non-dict items in a hierarchical dict data structure. The order of the items have no intended meaning. e.g. myheir = { 0: '0.0', 1: '0.1', 2: {0: '1.0', 1: '1.1'}, 3: {0: '1.2', 1: {0: '2.0', 1: '2.1', 2: {0: '3.0'}, 3:'2.2'}}, 4: {0: '1.3', 1: '1.4'}, 5: '0.2', } get_dictvals(myheir) >> ['0.0', '0.1', '1.0', '1.1', '1.2', '2.0', '2.1', '3.0', '2.2', '1.3', '1.4', '0.2'] """ values = [] for val in mydict.values(): if isinstance(val, dict): values.extend(get_dictvals(val)) else: values.append(val) return values
2d94b21224090a49f60ae3ca89c06458ae29e896
581,030
def panel_to_multiindex(panel, filter_observations=False): """Convert a panel to a MultiIndex DataFrame with the minor_axis of the panel as the columns and the items and major_axis as the MultiIndex (levels 0 and 1, respectively). Parameters ---------- panel : a pandas Panel filter_observations : boolean, default False Whether to drop (major, minor) pairs without a complete set of observations across all the items. """ return (panel.transpose(2, 0, 1) .to_frame(filter_observations=filter_observations))
37a90ba6f7e9f1b022dc87c0d3b9524509a6742a
665,064
def percentage(df, new_column, column, group_cols=None): """ Add a column to the dataframe according to the groupby logic on group_cols :param df: Dataframe :param new_column: name of the new column :param column: name of the desired column you need percentage on :param group_cols: (str | list of str) or None :return: df + the percentage column """ if group_cols is None: df[new_column] = 100. * df[column] / sum(df[column]) else: df[new_column] = 100. * df[column] / df.groupby(group_cols)[column].transform(sum) return df
6c6a8f7f890431eee70b1ba0e5da152e48f190d4
434,786
import math def sqrt(x): """Returns square root of x value""" return math.sqrt(x)
4252f3d464250cd8f63412473f5707ccdfcec95b
625,978
def command_result_processor_parameter_extra(parameter_values): """ Command result message processor if received extra parameter(s). Parameters ---------- parameter_values : `str` Extra parameters. Returns ------- message : `str` """ message_parts = [] message_parts.append('Extra parameters: ') index = 0 limit = len(parameter_values) while True: parameter_value = parameter_values[index] index += 1 message_parts.append(repr(parameter_value)) if index == limit: break message_parts.append(', ') continue message_parts.append('.\n') return ''.join(message_parts)
a135e54617e30189cef66bf0c6ee6404ec9dbf7e
294,098