content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def cisco_ios_l3_acl_parsed():
"""Cisco IOS L3 Interface with ip address, acl, description and vlan."""
vlan = Vlan(id="300", encapsulation="dot1Q")
ipv4 = IPv4(address="10.3.3.13", mask="255.255.255.128")
acl_in = ACL(name="Common_Client_IN", direction="in")
acl_out = ACL(name="TEST_ACL_03", direct... | 20,100 |
def brillance(p, g, m = 255):
"""
p < 0 : diminution de la brillance
p > 0 : augmentation de la brillance
"""
if (p + g < m + 1) and (p + g > 0):
return int(p + g)
elif p + g <= 0:
return 0
else:
return m | 20,101 |
def fetch_fact():
"""Parse the command parameters, validate them, and respond.
Note: This URL must support HTTPS and serve a valid SSL certificate.
"""
# Parse the parameters you need
token = request.form.get('token', None) # TODO: validate the token
command = request.form.get('command', None)
... | 20,102 |
def payback(request):
"""
微信支付回调函数
:param request:
:return:
"""
return HttpResponse('payback') | 20,103 |
def get_index_shares(name, end_date=None):
"""获取某一交易日的指数成分股列表
symbols = get_index_shares("上证50", "2019-01-01 09:30:00")
"""
if not end_date:
end_date = datetime.now().strftime(date_fmt)
else:
end_date = pd.to_datetime(end_date).strftime(date_fmt)
constituents = get_history_const... | 20,104 |
def erfcx(x):
"""Elementwise scaled complementary error function.
.. note::
Forward computation in CPU cannot be done if
`SciPy <https://www.scipy.org/>`_ is not available.
Args:
x (:class:`~chainer.Variable` or :ref:`ndarray`): Input variable.
Returns:
~chainer.Variable... | 20,105 |
def fetch_data_async(blob, start_index, end_index, rpc=None):
"""Asynchronously fetches data for a blob.
Fetches a fragment of a blob up to `MAX_BLOB_FETCH_SIZE` in length. Attempting
to fetch a fragment that extends beyond the boundaries of the blob will return
the amount of data from `start_index` until the ... | 20,106 |
def get_legal_moves(color, size, board):
"""
Get Legal Moves
"""
legal_moves = {}
for y in range(size):
for x in range(size):
reversibles = get_reversibles(color, size, board, x, y)
if reversibles:
legal_moves[(x, y)] = reversibles
return legal_... | 20,107 |
def cleanup_duplicate_residuals(task):
"""Cleans the duplicate attributes in the hierarchy
:param task: The top task in the hierarchy
:return:
"""
try:
delattr(task, 'duplicate')
except AttributeError:
pass
for child in task.children:
cleanup_duplicate_residuals(chi... | 20,108 |
def edition(self, key, value):
"""Translates edition indicator field."""
sub_a = clean_val("a", value, str)
if sub_a:
return sub_a.replace("ed.", "")
raise IgnoreKey("edition") | 20,109 |
async def help(ctx):
"""
Sends a embeded message specifing all the commands currently there
"""
embed = discord.Embed(
colour=discord.Colour.red(),
title="--SongBird--",
description=
"Bot Prefix is - (dash)\n This is a Simple Discord Bot to send Memes & Play Songs\n ",
... | 20,110 |
def get_site_data(hostname: str) -> SiteData:
"""Get metadata about a site from the API"""
url = f"https://{hostname}/w/api.php"
data = dict(
action="query",
meta="siteinfo",
siprop="|".join(
[
"namespaces",
"namespacealiases",
... | 20,111 |
def clear_monitor(nodenet_uid, monitor_uid):
"""Leaves the monitor intact, but deletes the current list of stored values."""
micropsi_core.runtime.get_nodenet(nodenet_uid).get_monitor(monitor_uid).clear()
return True | 20,112 |
def loadGrammarFrom(filename, data=None):
"""Return the text of a grammar file loaded from the disk"""
with open(filename, 'r') as f:
text = f.read()
lookup = mako.lookup.TemplateLookup(directories=[relativePath('grammars')])
template = mako.template.Template(text, lookup=lookup)
#
base_... | 20,113 |
def create_generator_selfatt(generator_inputs, generator_outputs_channels, flag_I=True):
"""
Add Conditional Self-Attention Modual to the U-Net Generator.
By default, 256x256 => 256x256
Args:
generator_inputs: a tensor of input images, [b, h, w, n], with each pixel value [-1, 1].
generator_... | 20,114 |
def unsubscribe():
"""
Remove broken connection from subscribers list.
"""
client_lock.acquire()
print("Unsubscribing")
del clients[request.sid]
client_lock.release() | 20,115 |
def by_tag(articles_by_tag, tag):
""" Filter a list of (tag, articles) to list of articles by tag"""
for a in articles_by_tag:
if a[0].slug == tag:
return a[1] | 20,116 |
def experiment(dataset='SUPPORT', quantiles=(0.25, 0.5, 0.75), prot_att='race',
groups=('black', 'white'), model='dcm', adj='KM',
cv_folds=5, seed=100, hyperparams=None, plot=True, store=False):
"""Top level interface to train and evaluate proposed survival models.
This is the top le... | 20,117 |
def _rmse(orig_score, rep_core, pbar=False):
"""
Helping function returning a generator to determine the Root Mean Square Error (RMSE) for all topics.
@param orig_score: The original scores.
@param rep_core: The reproduced/replicated scores.
@param pbar: Boolean value indicating if progress bar sho... | 20,118 |
def cli_gb_list_grades(session, out):
"""List assignments"""
try:
gList = session.query(Grade).all()
for g in gList:
out.write(
'''Student: {0.student.name}
Assignment: {0.assignment.name}
Grade: {0.grade}
Notes:
{0.notes}\n\n'''.format(g))
except:
pass | 20,119 |
def ldns_str2rdf_type(*args):
"""LDNS buffer."""
return _ldns.ldns_str2rdf_type(*args) | 20,120 |
def scramble(password, message):
"""scramble message with password"""
scramble_length = 20
sha_new = partial(hashlib.new, 'sha1')
if not password:
return b''
stage1 = sha_new(password).digest()
stage2 = sha_new(stage1).digest()
buf = sha_new()
buf.update(message[:scramble_length... | 20,121 |
def print_twoe(twoe, nbf):
"""Print the two-electron values."""
ij = 0
for i in range(nbf):
for j in range(i + 1):
ij += 1
kl = 0
for k in range(nbf):
for l in range(k + 1):
kl += 1
if ij >= kl and abs(twoe[i... | 20,122 |
def dp_port_id(switch: str, port: str) -> str:
"""
Return a unique id of a DP switch port based on switch name and port name
:param switch:
:param port:
:return:
"""
return 'port+' + switch + ':' + port | 20,123 |
def request_item(zip_code, only_return_po_boxes=False, spatial_reference='4326'):
"""
Request data for a single ZIP code, either routes or PO boxes.
Note that the spatial reference '4326' returns latitudes and longitudes of results.
"""
url = BASE_URL.format(
zip_code=str(zip_code),
... | 20,124 |
def data_from_file(fname):
"""Function which reads from the file and yields a generator"""
file_iter = open(fname, 'rU')
for line in file_iter:
line = line.strip().rstrip(',') # Remove trailing comma
record = frozenset(line.split(','))
yield record | 20,125 |
def test_cache_manager_contains():
"""Test that CacheManager contains returns whether named cache exists."""
settings = {str(n): {} for n in range(5)}
cacheman = CacheManager(settings)
for name in settings.keys():
assert name in cacheman | 20,126 |
def write_css_files():
"""Make a CSS file for every module in its folder"""
for mdl in sheet.modules:
mdl.write_css() | 20,127 |
def smoothen_histogram(hist: np.array) -> np.array:
""" Smoothens a histogram with an average filter.
The filter as defined as multiple convolutions
with a three-tap box filter [1, 1, 1] / 3.
See AOS section 4.1.B.
Args:
hist: A histogram containing gradient orientation counts.
... | 20,128 |
def end_point(min_radius: float, max_radius: float) -> Tuple[int, int]:
"""
Generate a random goal that is reachable by the robot arm
"""
# Ensure theta is not 0
theta = (np.random.random() + np.finfo(float).eps) * 2 * np.pi
# Ensure point is reachable
r = np.random.uniform(low=min_ra... | 20,129 |
def expand_tile(value, size):
"""Add a new axis of given size."""
value = tf.convert_to_tensor(value=value, name='value')
ndims = value.shape.ndims
return tf.tile(tf.expand_dims(value, axis=0), [size] + [1]*ndims) | 20,130 |
def test_list_base64_binary_pattern_3_nistxml_sv_iv_list_base64_binary_pattern_4_3(mode, save_output, output_format):
"""
Type list/base64Binary is restricted by facet pattern with value
[a-zA-Z0-9+/]{48} [a-zA-Z0-9+/]{72} [a-zA-Z0-9+/]{52}
[a-zA-Z0-9+/]{48} [a-zA-Z0-9+/]{12} [a-zA-Z0-9+/]{72}
[a-zA... | 20,131 |
def truv2df_main(args):
"""
Main entry point for running DataFrame builder
"""
args = parse_args(args)
out = None
if args.vcf:
out = vcf_to_df(args.directory, args.info, args.format)
else:
vcfs = get_files_from_truvdir(args.directory)
all_dfs = []
for key in ... | 20,132 |
def parse_header(
info: Mapping[str, Any],
field_meta_data: Mapping[str, FieldMetaData],
component_meta_data: Mapping[str, ComponentMetaData]
) -> Mapping[str, MessageMemberMetaData]:
"""Parse the header.
Args:
info (Mapping[str, Any]): The header.
field_meta_data (Mappi... | 20,133 |
def amina_choo(update, context): #3.2.1
"""Show new choice of buttons"""
query = update.callback_query
bot = context.bot
keyboard = [
[InlineKeyboardButton("Yes", callback_data='0'),
InlineKeyboardButton("No", callback_data='00')],
[InlineKeyboardButton("Back",callback_data='3.... | 20,134 |
def test_validate_cidr():
"""Test ``validate_cidr()``."""
# IPv4
assert validate_cidr('0.0.0.0/0')
assert validate_cidr('1.2.3.4/32')
# IPv6
assert validate_cidr('::/0')
assert validate_cidr('fe8::/10')
# Bad
assert not validate_cidr('bogus')
assert not validate_cidr(None)
... | 20,135 |
def lighten(data, amt=0.10, is255=False):
"""Lighten a vector of colors by fraction `amt` of remaining possible intensity.
New colors are calculated as::
>>> new_colors = data + amt*(1.0 - data)
>>> new_colors[:, -1] = 1 # keep all alpha at 1.0
Parameters
----------
data : matplot... | 20,136 |
def _determine_function_name_type(node):
"""Determine the name type whose regex the a function's name should match.
:param node: A function node.
:returns: One of ('function', 'method', 'attr')
"""
if not node.is_method():
return 'function'
if node.decorators:
decorators = node.... | 20,137 |
def print_top_videos(videos: List[ResultItem], num_to_print: int = 5):
"""Prints top videos to console, with details and link to video."""
for i, video in enumerate(videos[:num_to_print]):
title = video.title
views = video.views
subs = video.num_subscribers
link = video.video_url... | 20,138 |
def find_egl_engine_windows(association: str) -> Optional[UnrealEngine]:
"""Find Epic Games Launcher engine distribution from EngineAssociation string."""
if platform.system() != "Windows":
return None
if os.path.isfile(DAT_FILE):
with open(DAT_FILE, encoding="utf-8") as _datfile:
... | 20,139 |
def create_dataset(
template_path:
str = 'com_github_corypaik_coda/projects/coda/data/coda/templates.yaml',
objects_path:
str = 'com_github_corypaik_coda/projects/coda/data/coda/objects.jsonl',
annotations_path:
str = 'com_github_corypaik_coda/projects/coda/data/coda/annotations.jsonl',
seed... | 20,140 |
def escape_blog_content(data):
"""Экранирует описание блога."""
if not isinstance(data, binary):
raise ValueError('data should be bytes')
f1 = 0
f2 = 0
# Ищем начало блока
div_begin = b'<div class="blog-description">'
f1 = data.find(b'<div class="blog-content text">')
if f1 >= 0... | 20,141 |
def deleteMatches():
"""Remove all the match records from the database."""
DB = connect()
c = DB.cursor()
c.execute("DELETE FROM matches")
DB.commit()
DB.close() | 20,142 |
def read_csv(file_path, delimiter=",", encoding="utf-8"):
"""
Reads a CSV file
Parameters
----------
file_path : str
delimiter : str
encoding : str
Returns
-------
collection
"""
with open(file_path, encoding=encoding) as file:
data_in = list(csv.reader(file, ... | 20,143 |
def test_shuffle_05():
"""
Test shuffle: buffer_size > number-of-rows-in-dataset
"""
logger.info("test_shuffle_05")
# define parameters
buffer_size = 13
seed = 1
# apply dataset operations
data1 = ds.TFRecordDataset(DATA_DIR, shuffle=ds.Shuffle.FILES)
ds.config.set_seed(seed)
... | 20,144 |
def delete_ipv6_rule(group, address, port):
""" Remove the IP address/port from the security group """
ec2.revoke_security_group_ingress(
GroupId=group['GroupId'],
IpPermissions=[{
'IpProtocol': "tcp",
'FromPort': port,
'ToPort': port,
'Ipv6Ranges... | 20,145 |
def get_cmd_items(pair: Tuple[str, Path]):
"""Return a list of Albert items - one per example."""
with open(pair[-1], "r") as f:
lines = [li.strip() for li in f.readlines()]
items = []
for i, li in enumerate(lines):
if not li.startswith("- "):
continue
desc = li.ls... | 20,146 |
def save_excels(excel_metrics, excel_models):
"""It saves the excels with the information"""
default_sheet_metrics = excel_metrics.book[excel_metrics.book.sheetnames[0]]
excel_metrics.book.remove(default_sheet_metrics)
excel_metrics.save()
excel_metrics.close()
default_sheet_models = excel_mode... | 20,147 |
def init_environment(config):
"""Load the application configuration from the specified config.ini
file to allow the Pylons models to be used outside of Pylons."""
config = paste.deploy.appconfig('config:' + config)
herder.config.environment.load_environment(
config.global_conf, config.local_co... | 20,148 |
def import_activity_class(activity_name, reload=True):
"""
Given an activity subclass name as activity_name,
attempt to lazy load the class when needed
"""
try:
module_name = "activity." + activity_name
importlib.import_module(module_name)
return True
except ImportError a... | 20,149 |
def rgb2hsv(rgb):
"""
Reverse to :any:`hsv2rgb`
"""
eps = 1e-6
rgb = np.asarray(rgb).astype(float)
maxc = rgb.max(axis=-1)
minc = rgb.min(axis=-1)
v = maxc
s = (maxc - minc) / (maxc + eps)
s[maxc <= eps] = 0.0
rc = (maxc - rgb[:, :, 0]) / (maxc - minc + eps)
gc = (maxc - ... | 20,150 |
def tile_wcrs(graph_or_subgraph: GraphViewType,
validate_all: bool,
prefer_partial_parallelism: bool = None) -> None:
"""
Tiles parallel write-conflict resolution maps in an SDFG, state,
or subgraphs thereof. Reduces the number of atomic operations by tiling
and introducing t... | 20,151 |
def pandas_candlestick_ohlc(dat, stick = "day", otherseries = None):
"""
:param dat: pandas DataFrame object with datetime64 index, and float columns "Open", "High", "Low", and "Close", likely created via DataReader from "yahoo"
:param stick: A string or number indicating the period of time covered by a sin... | 20,152 |
def execute_cgx(infile):
"""Run CGX with the batch input file to generate the mesh output files."""
if LOCAL_EXECUTES["CGX"]:
subprocess.run(
LOCAL_EXECUTES["CGX"] + " -bg " + infile.parts[-1],
cwd=infile.parent,
shell=True,
check=True,
capture... | 20,153 |
def fig_colorbar(fig, collections, *args, **kwargs):
"""Add colorbar to the right on a figure."""
fig.subplots_adjust(right=0.8)
cax = fig.add_axes([0.85, 0.15, 0.05, 0.7])
cbar = fig.colorbar(collections, cax, *args, **kwargs)
plt.pause(0.1)
return cbar | 20,154 |
def _merge_css_item(item):
"""Transform argument into a single list of string values."""
# Recurse lists and tuples to combine into single list
if isinstance(item, (list, tuple)):
return _merge_css_list(*item)
# Cast to string, be sure to cast falsy values to ''
item = "{}".format(item) if i... | 20,155 |
def register_x509_certificate_alg(cert_algorithm):
"""Register a new X.509 certificate algorithm"""
if _x509_available: # pragma: no branch
_certificate_alg_map[cert_algorithm] = (None, SSHX509CertificateChain)
_x509_certificate_algs.append(cert_algorithm) | 20,156 |
def write_Stations_grid(grd, filename='roms_sta_grd.nc'):
"""
write_Stations_grid(grd, filename)
Write Stations_CGrid class on a NetCDF file.
"""
Sm = grd.hgrid.x_rho.shape[0]
# Write Stations grid to file
fh = nc.Dataset(filename, 'w')
fh.Description = 'Stations grid'
fh.Author =... | 20,157 |
def extract_arguments(start, string):
""" Return the list of arguments in the upcoming function parameter closure.
Example:
string (input): '(blocks, threads, 0, THCState_getCurrentStream(state))'
arguments (output):
'[{'start': 1, 'end': 7},
{'start': 8, 'end': 16},
... | 20,158 |
def play_game():
"""
Play a sample game between two UCT players where each player gets a different number of UCT iterations.
"""
board = chess.Board()
board.reset()
print(chess.svg.board(board))
state = ChessState(board=board, side_to_move=board.turn)
while state.get_moves():
pr... | 20,159 |
def augment_img(img):
"""Data augmentation with flipping and rotation"""
# TODO: Rewrite with torchvision transform
flip_idx = np.random.choice([0, 1, 2])
if flip_idx != 0:
img = np.flip(img, axis=flip_idx)
rot_idx = int(np.random.choice([0, 1, 2, 3]))
img = np.rot90(img, k=rot_idx, axes... | 20,160 |
def iter_archive(path, method):
"""Iterate over an archive.
Args:
path: `str`, archive path
method: `tfds.download.ExtractMethod`, extraction method
Returns:
An iterator of `(path_in_archive, f_obj)`
"""
return _EXTRACT_METHODS[method](path) | 20,161 |
def unfoldPath(cwd, path):
"""
Unfold path applying os.path.expandvars and os.path.expanduser.
Join 'path' with 'cwd' in the beginning If 'path' is not absolute path.
Returns normalized absolute path.
"""
if not path:
return path
path = _expandvars(path)
path = _expanduser(path... | 20,162 |
def readConfig(config):
"""
This function reads configuration file and combine it with parameters from
console input to generate the configuration list.
Args:
* config: configuration file to be readed
Options:
* keyfile (-k): str, path to a file containing the random data used as k... | 20,163 |
def main(argv):
"""Decide whether the needed jobs got satisfactory results."""
inputs = parse_inputs(
raw_allowed_failures=argv[1],
raw_allowed_skips=argv[2],
raw_jobs=argv[3],
)
jobs = inputs['jobs'] or {}
jobs_allowed_to_fail = set(inputs['allowed_failures'] or [])
jo... | 20,164 |
def get_predictions(logits):
"""
Convert logits into softmax predictions
"""
probs = F.softmax(logits, dim=1)
confidence, pred = probs.max(dim=1, keepdim=True)
return confidence, pred, probs | 20,165 |
def test_parse_boolean():
"""TEST 1.2: Parsing single booleans.
Booleans are the special symbols #t and #f. In the ASTs they are
represented by Python's True and False, respectively."""
assert_equals(True, parse('#t'))
assert_equals(False, parse('#f')) | 20,166 |
def post_to_sns(aws_access_key: str, aws_secret_key: str, sns_topic_arn: str,
message_subject: str, message_body: str):
"""Post a message and subject to AWS SNS
Args:
aws_access_key: The AWS access key your bot will use
aws_secret_key: The AWS secret access key
sns_topic_arn: The SN... | 20,167 |
def lookup_capacity(lookup_table, environment, cell_type, frequency, bandwidth,
generation, site_density):
"""
Use lookup table to find capacity by clutter environment geotype,
frequency, bandwidth, technology generation and site density.
"""
if (environment, cell_type, frequency, bandwidth, ge... | 20,168 |
def contig_slow(fn, num):
"""brute force, quadratic"""
data = parse(fn)
for i in range(len(data)-2):
for j in range(i + 2, len(data)-1):
s = sum(data[i:j])
if s == num:
return min(data[i:j]) + max(data[i:j]) | 20,169 |
def secretmap(ctx):
"""
Encrypt, decrypt, and edit files.
\f
:return: Void
:rtype: ``None``
"""
ctx.obj = Keychain() | 20,170 |
def handle_pair(pair, blackpairs, badpairs, newpairs, tickerlist):
"""Check pair conditions."""
# Check if pair is in tickerlist and on 3Commas blacklist
if pair in tickerlist:
if pair in blacklist:
blackpairs.append(pair)
else:
newpairs.append(pair)
else:
... | 20,171 |
def create_consts(*args) -> superclasses.PyteAugmentedArgList:
"""
Creates a new list of names.
:param args: The args to use.
"""
return _create_validated(*args, name="consts") | 20,172 |
def opts2constr_feat_gen(opts):
"""Creates ConstFeatPlanes functor by calling its constructor with
parameters from opts.
Args:
opts (obj): Namespace object returned by parser with settings.
Returns:
const_feat_planes (obj): Instantiated ConstFeatPlanes functor.
"""
return Cons... | 20,173 |
def inhibit_activations(activations, times, window_length):
"""
Remove any activations within a specified time window following a previous activation.
TODO - this is extremely slow for non-sparse activations
Parameters
----------
activations : ndarray
Provided activations
times : nda... | 20,174 |
def cmd_convert_items_to_cheetah_list(list):
"""
Cheetah templates can't iterate over a list of classes, so
converts all data into a Cheetah-friendly list of tuples
(NAME, DESCRIPTION, ENUM, HAS_BIT_OFFSET, BIT_OFFSET, BITS, TYPE, MIN, MAX, DEFAULT)
"""
temp = []
for i in list:
... | 20,175 |
def pose223(pose:gtsam.Pose2) -> gtsam.Pose3:
"""convert a gtsam.Pose2 to a gtsam.Pose3
Args:
pose (gtsam.Pose2): the input 2D pose
Returns:
gtsam.Pose3: the 3D pose with zeros for the unkown values
"""
return gtsam.Pose3(
gtsam.Rot3.Yaw(pose.theta()), gtsam.Point3(pose.x(... | 20,176 |
def test_call_wiz_cli_without_subcommand():
"""
Calling wiz-cli without a sub-command. Added for code coverage.
"""
with pytest.raises(SystemExit) as e:
main([])
assert e.value.code == 0 | 20,177 |
def pivot_calibration_with_ransac(tracking_matrices,
number_iterations,
error_threshold,
concensus_threshold,
early_exit=False
):
"""
Written ... | 20,178 |
def find_companies_name_dict():
"""
Finds companies names and addresses
:return: a dict with resource name eg.area of companies and url of available data
"""
base = "https://data.gov.ro/api/3/action/"
query = "Date-de-identificare-platitori"
address = url_build.build_url_package_query(base,... | 20,179 |
def error_to_response(request: web.Request,
error: typing.Union[Error, ErrorList]):
"""
Convert an :class:`Error` or :class:`ErrorList` to JSON API response.
:arg ~aiohttp.web.Request request:
The web request instance.
:arg typing.Union[Error, ErrorList] error:
The... | 20,180 |
def test_link_company_with_dnb_success(
requests_mock,
dnb_response_uk,
base_company_dict,
):
"""
Test the link_company_with_dnb utility.
"""
requests_mock.post(
DNB_V2_SEARCH_URL,
json=dnb_response_uk,
)
company = CompanyFactory()
original_company = Company.objec... | 20,181 |
def read(handle):
"""read(handle)"""
record = Record()
__read_version(record, handle)
__read_database_and_motifs(record, handle)
__read_section_i(record, handle)
__read_section_ii(record, handle)
__read_section_iii(record, handle)
return record | 20,182 |
def validate_telegam():
"""Validate telegram token and chat ID
"""
configs = InitialConfig()
confs = ["chat_id", "bot_token"]
conf_dict = {}
if request.method == "GET":
for conf in confs:
conf_dict[conf] = getattr(configs, conf)
conf_json = json.dumps(conf_dict)
... | 20,183 |
def find_even(values):
"""Wyszukaj liczby parzyste.
:param values: lista z liczbami calkowitymi
:returns: lista ze znalezionymi liczbami parzystymi bez powtorzeń.
"""
result = []
print(f'lista: {values}')
for value in values:
if value % 2 == 0 and value not in result:
re... | 20,184 |
def hour(e):
"""
:rtype: Column
"""
return col(Hour(ensure_column(e))) | 20,185 |
def infer_gaussian(data):
"""
Return (amplitude, x_0, y_0, width), where width - rough estimate of
gaussian width
"""
amplitude = data.max()
x_0, y_0 = np.unravel_index(np.argmax(data), np.shape(data))
row = data[x_0, :]
column = data[:, y_0]
x_0 = float(x_0)
y_0 = float(y_0)
... | 20,186 |
def extract_freq(bins=5, **kwargs):
"""
Extract frequency bin features.
Args:
bins (int): The number of frequency bins (besides OOV)
Returns:
(function): A feature extraction function that returns the log of the \
count of query tokens within each frequency bin.
"""
... | 20,187 |
def test_get_regex_match(pattern, string, result):
"""Test get_regex_match."""
if result:
assert get_regex_match(re.compile(pattern), string) is not None
else:
assert get_regex_match(re.compile(pattern), string) is None | 20,188 |
def base_url(base_url):
"""Add '/' if base_url not end by '/'."""
yield base_url if base_url[-1] == "/" else base_url + "/" | 20,189 |
def create_private_key_params(key_type: str) -> typing.Type[PrivateKeyParams]:
"""Returns the class corresponding to private key parameters objects of the
given key type name.
Args:
key_type
The name of the OpenSSH key type.
Returns:
The subclass of :any:`PrivateKeyParams` ... | 20,190 |
def get_response(msg):
"""
访问图灵机器人openApi
:param msg 用户输入的文本消息
:return string or None
"""
apiurl = "http://openapi.tuling123.com/openapi/api/v2"
# 构造请求参数实体
params = {"reqType": 0,
"perception": {
"inputText": {
... | 20,191 |
def lm_sample_with_constraints(lm_model,
max_decode_steps,
use_cuda,
device,
batch_size=1,
alpha_0=1,
alpha=1,
... | 20,192 |
def validate_official(args, data_loader, model, global_stats=None):
"""Run one full official validation. Uses exact spans and same
exact match/F1 score computation as in the SQuAD script.
Extra arguments:
offsets: The character start/end indices for the tokens in each context.
texts: Map of ... | 20,193 |
def tuple_list_to_lua(tuple_list):
"""Given a list of tuples, return a lua table of tables"""
def table(it):
return "{" + ",".join(map(str, it)) + "}"
return table(table(t) for t in tuple_list) | 20,194 |
def list_actions(cont, fend):
"""initware, получающее список экшнов для подсистемы проверки прав. """
from pynch.core import iter_frontends
for path, sub_fend in iter_frontends(fend):
path = '/'.join(path + ('%s',))
for ctl, action in sub_fend.api:
AVAILABLE_ACTIONS.append((path... | 20,195 |
def reset_user_messages(request: Request):
"""
For given user reset his notifications.
"""
profile: Profile = get_object_or_404(Profile, user=request.user)
profile.messages = 0
profile.save()
return Response(status=status.HTTP_200_OK) | 20,196 |
def test():
"""Test command.
Notes
-----
Only intended to ensure all modules (sans `nlp`) are imported correctly.
When run, prints "Motel requirements installed and loaded successfully." to standard output.
"""
print("Motel requirements installed and loaded successfully.") | 20,197 |
def define_scope(function, scope=None, *args, **kwargs):
"""
A decorator for functions that define TensorFlow operations. The wrapped
function will only be executed once. Subsequent calls to it will directly
return the result so that operations are added to the graph only once.
The operations added ... | 20,198 |
def load_yaml(fname: str) -> Union[List, Dict]:
"""Load a YAML file."""
try:
with open(fname, encoding='utf-8') as conf_file:
# If configuration file is empty YAML returns None
# We convert that to an empty dict
return yaml.load(conf_file, Loader=SafeLineLoader) or Or... | 20,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.