content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def make_hashable(data): """Make the given object hashable. It makes it ready to use in a `hash()` call, making sure that it's always the same for lists and dictionaries if they have the same items. :param object data: the object to hash :return: a hashable object :rtype: object """ if isinstance(data, (list, tuple)): return tuple((make_hashable(item) for item in data)) elif isinstance(data, dict): return tuple( (key, make_hashable(value)) for key, value in sorted(data.items()) ) else: return data
e4b88978ddee6d4dfc354845184a0e80b1f434bf
4,954
def a_function(my_arg, another): """ This is the brief description of my function. This is a more complete example of my function. It can include doctest, code blocks or any other reST structure. >>> a_function(10, [MyClass('a'), MyClass('b')]) 20 :param int my_arg: The first argument of the function. Just a number. :param another: The other argument of the important function. :type another: A list of :class:`MyClass` :return: The length of the second argument times the first argument. :rtype: int """ return my_arg * len(another)
8624edfe3ec06b53e065a6672c3b21682cdefe06
4,958
def sanitize_email(email): """ Returns an e-mail address in lower-case and strip leading and trailing whitespaces. >>> sanitize_email(' [email protected] ') '[email protected]' """ return email.lower().strip()
b99e9c38db4fe889e1d0a9175d6535c4790f2f43
4,967
import six import pytz def make_aware(dt, tz=None): """ Convert naive datetime object to tz-aware """ if tz: if isinstance(tz, six.string_types): tz = pytz.timezone(tz) else: tz = pytz.utc if dt.tzinfo: return dt.astimezone(dt.tzinfo) else: return tz.localize(dt)
b5003de5055c5d283f47e33dfdd6fbe57d6fce96
4,972
from itertools import product def listCombination(lists) -> list: """ 输入多个列表组成的列表,返回多列表中元素的所有可能组合 :param lists: 多个列表组成的列表 :return: 所有元素可能的组合 """ result = [] resultAppend = result.append for i in product(*lists): resultAppend(i) return result
6023cdc205b2780c5cd2cf56113d48a0675b98bf
4,973
from typing import List def sequence_to_ngram(sequence: str, N: int) -> List[str]: """ Chops a sequence into overlapping N-grams (substrings of length N) :param sequence: str Sequence to convert to N-garm :type sequence: str :param N: Length ofN-grams (int) :type N: int :return: List of n-grams :rtype: List[str] """ return [sequence[i : i + N] for i in range(len(sequence) - N + 1)]
8cbe97ee34c75ca3aad038236bd875ea0c3450cd
4,974
def _format_path(path): """Format path to data for which an error was found. :param path: Path as a list of keys/indexes used to get to a piece of data :type path: collections.deque[str|int] :returns: String representation of a given path :rtype: str """ path_with_brackets = ( ''.join('[{!r}]'.format(fragment) for fragment in path) ) return '{}'.format(path_with_brackets)
1809080453af154824e867cd8104cedbd616b937
4,975
def _get_embl_key(line): """Return first part of a string as a embl key (ie 'AC M14399;' -> 'AC')""" # embl keys have a fixed size of 2 chars return line[:2]
b54f1a94f120f7ac63a0dd2a22bd47d5a5d5eeb9
4,979
def get_query_string_from_process_type_string(process_type_string: str) -> str: # pylint: disable=invalid-name """ Take the process type string of a Node and create the queryable type string. :param process_type_string: the process type string :type process_type_string: str :return: string that can be used to query for subclasses of the process type using 'LIKE <string>' :rtype: str """ if ':' in process_type_string: return f'{process_type_string}.' path = process_type_string.rsplit('.', 2)[0] return f'{path}.'
1380ad90a98da26237176890c52a75684e92964e
4,982
import re def filter_output(output, regex): """Filter output by defined regex. Output can be either string, list or tuple. Every string is split into list line by line. After that regex is applied to filter only matching lines, which are returned back. :returns: list of matching records """ result = [] if isinstance(output, str): for line in output.splitlines(): result += re.findall(regex, line) elif isinstance(output, (list, tuple)): for item in output: result.append(filter_output(item, regex)) else: raise RuntimeError('Only strings and lists are supported by filter_output(), ' 'but output has type {}'.format(type(output))) return result
d9760a644bb83aee513391966522946a6514ab72
4,990
def denormalize_ged(g1, g2, nged): """ Converts normalized ged into ged. """ return round(nged * (g1.num_nodes + g2.num_nodes) / 2)
214813120d552ef5ece10349978238117fe26cf3
4,995
def convert_to_signed_int_32_bit(hex_str): """ Utility function to convert a hex string into a 32 bit signed hex integer value :param hex_str: hex String :return: signed 32 bit integer """ val = int(hex_str, 16) if val > 0x7FFFFFFF: val = ((val+0x80000000) & 0xFFFFFFFF) - 0x80000000 return val
f8d39b20475c30f162948167f8534e367d9c58e8
4,998
def check_if_bst(root, min, max): """Given a binary tree, check if it follows binary search tree property To start off, run `check_if_bst(BT.root, -math.inf, math.inf)`""" if root == None: return True if root.key < min or root.key >= max: return False return check_if_bst(root.left, min, root.key) and check_if_bst( root.right, root.key, max )
1bb4b601ef548aec9a4ab2cf5242bc5875c587a2
5,001
def aggregate(collection, pipeline): """Executes an aggregation on a collection. Args: collection: a `pymongo.collection.Collection` or `motor.motor_tornado.MotorCollection` pipeline: a MongoDB aggregation pipeline Returns: a `pymongo.command_cursor.CommandCursor` or `motor.motor_tornado.MotorCommandCursor` """ return collection.aggregate(pipeline, allowDiskUse=True)
03ea889ea23fb81c6a329ee270df2ac253e90d69
5,002
def _floor(n, base=1): """Floor `n` to a multiple of `base`""" return n // base * base
49019e4aa925b4f77a7f13f9919d36948bd132cc
5,007
import torch def n_step_returns(q_values, rewards, kls, discount=0.99): """ Calculates all n-step returns. Args: q_values (torch.Tensor): the Q-value estimates at each time step [time_steps+1, batch_size, 1] rewards (torch.Tensor): the rewards at each time step [time_steps, batch_size, 1] kls (torch.Tensor): the scaled kl divergences at each time step [time_steps, batch_size, 1] discount (float): the temporal discount factor """ discounts = torch.cat([(discount*torch.ones_like(q_values[:1]))**i for i in range(rewards.shape[0])], 0) rewards[1:] = rewards[1:] - kls[:-1] discounted_returns = torch.cumsum(discounts * rewards, dim=0) terminal_values = discount * discounts * (q_values[1:] - kls) # return torch.cat([q_values[:1], discounted_returns], dim=0) return torch.cat([q_values[:1], discounted_returns + terminal_values], dim=0)
3bbd6026046328dc8ef63ab3e871f6c47636cb80
5,010
def get_character_bullet(index: int) -> str: """Takes an index and converts it to a string containing a-z, ie. 0 -> 'a' 1 -> 'b' . . . 27 -> 'aa' 28 -> 'ab' """ result = chr(ord('a') + index % 26) # Should be 0-25 if index > 25: current = index // 26 while current > 0: result = chr(ord('a') + (current - 1) % 25) + result current = current // 26 return result
357f68feb302f11a996b5446c642ad9ca1f0f8d3
5,012
def getNamespace(modelName): """Get the name space from rig root Args: modelName (str): Rig top node name Returns: str: Namespace """ if not modelName: return "" if len(modelName.split(":")) >= 2: nameSpace = ":".join(modelName.split(":")[:-1]) else: nameSpace = "" return nameSpace
abfb4c54f2dd1b54563f6c7c84e902ed4ee77b01
5,018
def make_matrix(num_rows, num_cols, entry_fn): """retorna a matriz num_rows X num_cols cuja entrada (i,j)th é entry_fn(i, j)""" return [[entry_fn(i, j) # dado i, cria uma lista for j in range(num_cols)] # [entry_fn(i, 0), ... ] for i in range(num_rows)]
f706773245730eab3ce6cf41b0f6e81fbe3d52ab
5,021
import traceback def format_traceback_string(exception): """Format exception traceback as a single string. Args: exception: Exception object. Returns: Full exception traceback as a string. """ return '\n'.join( traceback.TracebackException.from_exception(exception).format() )
debdf53966b26b6562671bf48d283a3bf10d85d5
5,025
def is_batch_norm(layer): """ Return True if `layer` is a batch normalisation layer """ classname = layer.__class__.__name__ return classname.find('BatchNorm') != -1
6494b75a3fbfbfd55ff43b05536a1094290ea915
5,026
async def find_user_by_cards(app, cards, fields=["username"]): """Find a user by a list of cards assigned to them. Parameters ---------- app : aiohttp.web.Application The aiohttp application instance cards : list The list of cards to search for fields : list, default=["username"] The fields to be returned in the user document Returns ------- user : dict The user document """ if not isinstance(cards, list): cards = [cards] projection = {} for field in fields: projection[field] = 1 if "_id" not in fields: projection["_id"] = 0 return await app["db"].users.find_one({"cards": cards}, projection)
ef5b20ea668b39eda51c859a3b33f1af30a644f5
5,030
def make_keyword_html(keywords): """This function makes a section of HTML code for a list of keywords. Args: keywords: A list of strings where each string is a keyword. Returns: A string containing HTML code for displaying keywords, for example: '<strong>Ausgangsw&ouml;rter:</strong> Nature, Plants, Fauna' """ res_html = '<strong>Ausgangsw&ouml;rter:</strong> ' for word in keywords[:-1]: res_html += word + ', ' res_html += keywords[-1] return res_html
71e35245ad7b2fe2c67f6a4c27d53374945089bd
5,031
def __hit(secret_number, choice): """Check if the choice is equal to secret number""" return secret_number == choice
55bee8370a2480b5ca84cd5f478fd8eb367276bd
5,035
import json def to_pretty_json(obj): """Encode to pretty-looking JSON string""" return json.dumps(obj, sort_keys=False, indent=4, separators=(',', ': '))
b325c4e6e150e089da1d9027299831bd1576e57f
5,039
def append_id(endpoint, _id): """ append '_id' to endpoint if provided """ if _id is not None: return '/'.join([endpoint.rstrip('/'), _id]) return endpoint
60586a70bc8b9c9b10c1d54f6810c4528c5c0dec
5,044
def get_host_finding_vulnerabilities_hr(vulnerabilities): """ Prepare human readable json for "risksense-get-host-finding-detail" command. Including vulnerabilities details. :param vulnerabilities: vulnerabilities details from response. :return: list of dict """ vulnerabilities_list = [{ 'Name': vulnerability.get('cve', ''), 'V2/Score': vulnerability.get('baseScore', ''), 'Threat Count': vulnerability.get('threatCount', ''), 'Attack Vector': vulnerability.get('attackVector', ''), 'Access Complexity': vulnerability.get('accessComplexity', ''), 'Authentication': vulnerability.get('authentication', '') } for vulnerability in vulnerabilities] # To present human readable horizontally if len(vulnerabilities) == 1: vulnerabilities_list.append({}) return vulnerabilities_list
8f0689441f2fef41bbd5da91c802dfb8baa2b979
5,046
def get_notebook_title(nb_json, default=None): """Determine a suitable title for the notebook. This will return the text of the first header cell. If that does not exist, it will return the default. """ cells = nb_json['cells'] for cell in cells: if cell['cell_type'] == 'heading': return cell['source'] return default
4a20fe9890371ab107d0194e791c6faf9901d714
5,048
def embed(tokenizer, text): """ Embeds a text sequence using BERT tokenizer :param text: text to be embedded :return: embedded sequence (text -> tokens -> ids) """ return tokenizer.convert_tokens_to_ids(tokenizer.tokenize(text))
453d411d9c460dfc28cb54c7a6a807290905bed3
5,051
def is_collection(obj): """ Check if a object is iterable. :return: Result of check. :rtype: bool """ return hasattr(obj, '__iter__') and not isinstance(obj, str)
70fa0262ea7bf91a202aade2a1151d467001071e
5,054
import hashlib def file_md5(fpath): """Return the MD5 digest for the given file""" with open(fpath,'rb') as f: m = hashlib.md5() while True: s = f.read(4096) if not s: break m.update(s) return m.hexdigest()
40b355b9a628d286bf86b5199fd7e2a8bea354de
5,055
def formatUs(time): """Format human readable time (input in us).""" if time < 1000: return f"{time:.2f} us" time = time / 1000 if time < 1000: return f"{time:.2f} ms" time = time / 1000 return f"{time:.2f} s"
7546db60e3977e07dbbbad0a3ab767865840c2e3
5,058
def shiftField(field, dz): """Shifts the z-coordinate of the field by dz""" for f in field: if f.ID == 'Polar Data': f.set_RPhiZ(f.r, f.phi, f.z + dz) elif f.ID == 'Cartesian Data': f.set_XYZ(f.x, f.y, f.z + dz) return field
c3c592356dc21688049a94291d075879a12012ee
5,064
def chars_count(word: str): """ :param word: string to count the occurrences of a character symbol for. :return: a dictionary mapping each character found in word to the number of times it appears in it. """ res = dict() for c in word: res[c] = res.get(c, 0) + 1 return res
30c27b23c04909a65264247d068e9e2c695c6ecc
5,071
def t90_from_t68(t68): """ ITS-90 temperature from IPTS-68 temperature This conversion should be applied to all in-situ data collected between 1/1/1968 and 31/12/1989. """ return t68 / 1.00024
a2d8c7ccc0797d47fa8f732bdb61c1ec1e15700e
5,073
def _pad( s: str, bs: int, ) -> str: """Pads a string so its length is a multiple of a specified block size. :param s: The string that is to be padded :type s: str :param bs: The block size :type bs: int :returns: The initial string, padded to have a length that is a multiple of the specified block size :rtype: str """ number_of_bytes_to_pad = bs - len(s) % bs ascii_string = chr(number_of_bytes_to_pad) padding_str = number_of_bytes_to_pad * ascii_string return s + padding_str
1da441d51c57da688ebcf46b7a30feb36cd007fe
5,074
def PH2_Calc(KH2, tH2, Kr, I, qH2): """ Calculate PH2. :param KH2: hydrogen valve constant [kmol.s^(-1).atm^(-1)] :type KH2 : float :param tH2: hydrogen time constant [s] :type tH2 : float :param Kr: modeling constant [kmol.s^(-1).A^(-1)] :type Kr : float :param I: cell load current [A] :type I : float :param qH2: molar flow of hydrogen [kmol.s^(-1)] :type qH2 : float :return: PH2 [atm] as float """ try: result = ((1 / KH2) / (1 + tH2)) * (qH2 - 2 * Kr * I) return result except (TypeError, ZeroDivisionError): print( "[Error] PH2 Calculation Failed (KH2:%s, tH2:%s, Kr:%s, I:%s, qH2:%s)" % (str(KH2), str(tH2), str(Kr), str(I), str(qH2)))
fe69353bfdde4f301439b89f9946782457d07645
5,077
def build_pubmed_url(pubmed_id) -> str: """ Generates a Pubmed URL from a Pubmed ID :param pubmed_id: Pubmed ID to concatenate to Pubmed URL :return: Pubmed URL """ return "https://pubmed.ncbi.nlm.nih.gov/" + str(pubmed_id)
5794fbec75de0451547d6f0570bb89964026c394
5,081
def choose(n,r): """ number of combinations of n things taken r at a time (order unimportant) """ if (n < r): return 0 if (n == r): return 1 s = min(r, (n - r)) t = n a = n-1 b = 2 while b <= s: t = (t*a)//b a -= 1 b += 1 return t
5852054f1a6381278039b0ec2184d0887e2b1d2b
5,083
import math def isPrime(n): """ check if the input number n is a prime number or not """ if n <= 3: return n > 1 if n % 6 != 1 and n % 6 != 5: return False sqrt = math.sqrt(n) for i in range(5, int(sqrt)+1, 6): if n % i == 0 or n % (i+2) == 0: return False return True
91da5b13840181d039902e2db3efb8cc09609465
5,091
def _execute_query(connection, query): """Executes the query and returns the result.""" with connection.cursor() as cursor: cursor.execute(query) return cursor.fetchall()
9f71eb650d323f7a5ead3451810a7b9f9d77b4b0
5,096
def vectorvalued(f): """ Decorates a distribution function to disable automatic vectorization. Parameters ---------- f: The function to decorate Returns ------- Decorated function """ f.already_vectorized = True return f
cc498fe0731acdbde0c4d9b820a1accb5dc94fea
5,098
import unicodedata def remove_diacritics(input_str: str) -> str: """Remove diacritics and typographical ligatures from the string. - All diacritics (i.e. accents) will be removed. - Typographical ligatures (e.g. ffi) are broken into separated characters. - True linguistic ligatures (e.g. œ) will remain. - Non-latin scripts will remain. Args: input_str (str): The original string with diacritics and ligatures. Returns: str: The string without diacritics and typographical ligatures. """ nfkd_form = unicodedata.normalize('NFKD', input_str) return u"".join([c for c in nfkd_form if not unicodedata.combining(c)])
23c3e9ce0029704f0012a825460f10f370e3c681
5,099
def lambda_plus_mu_elimination( offspring: list, population: list, lambda_: int): """ Performs the (λ+μ)-elimination step of the evolutionary algorithm Args: offspring (list): List of the offspring population (list): List of the individuals in a population lambda_ (int): Number of top lambda_ candidates that will be retained Returns: new_combined: Top lambda_ candidates that are retained """ # combine population and offspring combined = population + offspring # sort new population combined = sorted(combined, key=lambda k: k.fitness, reverse=False) # pick top lambda candidates combined = combined[:lambda_] return combined
d4f55fa621e3f33e2773da81a6cf0b2fc0439ba9
5,101
def signum(x): """ Return -1 if x < 0, 1 if 0 < x, or 0 if x == 0 """ return (x > 0) - (x < 0)
59568d4fbf1f5a226528b7f12f8c5011b641bc4e
5,108
def lower_text(text: str) -> str: """Transform all the text to lowercase. Args: text : Input text Returns: Output text """ return text.lower()
2a657464a014703464ca47eeb77ed6a630535819
5,112
import base64 def base64url_decode(msg): """ Decode a base64 message based on JWT spec, Appendix B. "Notes on implementing base64url encoding without padding" """ rem = len(msg) % 4 if rem: msg += b'=' * (4 - rem) return base64.urlsafe_b64decode(msg)
f0f46749ae21ed8166648c52c673eab25f837881
5,113
def reverse_complement_sequence(sequence, complementary_base_dict): """ Finds the reverse complement of a sequence. Parameters ---------- sequence : str The sequence to reverse complement. complementary_base_dict: dict A dict that maps bases (`str`) to their complementary bases (`str`). Returns ------- str The reverse complement of the input sequence. """ rev_comp_bases = [complementary_base_dict[b] for b in sequence[::-1]] return ''.join(rev_comp_bases)
1130f5b321daf72cdd40704fc8671ba331376ded
5,115
import math def top2daz(north, east, up): """Compute azimouth, zenith and distance from a topocentric vector. Given a topocentric vector (aka north, east and up components), compute the azimouth, zenith angle and distance between the two points. Args: north (float): the north component (in meters) east (float) : the east component (in meters) up (float) : the up component (in meters) Returns: tuple (floats): a tuple of three floats is returned, as: [distance, azimouth, zenith], where distance is in meters, and azimouth and zenith are in radians. """ distance = math.sqrt(north*north + east*east + up*up) a = math.atan2(east, north) % (math.pi*2e0) # normalized [0, 2pi] zenith = math.acos(up/distance); return distance, a, zenith
67a127957b0dc131a6fe5505de05b89871542009
5,116
import torch def get_ground_truth_vector(classes : torch.Tensor, n_domains : int, n_classes : int) -> torch.Tensor: """ Get the ground truth vector for the phase where the feature extractor tries that discriminator cannot distinguish the domain that the sample comes from. Args: classes (torch.Tensor): Class labels. n_domains (int): Number of domains. n_classes (int): Number of classes. Returns: torch.Tensor: Tensor containing the ground truth for each sample. """ # Create the ground truth tensor total_size = n_domains * n_classes gt = torch.zeros(len(classes), total_size) # Value to be placed in the corresponding categories and domains positions # It is uniform so the discriminator cannot distinguish which domain the # sample comes from non_zero_value = 1 / n_domains for row in range(len(classes)): # The indices are the corresponding position for each class into each # domain non_zero_indices = [i+classes[row] for i in range(0, total_size, n_classes)] gt[row, non_zero_indices] = non_zero_value return gt
429c0c69d85572073aab66372d651d4981324e2b
5,117
import re def extract_words(path_to_file): """ Takes a path to a file and returns the non-stop words, after properly removing nonalphanumeric chars and normalizing for lower case """ words = re.findall('[a-z]{2,}', open(path_to_file).read().lower()) stopwords = set(open('../stop_words.txt').read().split(',')) return [w for w in words if w not in stopwords]
4f5031693d10542c31a3055341d1794d0d7bf4f0
5,122
def get_activity_id(activity_name): """Get activity enum from it's name.""" activity_id = None if activity_name == 'STAND': activity_id = 0 elif activity_name == 'SIT': activity_id = 1 elif activity_name == 'WALK': activity_id = 2 elif activity_name == 'RUN': activity_id = 3 elif activity_name == 'WALK_UPSTAIRS': activity_id = 4 elif activity_name == 'WALK_DOWNSTAIRS': activity_id = 5 elif activity_name == 'LIE': activity_id = 6 elif activity_name == 'BIKE': activity_id = 7 elif activity_name == 'DRIVE': activity_id = 8 elif activity_name == 'RIDE': activity_id = 9 else: activity_id = 10 return activity_id
b5e18063b5448c3f57636daa732dfa2a4f07d801
5,124
import socket def is_ipv4(v): """ Check value is valid IPv4 address >>> is_ipv4("192.168.0.1") True >>> is_ipv4("192.168.0") False >>> is_ipv4("192.168.0.1.1") False >>> is_ipv4("192.168.1.256") False >>> is_ipv4("192.168.a.250") False >>> is_ipv4("11.24.0.09") False """ X = v.split(".") if len(X) != 4: return False try: return len([x for x in X if 0 <= int(x) <= 255]) == 4 and bool(socket.inet_aton(v)) except Exception: return False
e81fae435a8e59dbae9ab1805941ce3ba9909ba9
5,125
def permitted_info_attributes(info_layer_name, permissions): """Get permitted attributes for a feature info result layer. :param str info_layer_name: Layer name from feature info result :param obj permissions: OGC service permissions """ # get WMS layer name for info result layer wms_layer_name = permissions.get('feature_info_aliases', {}) \ .get(info_layer_name, info_layer_name) # return permitted attributes for layer return permissions['layers'].get(wms_layer_name, {})
57fcb05e5cd1c7e223c163929e78ecdb00d1ad09
5,126
def is_metageneration_specified(query_params): """Return True if if_metageneration_match is specified.""" if_metageneration_match = query_params.get("ifMetagenerationMatch") is not None return if_metageneration_match
d37c513f3356aef104e7f6db909d5245e2664c90
5,130
import six def qualified_name(obj): """Return the qualified name (e.g. package.module.Type) for the given object.""" try: module = obj.__module__ qualname = obj.__qualname__ if six.PY3 else obj.__name__ except AttributeError: type_ = type(obj) module = type_.__module__ qualname = type_.__qualname__ if six.PY3 else type_.__name__ return qualname if module in ('typing', 'builtins') else '{}.{}'.format(module, qualname)
02444c19d200650de8dc9e2214f7788fca0befd2
5,132
def ConvertToCamelCase(input): """Converts the input string from 'unix_hacker' style to 'CamelCase' style.""" return ''.join(x[:1].upper() + x[1:] for x in input.split('_'))
8070516c61768ea097eccc62633fc6dea2fa7096
5,133
def get_output_shape(tensor_shape, channel_axis): """ Returns shape vector with the number of channels in the given channel_axis location and 1 at all other locations. Args: tensor_shape: A shape vector of a tensor. channel_axis: Output channel index. Returns: A shape vector of a tensor. """ return [-1 if i is channel_axis else 1 for i in range(len(tensor_shape))]
7c7058c2da9cb5a4cdb88377ece4c2509727894a
5,138
def get_color_pattern(input_word: str, solution: str) -> str: """ Given an input word and a solution, generates the resulting color pattern. """ color_pattern = [0 for _ in range(5)] sub_solution = list(solution) for index, letter in enumerate(list(input_word)): if letter == solution[index]: color_pattern[index] = 2 sub_solution[index] = "_" for index, letter in enumerate(list(input_word)): if letter in sub_solution and color_pattern[index] != 2: color_pattern[index] = 1 sub_solution[sub_solution.index(letter)] = "_" color_pattern = "".join([str(c) for c in color_pattern]) return color_pattern
a8746a5854067e27e0aefe451c7b950dd9848f50
5,140
import inspect def getargspec(obj): """Get the names and default values of a function's arguments. A tuple of four things is returned: (args, varargs, varkw, defaults). 'args' is a list of the argument names (it may contain nested lists). 'varargs' and 'varkw' are the names of the * and ** arguments or None. 'defaults' is an n-tuple of the default values of the last n arguments. Modified version of inspect.getargspec from the Python Standard Library.""" if inspect.isfunction(obj): func_obj = obj elif inspect.ismethod(obj): func_obj = obj.__func__ else: raise TypeError('arg is not a Python function') args, varargs, varkw = inspect.getargs(func_obj.__code__) return args, varargs, varkw, func_obj.__defaults__
bcfe75de95ccf22bcefdba52c8556f0722dbbcb7
5,141
from pathlib import Path def build_name(prefix: str, source_ind: int, name: Path) -> str: """Build a package name from the index and path.""" if name.name.casefold() == '__init__.py': name = name.parent name = name.with_suffix('') dotted = str(name).replace('\\', '.').replace('/', '.') return f'{prefix}_{source_ind:02x}.{dotted}'
d777b1b875ff6ab6f3228538a9e4c1cfa3c398a0
5,143
import re def _format_param_value(value_repr): """ Format a parameter value for displaying it as test output. The values are string obtained via Python repr. """ regexs = ["^'(.+)'$", "^u'(.+)'$", "^<class '(.+)'>$"] for regex in regexs: m = re.match(regex, value_repr) if m and m.group(1).strip(): return m.group(1) return value_repr
87d881a3159c18f56dd2bb1c5556f3e70d27c1bc
5,144
from typing import Dict from typing import Any def get_stratum_alert_data(threshold: float, notification_channel: int) -> Dict[str, Any]: """ Gets alert config for when stratum goes below given threshold :param threshold: Below this value, grafana should send an alert :type description: float :param notification_channel: Id of the notification channel the alert should be sent to :type notification_channel: int :return: Data of the alert :rtype: Dict """ return { "conditions": [ { "evaluator": { "params": [threshold], "type": "lt" }, "operator": {"type": "and"}, "query": { "params": ["A", "5m", "now"] }, "reducer": { "params": [], "type": "avg" }, "type": "query" } ], "executionErrorState": "alerting", "frequency": "60s", "handler": 1, "name": "Estimated hash rate on stratum alert", "noDataState": "alerting", "notifications": [{"id": notification_channel}] }
bae4aafe18286eeb5b0f59ad87804a19936ec182
5,146
def ewma(current, previous, weight): """Exponentially weighted moving average: z = w*z + (1-w)*z_1""" return weight * current + ((1.0 - weight) * previous)
5a678b51618ebd445db0864d9fa72f63904e0e94
5,147
from bs4 import BeautifulSoup def get_post_mapping(content): """This function extracts blog post title and url from response object Args: content (request.content): String content returned from requests.get Returns: list: a list of dictionaries with keys title and url """ post_detail_list = [] post_soup = BeautifulSoup(content,"lxml") h3_content = post_soup.find_all("h3") for h3 in h3_content: post_detail_list.append( {'title':h3.a.get_text(),'url':h3.a.attrs.get('href')} ) return post_detail_list
0b3b31e9d8c5cf0a3950dc33cb2b8958a12f47d4
5,150
def len_iter(iterator): """Count items in an iterator""" return sum(1 for i in iterator)
1d828b150945cc4016cdcb067f65753a70d16656
5,152
def how_many(num): """Count the number of digits of `num`.""" if num < 10: return 1 else: return 1 + how_many(num // 10)
6b6f8c2a95dac9f2a097300924e29bbca0bdd55c
5,160
def line_length_check(line): """Return TRUE if the line length is too long""" if len(line) > 79: return True return False
2cde1a2b8f20ebf57c6b54bf108e97715789a51d
5,161
import re def dtype_ripper(the_dtype, min_years, max_years): """Extract the range of years from the dtype of a structured array. Args: the_dtype (list): A list of tuples with each tuple containing two entries, a column heading string, and a string defining the data type for that column. Formatted as a numpy dtype list. min_years (list): The earliest years found in the imported data. max_years (list): The latest years found in the imported data. Returns: Updated lists of minimum and maximum years with the minimum and maximum found in data_array. The minimum and maximum years, as integers, that were contained in the column headings of the dtype definition. """ # Strip the dtype into its constituent lists: column names and data formats colnames, dtypes = zip(*the_dtype) # Preallocate a list for the years extracted from the column names year_list = [] # Loop over the list of column names, identify entries that have # the format specified by a regex, and add the matches to a list for name in colnames: year = re.search('^[1|2][0-9]{3}$', name) if year: year_list.append(year.group()) # Identify the minimum and maximum years from the list of the years # in the column names and record them as integers instead of strings min_yr = int(min(year_list)) max_yr = int(max(year_list)) # Circumvents the action of .append() modifying in place the lists # passed to the function new_min_years = min_years + [min_yr] new_max_years = max_years + [max_yr] return new_min_years, new_max_years
1cbcc30cf7760d466187873aa5ea221691b2092d
5,165
def create_msg(q1,q2,q3): """ Converts the given configuration into a string of bytes understood by the robot arm. Parameters: q1: The joint angle for the first (waist) axis. q2: The joint angle for the second (shoulder) axis. q3: The joint angle for the third (wrist) axis. Returns: The string of bytes. """ return ('%d,%d,%d\n' % (q1,q2,q3)).encode()
26f9954a55686c9bf8bd08cc7a9865f3e4e602e3
5,169
def pnorm(x, p): """ Returns the L_p norm of vector 'x'. :param x: The vector. :param p: The order of the norm. :return: The L_p norm of the matrix. """ result = 0 for index in x: result += abs(index) ** p result = result ** (1/p) return result
110fea5cbe552f022c163e9dcdeacddd920dbc65
5,172
def vehicle_emoji(veh): """Maps a vehicle type id to an emoji :param veh: vehicle type id :return: vehicle type emoji """ if veh == 2: return u"\U0001F68B" elif veh == 6: return u"\U0001f687" elif veh == 7: return u"\U000026F4" elif veh == 12: return u"\U0001F686" else: return u"\U0001F68C"
8068ce68e0cdf7f220c37247ba2d03c6505a00fe
5,174
def scroll_down(driver): """ This function will simulate the scroll down of the webpage :param driver: webdriver :type driver: webdriver :return: webdriver """ # Selenium supports execute JavaScript commands in current window / frame # get scroll height last_height = driver.execute_script("return document.body.scrollHeight") # scroll to the end of the page driver.execute_script("window.scrollTo(0, {});".format(last_height)) return driver
7d68201f3a49950e509a7e389394915475ed8c94
5,176
def parent_path(xpath): """ Removes the last element in an xpath, effectively yielding the xpath to the parent element :param xpath: An xpath with at least one '/' """ return xpath[:xpath.rfind('/')]
b435375b9d5e57c6668536ab819f40ae7e169b8e
5,179
def is_stateful(change, stateful_resources): """ Boolean check if current change references a stateful resource """ return change['ResourceType'] in stateful_resources
055465870f9118945a9e5f2ff39be08cdcf35d31
5,182
import difflib def _get_diff_text(old, new): """ Returns the diff of two text blobs. """ diff = difflib.unified_diff(old.splitlines(1), new.splitlines(1)) return "".join([x.replace("\r", "") for x in diff])
bd8a3d49ccf7b6c18e6cd617e6ad2ad8324de1cc
5,185
def ft2m(ft): """ Converts feet to meters. """ if ft == None: return None return ft * 0.3048
ca2b4649b136c9128b5b3ae57dd00c6cedd0f383
5,187
from typing import Dict def _get_setup_keywords(pkg_data: dict, keywords: dict) -> Dict: """Gather all setuptools.setup() keyword args.""" options_keywords = dict( packages=list(pkg_data), package_data={pkg: list(files) for pkg, files in pkg_data.items()}, ) keywords['options'].update(options_keywords) return keywords
34f2d52c484fc4e49ccaca574639929756cfa4dc
5,188
def release_date(json): """ Returns the date from the json content in argument """ return json['updated']
635efd7140860c8f0897e90433a539c8bd585945
5,190
def find_used_modules(modules, text): """ Given a list of modules, return the set of all those imported in text """ used = set() for line in text.splitlines(): for mod in modules: if 'import' in line and mod in line: used.add(mod) return used
0b1b2b31f60a565d7ba30a9b21800ba7ec265d0c
5,198
def string2mol2(filename, string): """ Writes molecule to filename.mol2 file, input is a string of Mol2 blocks """ block = string if filename[-4:] != '.mol2': filename += '.mol2' with open(filename, 'w') as file: file.write(block) return None
51043e7f4edde36682713455dc33c643f89db397
5,199
from datetime import datetime def tradedate_2_dtime(td): """ convert trade date as formatted by yfinance to a datetime object """ td_str = str(int(td)) y, m, d = int(td_str[:4]), int(td_str[4:6]), int(td_str[6:]) return datetime(y, m, d)
29db7ed41a5cac48af1e7612e1cd2b59ab843a1f
5,200
import requests def get(target: str) -> tuple: """Fetches a document via HTTP/HTTPS and returns a tuple containing a boolean indicating the result of the request, the URL we attempted to contact and the request HTML content in bytes and text format, if successful. Otherwise, returns a tuple containing a boolean indicating the result of the request, the URL we attempted to contact and the HTTP status code or exception error output from the request. :param target: :return: tuple """ if target.startswith('http://') is False and target.startswith('https://') is False: target = 'http://{0}'.format(target) try: request = requests.get(url=target, timeout=3, verify=False) except Exception as e: return False, target, e.__str__() try: request.raise_for_status() except requests.exceptions.HTTPError as e: return False, target, e.__str__() if request.ok: return True, request.url, request.content, request.text return False, request.url, request.status_code
1d9d650d77776419318cbd204b722d8abdff94c5
5,204
def makeSatelliteDir(metainfo): """ Make the directory name for the 'satellite' level. """ satDir = "Sentinel-" + metainfo.satId[1] return satDir
dfbb43f235bc027f25fc9b624097e8f2e0dee4f9
5,206
import re def safe_filename(name: str, file_ending: str = ".json") -> str: """Return a safe version of name + file_type.""" filename = re.sub(r"\s+", "_", name) filename = re.sub(r"\W+", "-", filename) return filename.lower().strip() + file_ending
98a887788046124354676a60b1cf7d990dbbc02f
5,211
import six def find_only(element, tag): """Return the only subelement with tag(s).""" if isinstance(tag, six.string_types): tag = [tag] found = [] for t in tag: found.extend(element.findall(t)) assert len(found) == 1, 'expected one <%s>, got %d' % (tag, len(found)) return found[0]
fd4ec56ba3e175945072caec27d0438569d01ef9
5,217
def verse(day): """Produce the verse for the given day""" ordinal = [ 'first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh', 'eighth', 'ninth', 'tenth', 'eleventh', 'twelfth', ] gifts = [ 'A partridge in a pear tree.', 'Two turtle doves,', 'Three French hens,', 'Four calling birds,', 'Five gold rings,', 'Six geese a laying,', 'Seven swans a swimming,', 'Eight maids a milking,', 'Nine ladies dancing,', 'Ten lords a leaping,', 'Eleven pipers piping,', 'Twelve drummers drumming,', ] # First part of the verse is a constant day_verse = [ f'On the {ordinal[day - 1]} day of Christmas,', f'My true love gave to me,' ] # extend takes in a list as an arg, expands it, # and adds each element to the new list # day is used to slice gifts, that is then reversed to # count down # gifts[:3] would return 'A partridge in a pear tree.', # 'Two turtle doves,', 'Three French hens,', this slice # is then reversed added to day_verse day_verse.extend(reversed(gifts[:day])) # if there are multiple days, verse needs to have # 'And a partridge...' not just 'A' if day > 1: day_verse[-1] = 'And ' + day_verse[-1].lower() return '\n'.join(day_verse) # My first attempt below, using dicts adds to readability, # same with if block down below, however lists would be # better off to utilize slicing and get rid of the # for loop # ordinal = { # 1 : 'first', # 2 : 'second', # 3 : 'third', # 4 : 'fourth', # 5 : 'fifth', # 6 : 'sixth', # 7 : 'seventh', # 8 : 'eighth', # 9 : 'ninth', # 10 : 'tenth', # 11 : 'eleventh', # 12 : 'twelfth', # } # gifts = { # 1 : 'partridge in a pear tree.', # 2 : 'Two turtle doves,', # 3 : 'Three French hens,', # 4 : 'Four calling birds,', # 5 : 'Five gold rings,', # 6 : 'Six geese a laying,', # 7 : 'Seven swans a swimming,', # 8 : 'Eight maids a milking,', # 9 : 'Nine ladies dancing,', # 10 : 'Ten lords a leaping,', # 11 : 'Eleven pipers piping,', # 12 : 'Twelve drummers drumming,', # } # day_verse = [ # f'On the {ordinal[day]} day of Christmas,', # f'My true love gave to me,' # ] # for n in range(day, 0, -1): # if day > 1 and n > 1: # day_verse.append(f'{gifts[n]}') # elif day > 1 and n == 1: # day_verse.append(f'And a {gifts[n]}') # else: # day_verse.append(f'A {gifts[n]}') # return '\n'.join(day_verse)
027cedf0b1c2108e77e99610b298e1019629c880
5,220
def pairs_to_annotations(annotation_pairs): """ Convert an array of annotations pairs to annotation array. :param annotation_pairs: list(AnnotationPair) - annotations :return: list(Annotation) """ annotations = [] for ap in annotation_pairs: if ap.ann1 is not None: annotations.append(ap.ann1) if ap.ann2 is not None: annotations.append(ap.ann2) return annotations
b0e08889f541b14d596616d08b366f59b7f8ddd3
5,226
def get_infection_probas_mean_field(probas, transmissions): """ - probas[i,s] = P_s^i(t) - transmissions = csr sparse matrix of i, j, lambda_ij(t) - infection_probas[i] = sum_j lambda_ij P_I^j(t) """ infection_probas = transmissions.dot(probas[:, 1]) return infection_probas
70d5585b405bdff54f65bced166dead6ae45d26b
5,228
def find_project(testrun_url): """ Find a project name from this Polarion testrun URL. :param testrun_url: Polarion test run URL :returns: project name eg "CEPH" or "ContainerNativeStorage" """ url_suffix = testrun_url[59:] index = url_suffix.index('/') return url_suffix[:index]
a19019846fa084398a4967cb99417e7aebc90499
5,230
def c2ip(c2, uname): """ return complete ip address for c2 with substituted username """ return c2['ip_address'].replace('USER', uname)
c6f79b2330e78c8ebc85a3fb99ce1c5be407f158
5,231
def t_returns(inv, pfl, prices, date): """ Computes the total return of a portfolio. Parameters: - `inv` : :class:`list` investment session `db` row - `pfl` : :class:`string` name of the portfolio - `prices` : :class:`dict` latest investment's ticker prices - `date` : :class:`string` date of the purchase Computes the sum of the shares when the invesment was made to the sum of the shares now. The absolute change and returns are calculated with the same formulas as in :py:func:`check.returns` Returns a :class:`dict` containing the total initial price, the new price, the absolute change, the returns and the date of the purchase. """ t_old = sum(map(lambda key: inv[pfl][key]*inv['prc'][key], inv[pfl].keys())) t_old = round(t_old, 1) t_new = sum(map(lambda key: inv[pfl][key]*prices[key], inv[pfl].keys())) t_new = round(t_new, 1) abs = round(t_new - t_old, 1) rel = round(((t_new - t_old) / t_old) * 100, 2) return {'abs': abs, 'rel': rel, 'old': t_old, 'new': t_new, 'qty': 'NA', 'date': date}
8a928e0806b0e87d2a0539ff905112ad0d3d66ae
5,232
def read_words(file="words.txt"): """ Reads a list of words from a file. There needs to be one word per line, for this to work properly. Args: file: the file to read from Returns: An array of all the words in the file """ with open(file, "r") as f: return f.read().lower().splitlines()
d3d82c4f9afc7db73b4f82f4715cab9b2e99973c
5,233
def str_repeat(space, s, repeat): """Repeat a string.""" return space.newstr(s * repeat)
3e947da1fa3bf403b0836bd4e7ae0052d310636e
5,242
from typing import Dict def basic_extractor( data: Dict, ) -> list: """ Returns list of the total_recieved token, the total sent token and the number of transactions the wallet participated in. """ return [data["total_received"],data["total_sent"],data["n_tx"]]
946611423cf98c6104fa49e0ccb82308d741f900
5,245
def rating_value(value): """Check that given value is integer and between 1 and 5.""" if 1 <= int(value) <= 5: return int(value) raise ValueError("Expected rating between 1 and 5, but got %s" % value)
cadb45a131a423940e1b3a763935f5e40d84285b
5,248
def sous_tableaux(arr: list, n: int) -> list: """ Description: Découper un tableau en sous-tableaux. Paramètres: arr: {list} -- Tableau à découper n: {int} -- Nombre d'éléments par sous-tableau Retourne: {list} -- Liste de sous-tableaux Exemple: >>> sous_tableaux([0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 0, 1], 3) [[0, 0, 0], [1, 0, 0], [1, 1, 0], [1, 1, 1], [0, 1, 1], [0, 0, 1]] """ if n <= 0: return [] if len(arr) < n: return [] return [arr[i:i + n] for i in range(0, len(arr), n)]
4f0a627ea00beafb5b6bc77490e71631e8a55e28
5,251
import json def normalize_cell_value(value): """Process value for writing into a cell. Args: value: any type of variable Returns: json serialized value if value is list or dict, else value """ if isinstance(value, dict) or isinstance(value, list): return json.dumps(value) return value
8ef421814826c452cdb6528c0645133f48bd448a
5,254
def genBinaryFileRDD(sc, path, numPartitions=None): """ Read files from a directory to a RDD. :param sc: SparkContext. :param path: str, path to files. :param numPartition: int, number or partitions to use for reading files. :return: RDD with a pair of key and value: (filePath: str, fileData: BinaryType) """ numPartitions = numPartitions or sc.defaultParallelism rdd = sc.binaryFiles( path, minPartitions=numPartitions).repartition(numPartitions) #rdd = rdd.map(lambda x: (x[0], bytearray(x[1]))) return rdd
85ef3c657b932946424e2c32e58423509f07ceae
5,259
def extract_year_month_from_key(key): """ Given an AWS S3 `key` (str) for a file, extract and return the year (int) and month (int) specified in the key after 'ano=' and 'mes='. """ a_pos = key.find('ano=') year = int(key[a_pos + 4:a_pos + 8]) m_pos = key.find('mes=') month = int(key[m_pos + 4:m_pos + 5]) return year, month
b52dc08d393900b54fca3a4939d351d5afe0ef3c
5,260