content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
from typing import List def cal_group_angle(dist_no: int, group: List[str], **kwargs): """helper function for dandelion data class. Calculates distribution of first circle around center.""" g_ang = dist_no / len(group) # group_ang and distribution number output_list = [] for i in range(len(group)...
ab7b508ac9ad59711aceb16e5661dd15c8db4818
693,502
def checker_O2(opcodes_list): """ given a list of opcodes checks that the """ filtered_l = list(filter(lambda s: any(s.startswith(x) for x in "34578"), opcodes_list)) format_l = list(map(lambda s: s[0], filtered_l)) correct_indexes = [] for i in range(len(format_l)): ...
2a5eae2774aa788d47c414da7cdb2bae0f719bd1
693,503
def hk_aocs_modes(bits: list) -> bytes: """ First bit should be on the left, bitfield is read from left to right """ enabled_bits = 0 bits.reverse() for i in range(len(bits)): enabled_bits |= bits[i] << i return enabled_bits.to_bytes(1, byteorder='big')
7a11210d368364cdfc60b14689807ce55358c399
693,504
def include_session_id(endpoint_context, client_id, where): """ :param endpoint_context: :param client_id: :param where: front or back :return: """ _pinfo = endpoint_context.provider_info # Am the OP supposed to support {dir}-channel log out and if so can # it pass sid in logout to...
a48640057520a6ca3d2f01463446ff1c90ed5379
693,505
import re def remove_escape_sequences(string): """ Replaces all contiguous instances of "\r\n\t\v\b\f\a " and replaces it with a single space. Preserves at most one space of surrounding whitespace """ escape_seqs = r'[\r\n\t\v\b\f\a ]+' return re.sub(escape_seqs,' ', string)
6f6fb756125569cba1882e936c7c796125447c22
693,506
def dnac_get_modules(dnac_session, dnac_host, dnac_headers, device_id): """DNAC Modules of a Network Device""" tmp_url = 'https://%s/dna/intent/api/v1/' % dnac_host tmp_url = tmp_url + 'network-device/module?deviceId=%s' % device_id r = dnac_session.get(tmp_url, verify=False, ...
4cf0ba4c7afa75c60016b30fe933609ce7b32a56
693,507
def clean_comment(comment): """ Clean the comment """ try: name = comment.author.name except: name = "None" data = { "author": name, "body": comment.body, "ups": comment.ups, "fullname": comment.fullname } for k, v in data.items(): ...
54176112cfdd47970fe3891687eea76352404dea
693,508
import argparse def parse_that_shit(): """Parse that shit.""" parser = argparse.ArgumentParser(description="Take filename.") parser.add_argument("filename", help="Filename of report.") return parser.parse_args()
a3065349043f50f3bd321d9b5f3508db697f1446
693,509
import re def extract_patents(line, default_country=None): """ Extract a list of patent number strings Supports only standard patent publication number like WO2012066519 Tolerance with spaces, punctuations, slashes Keep application numbers like PCT/IB2011055210 If a iso2 country code is pro...
af21658e2ba42f3f76c49f6aa15a54fcbf76238a
693,510
import json def convert_organization_response(fetch_rows): """レスポンス用JSON変換 organization情報のselect(fetch)した結果をレスポンス用のjsonに変換する Args: fetch_rows (dict): organizationテーブル取得結果 Returns: dict: レスポンス用json """ result = [] for fetch_row in fetch_rows: result_row = { ...
f932eb46e5f4109a9bedb9327c64af2c88a88284
693,511
def floyd_warshall(G): """find all shortest paths in a dense integer weighted directed graph An implementation of the Floyd-Warshall algorithm[1][2]. Complexity is cubic: O(n**3). If the weights in G are small, complexity can be as low as O(n**2.575) [3]. Arguments: G: Type List[List[int]]. A dense direc...
ec5a9a9df47d0fb49820cb97658a24fc629c477c
693,512
def unf_bo_below_pb_m3m3(rho_oil_st_kgm3=820, rs_m3m3=100, rho_oil_insitu_kgm3=700, gamma_gas=0.8): """ Oil Formation Volume Factor according McCain correlation for pressure below bubble point pressure :param rho_oil_st_kgm3: density of stock-tank oil, kgm3 :param rs_m3m3: solution gas-oil ratio, m...
932047445c902e8af233bb276524da70e16cb599
693,513
def content_is_xml(maintype): """Check if HTML content type is an image.""" return maintype in ("text/xml", "application/xml")
15abca42f156df74e06eb43ba7a1b78361de3eca
693,514
from typing import Callable def euler_step(f: Callable[[float, float], float], t_k: float, y_k: float, h: float) -> float: """ Computes the euler step function for a given function Parameters: f (function) - The derivate to approximate the integral of t_k (float) y_k (float)...
69e5caea31fb7d2c84d52b408e5350c20564e81b
693,515
def flatten (alst): """A recursive flattening algorithm for handling arbitrarily nested iterators >>> flatten([0, [1,(2, 3), [4, [5, [6, 7]]]], 8]) [1, 2, 3, 4, 5, 6, 7, 8] """ def _recur (blst): for elem in blst: if hasattr(elem, "__iter__"): for i in _recur(ele...
8f89aab3dba6e73ba92273f2d8f2f631a5071918
693,516
def create_non_rym_dataframe(dataframe): """Create CSV file of movies on OMDb and not on RYM. Args: dataframe: dataframe of movies with omdb and rym info Returns: Dataframe of non RYM movies """ return dataframe.loc[not dataframe['in_rym'], ['imdb_id', 'title', 'year']]
030644bb879def9edcc8508159b958139e89f0a0
693,517
def bson2bytes(bval: bytes) -> bytes: """Decode BSON Binary as bytes.""" return bval
ec58026ef94f594179d51dd2688943624a8601ff
693,518
def rivers_with_station(stations): """ Given list of stations, return as set of all the rivers names contained within these stations """ return set([station.river for station in stations])
40e4dbcfdc87dcacac39e7d9fdaef17ecf34cb7c
693,519
def parse_darkhorse(input_f, output_fp, low_lpi=0.0, high_lpi=0.6): """ Parse output of DarkHorse (smry file). Paramters --------- input_f: string file descriptor for Consel output results output_fp: str Filepath to output best hit genome IDs low_lpi: float lower LPI (li...
2d963835a59ce8aac6ab00528aecf24f4bb4eac4
693,520
import json def load_json_file(file): """ JSON file parser. Arguments --------- file: "String containing the desired file to parse from json folder" Modules ------- json: "JavaScript syntax data interchange format" Returns ------- "Dictionary containing the j...
0507c34c41edb6123bd67ec7b1e9c85c15734eb6
693,521
def string_chunker(strin, char_num): """ Splits a string into an array of chars :param strin: :param char_num: :return: """ return [strin[i : i + char_num] for i in range(0, len(strin), char_num)]
0875e4423c15d6cec479b8155e3569c35caf74bc
693,522
def interceptable_sender(func, key=None): """Get the signal sender to intercept a function call. :param func: The function that should be intercepted :param key: An optional key in case using just the function name would be too generic (e.g. most utils) """ name = '{}.{}'.format(fun...
6c74ee13b8ef60e712cf215d08ede801a4535fc1
693,523
def escape(html): """Returns the given HTML with ampersands, quotes and carets encoded.""" return html.replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;').replace('"', '&quot;').replace("'", '&#39;').replace(":","&#58;")
eb49c178c7f80766054371c973da156bf882f82d
693,524
def is_float(s: str) -> bool: """ Checks if input string can be turned into an float Checks if input string can be turned into an float :param s: input string :type s: str :return: True if input can be turned into an float False otherwise :rtype: bool """ try: out = fl...
553bee103337e46b73c710799a921f18950a19b3
693,525
import logging def bases_to_complete_next_codon(phase): # pylint: disable=invalid-name """ Return the bases at the exon end that completes the next codon. >>> bases_to_complete_next_codon(0) # e.g. -----XXX 0 >>> bases_to_complete_next_codon(2) # e.g. XX-----X 2 >>> bases_to_complete_nex...
a59e209b1c764a73eb35cb67807f954259ee4b08
693,526
import six def url_join(url, path): """ url version of os.path.join """ p = six.moves.urllib.parse.urlparse(url) t = None if p.path and p.path[-1] == '/': if path and path[0] == '/': path = path[1:] t = ''.join([p.path, path]) else: t = ('' if path and path...
bf7b9f3f6cade51fd12e8dc6b26ab5e1aaecd69e
693,527
def db2pow(x): """ Converts from dB to power ratio Parameters ---------- x - Input in dB Returns ------- m - magnitude ratio """ m = 10.0 ** (x / 10.0) return m
f8f03139ccca73fe9aff97d56d6e41dbcaf3efb9
693,528
def gcd(a, b): """ a = kb + r --> r = a % b we have: c = gcd(a, b) r = a - kb c|r --> c = gcd(b, r) gcd(a, b) = gcd(b, a % b ) """ if b == 0: return a else: return gcd(b, a % b)
01b8d4b158365b745de041ad23cb92df26b57975
693,530
def default_feature_func(_, X, t): """ Returns a list of feature strings. (Default feature function) :param X: An observation vector :param t: time :return: A list of feature strings """ length = len(X) features = list() features.append('U[0]:%s' % X[t][0]) features.append('...
885e2b296959ac611d444a4c82a733031ac4004e
693,531
def scale_early_stop_indices_to_iterations(stop_indices, plot_step): """ Scale 'stop_indices', as calculated by find_early_stop_indices(...)), to match early-stopping iterations. """ return (stop_indices + 1) * plot_step
ae9cb2081ab2518a302c80da6fd0ba41babb6f19
693,532
def _spreadsheet_list(api): """sheets 파일 리스트(google cloud account 내에 있는 모든 spreadsheets) Args: api (obj): gspread object Returns: [dict]: {<title>: <id>} """ return { spreadsheet.title: spreadsheet.id for spreadsheet in api.openall() }
8625c5cf7ec7460683ba65b21593b387d33fa8af
693,533
from typing import Tuple def get_text_dimensions(text: str, font) -> Tuple[int, int]: """ Compute the approximate text size for the given string and font. :param text: String of text. Will be split over line breaks. :param font: The font to use. :return: Width and height of the text. :raises ...
ed876693946637543c8fa453d8d28625148ef773
693,534
import configparser def load_config(config_file_path): """ Parse a WORC configuration file. Arguments: config_file_path: path to the configuration file to be parsed. Returns: settings_dict: dictionary containing all parsed settings. """ settings = configparser.ConfigParser() ...
6cd20957234bec969b9e54fd35fe3965e6239c09
693,535
def find_sequence(doc): """ Finds the sequence of an sbol component given a document containing full sbol Requires -------- None. Parameters ---------- doc : object of sbol2.document module a full depth sbol document Returns ------- seq: string series o...
23be7b7841e18eac911f9ad596b4dabcb0643355
693,536
import os import re import html import unicodedata def sanitize_filename(name): """ Replace reserved characters/names with underscores (windows) Args: name(str) Returns: str """ if isinstance(name, int): return str(name) if os.sep == '/': bad_chars = re.c...
2a1db419c8ef0bebc5414038d528e652927db032
693,537
def strHypInd(i, j): """ Returns string identifier for a hyperplane of ith and jth observation, regardless of ordering. """ if i > j: i, j = j, i return str(i) + '-' + str(j)
f66c462d8ba0ca62878cfa92db7ce7d06bf47024
693,538
import random def randomMAC(type="xen"): """Generate a random MAC address. 00-16-3E allocated to xensource 52-54-00 used by qemu/kvm The OUI list is available at http://standards.ieee.org/regauth/oui/oui.txt. The remaining 3 fields are random, with the first bit of the first random field set 0...
ec5af0a24439f888376bf770e243193b10c9a5a3
693,539
def flat_dict_from_dict(dict_): """ Create a dictionary without depth. { 'depth0': { 'depth1': { 'depth2': 'test1', 'depth2': 'test2' } } } => depth0.depth1.depth2:test1;depth0.depth1.depth2:test2 """ flat_dict = di...
a2544b596fb6c4824f2ccb10d1c278f184eb7583
693,540
def empty(list): """ Checks whether the `list` is empty. Returns `true` or `false` accordingly.""" return len(list) == 0
c1e94267226053e555627728dd4fc12cb337ff8d
693,541
def add4(a, h): """ This function helps us to add datatype. a: Give same datatype values for a and b. b: Give same datatype values for a and b. """ print("Value of a:", a) print("Value of h:", h) return a+h
fb9e01db3855cea2e90051f501d7960b283922ee
693,542
def moments_get_skew(m): """Returns the skew from moments.""" return m['mu11']/m['mu02']
03ece117646fa56719dee8abffc01226706100a9
693,543
def get_sub_dict(data_dict, key_list, default_value='default_value'): """ 从字典中提取子集 :param: * data_dict: (dict) 需要提取子集的字典 * key_list: (list) 需要获取子集的键列表 * default_value: (string) 当键不存在时的默认值,默认为 default_value :return: * sub_dict: (dict) 子集字典 举例如下:: print('---...
b9fead5e233642d9dfe714281d5358a98622fb2c
693,544
def date_cmp(item1, item2): """ Compare items for ordering purposes """ if item1.end_date is None and item2.end_date is None: if item1.start_date < item2.start_date: return 1 if item2.start_date < item1.start_date: return -1 return 0 if item1.end_date ...
0c658595cda81bf35bcd591b37419f01a73a3d1b
693,546
def sanitize_str(string): """ Sanitize string to uppercase alpha only """ return filter(str.isalpha, string.upper())
e693d61f19ab56103395a798c930a1b9937eafd5
693,547
def pad_diff(actual_height, actual_width, desired_height, desired_width): """ Pads img_arr width or height < samples_size with zeros """ h_diff = desired_height - actual_height w_diff = desired_width - actual_width padding = (0, 0, w_diff, h_diff) # left, top, right, bottom return padding
5796ceaa57b30a83f83bf7b1a8696aa6889a85f6
693,548
def parse_h5_attr(f, attr): """A Python3-safe function for getting hdf5 attributes. If an attribute is supposed to be a string, this will return it as such. """ val = f.attrs.get(attr, None) if isinstance(val, bytes): return val.decode("utf8") else: return val
75774def6f8ac3abf8c78aa97557fcb91cb2628e
693,549
import copy import random def default_policy(state): """Return results of random search""" init_state = copy.deepcopy(state) while not state.terminal_test(): action = random.choice(state.actions()) state = state.result(action) return -1 if state._has_liberties(init_state.player()) els...
98f9bc4faa23b874d98f55035f783478e0731265
693,550
def invert_dict(d): """Invert a dictionary's key/value""" #return dict(map(lambda t: list(reversed(t)), d.items())) return dict([(v, k) for k, v in d.items()])
b1327055cc613c0701355409e1d782f334bbe57b
693,551
def process_license(license): """If license is Creative Common return the zenodo style string else return license as in plan Parameters ---------- license : dict A string defining the license Returns ------- zlicense : dict A modified version of the license dictionar...
b6d07168a1e11641ec78ea52becb4d08c957dd69
693,552
def strhash(*args, **kwargs): """ Generate a string hash value for an arbitrary set of args and kwargs. This relies on the repr of each element. :param args: arbitrary tuple of args. :param kwargs: arbitrary dictionary of kwargs. :returns: hashed string of the arguments. """ if kwargs:...
8b56ab2c205e8d5788d6c3d1788c8353400c8f79
693,553
def over(*, aalpha, oomega): """Define the dyadic over ⍥ operator. Monadic case: f⍥g ⍵ f g ⍵ Dyadic case: ⍺ f⍥g ⍵ (g ⍺) f (g ⍵) """ def derived(*, alpha=None, omega): if alpha is None: return aalpha(alpha=alpha, omega=oomega(omega=omega)) else: ...
68079977befc9ec576aaf8706579d05864f21d24
693,554
def has_duplicates2(t): """Checks whether any element appears more than once in a sequence. Faster version using a set. t: sequence """ return len(set(t)) < len(t)
7c815aa1467648b3c5aa405b6359ba10d911ac77
693,555
def notebook_name(params, filetype): """ Returns URL encoded notebook name without .ipynb extension. """ args = [param.replace('/', '') for param in params if param is not None] print(args) return '"{}.{}"'.format(args[-1][:-6], filetype)
5b06fb731ccefe70aef7d007160e0cc23039b416
693,556
def box_outside_box(v1, v2): """return true if v1 is outside v2""" return (v1['p1'] < v2['p1']).all() and (v1['p2'] > v2['p2']).all()
dd25f563a1064a6b09d30f0f58932e1dbb7912ae
693,557
def test_default_timeout(monkeypatch, fake_response, aqhttp): """Timeout should default to aqhttp.TIMEOUT is timeout is absent from aqhttp.post.""" # A fake requests sessions object class mock_request: @staticmethod def request(method, path, timeout=None, **kwargs): assert t...
44188a45e5a2780669377297b12b252b71663576
693,559
def extractOutput(queryResults): """convenience function to extract results from active query object""" if not queryResults: return None try: return [x.toDict() if x else None for x in queryResults] except TypeError: return queryResults.toDict() return None
3191987adfa4932c6456a3e6f449d081ba80c316
693,560
def _get_topic_name(klass): """Try to extract the Name of an Admin Topic from the path. Still somewhat like Django App-Names. >>> get_app_name('frontend.news.models.NewsItem') 'news' >>> get_app_name('common.models.Sparepart') 'Sparepart' """ if not hasattr(klass, '__module__'): ...
7c9ae9a77c980365724e69497d2bb77dfd734419
693,561
def haversine(lat, lon): """ Formula haversine para buscar as lojas ordenando pela distancia. Para limitar os resultados a partir de uma distancia, descomentar a linha do where. """ return f""" SELECT id FROM ( SELECT id, 111.045 * DEGREES(...
b9fc22244be3a537632490656d86c2547a293101
693,562
from pathlib import Path from typing import Optional from typing import Union from typing import List from typing import Iterator import itertools def directories( PATH: Path, INCLUDES: Optional[Union[str, List[str]]] = None, EXCLUDES: Optional[Union[str, List[str]]] = None, ) -> Iterator[Path]: """It...
b0c3db317f298b75cd70844ca9538612e0e0a0c2
693,563
import argparse def get_args(dataset="replica"): """ @Brief: parse input arguments. @Usage: args = get_args(dataset) """ parser = argparse.ArgumentParser() parser.add_argument( "--config-path", type=str, default="ss_baselines/av_nav/config/audionav/{}/train_telephone/p...
cb4aad5f5df0450a18281940b368ac3d4b0e0ffc
693,564
import glob def get_file_names(directory): """ Get the names of the completed csv files used to store the plot details """ return glob.glob(directory + '/*.csv')
49afbb85c7cf66c9f7df95a6dfa35b4005c83195
693,565
def decoded_api_json_data_complex(): """Data to be displayed in a VMC view""" return [ { "id": 1, "string": "Peter", "number": 35, "boolean": True, "empty": None, "object": {"a": "abcde", "b": 60}, "array": [1, 2, 3], ...
6974aa1c3ecb58e6fecb90bcbe7dada805883461
693,566
def get_communities_filenames(database): """ This function retrieves all filenames (and the file count) for every community of similar documents. """ query = ('MATCH (d:Document) RETURN d.community, ' 'collect(d.filename) AS files, ' 'count(d.filename) AS file_count ' ...
48cf5f14023ee34c805be88ead9873a0f6409d0d
693,567
def getListObjectFromIndex(listIndex, listObject): """Lấy ra một list các object dựa theo list index được truyền vào.""" output = [] for i in listIndex: output.append(listObject[i]) return output
958df0c322a781758c1093bf1265fddf2153d9fb
693,568
def _doublet(plist, J): """ Applies a *J* coupling to each signal in a list of (frequency, intensity) signals, creating two half-intensity signals at +/- *J*/2. Parameters --------- plist : [(float, float)...] a list of (frequency{Hz}, intensity) tuples. J : float The coupli...
5b88ec2889bcbfecf6001e1c84fabe835ed4f678
693,569
def gradeReport(course): """Assumes: course is of type Grades""" report = [] for student in course.allStudents(): total = 0.0 numOfGrades = 0 for grade in course.getGrades(student): total += grade numOfGrades += 1 try: average = total / num...
7ff2d3eb4de9166ed1443b0d265b2248f5bb2f5c
693,570
def get_object_root_module(obj): """ Get the obj module version :param T obj: Any object :rtype: str :return The root module of the object's type """ return type(obj).__module__.split('.')[0]
2cfa6e05d1215227873dbd122112ef34b0795550
693,571
import codecs def get_long_description(): """ Strip the content index from the long description. """ with codecs.open('README.rst', encoding='UTF-8') as f: readme = [line for line in f if not line.startswith('.. contents::')] return ''.join(readme)
985e4d6a4b6b64f7d0b9acbba9b9569f2e96adf5
693,572
def frac_cont(frm_count_dict): """ This function specifically takes as input the dictionary output from aa_frmcount function and outputs a dictionary, nlkts, where each key is an amino acid type and whose corresponding value is as follows: - nlkts: dictionary output # co_grpaa[i] (Total no. ...
9dd7bdc939047a34a8db81c5866bf6aa19fefca0
693,573
def _string_to_bool(value, triple=True): """Translates a string into bool value or None. Args: value: The string value to evaluate. (string) triple: If True, None is returned if not found, if False, False Returns: The a bool value of tag or if triple is True None. """ if v...
b46ee6d517e353fae8d28caba6c20e80bd894a5e
693,574
def reverse_string(s): """ Reverse a string. """ s[1] return 'y' % 5 and 'wtf'
df9fdf6cd02b0cd8f2f2dea05194e6cf72542650
693,575
def int2bin(i: int) -> str: """Convert an 8-bit integer to a binary string. Args: i (int): Integer value to be converted. Note: The passed integer value must be <= 255. Raises: ValueError: If the passed integer is > 255. Returns: str: A binary string representatio...
e95fe826a432ec4e680864fbc36fcbf188912289
693,576
def parse_search_value(search_value): """The <search-value> can be of the form:: d<device_id>r<region>z<zone>-<ip>:<port>[R<r_ip>:<r_port>]/ <device_name>_<meta> Where <r_ip> and <r_port> are replication ip and port. Any part is optional, but you must include at least one part. Exam...
20af4b46e435de450c06f79e387a0412ef43566c
693,577
def join_regex(regexes): """Combine a list of regexes into one that matches any of them.""" if len(regexes) > 1: return "(" + ")|(".join(regexes) + ")" elif regexes: return regexes[0] else: return ""
616a4b51a64244e14b6029a91026f65a20077f06
693,578
def num_misses(df): """Total number of misses.""" return df.Type.isin(['MISS']).sum()
72bb2277b5de1aa686cdaa1772a2d85f06d41a9e
693,579
import os def get_file_extension(file_path): """ >>> get_file_extension("/a/b/c") '' >>> get_file_extension("/a/b.txt") 'txt' >>> get_file_extension("/a/b/c.tar.xz") 'xz' """ _ext = os.path.splitext(file_path)[-1] if _ext: return _ext[1:] if _ext.startswith('.') else _e...
2db6837cbc55d89ba18ff085c9ce0b7b96d3dff3
693,580
import os def locate(filename, search_path=os.environ['PATH'], path_sep=os.pathsep): """ Helper function to locate a file in the os PATH. """ for path in search_path.split(path_sep): cur = os.path.join(path, filename) if os.path.exists(cur): return os.path.abspath(cur) ...
deaa5dbf495f4175a90ecda7b3a2f1066d49041e
693,581
def explain_node_str(root, indent=0): """Returns an indendeted outline-style representation of the subtree. """ indent_string = " " * indent buf = f"{indent_string}Node<item={root[0]}>" if not root[1] and not root[2]: buf += "\n" else: buf += ":\n" if root[1]: b...
6bc6136fc12171841a0988b79107ab4032b108a3
693,582
def check_keys_in_dict(dictionary, keys): """ Checks that a list of keys exist in a dictionary. Parameters ---------- dictionary: dict The input dictionary. keys: list of strings The keys that the dictionary must contain. Returns ------- bool: Returns *True...
a28a8a97e0a51196080c92400f01cb08b9ac6cc7
693,583
import os def inject_python(code_info): """Injects code snippet in python code""" cwd = os.getcwd() append = u'# Injected by egtest\n' append += u'import sys\n' append += u'sys.path.insert(0, "%s")\n\n' % cwd append += code_info.code return append
c3ba5dac4dd74b3513b40cd93c15d6cf79cc97c6
693,584
def percent_difference(test_stat, ctrl_stat): """Calculates ratio between test and control. Useful when your statistics might be close to zero. Provides a symmetric result. Args: test_stat: numpy array of test statistics ctrl_stat: numpy array of control statistics Returns: (...
83cc3c1ac7a13cd16d645d927e7d9b50154f3e72
693,585
def parse_dhm_request(msg: str) -> int: """Parse client's DHM key exchange request :param msg: client's DHMKE initial message :return: number in the client's message """ return int(msg.split(':')[1])
8664b1998a5d19718efb0efdddc1a94ede76a281
693,587
def deparen(s): """ Remove all interior parantheses from sequence. """ return s.replace("(", "").replace(")", "")
837eb4903da8437d6b2c14ba3cee7040431c6a43
693,589
import argparse def parseArgs(): """Calculate AS Numbers from AS-DOT or AS-PLAIN""" # Configure the option parser for CLI options to the script usage = "usage: %prog [options] BGP AS Number" parser = argparse.ArgumentParser(description="Calculate BGP AS Numbers") parser.add_argument("ASN", type=s...
1f50f1aa9ab8e08f4b4f9eb065b2ea18d014a918
693,591
def _clean_value(line1, line2): """Clean up attribute value for display.""" _line1 = line1.strip() _line2 = line2.strip() # Let trailing space to make the code easier to read if _line1[-1:] in ["{", "}", "(", ")", "[", "]", ";", ","]: _line1 += " " return _line1 + _line2
8b0e4576a2aca6289a7420783def68c4f224fa97
693,592
def readfile(filename, mode='r'): """ returns the content of a file :param filename: the filename :return: """ if mode not in ['r', 'rb']: raise ValueError(f"incorrect mode : expected 'r' or 'rb' given {mode}") with open(filename, mode)as file: content = file.read() ...
91d5984c1587c080b79a21071a73937feb382468
693,593
def jp_author_name(forename, surname): """Construct the name of a person as a single string.""" if len(forename) == 1: forename = forename+'.' return forename+" "+surname
63cb37b5ba3b7dafe9653fcce8d0fd99fed3906b
693,595
def deduplicate_ref_texts(ref_texts): """Deduplicate reference texts by removing those that have the same content.""" new_ref_texts=[] for rt in ref_texts: to_keep=True for other_rt in ref_texts: if rt.language==other_rt.language and rt.name<other_rt.name: if rt.c...
96f351129a5c40b8dedea2722b68fff48ca960c7
693,596
def home(): """"View for the Home page of the Website""" return "Welcome to the HomePage!"
6a1557ae06d2caafd8b1b0698aa8ab249537c0e3
693,597
def remain_alpha(symbol: str) -> str: """ 返回合约的字母字符串大写 """ symbol_mark = "".join(list(filter(str.isalpha, symbol))) return symbol_mark.upper()
04b5a71044a48f05291105b308a6f7b91263134b
693,598
from typing import Dict from typing import List import re def get_repo_name_from_url( repo_url: str, default_version: str, valid: Dict[str, List[str]], ) -> str: """ Extract repository name from URL. If it cannot be extracted, the name of the first package of the default version is used. ...
f7dd60e89c3fd3db4c983c8a5ac5dc652d4ebe45
693,599
from datetime import datetime def start_dt() -> datetime: """Show the start time. Returns ------- datetime The date time this call was made. """ dt = datetime.now() print('stop_watch', 'Started>', dt.isoformat(timespec='microseconds'), flush=True) return dt
b815649d338f0d0a8823ecb7297c974e9bc81048
693,600
def Strip(txt): """Return stripped string, can handle None""" try: return txt.strip() except: return None
44edfab97b1cdbfec4174cf554c78077fb31cfd7
693,601
def make_game(serverid, name, extras=None): """Create test game instance.""" result = { 'serverid': serverid, 'name': name, 'game_state': {'players': {}, 'min_players': 2, 'max_players': 4}, } if extras: result.update(extras) return result
1e97747c99ed0fa6cde87d1710b1fca7d9512f7b
693,602
def checkConditions(specs, content): """#iterate all elements of specs (array) in content (dictionary) and apply the correspondent function """ result = [] for key, value in specs.items(): controlResult = value(content.get(key)) if controlResult: result.append(controlRes...
8da865888edbf03cdf6120f82286100c86cc0671
693,603
import time def tot_exec_time_str(time_start): """ execution time This function gives out the formatted time string. """ time_end = time.time() exec_time = time_end-time_start tmp_str = "execution time: %0.2fs (%dh %dm %0.2fs)" %(exec_time, exec_time/3600, (exec_time%3600)/60,(exec_time%36...
f8735cc82507089767af077c911611223d1d5465
693,604
def line_search(py, n_total, cmts_directory, windows_directory, data_info_directory, data_asdf_directory, sync_raw_directory, sync_perturbed_directory, stations_path, min_periods, max_periods, search_range, search_step): """ do the structure line search. """ script = "export IBRUN_TASKS_PER_NODE=12; \n"...
1c9b809d8d3425fee51b1a4210d598ddd0abbdad
693,605
import glob def generate_file_list(): """ Make list of the files we want flask to reload when changed """ glist = ['templates/*.html', 'templates/tests/*.html', 'static/js/*.js', 'static/js/tests-jasmine/*.js', ] rval = [] for gexpr in glist:...
2c415e8ddc8cf4eba8fff607a613b8a6bc828200
693,606
def knots_to_kmh(knots: float) -> float: """ Convert velocity in knots to km/h 1 knot (i.e. 1 nm/h or 1 nautical mile per hour) is 1.852 km/h. :param knots: velocity in knots :returns: velocity in km/h """ return knots * 1.852
8793def54f9b7a8e3895cc8d32156e30f67c9d67
693,607
def nonexistent_user(): """Данные несуществующего пользователя.""" return { 'username': 'unknown_username', 'email': 'unknown@mail.ru', 'phone_number': '+79001234567' }
c00241cc8894fe480b6d0970d6069c7f69473f8b
693,608