content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def get_attr_number(node): """ For Understanding """ # print(f"\n{node} -> {node.getchildren()}") # print(f"{node.attrib}") # print(f"{len(node.attrib)}") """ get_attr_number(node) """ # # <Element 'feed' at 0x7f1cdd3ff0e8> -> [<Element 'title' at 0x7f1cdd2a94a8>, <Element 'subtitle' at 0x7f1cdd283368>, <Element 'link' at 0x7f1cdd2839f8>, <Element 'updated' at 0x7f1cdd292b88>] # {'{http://www.w3.org/XML/1998/namespace}lang': 'en'} # 1 """ [get_attr_number(child) for child in node] """ # # <Element 'title' at 0x7f1cdd2a94a8> -> [] # {} # 0 # # <Element 'subtitle' at 0x7f1cdd283368> -> [] # {'lang': 'en'} # 1 # # <Element 'link' at 0x7f1cdd2833b8> -> [] # {'rel': 'alternate', 'type': 'text/html', 'href': 'http://hackerrank.com/'} # 3 # # <Element 'updated' at 0x7f1cdd292b88> -> [] # {} # 0 return len(node.attrib) + sum(get_attr_number(child) for child in node)
693d153e309b5f1af0ba9e27fe727155eda93f6c
36,349
import re import os def name_from_path(path: str) -> str: """Returns a safe to use executable name based on a filesystem path.""" return re.sub('\\W', '_', os.path.basename(path.rstrip(os.sep)))
f9a47667fb480d2ba9ae2ce0e02de312b4dc9ca9
36,350
import subprocess def getUrl(url): """ A helper to do an HTTP GET without requiring 3rd party libraries. :param url: str The URL to GET. :return: str """ responseStr = subprocess.check_output(['curl', '-s', url]) if responseStr is None: return None return responseStr.decode('utf-8')
3c935922a0e0fd90fd86195f74ee9463372b7e42
36,352
def serialize(temp_file_name: str) -> bytes: """ Serializes the graph Parameters ------------ temp_file_name Path to the temporary file hosting the graph """ with open(temp_file_name, "rb") as f: return f.read()
93176b37fe23ece2cf2b92f7c4629b480b7a049c
36,353
import os def guess_service_name(): """Deduce the service name from the pwd :return : A string representing the service name """ return os.path.basename(os.getcwd())
3d6ef4891863acf1eb302cd8d998459925b0a281
36,354
def alignment_percentage(document_a, document_b, model): """ Returns the percentage of alignments of `document_a` and `document_b` using the model provided. - `document_a` and `document_b` are two lists of Sentences to align. - `model` can be a YalignModel or a path to a yalign model. """ if len(document_a) == 0 and len(document_b) == 0: return 100.0 align = model.align(document_a, document_b) align = [x for x in align if x[0] is not None and x[1] is not None] ratio = len(align) / float(max(len(document_a), len(document_b))) return round(ratio * 100, 2)
dbd11fbdf9649e6f2c3a20e8407a799a3faeb428
36,355
import re def float_through(num36: str, mask: str, mem: dict): """Used in part 2""" ones = [m.start() for m in re.finditer("1", mask)] quantums = [m.start() for m in re.finditer("X", mask)] fixed = "" for i, digit in enumerate(num36): if i in ones: c = "1" elif i in quantums: c = "X" else: c = digit fixed += c return mem
606be139b45df0d39f0e528835992af60e02932e
36,356
import re def format_card(card_num): """ Formats card numbers to remove any spaces, unnecessary characters, etc Input: Card number, integer or string Output: Correctly formatted card number, string """ card_num = str(card_num) # Regex to remove any nondigit characters return re.sub(r"\D", "", card_num)
0c967a499a71ff8934b7578a3f62a31874f22ca2
36,357
def Welcome(): """List all available api routes.""" return ( """Available Routes:<br/> /api/v1.0/precipitation<br/> /api/v1.0/stations<br/> /api/v1.0/tobs<br/> *You can search temperature stats from a starting date adding the date after the slash (/) with the format yyyy-mm-dd<br/> /api/v1.0/<start><br/> *You can search temperature stats between dates adding the starting date after the first slash (/) and the end after the second one with the format yyyy-mm-dd<br/> /api/v1.0/<start>/<end><br/> """ )
971d9a5394d23610041c8f39d8281e27aedf03bf
36,359
def _produce_scores(scores, exp): """Produces the scores dictionary. Args: scores: Is either the score dictionary, or a function that produces the score dictionary based on an experiment. exp: The experiment ojbect. Returns: The dictionary of scores. """ if isinstance(scores, dict): return scores return scores(exp)
bd7d3e4883f294ba7daed987a555c8e5310160e7
36,362
import functools def get_itemset(keys, dic): """Merge elements of dic given keys The item values of dic should be comparable >>> get_itemset([1], {1: ['1', 'a']}) ['1', 'a'] """ return sorted(functools.reduce(lambda x, y: set(x).union(y), [dic[k] for k in keys]))
425453ce2651c068eaf68b0d50fad05d16100172
36,363
def bessel_spoles(n, Ts=1): """ Return the roots of the reverse Bessel polynomial normalized the given settling time. The settling time is 1 second by default. Adapted from Digital Control: A State-Space Approach, Table 6.3. Args: n: The order of the Bessel polynomial. Ts (optional): The settling time to scale to. Returns: list: The roots of the Bessel polynomial. """ spoles = [0] if n == 1: spoles = [-4.6200 + 0j] elif n == 2: spoles = [-4.0530 + 2.3400j, -4.0530 - 2.3400j] elif n == 3: spoles = [-5.0093 + 0j, -3.9668 + 3.7845j, -3.9668 - 3.7845j] elif n == 4: spoles = [-4.0156 + 5.0723j, -4.0156 - 5.0723j, -5.5281 + 1.6553j, -5.5281 - 1.6553j] elif n == 5: spoles = [-6.4480 + 0j, -4.1104 + 6.3142j, -4.1104 - 6.3142j, -5.9268 + 3.0813j, -5.9268 - 3.0813j] elif n == 6: spoles = [-4.2169 + 7.5300j, -4.2169 - 7.5300j, -6.2613 + 4.4018j, -6.2613 - 4.4018j, -7.1205 + 1.4540j, -7.1205 - 1.4540j] elif n == 7: spoles = [-8.0271 + 0j, -4.3361 + 8.7519j, -4.3361 - 8.7519j, -6.5714 + 5.6786j -6.5714 - 5.6786j, -7.6824 + 2.8081j -7.6824 - 2.8081j] elif n == 8: spoles = [-4.4554 + 9.9715j, -4.4554 - 9.9715j, -6.8554 + 6.9278j, -6.8554 - 6.9278j, -8.1682 + 4.1057j, -8.1682 - 4.1057j, -8.7693 + 1.3616j, -8.7693 - 1.3616j] elif n == 9: spoles = [-9.6585 + 0j, -4.5696 + 11.1838j, -4.5696 - 11.1838j, -7.1145 + 8.1557j, -7.1145 - 8.1557j, -8.5962 + 5.3655j, -8.5962 - 5.3655j, -9.4013 + 2.6655j, -9.4013 - 2.6655j] elif n == 10: spoles = [-4.6835 + 12.4022j, -4.6835 - 12.4022j, -7.3609 + 9.3777j, -7.3609 - 9.3777j, -8.9898 + 6.6057j, -8.9898 - 6.6057j, -9.9657 + 3.9342j, -9.9657 - 3.9342j, -10.4278 + 1.3071j, -10.4278 - 1.3071j] return [ spole/Ts for spole in spoles ]
4e2191c9c1201997e77da314316ef1ebc208f7d4
36,364
from typing import List from typing import Tuple def words_to_ngrams(words: List[str]) -> List[Tuple[str]]: """ Convert a list of words to uni-grams :param words: The list of words to convert :return: A list of the same size, containing single-element tuples of uni-grams. """ return [(w,) for w in words]
3d4fa456bd9c8bbe034b9441521bdc62940f8cf9
36,366
def mod_mapping(codon, productions): """ Default mapping function introduced by GE.""" return codon%len(productions)
a80e5e5cd48fd9b85f4ffb7680f6fc7f141b5c15
36,368
from unittest.mock import patch def dont_handle_secret_request_mock(app): """Takes in a raiden app and returns a mock context where secret request is not processed Example usage: mock = dont_handle_secret_request_mock(app) with mock: # here we know that the transfer will not complete as long as we are # inside the with context block app.raiden.mediated_transfer_async( token_network_identifier=token_network_identifier, amount=amount, target=target, identifier=payment_identifier, ) """ def do_nothing(raiden, message): pass return patch.object( app.raiden.message_handler, 'handle_message_secretrequest', side_effect=do_nothing, )
ceba6b0f47e0b92e7b237f906ffded43af845044
36,370
def _copy_non_t_vars(data0, data1): """Copies non-t-indexed variables from data0 into data1, then returns data1""" non_t_vars = [v for v in data0.data_vars if 't' not in data0[v].dims] # Manually copy over variables not in `t`. If we don't do this, # these vars get polluted with a superfluous `t` dimension for v in non_t_vars: data1[v] = data0[v] return data1
81c0a21f61fd284fd572383acff2ac8744101777
36,371
def toHex(self, num): # ! 这个是常规方法, 37ms """ :type num: int :rtype: str """ if num is 0: return '0' if num < 0: num += 2 ** 32 dict_hex = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'] res = '' # ! 短除法,用于解决进制转换问题 while num: res += dict_hex[num % 16] num = num // 16 else: return res[::-1]
16ce2cc0a1626ea88f34ad7b2484058e1237e5df
36,372
def my_fix(request): """Our saved fixture, that will be saved in the store fixture""" # convert the parameter to a string so that the fixture is different from the parameter return "my_fix #%s" % request.param
74e0d94436beab6a14dbedf4778ff48d3a298b33
36,373
import json def parse_response(self, request): """解析指定请求的响应数据 Returns: list: 数据字典列表 """ response = request.response res = [] # 默认为空 if response is None: return res if response.status_code == 200: # 同上说明 # body = request._client.get_response_body(request.id) body = request.response.body data = json.loads(body) # 解析结果 402 不合法的参数 if data['resultcode'] == 200: # 记录列表 res = data['records'] return res
2d5c641fd77ad48c21e60cc86d68e45d4aada3d9
36,374
import requests def fetch_player_info(): """ Fetch player info for the most recent season. """ url = "https://fantasy.premierleague.com/drf/bootstrap-static" r = requests.get(url) positions = [] for player in r.json()["elements"]: positions.append( { "position_id": player["element_type"], "player_id": player["code"], "team_id": player["team_code"], "full_name": player["first_name"] + " " + player["second_name"], "now_cost": player["now_cost"], "selected_by": player["selected_by_percent"], } ) return positions
01acfdc8f39a749a27a250a23252cb8f140d074b
36,376
from typing import Dict from typing import Any from typing import List def filter_dict(mydict: Dict[str, Any], keys: List[str]) -> Dict[str, Any]: """Filter dictionary by desired keys. Args: mydict: disctionary with strings as keys. keys: a list of key names to keep. Returns: the same dictionary only at the desired keys. """ return {k: v for k, v in mydict.items() if k in keys}
339101fc16fc69110f3d470668eda455f430c062
36,377
import random def gen_individual(toolbox, config, out_type='out'): """ Generates a random tree individual using the toolbox and arity and height configuration. The ``ou_type`` parameter specifies the output type of the root of the tree. :param toolbox: Toolbox which contains methods to create the individual. :param GenensConfig config: Configuration of Genens :param out_type: Output type of the root of the tree individual. :return: A new random tree individual. """ arity = random.randint(config.min_arity, config.max_arity) # randint is inclusive for both limits height = random.randint(config.min_height, config.max_height) return toolbox.individual(max_height=height, max_arity=arity, first_type=out_type)
5fb0d051502cd9764e8bedc31dc2c717200f618f
36,378
def top_n(n: int, tokens: list) -> list: """Return a list of top-n unique elements of the dataset Arguments: n {int} -- number of top unique elements to return Returns: list -- array of top-n elements within a dataset """ top_n_elements = tokens[:n] return top_n_elements
6d0e03b3d041edb460a874394af171cf589b2b1b
36,380
from typing import List from typing import Type def validate_objects(elements: List, element_class: Type) -> bool: """ Check if all the elements are instance of the element_class. Args: elements: List of objects that should be instance of element_class. element_class: class of the objects. Returns: True if all the elements are instance of element_class. Raises: ValueError if one element is not an instance of element_class. """ for element in elements: if not isinstance(element, element_class): raise ValueError(f"{element} is not a {element_class}") return True
cd913ef4005d5360f8c2053ae30a72173e41d886
36,381
def check_day(n): """ Given an integer between 1 and 7 inclusive, return either string 'work!' or string 'rest!' depending on whether the day is a workday or not """ if n < 1 or n > 7: return None if n >= 6: return "rest!" return "work!"
f7329fb411a737c2fb9799a37a0bb52e28d4db83
36,382
def tolist(x): """convert x to a list""" return x if isinstance(x, list) else [x]
eb987b9766d09d7a36f1e671e5cf266296c0604e
36,383
def is_one_of(x, ys): """判断x是否在ys之中 等价于x in ys,但有些情况下x in ys会报错 """ for y in ys: if x is y: return True return False
8ec0a6e145d0640e7c844e514f3974e199567e45
36,384
def get_index_of_table_a_1(type): """表A.1における行番号を取得する Args: type(str): 主たる居室に設置する暖冷房設備機器等 Returns: int: 表A.1における行番号 """ key_table = { '電気蓄熱暖房器': 0, '温水暖房用パネルラジエーター': 1, '温水暖房用床暖房': 2, '温水暖房用ファンコンベクター': 3, 'ルームエアコンディショナー': 4, 'FF暖房機': 5, '電気ヒーター床暖房': 6, 'ルームエアコンディショナー付温水床暖房機': 7 } return key_table[type]
70f2087e08d05520bb1db7fb04fa2f66b8f5d445
36,385
def get_search_stuff(): """ Return tuple of targets, constraints, subgoals """ # List of targets for each subgoal targets = [1, 2, 3, (4,5), (4,5), 6, 7, 8, (9, 10), (9, 10), 11, 12, 13, (14, 15), (14, 15), (16, 21), (17, 22), (18, 23), (19, 24), 20] # As the puzzle progresses, constrain the actions constraints = [ [], [(0, 0)], [(0, 0), (0, 1)], [(0, 0), (0, 1), (0, 2)], [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (2, 0), (2, 1), (3, 0), (3, 1), (4, 0), (4, 1), (4, 2), (4, 3), (4, 4)], [(0, 0), (0, 1), (0, 2), (0, 3), (0, 4)], [(0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (1, 0)], [(0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (1, 0), (1, 1)], [(0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (1, 0), (1, 1), (1, 2)], [(0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2), (3, 0), (3, 1), (3, 2)], [(0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (1, 0), (1, 1), (1, 2), (1, 3), (1, 4)], [(0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (1, 0), (1, 1), (1, 2), (1, 3), (1, 4), (2, 0)], [(0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (1, 0), (1, 1), (1, 2), (1, 3), (1, 4), (2, 0), (2, 1)], [(0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (1, 0), (1, 1), (1, 2), (1, 3), (1, 4), (2, 0), (2, 1), (2, 2)], [(0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (1, 0), (1, 1), (1, 2), (1, 3), (1, 4), (2, 0), (2, 1), (2, 2), (3, 0), (3, 1), (3, 2)], [(0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (1, 0), (1, 1), (1, 2), (1, 3), (1, 4), (2, 0), (2, 1), (2, 2), (2, 3), (2, 4)], [(0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (1, 0), (1, 1), (1, 2), (1, 3), (1, 4), (2, 0), (2, 1), (2, 2), (2, 3), (2, 4), (3, 0), (4, 0)], [(0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (1, 0), (1, 1), (1, 2), (1, 3), (1, 4), (2, 0), (2, 1), (2, 2), (2, 3), (2, 4), (3, 0), (3, 1), (4, 0), (4, 1)], [(0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (1, 0), (1, 1), (1, 2), (1, 3), (1, 4), (2, 0), (2, 1), (2, 2), (2, 3), (2, 4), (3, 0), (3, 1), (3, 2), (4, 0), (4, 1), (4, 2)], [(0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (1, 0), (1, 1), (1, 2), (1, 3), (1, 4), (2, 0), (2, 1), (2, 2), (2, 2), (2, 3), (3, 0), (3, 1), (3, 2), (4, 0), (4, 1), (4, 2)] ] corner_goal = lambda x, t1, t2 : \ (x.matrix.index(x.target[0]) == t1 and (x.matrix.index(x.target[1]) == t2))\ or (x.matrix[x.target[0] - 1:x.target[1] - 1] == x.target) subgoals = [ lambda x: x.matrix[x.target - 1] == x.target, lambda x: x.matrix[x.target - 1] == x.target, lambda x: x.matrix[x.target - 1] == x.target, lambda x: corner_goal(x, 9, 14) or corner_goal(x, 8, 13), lambda x: x.matrix[x.target[0] - 1:x.target[1]] == x.target, lambda x: x.matrix[x.target-1] == x.target, lambda x: x.matrix[x.target-1] == x.target, lambda x: x.matrix[x.target-1] == x.target, lambda x: corner_goal(x, 14, 19), lambda x: x.matrix[x.target[0] - 1:x.target[1]] == x.target, lambda x: x.matrix[x.target-1] == x.target, lambda x: x.matrix[x.target-1] == x.target, lambda x: x.matrix[x.target-1] == x.target, lambda x: corner_goal(x, 19, 24), lambda x: x.matrix[x.target[0] - 1:x.target[1]] == x.target, lambda x: corner_goal(x, 15, 20), lambda x: corner_goal(x, 16, 21), lambda x: corner_goal(x, 17, 22), lambda x: corner_goal(x, 18, 23), lambda x: x.matrix[x.target-1] == x.target ] return targets, constraints, subgoals
941885979d17d6e32266ebcc5828ab991ebc078e
36,387
def df_filter(df, filter_params): """Filter parameter by values.""" df = df.copy() for key, value in filter_params.items(): if value != ("0.0", "0.0"): df = df.loc[ (df[key] >= float(value[0])) and (df[key] <= float(value[1])) ] return df
dd397c1ba7a9c365d23b4dce5b4e1c1524c1cc07
36,388
import os def filename_from_path(path, remove_extension=False): """ Takes a filepath and returns only the filename, optionally removes the file extension :param path: Filepath :param remove_extension: If True, remove the file extension too. Default: False :return: filename """ filename = os.path.basename(path) if remove_extension: filename = os.path.splitext(filename)[0] return filename
0b1445e224aa16556e02eccfd7055bdfdd12a633
36,391
def neg_network(network): """ Perform the operation ``-1 * network`` where ``network`` is an instance of ``Network``. """ return network * -1
da1e59f09ca8c91efb6fdaa22bf03e58a6fb7e43
36,393
def normalize_VM(inputVM): """ Rules 1- Can't be null => 1 """ outputVM = inputVM if outputVM == "": return "1" return outputVM
092bdebdf6c53cafe738468ebbb06f0088d63299
36,394
def cell_width(cell_name): """ Set the width of the cells from the pdf report file.""" if cell_name == "No": table_cell_width = 6 elif cell_name == "Phrase": table_cell_width = 73 elif cell_name == "Question": table_cell_width = 57 else: table_cell_width = 25 return table_cell_width
fac9e9dc0f8ad3cac09ed3054a798e7d832cdcc6
36,396
import numpy def nearest_neighbor(d): """Classical greedy algorithm. (Start somewhere and always take the nearest item.) """ n = d.shape[0] idx = numpy.arange(n) path = numpy.empty(n, dtype=int) mask = numpy.ones(n, dtype=bool) last_idx = 0 path[0] = last_idx mask[last_idx] = False for k in range(1, n): last_idx = idx[mask][numpy.argmin(d[last_idx, mask])] path[k] = last_idx mask[last_idx] = False return path
8baffbf9292b3ebf97a6b2cf57ebc081ae069cb2
36,397
def project_exists(cur, key): """ Check whether the project exists in the database. """ project_data = cur.execute( "SELECT * FROM projects WHERE \"key\"=?", (key,) ).fetchone() if not project_data: return False, project_data return True, project_data
6aa16d6a419a203405787fa13b92f0b2b16dabe8
36,398
def get_shape_from_dims(axis_0, axis_1=None): """ Constructs a chain shape tuple from an array-like axis_0 and an optional array-like axis_1 :param axis_0: Iterable of dimensions for the first leg on each site of the chain :param axis_1: Optional iterable of dimensions for the second leg on each site of the chain (of the same size as axis_0) :return: chain shape tuple """ if axis_1 is None: return tuple([(dim, )for dim in axis_0]) else: assert len(axis_0) == len(axis_1) return tuple([(dim0, dim1) for dim0, dim1 in zip(axis_0, axis_1)])
3508654e6b94ab515bf1975755d95923775c4849
36,399
import string import random def random_port(length, alph=string.digits): """ Random text generator. NOT crypto safe. Generates random text with specified length and alphabet. """ port = ''.join(random.choice(alph) for _ in range(length)) if port.startswith('0'): port = '1'+port[1:] return port
1dcc3d6f45a5550a48c6ccf6c0a866a16ed353d7
36,402
import struct def get_table_idbb_field(endianess, data): """ Return data from a packed TABLE_IDB_BFLD bit-field. :param str endianess: The endianess to use when packing values ('>' or '<') :param str data: The packed and machine-formatted data to parse :rtype: tuple :return: Tuple of (proc_nbr, std_vs_mfg) """ bfld = struct.unpack(endianess + 'H', data[:2])[0] proc_nbr = bfld & 0x7ff std_vs_mfg = bool(bfld & 0x800) selector = (bfld & 0xf000) >> 12 return (proc_nbr, std_vs_mfg, selector)
1a692ec78a224eb7dd5c935dc63e5195799190fe
36,403
def R2K(degR): """degR -> degK""" return degR/1.8
93f5651e3f5aaaad67bf922dcb2204a51b626db3
36,404
def add_node(nodes, parent, time): """Adds a node with specified parent and creation time. This functions assumes that a node has been already allocated by "child" functions `add_node_classifier` and `add_node_regressor`. Parameters ---------- nodes : :obj:`Nodes` The collection of nodes. parent : :obj:`int` The index of the parent of the new node. time : :obj:`float` The creation time of the new node. Returns ------- output : `int` Index of the new node. """ node_index = nodes.n_nodes nodes.index[node_index] = node_index nodes.parent[node_index] = parent nodes.time[node_index] = time nodes.n_nodes += 1 return nodes.n_nodes - 1
d204d618114b13ffcbfc038c91884f4a87e743c0
36,405
from typing import List def merge(array1: List[int], array2: List[int]) -> List[int]: """Merges two arrays""" array = [] # Merged array first = second = 0 # Starting points while first < len(array1) and second < len(array2): if array1[first] > array2[second]: array.append(array2[second]) second += 1 elif array1[first] < array2[second]: array.append(array1[first]) first += 1 else: array.append(array1[first]) first += 1 array.append(array2[second]) second += 1 while first < len(array1): array.append(array1[first]) first += 1 while second < len(array2): array.append(array2[second]) second += 1 return array
fd646341f54d2ad8b9fc768e17337cd0a8213068
36,407
import sys def convert_network_drive_path( str_or_path, mapping=[("X:", "/Volumes/my_drive")] ): """ Convert network drive paths from those formatted for one OS into those formatted for another. (works for Windows <-> OSX) If a string that doesn't seem to represent a path in the other OS is given, it will be returned unchanged. Parameters: str_or_path: str string holding a filepath. mapping: list list of 2-tuples where 0th entry of each tuple is the name of a windows network drive location (e.g. "A:") and the 1st entry is OSX network drive location (e.g. "/Volumes/A"). Defaults to [("X:","/Volumes/my_folder")]. Returns: str_or_path: str string holding a converted filepath, or original in the case that no mapped network drive was found. Raises: Exception: When no mapping is given """ if not isinstance(str_or_path, str): return str_or_path if mapping: windows_drive_names = [pair[0].rstrip("\\") for pair in mapping] osx_drive_names = [pair[1].rstrip("/") for pair in mapping] else: raise Exception("No network drive mappings given") if sys.platform.startswith("win"): for i, name in enumerate(osx_drive_names): if str_or_path.startswith(name): str_or_path = str_or_path.replace( name, windows_drive_names[i] ).replace("/", "\\") break elif sys.platform.startswith("darwin"): for i, name in enumerate(windows_drive_names): if str_or_path.startswith(name): str_or_path = str_or_path.replace("\\", "/").replace( name, osx_drive_names[i] ) break return str_or_path
498ba85db9fefb0dc8efd8d0f22885b9005a1fb5
36,410
def crop_label_to_size(x1, x2): """ Crops x1 (labels shaped [batch, y, x]) to the x2's (logits shaped [batch, c, y, x]) size and concatenate the tensors across the channels. Is assumed that x1 is bigger than x2. The tensors have shape [batch, y, x] """ x_off = (x1.size()[2] - x2.size()[3]) // 2 y_off = (x1.size()[1] - x2.size()[2]) // 2 xs = x2.size()[3] ys = x2.size()[2] x = x1[:, y_off:y_off+ys, x_off:x_off+xs] return x
d1c51d919248e2b30245ecf668863a8d7053bb3d
36,413
def scale(y, yerr): """ Standardization of a given dataset y Parameters: y = data; subtract mean, divide by std yerr = errors; divide by std of x Returns: standardized y and yerr """ m, s = y.mean(), y.std() return (y-m)/s, yerr/s
5985fa930470d1535b4befde5878ce325f1dc86b
36,414
def isoforest_label_adjust(pred_func): """Adjusts isolation forest predictions to be 1 for outliers, 0 for inliers. By default the scikit-learn isolation forest returns -1 for outliers and 1 for inliers, so this method is used to wrap fit_predict or predict methods and return 0 for inliers, 1 for outliers. :param pred_func: Scikit-learn prediction function that returns a flat :class:`numpy.ndarray` of labels ``-1`` and ``1``. :type pred_func: function or method :rtype: function """ def adjust_pred_func(*args, **kwargs): res = pred_func(*args, **kwargs) res[res == -1] = 1 res[res == 1] = 0 return res return adjust_pred_func
11ac61f691404525a357a32e725c30dd2675a85a
36,415
def join_list(words: list, join_s: str): """ Take each strings in the list 'words' is joined in a single string spaced whit 'join_s' :param words: string to be joined :param join_s: spaced string :return: joined string """ return join_s.join(words)
cf7641ec81d7284c0ec6f65085567a572310d193
36,416
def write_gwosc_string(config, ifos, outdir): """ Write command string to execute bajes_read_gwosc.py given a config file """ read_string = 'bajes_read_gwosc.py --outdir {} '.format(outdir) try: read_string += '--event {} '.format(config['gw-data']['event']) except Exception: pass try: read_string += '--version {} '.format(config['gw-data']['version']) except Exception: pass for ifo in ifos: read_string += '--ifo {} '.format(ifo) read_string += '--seglen {} '.format(config['gw-data']['seglen']) read_string += '--srate {} '.format(config['gw-data']['srate']) read_string += '--t-gps {} '.format(config['gw-data']['t-gps']) return read_string
2c42d4956764b4328a92792cb6b6087fbb2daf57
36,417
def sum_two_smallest_numbers(numbers): """ Create a function that returns the sum of the two lowest positive numbers given an array of minimum 4 positive integers. No floats or non-positive integers will be passed. :param numbers: an array of 4 or more positive numbers. :return: the sum of the two smallest values in the array. """ return sum(sorted(numbers)[0:2])
e49ecf11e249c29fb0a1d051f0ff9e48fbde72ce
36,418
import gc import time def run_test(func, fobj): """Run func with argument fobj and measure execution time. @param func: function for test @param fobj: data for test @return: execution time """ gc.disable() try: begin = time.time() func(fobj) end = time.time() finally: gc.enable() return end - begin
c9851736cb5ad3886565fc3a06cb8ef2c2ee5478
36,420
def _CheckNoIn(input_api, output_api): """Checks that corpus tests don't contain .in files. Corpus tests should be .pdf files, having both can cause race conditions on the bots, which run the tests in parallel. """ results = [] for f in input_api.AffectedFiles(include_deletes=False): if f.LocalPath().endswith('.in'): results.append(output_api.PresubmitError( 'Remove %s since corpus tests should not use .in files' % f.LocalPath())) return results
814b7b52c59c373a3d7ec010f99b85d602b8dd02
36,421
import asyncio import functools def schedule_coroutine(delay, coro_func, *args, **kwargs): """ Creates a coroutine out of the provided coroutine function coro_func and the provided args and kwargs, then schedules the coroutine to be called on the running event loop after delay seconds (delay can be float or int). Returns asyncio.Task on which cancel() can be called to cancel the running of the coroutine. The coro_func parameter should not be a coroutine, but rather a coroutine function (a function defined with async). The reason for this is we want to defer creation of the actual coroutine until we're ready to schedule it with "ensure_future". Otherwise every time we cancel a TimerTask returned by "call_later", python prints "RuntimeWarning: coroutine '<coro-name>' was never awaited". """ # See method above for comment on "get_event_loop()" vs "get_running_loop()". loop = asyncio.get_event_loop() coro_partial = functools.partial(coro_func, *args, **kwargs) return loop.call_later(delay, lambda: asyncio.ensure_future(coro_partial()))
4df7fc85d20f15a5c1850f1d2d4b2645b22445cd
36,422
def pop_node_record(records): """Pops (removes and returns) a node record from the stack of records. Parameters ---------- records : Records A records dataclass containing the stack of node records Returns ------- output : tuple Outputs a tuple with eight elements containing the attributes of the node removed from the stack. There attributes are as follows: - parent : int, Index of the parent node - depth : int, Depth of the node in the tree - is_left : bool, True if the node is a left child, False otherwise - impurity : float, Impurity of the node. Used to avoid to split a "pure" node (with impurity=0). - start_train : int, Index of the first training sample in the node. We have that partition_train[start_train:end_train] contains the indexes of the node's training samples - end_train : int, End-index of the slice containing the node's training samples indexes - start_valid : int, Index of the first validation (out-of-the-bag) sample in the node. We have that partition_valid[start_valid:end_valid] contains the indexes of the node's validation samples - end_valid : int, End-index of the slice containing the node's validation samples indexes """ records.top -= 1 stack_top = records.stack[records.top] return ( stack_top["parent"], stack_top["depth"], stack_top["is_left"], stack_top["impurity"], stack_top["start_train"], stack_top["end_train"], stack_top["start_valid"], stack_top["end_valid"], )
2cc535ab444c7cb86a544ec2f98de176fcc546db
36,423
def convert_bcd_to_string(bytes=[]): """Convert the BCD bytes array to string >>> vals = [0x98, 0x68, 0x00, 0x90, 0x91, 0x11, 0x09, 0x00, 0x10, 0x80] >>> convert_bcd_to_string(vals) '89860009191190000108' """ ret_content = "" for i in range(0, len(bytes)): ret_content += str(bytes[i] & 0x0F) + str(bytes[i] >> 4) return ret_content
a2712ecdf50d5f28f54d6ba606692cc5266de890
36,424
def best_stock(a: dict) -> str: """ You are given the current stock prices. You have to find out which stocks cost more. Input: The dictionary where the market identifier code is a key and the value is a stock price. Output: The market identifier code (ticker symbol) as a string. """ new_stock = sorted(a.items(), key=lambda d: (d[1], d[0]), reverse=True) return new_stock[0][0]
ce96e91bc7741bb1ed64627c766aa46f5e18fa72
36,425
import os def find_tags_relative_to(path, tag_file): """ Find the tagfile relative to a file path. :param path: path to a file :param tag_file: name of tag file :returns: path of deepest tag file with name of ``tag_file`` """ if not path: return None dirs = os.path.dirname(os.path.normpath(path)).split(os.path.sep) while dirs: joined = os.path.sep.join(dirs + [tag_file]) if os.path.exists(joined) and not os.path.isdir(joined): return joined else: dirs.pop() return None
2d5682507070c3fcb7a98d05f037b83f8cc67e9e
36,426
import requests from bs4 import BeautifulSoup def sanitize_version(version, base): """ Ensure the version number we got is legit. Sometimes the upstream repository will delete old versions unexpectedly since you theoretically should not be using them anyway. This doesnt work for us so if that happens, stop the job before its to late. """ url = "%s/%s" % (base, version) r = requests.get(url) if r.status_code != 200: raise Exception("Verison URL %s is broken" % url) soup = BeautifulSoup(r.text, "html.parser") if len(soup.find_all('a')) < 5: raise Exception("This mirror has been deleted. You may need to " "find a legacy source.") return version
e5454f80191042d13117f481bdbfec91f1fcb36d
36,427
from typing import Sequence import re def _validate_against_blacklist(string: str, blacklist: Sequence[str]): """Validates a string against a regex blacklist.""" return not any(re.search(pattern, string, re.IGNORECASE) for pattern in blacklist)
7c1e3ca9b9b295d3927d8b516f0562a2a04858af
36,428
def cycles_per_trial(nwb): """Get the number of microscope cycles/trial. That is, the number of times each point is imaged in each trial. Currently looks at the first imaging timeseries in the first trial, and assumes they're all the same. """ trial1 = nwb['/epochs/trial_0001'] for ts_name in trial1: ts = trial1[ts_name] is_image_series = ts['timeseries/pixel_time_offsets'] is not None if is_image_series: return ts['count'].value else: raise ValueError('No imaging timeseries found')
dbe421716267669041ee654bb357426259ed2703
36,429
def format_name(f_name, l_name): """Take a first and last name and format it to return the title case version of the name. Args: f_name ([string]) l_name ([string]) Returns: f_name + l_name in title """ if f_name == "" or l_name == "": return "You not enter a valid name!" full_name = f"{f_name} {l_name}" return full_name.title()
59c7a9b135d0001c7bc1a378bbcbfb68a4dfa36a
36,431
def stringify_env(env): """ convert each key value pairs to strings in env list""" return dict(((str(key), str(val)) for key, val in env.items()))
36bb35053f07b2c3510c0abe70e9e6db0391a0e5
36,432
import re def parse_num(s): """Parse data size information into a float number. Here are some examples of conversions: 199.2k means 203981 bytes 1GB means 1073741824 bytes 2.1 tb means 2199023255552 bytes """ g = re.match(r'([-+\d.e]+)\s*(\w*)', str(s)) if not g: raise ValueError("can't parse %r as a number" % s) (val, unit) = g.groups() num = float(val) unit = unit.lower() if unit in ['t', 'tb']: mult = 1024*1024*1024*1024 elif unit in ['g', 'gb']: mult = 1024*1024*1024 elif unit in ['m', 'mb']: mult = 1024*1024 elif unit in ['k', 'kb']: mult = 1024 elif unit in ['', 'b']: mult = 1 else: raise ValueError("invalid unit %r in number %r" % (unit, s)) return int(num*mult)
721cc52cdf543bcaf3ff77d8059a7bfe6cb6d892
36,433
import jinja2 def converter(content, context): """ >>> converter('hello {{ name }}!', {'name': 'world'}) 'hello world!' """ return jinja2.Template(content).render(context)
df67cf82a66ae430cde7cff02315cfd7a4238cd9
36,435
def extractBlockStr(f, lastLine=None): """ read one block from a maf file handle and turn it into a single string """ if lastLine is None: block = '' else: block = lastLine + '\n' for line in f: line = line.strip() if line == '': return block + '\n' block += '%s\n' % line if block == '': return None else: return block + '\n'
356660cc1799b9ca2c9180e88eb6de7565228c92
36,437
def rstrip_line(line): """Removes trailing whitespace from a string (preserving any newline)""" if line[-1] == '\n': return line[:-1].rstrip() + '\n' return line.rstrip()
adb3b707ddb450996b1677e68ad1861a76313cc6
36,438
def split_sentence(text, punctuation_list='!?。!?'): """ 将文本段安装标点符号列表里的符号切分成句子,将所有句子保存在列表里。 """ sentence_set = [] inx_position = 0 # 索引标点符号的位置 char_position = 0 # 移动字符指针位置 for char in text: char_position += 1 if char in punctuation_list: next_char = list(text[inx_position:char_position + 1]).pop() if next_char not in punctuation_list: sentence_set.append(text[inx_position:char_position]) inx_position = char_position if inx_position < len(text): sentence_set.append(text[inx_position:]) sentence_with_index = {i: sent for i, sent in enumerate(sentence_set)} # dict(zip(sentence_set, range(len(sentences)))) return sentence_set, sentence_with_index
423fffa5fbe2efe3194f6468bd36503e9d8dc5ab
36,439
import inspect import typing def get_type(type): """ Helper function which converts the given type to a torchScript acceptable format. """ if isinstance(type, str): return type elif inspect.getmodule(type) == typing: # If the type is a type imported from typing # like Tuple, List, Dict then replace `typing.` # with a null string. This needs to be done since # typing.List is not accepted by TorchScript. type_to_string = str(type) return type_to_string.replace(type.__module__ + '.', '') elif type.__module__.startswith('torch'): # If the type is a subtype of torch module, then TorchScript expects a fully qualified name # for the type which is obtained by combining the module name and type name. return type.__module__ + '.' + type.__name__ else: # For all other types use the name for the type. return type.__name__
116e169107460cd0807257eef303d4959323319b
36,440
import operator def round_and_sort_dict(feat_imp: dict) -> list: """ Round and sort a dictionary :param dict feat_imp: A dictionary :return: - A sorted list """ # round importances for dict_key in feat_imp: feat_imp[dict_key] = round(feat_imp[dict_key]) # sort by importances sorted_x = sorted(feat_imp.items(), key=operator.itemgetter(1)) sorted_x.reverse() return sorted_x
f94881bcb246469573df4cae98aea9ae69d0cdb9
36,442
def get_commands_to_config_vrf(delta, vrf): """Gets commands to configure a VRF Args: delta (set): params to be config'd- created in nxos_vrf vrf (str): vrf name Returns: list: ordered list to config a vrf Note: Specific for Ansible module(s). Not to be called otherwise. """ commands = [] for param, value in delta: command = None if param == 'description': command = 'description ' + value elif param == 'admin_state': if value.lower() == 'up': command = 'no shutdown' elif value.lower() == 'down': command = 'shutdown' if command: commands.append(command) if commands: commands.insert(0, 'vrf context ' + vrf) return commands
76e13d480573cdc9ffde2e529853f5324592adb7
36,443
import functools def exception(function): """ If exception was specified for prepared_request, inject this into SMCRequest so it can be used for return if needed. """ @functools.wraps(function) def wrapper(*exception, **kwargs): result = function(**kwargs) if exception: result.exception = exception[0] return result return wrapper
c36bbfe11fa454a8ea9803df37aeb19ead752ccf
36,446
import math def lcm(x, y): """This function takes two integers and returns the L.C.M.""" lcm = (x*y)//math.gcd(x,y) return lcm
1f562e763dd08cb0fd3e586c5d510d0efa42c47f
36,447
def _get_cluster_data(cluster_analysis): """ Extracts the cluster analysis data into a format suitable for scatter plot with matplotlib Args: :cluster_analysis: Returns: data, colors, groups """ def _get_cluster(datapoint, clusters): return list(filter(lambda x: x.datapoint_name == datapoint.name, clusters))[0].cluster def _unique_clusters(clusters): return list(set(list(map(lambda x: x.cluster, clusters)))) all_colors = ["red", "green", "blue", "orange", "black", "purple", "green"] u_clusters = _unique_clusters(cluster_analysis.clusters) clusters = cluster_analysis.clusters data_points = cluster_analysis.datapoints colors = [] data = [] groups = [] for idx, cluster in enumerate(u_clusters): color = all_colors[idx] data_points_x = [] data_points_y = [] filtered_dps = list(filter(lambda dp: _get_cluster(dp, clusters) == cluster, data_points)) for dp in filtered_dps: data_points_x.append(dp.first_dimension) data_points_y.append(dp.second_dimension) colors.append(color) data.append((data_points_x, data_points_y)) groups.append("cluster " + str(cluster)) colors = tuple(colors) groups = tuple(groups) return data, colors, groups
14675293dfe474fd9ab6f59271f7a80636b3c11c
36,448
def get_table_a_1(): """表A.1 本算定方式が適用可能である空気集熱式太陽熱利用設備の種類 Args: Returns: list: 表A.1 本算定方式が適用可能である空気集熱式太陽熱利用設備の種類 """ table_a_1 = [ # 給湯部 | 自立運転用太陽光発電装置 # | 空気搬送ファン | 循環ポンプ (True, True, True), (True, False, True), (True, True, False), (True, False, False), (False, True, True), (False, False, True), (False, True, False), (False, False, False), ] return table_a_1
9b8c938ce9b23b5269cc575aa343b7d8075f9120
36,449
def prep(stg, ns="{http://www.topografix.com/GPX/1/1}"): """ This modifies the namespace path thingy so it works. I'm a bit hazy on exactly what's happening here, but this works so I'm going with it for now. This function could probably dispensed with if I deal with the namespace correctly. I should read the [lxml documentation](http://lxml.de/tutorial.html) better and also refer to [this post](http://stackoverflow.com/questions/37964570/read-gpx-using-lxml-and-xpath). [This post](http://stackoverflow.com/questions/18071387/read-gpx-using-python-elementtree-register-namespace) seems even more on topic. """ return ns + stg.replace("/","/"+ns)
3647579333c021d20782e88ac3dd33251f495f17
36,450
def pow_mod(a: int, b: int, p: int) -> int: """ Computes a^b mod p using repeated squaring. param a: int param b: int param p: int return: int a^b mod p """ result = 1 while b > 0: if b & 1: result = (result * a) % p a = (a * a) % p b >>= 1 return result
e84085c1ed5e4c9c321f42a3a6275537736789bc
36,451
import functools def get_latex_name(func_in, **kwargs): """ Produce a latex formatted name for each function for use in labelling results. Parameters ---------- func_in: function kwargs: dict, optional Kwargs for function. Returns ------- latex_name: str Latex formatted name for the function. """ if isinstance(func_in, functools.partial): func = func_in.func assert not set(func_in.keywords) & set(kwargs), ( 'kwargs={0} and func_in.keywords={1} contain repeated keys' .format(kwargs, func_in.keywords)) kwargs.update(func_in.keywords) else: func = func_in param_ind = kwargs.pop('param_ind', 0) probability = kwargs.pop('probability', 0.5) kwargs.pop('handle_indexerror', None) if kwargs: raise TypeError('Unexpected **kwargs: {0}'.format(kwargs)) ind_str = r'{\hat{' + str(param_ind + 1) + '}}' latex_name_dict = { 'count_samples': r'samples', 'logz': r'$\mathrm{log} \mathcal{Z}$', 'evidence': r'$\mathcal{Z}$', 'r_mean': r'$\overline{|\theta|}$', 'param_mean': r'$\overline{\theta_' + ind_str + '}$', 'param_squared_mean': r'$\overline{\theta^2_' + ind_str + '}$'} # Add credible interval names if probability == 0.5: cred_str = r'$\mathrm{median}(' else: # format percent without trailing zeros percent_str = ('%f' % (probability * 100)).rstrip('0').rstrip('.') cred_str = r'$\mathrm{C.I.}_{' + percent_str + r'\%}(' latex_name_dict['param_cred'] = cred_str + r'\theta_' + ind_str + ')$' latex_name_dict['r_cred'] = cred_str + r'|\theta|)$' try: return latex_name_dict[func.__name__] except KeyError as err: err.args = err.args + ('get_latex_name not yet set up for ' + func.__name__,) raise
1eb376cd597e78a4d7e7c1c0144fc904ffa3ea60
36,452
import socket def hostname(): """ The name as a simple string o the name of the current local machine. This value may or may not be a fully qualified domain name for the machine. The result of this function call is unpredictable and should not be trusted for critical operations. :rtype: String :return: The name as a string of the current local machine, the definition of this value varies. """ return socket.gethostname()
c9656d8738c271cd4ed4c9b7fc905804a1657e1e
36,453
import warnings def is_lfe(frequency): """Determine if a channel is an LFE channel from its frequency metadata. This issues a warning if there is frequency information available but it is not recognised as specifying an LFE channel. Args: frequency (Frequency): Frequency info from channelFormat. Returns: bool """ if (frequency.lowPass is not None and frequency.lowPass <= 200 and frequency.highPass is None): return True else: if frequency.lowPass is not None or frequency.highPass is not None: warnings.warn("Not treating channel with frequency {!r} as LFE.".format(frequency)) return False
4eb149f34d40ef39adbb783c3333e577414021e7
36,454
import gzip def mock_request_get(*args, **kwargs): """Mock request.get() result for SV VCF ingestion.""" class MockContent: @property def content(self): """ """ file_contents = ( "##fileformat=VCFv4.0" "\n##fileDate=20210801" '\n##INFO=<ID=NS,Number=1,Type=Integer,Description="Number of Samples' ' With Data">' '\n##FORMAT=<ID=GT,Number=1,Type=String,Description="Genotype">' "\n#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT" "\tNA12879_sample\tNA12878_sample\tNA12877_sample" "\nchr1\t31908111\trs6054257\tG\tA\t108\tPASS\tNS=3\tGT\t0/0\t0/1\t0/0" ) file_contents = file_contents.encode("utf-8") content = gzip.compress(file_contents) return content return MockContent()
8ee239c2aee8bc8d2f10c3b3a7780b081423d85e
36,455
import yaml def create_blacklist(config_file): """ Generate a list of images which needs to be excluded from docker_image_list :param config_file: application_configuration file where images are. :return: """ with open(config_file, 'r') as f: file = yaml.load(f, Loader=yaml.SafeLoader) blacklist=[] for name, _ in file['runtime_images'].items(): path = file['runtime_images'][name]['path'] blacklist.append(path[1:]) return blacklist
9d0b7ae78b83670f06390abb43d2b19d3f3342e0
36,456
def join_segments_raw(segments): """Make a string from the joined `raw` attributes of an iterable of segments.""" return "".join(s.raw for s in segments)
ba2f3d1157ee505daaec3919c4e70ad6e49e5db2
36,457
import sys def validate_user(): """ validate the users ID """ try: user_id = int(input('\n Enter a customer id <Example 1 for user_id 1>: ')) if user_id < 0 or user_id > 3: print("\n Invalid customer number, program terminated...\n") sys.exit(0) return user_id except ValueError: print("\n Invalid number, program terminated...\n") sys.exit(0)
b67fe3326b1138582a940ddb198ab2da66034270
36,459
def arrstrip(arr): """ Strip beginning and end blanklines of an array """ if not arr[0]: arr.pop(0) if not arr[-1]: arr.pop() return arr
cd79ce4fe12c864e0b57f1513962e3123e291b8d
36,460
import os def find_unused_pages(referenced_pages, source_root_folder): """Returns any source help files in source_root_folder missing from the referenced_pages list. """ all_pages = [page for page in os.listdir(source_root_folder) if page.endswith(".txt") and page != "contents.txt"] return [page for page in all_pages if page not in referenced_pages]
c2e3aea1dc2d11ae611e10d726123d81e28e655d
36,461
def evaluate_part_two(expression: str) -> int: """Solve the expression giving preference to additions over multiplications""" while "+" in expression: expression_list = expression.split() i = expression_list.index("+") new_expression = str() for j, char in enumerate(expression_list): if j in [i, i - 1]: pass elif j == i + 1: new_expression += str(eval(f"{expression_list[i - 1]} + {expression_list[i + 1]}")) + " " else: new_expression += char + " " expression = new_expression.strip() return eval(expression)
5e9a28a0ca079abcfc364ce3085dbfd3ef3a695e
36,463
import torch def label2string(itow, label, start_idx=2, end_idx=3): """ Convert labels to string (question, caption, etc) Args: itow: dictionry for mapping index to word; dict() label: index of labels """ if isinstance(label, torch.Tensor): label = label.detach().cpu().numpy().squeeze() if label.ndim == 0: if label == end_idx: return itow[str(end_idx)] else: return itow[str(label)] assert label.ndim == 1, "{}".format(label.ndim) txt = [] for l in label: if l == start_idx: continue if l == end_idx: break else: txt.append(itow[str(l)]) return " ".join(txt).strip()
a5014edb313792d4de7f4f5e55df927ca039a89b
36,464
import math import cmath def qlrps(fmhz, zsys, en0, ipol, eps, sgm): """ General preparatory subroutine as in Section 41 by Hufford (see references/itm.pdf). Parameters ---------- fmhz : int Carrier frequency. en0 : Surface refractivity reduced to sea level. zsysz : General system elevation. eps : Polarization. sgm : Ground constants. wn : Wave number ens : Surface refractivity. gme : Effective earth curvature. zgnd : Surface impedance. """ gma = 157e-9 wn = fmhz / 47.7 ens = en0 if zsys != 0: ens = ens * math.exp(-zsys / 9460) gme = gma * (1 - 0.04665 * math.exp(ens / 179.3)) zq = complex(eps, 376.62 * sgm / wn) zgnd = cmath.sqrt(zq - 1) if ipol != 0: zgnd = zgnd / zq return wn, gme, ens, zgnd
761ccf8404bea313609969edfccb0cada5f1a46d
36,465
def markdown_image(url): """Markdown image markup for `url`.""" return '![]({})'.format(url)
df17ec7e51b8b5ad10e1e489dd499aa840dbc45b
36,467
def turn_inputs(): """ yield inputs for a single turn """ my_score, opponent_score = [int(i) for i in input().split()] scores = {'me': my_score, 'opponent': opponent_score} visible_pac_count = int(input()) # all your pacs and enemy pacs in sight pacs = {} my_pacs = {} enemy_pacs = {} for i in range(visible_pac_count): pac_id, mine, x, y, type_id, speed_turns_left, ability_cooldown = input().split() pac_id = int(pac_id) mine = mine != "0" x = int(x) y = int(y) speed_turns_left = int(speed_turns_left) ability_cooldown = int(ability_cooldown) pacman = {'coords': (x, y), 'type': type_id, 'boost': speed_turns_left, 'cooldown': ability_cooldown} if mine == 1: my_pacs[pac_id] = pacman else: enemy_pacs[pac_id] = pacman pacs['friends'] = my_pacs pacs['enemies'] = enemy_pacs visible_pellet_count = int(input()) # all pellets in sight pellets = [] for i in range(visible_pellet_count): pellets.append(tuple([int(j) for j in input().split()])) return scores, pacs, pellets
c09447e03506302f0f7fc4187be50cd2ba69c069
36,468
import platform def operating_system(): """Return a string identifying the operating system the application is running on. :rtype: str """ return '%s %s (%s)' % (platform.system(), platform.release(), platform.version())
a68f2161567a825b120bf4df61a24c4541fa05e7
36,469
def get_sentence(sentence_tag, word_sep=' ', pos_sep='/'): """ 文本拼接 :param sentence_tag: :param word_sep: :param pos_sep: :return: """ words = [] for item in sentence_tag.split(word_sep): if pos_sep in item: index = item.rindex(pos_sep) words.append(item[:index]) else: words.append(item.strip()) return word_sep.join(words)
d53fd544cfafcfd198e84c3fb02d835444736f50
36,470
def task_exists(twarrior, task_name: str) -> bool: """ Check if task exists before inserting it in Task Warrior. """ tasks = twarrior.load_tasks() for key in tasks.keys(): for task in tasks[key]: if task['description'] == task_name: return True return False
1a5dbd790b11492c7417b7611c7f62af544a7862
36,471
def get_bytes_from_file(filename, num_bytes): """ :param filename : The file to be read. :param num_bytes : number of bytes to read. :returns: The first num_bytes from the file. """ try: fd = open(filename, 'r') bytes_read = fd.read(num_bytes) fd.close() except IOError: return None return bytes_read
45c136a38b5c49d2b71dc221499f2848f99413fc
36,472
from threading import Thread import functools def timeout(timeout): """ Refer to https://stackoverflow.com/questions/21827874/timeout-a-function-windows Usage func = timeout(timeout=XXX)(My_Function) try: func() except: pass or @timeout(XX) def My_Function : .... """ def deco(func): @functools.wraps(func) def wrapper(*args, **kwargs): res = [Exception('function [%s] timeout [%s seconds] exceeded!' % (func.__name__, timeout))] def newFunc(): try: res[0] = func(*args, **kwargs) except Exception as e: res[0] = e t = Thread(target=newFunc) t.daemon = True try: t.start() t.join(timeout) except Exception as je: print ('error starting thread') raise je ret = res[0] if isinstance(ret, BaseException): raise ret return ret return wrapper return deco
31ddd308bc54b1c76435ef6cd48f691ce12882d6
36,474
import socket import os import stat import secrets def bind_unix_socket(path: str, *, mode=0o666, backlog=100) -> socket.socket: """Create unix socket. :param path: filesystem path :param backlog: Maximum number of connections to queue :return: socket.socket object """ """Open or atomically replace existing socket with zero downtime.""" # Sanitise and pre-verify socket path path = os.path.abspath(path) folder = os.path.dirname(path) if not os.path.isdir(folder): raise FileNotFoundError(f"Socket folder does not exist: {folder}") try: if not stat.S_ISSOCK(os.stat(path, follow_symlinks=False).st_mode): raise FileExistsError(f"Existing file is not a socket: {path}") except FileNotFoundError: pass # Create new socket with a random temporary name tmp_path = f"{path}.{secrets.token_urlsafe()}" sock = socket.socket(socket.AF_UNIX) try: # Critical section begins (filename races) sock.bind(tmp_path) try: os.chmod(tmp_path, mode) # Start listening before rename to avoid connection failures sock.listen(backlog) os.rename(tmp_path, path) except: # noqa: E722 try: os.unlink(tmp_path) finally: raise except: # noqa: E722 try: sock.close() finally: raise return sock
f2396544c08ef256965968455a2746d126fa649e
36,475
def fibonacci(number): """ return the nth fibonacci number """ number = int(number) if number <= 1: return 1 return fibonacci(number-1)+fibonacci(number-2)
82700359ef9ff58fde7900a1c958aa6c601f8785
36,476
def source_code(): """Get the source code of this script.""" with open(__file__, 'rb') as f: return f.read()
a4143309017b56383fc16b877d24d816bbeae38f
36,477
def select_coefs(model_coefs, idx): """ Auxiliary function for compute_couplings(). Used to select the desired subvector/submatrix from the vector/matrix of model coefficients. """ if len(model_coefs.shape) == 1: # Binomial case sel_coefs = model_coefs[range(idx, idx + 20)] else: # Multinomial case sel_coefs = model_coefs[:, range(idx, idx + 20)] return sel_coefs, idx + 20
b8a90fa20c5dc4ff9630291466eeaaea2f44046b
36,479
def get_neptune_params(FLAGS, callbacks=[]): """ :param FLAGS: :param callbacks: :return: """ neptune_params = { "project_name": FLAGS.setup.project_name, "experiment_name": FLAGS.setup.experiment_name, "tags": FLAGS.setup.tags.rstrip(',').split(','), "params": {**FLAGS.experiment, **FLAGS.trainer}, "callbacks": [type(cb).__name__ for cb in callbacks], "close_after_fit": False } return neptune_params
8e109bd92edf481b21b826dca273db8f33716593
36,480
def str_is_empty_or_space(s): """Checks if a string from a form submitted via a web page *looks like or is* an empty string. At one stage this was called a 'perceptual null'. """ if s: # A string isn't empty if it is at least one character long # A string doesn't look empty if it is not entirely composed of # whitespace. if (len(s) > 0) & (s.isspace() == False): return False else: return True
748514e17a9a8d7aa94e3a23ea219ec99645b9a6
36,481