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 0x7... | 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.
"""
... | 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 qu... | 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"... | 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... | 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 i... | 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... | 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... | 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 i... | 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... | 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 ... | 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 = ''
# ! 短除法,用于解决进制转换问题
... | 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... | 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_i... | 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... | 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 ind... | 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_element... | 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... | 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,
... | 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 th... | 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
"""
fil... | 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
retu... | 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] = Fals... | 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 sit... | 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:]
re... | 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)
""... | 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 node... | 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... | 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 ... | 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
... | 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 outli... | 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 Exce... | 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 s... | 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.... | 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().en... | 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 fl... | 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 containin... | 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[... | 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 =... | 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(o... | 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 hap... | 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 ... | 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 va... | 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:
r... | 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'
... | 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... | 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... | 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 im... | 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 otherwi... | 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:
... | 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.datap... | 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),
(Tr... | 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 shoul... | 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
ret... | 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... | 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: ... | 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 channelFor... | 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"
... | 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)... | 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 ... | 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 != "... | 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_li... | 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().... | 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 :
... | 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 =... | 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(it... | 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 Fals... | 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 IOErr... | 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 :
...... | 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 re... | 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: #... | 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": {*... | 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... | 748514e17a9a8d7aa94e3a23ea219ec99645b9a6 | 36,481 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.