content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
def weekDay(dayOfTheWeek):
d = {
0: 'Sunday',
1: 'Monday',
2: 'Tuesday',
3: 'Wednesday',
4: 'Thursday',
5: 'Friday',
6: 'Saturday'
}
return d[dayOfTheWeek]
| def week_day(dayOfTheWeek):
d = {0: 'Sunday', 1: 'Monday', 2: 'Tuesday', 3: 'Wednesday', 4: 'Thursday', 5: 'Friday', 6: 'Saturday'}
return d[dayOfTheWeek] |
def Load_data(filename):
with open(filename) as f:
content = f.readlines()
content = [x.strip() for x in content]
Transaction = []
for i in range(0, len(content)):
Transaction.append(content[i].split())
return Transaction
#To convert initial transaction into frozenset
def create_... | def load_data(filename):
with open(filename) as f:
content = f.readlines()
content = [x.strip() for x in content]
transaction = []
for i in range(0, len(content)):
Transaction.append(content[i].split())
return Transaction
def create_initialset(dataset):
ret_dict = {}
for tra... |
description = 'The just-bin-it histogrammer.'
devices = dict(
det_image1=device(
'nicos_ess.devices.datasources.just_bin_it.JustBinItImage',
description='A just-bin-it image channel',
hist_topic='ymir_visualisation',
data_topic='FREIA_detector',
brokers=['172.30.242.20:9092'... | description = 'The just-bin-it histogrammer.'
devices = dict(det_image1=device('nicos_ess.devices.datasources.just_bin_it.JustBinItImage', description='A just-bin-it image channel', hist_topic='ymir_visualisation', data_topic='FREIA_detector', brokers=['172.30.242.20:9092'], unit='evts', hist_type='2-D DET', det_width=... |
class Coverage(object):
def __init__(self):
self.swaggerTypes = {
'Chrom': 'str',
'BucketSize': 'int',
'MeanCoverage': 'list<int>',
'EndPos': 'int',
'StartPos': 'int'
}
def __str__(self):
return 'Chr' + self.Chrom + ": " + str... | class Coverage(object):
def __init__(self):
self.swaggerTypes = {'Chrom': 'str', 'BucketSize': 'int', 'MeanCoverage': 'list<int>', 'EndPos': 'int', 'StartPos': 'int'}
def __str__(self):
return 'Chr' + self.Chrom + ': ' + str(self.StartPos) + '-' + str(self.EndPos) + ': BucketSize=' + str(self.... |
DB_TABLES = []
class Table:
insertString = "CREATE TABLE {tableName} ("
def __init__(self, name, columns):
self.name = name
self.columns = columns
def getQuerry(self):
res = self.insertString.format(tableName=self.name)
for columns in self.columns:
... | db_tables = []
class Table:
insert_string = 'CREATE TABLE {tableName} ('
def __init__(self, name, columns):
self.name = name
self.columns = columns
def get_querry(self):
res = self.insertString.format(tableName=self.name)
for columns in self.columns:
res += col... |
### create list_of_tuples:
points = [
(1,2),
(3,4),
(5,6)
]
### retrieve the first element from the first tuple:
print(points[0][0])
# 1
### retrieve the last element from the first tuple:
print(points[0][-1])
# 2
### retrieve the first element from the last tuple:
print(points[-1][0])
# 5
### retrieve ... | points = [(1, 2), (3, 4), (5, 6)]
print(points[0][0])
print(points[0][-1])
print(points[-1][0])
print(points[-1][-1]) |
def reverse(string):
""" runtime complexity of this algorithm is O(n) """
# Starting index
start_index = 0
# Ending index
array = list(string)
last_index = len(array) - 1
while last_index > start_index:
# Swap items
array[start_index], array[last_index] = \
a... | def reverse(string):
""" runtime complexity of this algorithm is O(n) """
start_index = 0
array = list(string)
last_index = len(array) - 1
while last_index > start_index:
(array[start_index], array[last_index]) = (array[last_index], array[start_index])
start_index += 1
last_i... |
def to_string(val):
if val is None:
return ''
else:
return str(val) | def to_string(val):
if val is None:
return ''
else:
return str(val) |
x = int(input())
b = bool(input())
int_one_int_op_int_id = x + 0
int_one_int_op_bool_id = x + False
int_one_bool_op_int_id = x | 0
int_one_bool_op_bool_id = x | False
int_many_int_op_int_id = x + x + 0
int_many_int_op_bool_id = x + x + False
int_many_bool_op_int_id = x | x | 0
int_many_bool_op_bool_id = x | x | False
... | x = int(input())
b = bool(input())
int_one_int_op_int_id = x + 0
int_one_int_op_bool_id = x + False
int_one_bool_op_int_id = x | 0
int_one_bool_op_bool_id = x | False
int_many_int_op_int_id = x + x + 0
int_many_int_op_bool_id = x + x + False
int_many_bool_op_int_id = x | x | 0
int_many_bool_op_bool_id = x | x | False
b... |
attr = [[164, 5, 4, 3, 2, 1, 11, 10, 9, 8, 7, 6, 12, 14, 13, 15, 18, 16, 17, 19, 20, 22, 21, 25, 24,
23, 28, 26, 27, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76],
[163, 77,... | attr = [[164, 5, 4, 3, 2, 1, 11, 10, 9, 8, 7, 6, 12, 14, 13, 15, 18, 16, 17, 19, 20, 22, 21, 25, 24, 23, 28, 26, 27, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76], [163, 77, ... |
#!/usr/bin/python3
def safeDivide(x,y):
try:
a = x/y
except:
a = 0
finally:
return a
print(safeDivide(10,0))
# Can also specify a particular exception..
def this_fails():
x = 1/0
try:
this_fails()
except ZeroDivisionError as errmsg:
print('I am handling a run-time error:', errmsg)
| def safe_divide(x, y):
try:
a = x / y
except:
a = 0
finally:
return a
print(safe_divide(10, 0))
def this_fails():
x = 1 / 0
try:
this_fails()
except ZeroDivisionError as errmsg:
print('I am handling a run-time error:', errmsg) |
# Copyright 2009-2017 Ram Rachum.
# This program is distributed under the MIT license.
class CuteBaseTimer:
'''A base class for timers, allowing easy central stopping.'''
__timers = [] # todo: change to weakref list
def __init__(self, parent):
self.__parent = parent
CuteBaseTimer.__timers... | class Cutebasetimer:
"""A base class for timers, allowing easy central stopping."""
__timers = []
def __init__(self, parent):
self.__parent = parent
CuteBaseTimer.__timers.append(self)
@staticmethod
def stop_timers_by_frame(frame):
"""Stop all the timers that are associated... |
def sep_str():
inp = input(str("Enter word/words with '*' sign wherever you want: ")).rsplit("*", 1)[0]
return inp
print(sep_str())
| def sep_str():
inp = input(str("Enter word/words with '*' sign wherever you want: ")).rsplit('*', 1)[0]
return inp
print(sep_str()) |
"""
This package contains the sphinx extensions used by Astropy.
The `automodsumm` and `automodapi` modules contain extensions used by Astropy
to generate API documentation - see the docstrings for details. The `numpydoc`
module is dervied from the documentation tools numpy and scipy use to parse
docstrings in the nu... | """
This package contains the sphinx extensions used by Astropy.
The `automodsumm` and `automodapi` modules contain extensions used by Astropy
to generate API documentation - see the docstrings for details. The `numpydoc`
module is dervied from the documentation tools numpy and scipy use to parse
docstrings in the nu... |
ONE_DAY_IN_SEC = 86400
SCHEMA_VERSION = "2018-10-08"
NOT_APPLICABLE = "N/A"
ASFF_TYPE = "Unusual Behaviors/Application/ForcepointCASB"
BLANK = "blank"
OTHER = "Other"
SAAS_SECURITY_GATEWAY = "SaaS Security Gateway"
RESOURCES_OTHER_FIELDS_LST = [
"Name",
"suid",
"suser",
"duser",
"act",
"cat",
... | one_day_in_sec = 86400
schema_version = '2018-10-08'
not_applicable = 'N/A'
asff_type = 'Unusual Behaviors/Application/ForcepointCASB'
blank = 'blank'
other = 'Other'
saas_security_gateway = 'SaaS Security Gateway'
resources_other_fields_lst = ['Name', 'suid', 'suser', 'duser', 'act', 'cat', 'cs1', 'app', 'deviceFacili... |
input_file = open("input.txt","r")
input_lines = input_file.readlines()
#print(*input_lines)
rules = []
tickets = []
for line in input_lines:
if line[0].isalpha() and 'or' in line:
#print("Rule")
firstLow = line.split(' ')[-3].split('-')[0]
firstHigh = line.split(' ')[-3].split('-')[1]
... | input_file = open('input.txt', 'r')
input_lines = input_file.readlines()
rules = []
tickets = []
for line in input_lines:
if line[0].isalpha() and 'or' in line:
first_low = line.split(' ')[-3].split('-')[0]
first_high = line.split(' ')[-3].split('-')[1]
second_low = line.split(' ')[-1].split... |
#
# PySNMP MIB module PANASAS-BLADESET-MIB-V1 (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/PANASAS-BLADESET-MIB-V1
# Produced by pysmi-0.3.4 at Mon Apr 29 20:27:54 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 ... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, value_range_constraint, single_value_constraint, constraints_intersection, constraints_union) ... |
#!/usr/bin/env python3
def step(n):
if n%2==0:
return n/2
else:
return 3*n + 1
def to_one(n):
count = 0
while n != 1:
n = step(n)
count += 1
return count
def all_chains(highest):
for i in range(1, highest):
yield (i, to_one(i))
print(max( ... | def step(n):
if n % 2 == 0:
return n / 2
else:
return 3 * n + 1
def to_one(n):
count = 0
while n != 1:
n = step(n)
count += 1
return count
def all_chains(highest):
for i in range(1, highest):
yield (i, to_one(i))
print(max(all_chains(1000000), key=lambda... |
#program to check whether every even index contains an even number
# and every odd index contains odd number of a given list.
def odd_even_position(nums):
return all(nums[i]%2==i%2 for i in range(len(nums)))
print(odd_even_position([2, 1, 4, 3, 6, 7, 6, 3]))
print(odd_even_position([2, 1, 4, 3, 6, 7, 6, 4]))
print(od... | def odd_even_position(nums):
return all((nums[i] % 2 == i % 2 for i in range(len(nums))))
print(odd_even_position([2, 1, 4, 3, 6, 7, 6, 3]))
print(odd_even_position([2, 1, 4, 3, 6, 7, 6, 4]))
print(odd_even_position([4, 1, 2])) |
love = 'I would love to be in '
places = [ 'zion', 'bryce', 'moab', 'arches', 'candyland', 'sedona']
for x in places:
print(x)
| love = 'I would love to be in '
places = ['zion', 'bryce', 'moab', 'arches', 'candyland', 'sedona']
for x in places:
print(x) |
# This Python file uses the following encoding: utf-8
"""This file contains functions for the formatting of the the test results files."""
def line(char: str = "_", newline: bool = False) -> None:
"""Prints a character 70 times, with an optional preceding newline."""
if newline is True:
print ()
i... | """This file contains functions for the formatting of the the test results files."""
def line(char: str='_', newline: bool=False) -> None:
"""Prints a character 70 times, with an optional preceding newline."""
if newline is True:
print()
if len(char) == 1:
print(char * 70)
else:
... |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
load("//antlir/bzl:constants.bzl", "REPO_CFG")
def check_flavor_exists(flavor):
if flavor not in REPO_CFG.flavor_to_config:
fai... | load('//antlir/bzl:constants.bzl', 'REPO_CFG')
def check_flavor_exists(flavor):
if flavor not in REPO_CFG.flavor_to_config:
fail('{} must be in {}'.format(flavor, list(REPO_CFG.flavor_to_config)), 'flavor') |
# ======================================================================
# Subterranean Sustainability
# Advent of Code 2018 Day 12 -- Eric Wastl -- https://adventofcode.com
#
# Python implementation by Dr. Dean Earl Wright III
# ======================================================================
# ==============... | """A solver for the Advent of Code 2018 Day 12 puzzle"""
generations = 20
p2_generations = 50000000000
p2_100 = 2675
p2_delta = 22
class Pots(object):
"""Object for Subterranean Sustainability"""
def __init__(self, generations=GENERATIONS, text=None, part2=False):
self.part2 = part2
self.text ... |
"""
51 / 51 test cases passed.
Runtime: 108 ms
Memory Usage: 19.3 MB
"""
class Solution:
def gardenNoAdj(self, n: int, paths: List[List[int]]) -> List[int]:
graph = [[] for _ in range(n)]
ans = [0] * n
for x, y in paths:
graph[x - 1].append(y - 1)
graph[y - 1].append(... | """
51 / 51 test cases passed.
Runtime: 108 ms
Memory Usage: 19.3 MB
"""
class Solution:
def garden_no_adj(self, n: int, paths: List[List[int]]) -> List[int]:
graph = [[] for _ in range(n)]
ans = [0] * n
for (x, y) in paths:
graph[x - 1].append(y - 1)
graph[y - 1].a... |
#Python program to remove the n'th
# index character from a nonempty string.
inputStr = "akfjljfldksgnlfskgjlsjf"
n = 5
def abc(inputStr, n):
if n > len(inputStr):
print("invalid 'n'.")
return 0
return inputStr[0:n-1] + inputStr[n:]
newStr = abc(inputStr,n)
print(newStr)
| input_str = 'akfjljfldksgnlfskgjlsjf'
n = 5
def abc(inputStr, n):
if n > len(inputStr):
print("invalid 'n'.")
return 0
return inputStr[0:n - 1] + inputStr[n:]
new_str = abc(inputStr, n)
print(newStr) |
class SetCommands():
def __init__(self, command):
self.command = command
def speed(self, x: int):
"""
description: set speed to x cm/s x: 10-100
response: ok, error
"""
return self.command(f'speed {x}')
def rc_control(self, a, b, c, d):
... | class Setcommands:
def __init__(self, command):
self.command = command
def speed(self, x: int):
"""
description: set speed to x cm/s x: 10-100
response: ok, error
"""
return self.command(f'speed {x}')
def rc_control(self, a, b, c, d):
"""
de... |
## Copyright 2002-2003 Andrew Loewenstern, All Rights Reserved
# see LICENSE.txt for license information
def bucket_stats(l):
"""given a list of khashmir instances, finds min, max, and average number of nodes in tables"""
max = avg = 0
min = None
def count(buckets):
c = 0
for bucket in ... | def bucket_stats(l):
"""given a list of khashmir instances, finds min, max, and average number of nodes in tables"""
max = avg = 0
min = None
def count(buckets):
c = 0
for bucket in buckets:
c = c + len(bucket.l)
return c
for node in l:
c = count(node.tab... |
DEFAULT_MEROSS_HTTP_API = "https://iot.meross.com"
DEFAULT_MQTT_HOST = "mqtt.meross.com"
DEFAULT_MQTT_PORT = 443
DEFAULT_COMMAND_TIMEOUT = 10.0
| default_meross_http_api = 'https://iot.meross.com'
default_mqtt_host = 'mqtt.meross.com'
default_mqtt_port = 443
default_command_timeout = 10.0 |
t = int(input())
while t > 0:
s = input()
new = ''
c=1
for i in range(len(s)):
if i == 0:
new+=s[i]
elif i!=0 and s[i] != s[i-1]:
new+=str(c)
c=1
new+=s[i]
elif s[i] == s[i-1] and new[-1] == s[i]:
c+=1
print(new)
... | t = int(input())
while t > 0:
s = input()
new = ''
c = 1
for i in range(len(s)):
if i == 0:
new += s[i]
elif i != 0 and s[i] != s[i - 1]:
new += str(c)
c = 1
new += s[i]
elif s[i] == s[i - 1] and new[-1] == s[i]:
c += 1
... |
class RelinquishOptions(object,IDisposable):
"""
Options to control behavior of relinquishing ownership of elements and worksets.
RelinquishOptions(relinquishEverything: bool)
"""
def Dispose(self):
""" Dispose(self: RelinquishOptions) """
pass
def ReleaseUnmanagedResources(self,*args):
""" ... | class Relinquishoptions(object, IDisposable):
"""
Options to control behavior of relinquishing ownership of elements and worksets.
RelinquishOptions(relinquishEverything: bool)
"""
def dispose(self):
""" Dispose(self: RelinquishOptions) """
pass
def release_unmanaged_resources(self,... |
# Vim has the best keybindings ever
class Vim:
@property
def __best__(self):
return True
| class Vim:
@property
def __best__(self):
return True |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def all_messages():
return \
{
"0": "Nettacker-motor begon ...\n\n",
"1": "python nettacker.py [opties]",
"2": "Toon Nettacker Help Menu",
"3": "Gelieve de licentie en afspraken te lezen https://github.com/virain... | def all_messages():
return {'0': 'Nettacker-motor begon ...\n\n', '1': 'python nettacker.py [opties]', '2': 'Toon Nettacker Help Menu', '3': 'Gelieve de licentie en afspraken te lezen https://github.com/viraintel/OWASP-Nettacker\n', '4': 'Motor', '5': 'Motorinvoeropties', '6': 'selecteer een taal {0}', '7': "scan a... |
def compare(s, m):
""" Compute a scatter plot
Args:
s (ndarray): astrocat's true position over time
m (ndarray): astrocat's measured position over time according to the sensor
"""
fig = plt.figure()
ax = fig.add_subplot(111)
sbounds = 1.1*max(max(np.abs(s)), max(np.abs(m)))
ax.plot([-sbounds, ... | def compare(s, m):
""" Compute a scatter plot
Args:
s (ndarray): astrocat's true position over time
m (ndarray): astrocat's measured position over time according to the sensor
"""
fig = plt.figure()
ax = fig.add_subplot(111)
sbounds = 1.1 * max(max(np.abs(s)), max(np.abs(m)))
ax.plot([... |
FLOAT_PRECISION = 3
DEFAULT_MIN_TIME_IN_HOUR = 0
DEFAULT_MAX_TIME_IN_HOUR = 230
MINUTES_IN_AN_HOUR = 60
FS = "Fs"
FOIL = "Foil"
FG = "Fg"
PRES = "pressure"
DISCHARGE = "discharge"
WATER = "Fw"
PAA = "Fpaa"
DEFAULT_PENICILLIN_RECIPE_ORDER = [FS, FOIL, FG, PRES, DISCHARGE, WATER, PAA]
FS_DEFAULT_PROFILE = [
{"time... | float_precision = 3
default_min_time_in_hour = 0
default_max_time_in_hour = 230
minutes_in_an_hour = 60
fs = 'Fs'
foil = 'Foil'
fg = 'Fg'
pres = 'pressure'
discharge = 'discharge'
water = 'Fw'
paa = 'Fpaa'
default_penicillin_recipe_order = [FS, FOIL, FG, PRES, DISCHARGE, WATER, PAA]
fs_default_profile = [{'time': 3, 'v... |
def singleton(class_):
instances = {}
def getinstance(*args, **kwargs):
if class_ not in instances:
instances[class_] = class_(*args, **kwargs)
return instances[class_]
return getinstance
@singleton
class MyClass():
def test(self):
print(id(self))
class Singleton(object):
_instance = No... | def singleton(class_):
instances = {}
def getinstance(*args, **kwargs):
if class_ not in instances:
instances[class_] = class_(*args, **kwargs)
return instances[class_]
return getinstance
@singleton
class Myclass:
def test(self):
print(id(self))
class Singleton(ob... |
""" Drop unnecessary information """
def drop_dict(directory, dict_list):
"""drop record"""
target_dict_list = dict_list
target_dict_list = list(filter(
lambda any_dict:(directory not in any_dict["name"]) or ("stat" in any_dict),
target_dict_list))
target_dict_list = list(filter(
... | """ Drop unnecessary information """
def drop_dict(directory, dict_list):
"""drop record"""
target_dict_list = dict_list
target_dict_list = list(filter(lambda any_dict: directory not in any_dict['name'] or 'stat' in any_dict, target_dict_list))
target_dict_list = list(filter(lambda any_dict: directory ... |
class BaseTextOpinionsLinkageInstancesProvider(object):
def iter_instances(self, text_opinion_linkage):
raise NotImplementedError()
@staticmethod
def provide_label(text_opinion_linkage):
return text_opinion_linkage.First.Sentiment | class Basetextopinionslinkageinstancesprovider(object):
def iter_instances(self, text_opinion_linkage):
raise not_implemented_error()
@staticmethod
def provide_label(text_opinion_linkage):
return text_opinion_linkage.First.Sentiment |
class SkyblockProfileMember:
def __init__(self, member_data: dict) -> None:
"""
Parameters
----------
data: dict
The JSON data received from the Hypixel API.
"""
self.COIN_PURSE = member_data["coin_purse"]
self.DEATH_COUNT = member_data["death_coun... | class Skyblockprofilemember:
def __init__(self, member_data: dict) -> None:
"""
Parameters
----------
data: dict
The JSON data received from the Hypixel API.
"""
self.COIN_PURSE = member_data['coin_purse']
self.DEATH_COUNT = member_data['death_cou... |
def pattern_occurence(pattern, dna):
list_occurences=[]
k = len(pattern)
for i in range(len(dna)-k+1):
if(dna[i:i+k]==pattern):
list_occurences.append(i)
return list_occurences
def main():
with open('datasets/rosalind_ba1d.txt') as input_file:
pattern, dna =... | def pattern_occurence(pattern, dna):
list_occurences = []
k = len(pattern)
for i in range(len(dna) - k + 1):
if dna[i:i + k] == pattern:
list_occurences.append(i)
return list_occurences
def main():
with open('datasets/rosalind_ba1d.txt') as input_file:
(pattern, dna) = i... |
# Licensed to the .NET Foundation under one or more agreements.
# The .NET Foundation licenses this file to you under the Apache 2.0 License.
# See the LICENSE file in the project root for more information.
# generated by generate_indicestest.py
def test_indices(self):
def t(i, j, k, l, r):
rr = slice(i, ... | def test_indices(self):
def t(i, j, k, l, r):
rr = slice(i, j, k).indices(l)
self.assertEqual(rr, r, 'slice({i}, {j}, {k}).indices({l}) != {r}: {rr}'.format(i=i, j=j, k=k, l=l, r=r, rr=rr))
t(None, None, None, 0, (0, 0, 1))
t(None, None, None, 1, (0, 1, 1))
t(None, None, None, 5, (0, 5,... |
"""Test package.
Modules:
conftest
"""
| """Test package.
Modules:
conftest
""" |
# for index, character in enumerate("abcdefgh"):
# print(index, character)
for t in enumerate("abcdefgh"):
index, character = t
print(index, character)
print(t)
# the output has 8 tuples
# unpacking tuples is a valuable technique
index, character = [0, 'a']
print(index)
print(character)
| for t in enumerate('abcdefgh'):
(index, character) = t
print(index, character)
print(t)
(index, character) = [0, 'a']
print(index)
print(character) |
user_bin = int(input(), 2)
one = int(1)
zero = int(0)
user_int = int(user_bin)
user_int = int(user_int * 1)
oct_str = str(oct(user_int))
print(oct_str[2:])
| user_bin = int(input(), 2)
one = int(1)
zero = int(0)
user_int = int(user_bin)
user_int = int(user_int * 1)
oct_str = str(oct(user_int))
print(oct_str[2:]) |
controller = '''
from fastapi import APIRouter, HTTPException,Cookie, Depends,Header,File, Body,Query
from starlette.responses import JSONResponse
from core.factories import settings
import httpx
router = APIRouter()
''' | controller = '\nfrom fastapi import APIRouter, HTTPException,Cookie, Depends,Header,File, Body,Query\nfrom starlette.responses import JSONResponse\nfrom core.factories import settings\nimport httpx\n\nrouter = APIRouter()\n\n' |
# parse file
file_names = []
with open("train_file_controller.txt", 'r') as f:
for line in f:
file_names.append(line.strip().replace('\n', ''))
with open("val_file_controller.txt", 'r') as f:
for line in f:
file_names.append(line.strip().replace('\n', ''))
file_names.sort()
for file in file_names:
print(fi... | file_names = []
with open('train_file_controller.txt', 'r') as f:
for line in f:
file_names.append(line.strip().replace('\n', ''))
with open('val_file_controller.txt', 'r') as f:
for line in f:
file_names.append(line.strip().replace('\n', ''))
file_names.sort()
for file in file_names:
print(... |
__all__ = ['InputError']
class InputError(BaseException):
def __init__(self, errors):
self.errors = errors
super().__init__()
| __all__ = ['InputError']
class Inputerror(BaseException):
def __init__(self, errors):
self.errors = errors
super().__init__() |
class BadGrammar(Exception):
"""The rule definitions passed to Grammar contain syntax errors."""
class VisitationError(Exception):
"""Something went wrong while traversing a parse tree.
This exception exists to augment an underlying exception with information
about where in the parse tree the error o... | class Badgrammar(Exception):
"""The rule definitions passed to Grammar contain syntax errors."""
class Visitationerror(Exception):
"""Something went wrong while traversing a parse tree.
This exception exists to augment an underlying exception with information
about where in the parse tree the error oc... |
#
# PySNMP MIB module PDN-CP-IWF-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/PDN-CP-IWF-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:29:19 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2... | (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, value_range_constraint, single_value_constraint, constraints_intersection, value_size_constraint) ... |
def u64ToCounts(number):
"""
Convert an unsigned 64 bit number to a 25 element array containing the
photon counts for each of the 25 detector elements during a single dwell
time.
========== ===============================================================
Input Meaning
---------- ---... | def u64_to_counts(number):
"""
Convert an unsigned 64 bit number to a 25 element array containing the
photon counts for each of the 25 detector elements during a single dwell
time.
========== ===============================================================
Input Meaning
---------- --... |
# -*- coding: utf-8 -*-
class StringMutations:
@classmethod
def _list_shift(cls, l, n):
return l[n:] + l[:n]
@classmethod
def length(cls, mutation, value, story, line, operator, operand):
return len(value)
@classmethod
def replace(cls, mutation, value, story, line, operator,... | class Stringmutations:
@classmethod
def _list_shift(cls, l, n):
return l[n:] + l[:n]
@classmethod
def length(cls, mutation, value, story, line, operator, operand):
return len(value)
@classmethod
def replace(cls, mutation, value, story, line, operator, operand):
new_val... |
# Copyright 2016 Cisco Systems, Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requir... | class Encaps(object):
vlan = 'VLAN'
vx_lan = 'VxLAN'
mpls = 'MPLS'
no_encaps = 'NONE'
encaps_mapping = {'VLAN': VLAN, 'VXLAN': VxLAN, 'MPLS': MPLS, 'NONE': NO_ENCAPS}
@classmethod
def get(cls, network_type):
return cls.encaps_mapping.get(network_type.upper(), None)
class Chaintype(... |
# Given an list , use bucket sort to sort the elements of the list and return
# Input: [1, 2, 4, 3, 5]
# Output: [1, 2, 3, 4, 5]
# divide the elements into several lists known as buckets
# loop through each buckets and sort them(insertion/quick sort)
# return each element of the buckets since they would be sorted al... | def do_bucket_sort(nums: list) -> list:
buckets = []
list_len = len(nums)
nums_indx = 0
for i in range(list_len + 1):
buckets.append([])
for i in nums:
buckets[i].append(i)
buckets[i].sort()
for bucket in buckets:
for el in bucket:
nums[nums_indx] = el... |
class Error(Exception):
"""Handles general exceptions."""
class AbilityScoreImprovementError(Error):
"""Handles ability score improvement errors."""
class AnthropometricCalculatorError(Error):
"""Handles anthropometric calculator errors."""
class BlueprintError(Error):
"""Handles an invalid seamst... | class Error(Exception):
"""Handles general exceptions."""
class Abilityscoreimprovementerror(Error):
"""Handles ability score improvement errors."""
class Anthropometriccalculatorerror(Error):
"""Handles anthropometric calculator errors."""
class Blueprinterror(Error):
"""Handles an invalid seamstres... |
class A:
def __repr__(self):
True
a = A()
print(a.__repr__()) # ok
print(repr(a)) # fail
| class A:
def __repr__(self):
True
a = a()
print(a.__repr__())
print(repr(a)) |
# Declaring a list
L = [1, "a" , "string" , 1+2]
print (L)
L.append(6)
print (L)
L.pop()
print (L)
print (L[1]) | l = [1, 'a', 'string', 1 + 2]
print(L)
L.append(6)
print(L)
L.pop()
print(L)
print(L[1]) |
def func(a, b, *args, **kwargs):
print(a, b)
for arg in args:
print(arg)
for key, val in kwargs.items():
print (key, val)
def func2(a, b, c=30, d=40, **kwargs):
print(a, b)
print(c, d)
for key, val in kwargs.items():
print (key, val)
def func3(a, b, c=100, d=200):
p... | def func(a, b, *args, **kwargs):
print(a, b)
for arg in args:
print(arg)
for (key, val) in kwargs.items():
print(key, val)
def func2(a, b, c=30, d=40, **kwargs):
print(a, b)
print(c, d)
for (key, val) in kwargs.items():
print(key, val)
def func3(a, b, c=100, d=200):
... |
__title__ = 'hrflow'
__description__ = 'Python hrflow.ai API package'
__url__ = 'https://github.com/hrflow/python-hrflow-api'
__version__ = '1.9.0'
__author__ = 'HrFlow.ai'
__author_email__ = 'contact@hrflow.ai'
__license__ = 'MIT' | __title__ = 'hrflow'
__description__ = 'Python hrflow.ai API package'
__url__ = 'https://github.com/hrflow/python-hrflow-api'
__version__ = '1.9.0'
__author__ = 'HrFlow.ai'
__author_email__ = 'contact@hrflow.ai'
__license__ = 'MIT' |
dummy_registry = {}
def dummy_register(name, value):
dummy_registry[name] = value
return value
| dummy_registry = {}
def dummy_register(name, value):
dummy_registry[name] = value
return value |
#
# Copyright (C) 2020 Square, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
# in compliance with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... | def _java_executable(ctx):
java_home = ctx.os.environ.get('JAVA_HOME')
if java_home != None:
java = ctx.path(java_home + '/bin/java')
return java
elif ctx.which('java') != None:
return ctx.which('java')
fail('Cannot obtain java binary')
def _exec_jar(root, label):
return '%s... |
# -*- coding: utf-8 -*-
# @Author: jpch89
# @Email: jpch89@outlook.com
# @Date: 2018-07-12 21:01:08
# @Last Modified by: jpch89
# @Last Modified time: 2018-07-12 21:07:53
people = 30
cars = 40
trucks = 15
if cars > people:
print ("We should take the cars.")
elif cars < people:
print("We should not take t... | people = 30
cars = 40
trucks = 15
if cars > people:
print('We should take the cars.')
elif cars < people:
print('We should not take the cars.')
else:
print("We can't decide.")
if trucks > cars:
print("That's too many trucks.")
elif trucks < cars:
print('Maybe we could take the trucks.')
else:
pr... |
# A base sentence model for storing information related to sentences
# Created by: Mark Mott
class Sentence:
# A single underline denotes a private method/variable.
# Default is the property category
def __init__(self, sentence, subject, category='Property'):
self.setsentence(sentence)
self.... | class Sentence:
def __init__(self, sentence, subject, category='Property'):
self.setsentence(sentence)
self.setsubject(subject)
self.setcategory(category)
def setsentence(self, sentence):
self._sentence = sentence
def getsentence(self):
return self._sentence
d... |
# Practice debug statement
print("Hello Python")
a = 10
b = 5
c = a + b
print("Hello Python2")
print(c)
c = 99
print("Hello Python3:%d", c)
#####################################################
# ** operator has high precedences than *
print(2**3*4)
print(4*2**3)
def changeVal(x):
x += 2;
###################... | print('Hello Python')
a = 10
b = 5
c = a + b
print('Hello Python2')
print(c)
c = 99
print('Hello Python3:%d', c)
print(2 ** 3 * 4)
print(4 * 2 ** 3)
def change_val(x):
x += 2
def circle_area(r):
pi = 3.14
area = pi * r ** 2
return area
x = 1
change_val(x)
print(x)
r = 10
area = circle_area(r)
print('C... |
_base_ = [
'../../_base_/datasets/query_aware/few_shot_coco.py',
'../../_base_/schedules/schedule.py', '../attention-rpn_r50_c4.py',
'../../_base_/default_runtime.py'
]
# classes splits are predefined in FewShotCocoDataset
# FewShotCocoDefaultDataset predefine ann_cfg for model reproducibility
num_support_w... | _base_ = ['../../_base_/datasets/query_aware/few_shot_coco.py', '../../_base_/schedules/schedule.py', '../attention-rpn_r50_c4.py', '../../_base_/default_runtime.py']
num_support_ways = 2
num_support_shots = 9
data = dict(train=dict(num_support_ways=num_support_ways, num_support_shots=num_support_shots, repeat_times=50... |
"""Top-level package for CT Parsers."""
__author__ = """Nick Cannariato"""
__email__ = 'devrel@birdcar.dev'
__version__ = '0.1.0'
| """Top-level package for CT Parsers."""
__author__ = 'Nick Cannariato'
__email__ = 'devrel@birdcar.dev'
__version__ = '0.1.0' |
TRAINING_FILE = "../data/train_folds5.csv"
MODEL_OUTPUT = "../models/"
LABEL="rating_y"
BEST_FEATURES = ['rating_x',
'user_id',
'members',
'episodes',
'Action',
'Drama',
'Fantasy',
'Hentai',
'Romance',
'Adventure',
'Comedy',
'School',
'Shounen',
'Supernatural',
'Kids',
'Mecha',
'Sci-Fi',
'Slic... | training_file = '../data/train_folds5.csv'
model_output = '../models/'
label = 'rating_y'
best_features = ['rating_x', 'user_id', 'members', 'episodes', 'Action', 'Drama', 'Fantasy', 'Hentai', 'Romance', 'Adventure', 'Comedy', 'School', 'Shounen', 'Supernatural', 'Kids', 'Mecha', 'Sci-Fi', 'SliceofLife', 'type_OVA', 'D... |
def setup_subparser(subparsers, parents, python_version):
parser = subparsers.add_parser(
python_version,
description="""This sub command generates IDE and build files for Python {}
""".format(
"3.6" if python_version == "python36" else "3.7"
),
parents=parent... | def setup_subparser(subparsers, parents, python_version):
parser = subparsers.add_parser(python_version, description='This sub command generates IDE and build files for Python {}\n '.format('3.6' if python_version == 'python36' else '3.7'), parents=parents)
parser.set_defaults(language=python_version... |
def find_smallest_element_index(array):
smallest_elem_index, smallest_elem = 0, array[0]
for index in range(1,len(array)):
if(smallest_elem >= array[index]):
smallest_elem_index = index
return smallest_elem_index
#changes the original array and puts the elements in sorted order (asc... | def find_smallest_element_index(array):
(smallest_elem_index, smallest_elem) = (0, array[0])
for index in range(1, len(array)):
if smallest_elem >= array[index]:
smallest_elem_index = index
return smallest_elem_index
def selection_sort(array):
sorted_array = []
for i in range(le... |
"""Toyota Connected Services API constants."""
# URL ATTRIBUTE NAMES
BASE_URL = "base_url"
BASE_URL_CARS = "base_url_cars"
ENDPOINT_AUTH = "auth_endpoint"
TOKEN_VALID_URL = "auth_valid"
# REGIONS
SUPPORTED_REGIONS = {
"europe": {
TOKEN_VALID_URL: "https://ssoms.toyota-europe.com/isTokenValid",
... | """Toyota Connected Services API constants."""
base_url = 'base_url'
base_url_cars = 'base_url_cars'
endpoint_auth = 'auth_endpoint'
token_valid_url = 'auth_valid'
supported_regions = {'europe': {TOKEN_VALID_URL: 'https://ssoms.toyota-europe.com/isTokenValid', BASE_URL: 'https://myt-agg.toyota-europe.com/cma/api', BASE... |
# A program that reads in students names
# until the user enters a blank
# and then prints them all out again
# the program prints out all the studens names in a neat way
students = []
Firstname = input("Enter Firstname (blank to quit): ").strip()
while Firstname != "":
student = {}
student ["Firstn... | students = []
firstname = input('Enter Firstname (blank to quit): ').strip()
while Firstname != '':
student = {}
student['Firstname'] = Firstname
lastname = input('Enter lastname: ').strip()
student['lastname'] = lastname
students.append(student)
firstname = input('Enter Firstname of next (blank... |
class Command:
command = "template" # command name must be the same as the file name but can have spacial characters
description = "description of command"
argsRequired = 1 # number of arguments needed for command
usage = "<command>" # a usage example of required arguments
examples = [{
'... | class Command:
command = 'template'
description = 'description of command'
args_required = 1
usage = '<command>'
examples = [{'run': 'template', 'result': 'a template'}]
synonyms = ['tmp']
async def call(self, package):
pass |
# -*- coding: utf-8 -*-
"""
ASCII canvas
ASCII canvas module for drawing in console using ASCII chars
ASCII canvas supports the next objects:
- Point
- Line
- Rectangle
- Nine-Patch Rectangle
- Ellipse
- Text
And also supports Style for all these objects. The Style includes symbol,
foreground color, background co... | """
ASCII canvas
ASCII canvas module for drawing in console using ASCII chars
ASCII canvas supports the next objects:
- Point
- Line
- Rectangle
- Nine-Patch Rectangle
- Ellipse
- Text
And also supports Style for all these objects. The Style includes symbol,
foreground color, background color and font style. There... |
'''
Here is a basic example to plot a signal from an lcm message.
In this example, the channel is POSE_BODY.
The X coordinate is the message timestamp in microseconds,
and the Y value is pos[0], or the first value of the pos array.
Note, msg is a pre-defined variable that you must use in order
for this to work. When ... | """
Here is a basic example to plot a signal from an lcm message.
In this example, the channel is POSE_BODY.
The X coordinate is the message timestamp in microseconds,
and the Y value is pos[0], or the first value of the pos array.
Note, msg is a pre-defined variable that you must use in order
for this to work. When y... |
# -*- coding: utf-8 -*-
"""Exceptions for bkpaas_auth module
"""
class ServiceError(Exception):
"""Login or Token service is not available"""
class InvalidSkeyError(Exception):
"""Invalid uin/skey given"""
class InvalidTokenCredentialsError(Exception):
"""When invalid credentials are given when exchan... | """Exceptions for bkpaas_auth module
"""
class Serviceerror(Exception):
"""Login or Token service is not available"""
class Invalidskeyerror(Exception):
"""Invalid uin/skey given"""
class Invalidtokencredentialserror(Exception):
"""When invalid credentials are given when exchange access token""" |
# 001110010 prev = 0 cur = 0
# 0 01110010 prev = 0 cur = 1
# 0 0 1110010 prev = 0 cur = 2
# 00 1 110010 prev = 2 cur = 1 01
# 001 1 10010 prev = 2 cur = 2 0011
# 0011 1 0010 prev = 2 cur = 3
# 00111 0 010 prev = 3 cur = 1 10
# 001110 0 10 prev = 3 cur = 2 11... | class Solution:
def count_binary_substrings(self, s: str) -> int:
(prevlen, curlen, ans) = (0, 0, 0)
for i in range(len(s)):
if s[i] == s[i - 1]:
curlen += 1
else:
prevlen = curlen
curlen = 1
if prevlen >= curlen:
... |
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 16 09:57:15 2016
@author: Mathew Topper
"""
#pylint: disable=C0103,W0622,R0903
class abstractclassmethod(classmethod):
"""Not that to make this work, you should place cls() in the abstract
definition"""
__isabstractmethod__ = True
def __init__(self... | """
Created on Wed Mar 16 09:57:15 2016
@author: Mathew Topper
"""
class Abstractclassmethod(classmethod):
"""Not that to make this work, you should place cls() in the abstract
definition"""
__isabstractmethod__ = True
def __init__(self, callable):
callable.__isabstractmethod__ = True
... |
"""
import os
import bonobo
import logging
from dotenv import load_dotenv
from judah.utils.assets import get_asset_path
from judah.utils.logging import setup_rotating_file_logger
load_dotenv()
# Assuming you have an BBC ETL service, a rest_api_to_db child service and a number of microservices
# each corresponding ... | """
import os
import bonobo
import logging
from dotenv import load_dotenv
from judah.utils.assets import get_asset_path
from judah.utils.logging import setup_rotating_file_logger
load_dotenv()
# Assuming you have an BBC ETL service, a rest_api_to_db child service and a number of microservices
# each corresponding ... |
class GuidanceRejectionException(Exception):
_MSG = "Unit tests should not write files unless they clean them up too."
def __init__(self):
super(GuidanceRejectionException, self).__init__(GuidanceRejectionException._MSG) | class Guidancerejectionexception(Exception):
_msg = 'Unit tests should not write files unless they clean them up too.'
def __init__(self):
super(GuidanceRejectionException, self).__init__(GuidanceRejectionException._MSG) |
equipmentMultipliers = [
{"hp": 10},
{"hp": 20},
{"hp": 30},
{"hp": 40},
{"sp": 10},
{"sp": 20},
{"sp": 30},
{"sp": 40},
{"tp": 2},
{"tp": 4},
{"tp": 6},
{"tp": 8},
{"atk": 10},
{"atk": 20},
{"atk": 30},
{"atk": 40},
{"def": 10},
{"def": 20},
{"def": 30},
{"de... | equipment_multipliers = [{'hp': 10}, {'hp': 20}, {'hp': 30}, {'hp': 40}, {'sp': 10}, {'sp': 20}, {'sp': 30}, {'sp': 40}, {'tp': 2}, {'tp': 4}, {'tp': 6}, {'tp': 8}, {'atk': 10}, {'atk': 20}, {'atk': 30}, {'atk': 40}, {'def': 10}, {'def': 20}, {'def': 30}, {'def': 40}, {'mag': 10}, {'mag': 20}, {'mag': 30}, {'mag': 40},... |
# https://www.codechef.com/problems/MSNSADM1
for T in range(int(input())):
n,points=int(input()),0
scores,fouls=list(map(int,input().split())),list(map(int,input().split()))
for i in range(n):
if((scores[i]*20-fouls[i]*10)>points): points=scores[i]*20-fouls[i]*10
print(max(0,points)) | for t in range(int(input())):
(n, points) = (int(input()), 0)
(scores, fouls) = (list(map(int, input().split())), list(map(int, input().split())))
for i in range(n):
if scores[i] * 20 - fouls[i] * 10 > points:
points = scores[i] * 20 - fouls[i] * 10
print(max(0, points)) |
#!/usr/bin/python3.6
def getPathToDataExchangeFolder():
return 'src/backend/dataExchange/'
def getPathToLogFolder():
return 'src/backend/log/'
def getPathToDataOutput():
return 'src/backend/dataOutput/'
def getPathOfMainJsonFile(artifact_name):
return getPathToDataExchangeFolder() + artifact_nam... | def get_path_to_data_exchange_folder():
return 'src/backend/dataExchange/'
def get_path_to_log_folder():
return 'src/backend/log/'
def get_path_to_data_output():
return 'src/backend/dataOutput/'
def get_path_of_main_json_file(artifact_name):
return get_path_to_data_exchange_folder() + artifact_name +... |
def process_row_item(row_item):
if hasattr(row_item, 'strip'):
row_item = row_item.strip()
return row_item
def to_table_format(data_list):
header = []
rows = []
for row in data_list:
header = row.keys()
rows.append(list(map(process_row_item, row.values())))
return heade... | def process_row_item(row_item):
if hasattr(row_item, 'strip'):
row_item = row_item.strip()
return row_item
def to_table_format(data_list):
header = []
rows = []
for row in data_list:
header = row.keys()
rows.append(list(map(process_row_item, row.values())))
return (heade... |
#class common parameters
#put all parameters in there
#import module to baseline.py
class default_data:
def __init__(self):
#whoever is running this code make sure you change the name to your first name
self.user = "" #not needed, mainly to avoid file name conflicts
self.numLoops = 1
... | class Default_Data:
def __init__(self):
self.user = ''
self.numLoops = 1
self.scenario = 'rocket_basic'
self.config_file_path = 'scenarios/' + self.scenario + '.cfg'
self.epochs = 20
self.learning_rate = 0.00025
self.discount_factor = 0.99
self.learni... |
n = float(input())
i = 0
for i in range(i, 100, 1):
print('N[{}] = {:.4f}'.format(i, n))
n = (n / 2) | n = float(input())
i = 0
for i in range(i, 100, 1):
print('N[{}] = {:.4f}'.format(i, n))
n = n / 2 |
class Solution:
def toLowerCase(self, str):
"""
:type str: str
:rtype: str
"""
return str.lower()
input = "ABCdefG"
p = Solution()
print(p.toLowerCase(input)) | class Solution:
def to_lower_case(self, str):
"""
:type str: str
:rtype: str
"""
return str.lower()
input = 'ABCdefG'
p = solution()
print(p.toLowerCase(input)) |
"""Configuration information for PDB2PQR."""
# PDB2PQR version number.
VERSION = "3.0"
# How to format PDB2PQR title in output
TITLE_FORMAT_STRING = "PDB2PQR v{version} - biomolecular structure conversion software"
# Citation strings for PDB2PQR
CITATIONS = [("Please cite: Jurrus E, et al. Improvements to the APBS... | """Configuration information for PDB2PQR."""
version = '3.0'
title_format_string = 'PDB2PQR v{version} - biomolecular structure conversion software'
citations = ['Please cite: Jurrus E, et al. Improvements to the APBS biomolecular solvation software suite. Protein Sci 27 112-128 (2018).', 'Please cite: Dolinsky TJ,... |
def solve(a,b):
dict={}
for i in range(max(a, 1), b):
temp=factors(i)
dict[sum(temp)/i]=dict.get(sum(temp)/i, [])+[i]
return sum(j[0] for j in dict.values() if len(j)>1)
def factors(n):
res={1, n}
for i in range(2, int(n**0.5)+1):
if n%i==0:
res.add(i)
... | def solve(a, b):
dict = {}
for i in range(max(a, 1), b):
temp = factors(i)
dict[sum(temp) / i] = dict.get(sum(temp) / i, []) + [i]
return sum((j[0] for j in dict.values() if len(j) > 1))
def factors(n):
res = {1, n}
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
... |
# Local settings for WLM project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
DEBUG_PROPAGATE_EXCEPTIONS = DEBUG
ALLOWED_HOSTS = '*'
ADMINS = (
#('Name', 'mail@example.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': '',
'USER': '',
... | debug = True
template_debug = DEBUG
debug_propagate_exceptions = DEBUG
allowed_hosts = '*'
admins = ()
managers = ADMINS
databases = {'default': {'ENGINE': 'django.db.backends.mysql', 'NAME': '', 'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT': ''}}
geoip_path = '/usr/share/GeoIP/'
secret_key = '' |
# source: https://www.bilibili.com/video/av21540971/?p=23
def bubble_sort(alist):
"""bubble sort
best: O(n)
worst: O(n^2)
stable
"""
n = len(alist)
for j in range(n-1):
count = 0
for i in range(n-1-j):
if alist[i] > alist[i+1]:
alist[i], alist[i+... | def bubble_sort(alist):
"""bubble sort
best: O(n)
worst: O(n^2)
stable
"""
n = len(alist)
for j in range(n - 1):
count = 0
for i in range(n - 1 - j):
if alist[i] > alist[i + 1]:
(alist[i], alist[i + 1]) = (alist[i + 1], alist[i])
co... |
python = "Python"
print("h " + python[3]) # Note: string indexing starts with 0
p_letter = python[0]
print(p_letter)
| python = 'Python'
print('h ' + python[3])
p_letter = python[0]
print(p_letter) |
n =int(input())
count = 1
for i in range(1, n+1):
for j in range(1, i+1):
print(count*count, end=" ")
count+=1
print()
| n = int(input())
count = 1
for i in range(1, n + 1):
for j in range(1, i + 1):
print(count * count, end=' ')
count += 1
print() |
class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
dic = {}
ret = []
if len(nums1)<len(nums2):
for i in nums2:
if i not in dic:
dic[i] = 0
dic[i] += 1
for j in nums1:
... | class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
dic = {}
ret = []
if len(nums1) < len(nums2):
for i in nums2:
if i not in dic:
dic[i] = 0
dic[i] += 1
for j in nums1:
... |
def merge_sort(arr):
n = len(arr)
if n > 1:
mid = n//2
left = arr[0:mid]
right = arr[mid:n]
merge_sort(left)
merge_sort(right)
merge(left, right, arr)
def merge(left, right, arr):
i, j, k = 0, 0, 0
while i < len(left) and j < len(right):
if left[... | def merge_sort(arr):
n = len(arr)
if n > 1:
mid = n // 2
left = arr[0:mid]
right = arr[mid:n]
merge_sort(left)
merge_sort(right)
merge(left, right, arr)
def merge(left, right, arr):
(i, j, k) = (0, 0, 0)
while i < len(left) and j < len(right):
if ... |
class Solution(object):
def countGoodRectangles(self, rectangles):
"""
:type rectangles: List[List[int]]
:rtype: int
"""
maxLen = 0
counter = 0
for rectangle in rectangles:
# You can find the maximal square within a rectangle
maximalSq... | class Solution(object):
def count_good_rectangles(self, rectangles):
"""
:type rectangles: List[List[int]]
:rtype: int
"""
max_len = 0
counter = 0
for rectangle in rectangles:
maximal_square = min(rectangle[0], rectangle[1])
if maximal... |
positive_count = 0
zero_count = 0
negative_count = 0
n = int(input().strip())
arr = [int(arr_temp) for arr_temp in input().strip().split(' ')]
for num in arr:
if num > 0:
positive_count += 1
elif num == 0:
zero_count += 1
else:
negative_count += 1
print(positive_count / n)
print(negative_count / n)
print(zer... | positive_count = 0
zero_count = 0
negative_count = 0
n = int(input().strip())
arr = [int(arr_temp) for arr_temp in input().strip().split(' ')]
for num in arr:
if num > 0:
positive_count += 1
elif num == 0:
zero_count += 1
else:
negative_count += 1
print(positive_count / n)
print(nega... |
class Colors:
"""
This is a class that helps with printing out colors to the terminal.
"""
BLUE = '\033[96m'
PINK = '\033[95m'
PURPLE = '\033[94m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
RED = '\033[91m'
ENDC = '\033[0m'
CLEAR = '\x1b[2J\x1b[H'
def clear_screen(self):
... | class Colors:
"""
This is a class that helps with printing out colors to the terminal.
"""
blue = '\x1b[96m'
pink = '\x1b[95m'
purple = '\x1b[94m'
green = '\x1b[92m'
yellow = '\x1b[93m'
red = '\x1b[91m'
endc = '\x1b[0m'
clear = '\x1b[2J\x1b[H'
def clear_screen(self):
... |
ERROR_CHAR = "\u274c"
SUCCESS_CHAR = "\u2713"
def missingConfigurationFile():
print(
f"{ERROR_CHAR} nocpeasy.yml file does not exist, run `ocpeasy scaffold|init` first"
)
def stageCreated(stageId: str, pathProject: str):
print(
f"{SUCCESS_CHAR} new OpenShift stage created ({stageId}) for... | error_char = '❌'
success_char = '✓'
def missing_configuration_file():
print(f'{ERROR_CHAR} nocpeasy.yml file does not exist, run `ocpeasy scaffold|init` first')
def stage_created(stageId: str, pathProject: str):
print(f'{SUCCESS_CHAR} new OpenShift stage created ({stageId}) for project [{pathProject}]')
def ... |
# a Star topology centered on Z
# D G J
# \ | /
# \ | /
# E H K
# \ | /
# \ | /
# F I L
# \ | /
# ... | topo = {'A': ['B'], 'B': ['A', 'C'], 'C': ['B', 'Z'], 'D': ['E'], 'E': ['D', 'F'], 'F': ['E', 'Z'], 'G': ['H'], 'H': ['G', 'I'], 'I': ['H', 'Z'], 'J': ['K'], 'K': ['J', 'L'], 'L': ['K', 'Z'], 'M': ['Z', 'N'], 'N': ['M', 'O'], 'O': ['N'], 'P': ['Z', 'Q'], 'Q': ['P', 'R'], 'R': ['Q'], 'S': ['Z', 'T'], 'T': ['S', 'U'], 'U... |
"""
Codemonk link: https://www.hackerearth.com/problem/algorithm/the-monk-and-kundan-6f73d491/
Kundan being a good friend of Monk, lets the Monk know that he has a following string Initial which consists of the
following letters in the mentioned order: "abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ". ... | """
Codemonk link: https://www.hackerearth.com/problem/algorithm/the-monk-and-kundan-6f73d491/
Kundan being a good friend of Monk, lets the Monk know that he has a following string Initial which consists of the
following letters in the mentioned order: "abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ". ... |
class ErrorCode:
INVALID_ARGUMENT = 2
NOT_YET_SUPPORTED = 8
MISSING_REQUIREMENT = 9
FILE_NOT_FOUND = 20
FILE_CORRUPTED = 21
VPN_SERVICE_IS_NOT_WORKING = 90
VPN_ACCOUNT_NOT_FOUND = 91
VPN_ACCOUNT_NOT_MATCH = 92
VPN_NOT_YET_INSTALLED = 98
VPN_ALREADY_INSTALLED = 98
VPN_START_FA... | class Errorcode:
invalid_argument = 2
not_yet_supported = 8
missing_requirement = 9
file_not_found = 20
file_corrupted = 21
vpn_service_is_not_working = 90
vpn_account_not_found = 91
vpn_account_not_match = 92
vpn_not_yet_installed = 98
vpn_already_installed = 98
vpn_start_fa... |
"""
Store the global parameter dictionary to be imported and modified by each test
"""
OPT = {'dataset': 'Cora', 'self_loop_weight': 1, 'leaky_relu_slope': 0.2, 'heads': 2, 'K': 10,
'attention_norm_idx': 0, 'add_source': False, 'alpha': 1, 'alpha_dim': 'vc', 'beta_dim': 'vc',
'hidden_di... | """
Store the global parameter dictionary to be imported and modified by each test
"""
opt = {'dataset': 'Cora', 'self_loop_weight': 1, 'leaky_relu_slope': 0.2, 'heads': 2, 'K': 10, 'attention_norm_idx': 0, 'add_source': False, 'alpha': 1, 'alpha_dim': 'vc', 'beta_dim': 'vc', 'hidden_dim': 6, 'block': 'attention', 'fun... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.