content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
nome = input('Qual o seu nome? ')
sobrenome = input('Qual o seu sobrenome? ')
print('Seja bem-vindo(a), {} {}!'.format(nome, sobrenome))
print('Ordem natural: {0} {1}'.format(nome, sobrenome))
print('Ordem inversa: {1} {0}'.format(nome, sobrenome))
print('Outra forma: {0} {1} {other}'.format(nome, sobrenome, other = 'Santos')) | nome = input('Qual o seu nome? ')
sobrenome = input('Qual o seu sobrenome? ')
print('Seja bem-vindo(a), {} {}!'.format(nome, sobrenome))
print('Ordem natural: {0} {1}'.format(nome, sobrenome))
print('Ordem inversa: {1} {0}'.format(nome, sobrenome))
print('Outra forma: {0} {1} {other}'.format(nome, sobrenome, other='Santos')) |
# import time
# import os
# import stat
# import random
# import string
#
# import pytest
#
# import cattle
#
# from kubernetes import client as k8sclient, config as k8sconfig
#
BASE_URL = "http://%ip%:9333/v1"
token = ""
fqdn = ""
create_param = {
'fqdn': '',
'hosts': ["1.1.1.1", "2.2.2.2"]
}
update_param = {
'fqdn': '',
'hosts': ["3.3.3.3"]
}
def set_token_fqdn(result):
global token, fqdn
token = result['token']
fqdn = result['data']['fqdn']
def get_token_fqdn():
return token, fqdn
# SIZE = str(16 * 1024 * 1024)
# VOLUME_NAME = "longhorn-testvol"
# DEV_PATH = "/dev/longhorn/"
# VOLUME_RWTEST_SIZE = 512
# VOLUME_INVALID_POS = -1
# PORT = ":9500"
#
# RETRY_COUNTS = 300
# RETRY_ITERVAL = 0.5
#
# LONGHORN_NAMESPACE = "longhorn-system"
#
# COMPATIBILTY_TEST_IMAGE_PREFIX = "rancher/longhorn-test:version-test"
# UPGRADE_TEST_IMAGE_PREFIX = "rancher/longhorn-test:upgrade-test"
#
# ISCSI_DEV_PATH = "/dev/disk/by-path"
#
#
# @pytest.fixture
# def clients(request):
# k8sconfig.load_incluster_config()
# ips = get_mgr_ips()
# client = get_client(ips[0] + PORT)
# hosts = client.list_host()
# assert len(hosts) == len(ips)
# clis = get_clients(hosts)
# request.addfinalizer(lambda: cleanup_clients(clis))
# cleanup_clients(clis)
# return clis
#
#
# def cleanup_clients(clis):
# client = clis.itervalues().next()
# volumes = client.list_volume()
# for v in volumes:
# # ignore the error when clean up
# try:
# client.delete(v)
# except Exception:
# pass
# images = client.list_engine_image()
# for img in images:
# if not img["default"]:
# # ignore the error when clean up
# try:
# client.delete(img)
# except Exception:
# pass
#
#
# def get_client(address):
# url = 'http://' + address + '/v1/schemas'
# c = cattle.from_env(url=url)
# return c
#
#
# def get_mgr_ips():
# ret = k8sclient.CoreV1Api().list_pod_for_all_namespaces(
# label_selector="app=longhorn-manager",
# watch=False)
# mgr_ips = []
# for i in ret.items:
# mgr_ips.append(i.status.pod_ip)
# return mgr_ips
#
#
# def get_self_host_id():
# envs = os.environ
# return envs["NODE_NAME"]
#
#
# def get_backupstore_url():
# backupstore = os.environ['LONGHORN_BACKUPSTORES']
# backupstore = backupstore.replace(" ", "")
# backupstores = backupstore.split(",")
#
# assert len(backupstores) != 0
# return backupstores
#
#
# def get_clients(hosts):
# clients = {}
# for host in hosts:
# assert host["uuid"] is not None
# assert host["address"] is not None
# clients[host["uuid"]] = get_client(host["address"] + PORT)
# return clients
#
#
# def wait_for_device_login(dest_path, name):
# dev = ""
# for i in range(RETRY_COUNTS):
# files = os.listdir(dest_path)
# if name in files:
# dev = name
# break
# time.sleep(RETRY_ITERVAL)
# assert dev == name
# return dev
#
#
# def wait_for_volume_state(client, name, state):
# for i in range(RETRY_COUNTS):
# volume = client.by_id_volume(name)
# if volume["state"] == state:
# break
# time.sleep(RETRY_ITERVAL)
# assert volume["state"] == state
# return volume
#
#
# def wait_for_volume_delete(client, name):
# for i in range(RETRY_COUNTS):
# volumes = client.list_volume()
# found = False
# for volume in volumes:
# if volume["name"] == name:
# found = True
# if not found:
# break
# time.sleep(RETRY_ITERVAL)
# assert not found
#
#
# def wait_for_volume_engine_image(client, name, image):
# for i in range(RETRY_COUNTS):
# volume = client.by_id_volume(name)
# if volume["engineImage"] == image:
# break
# time.sleep(RETRY_ITERVAL)
# assert volume["engineImage"] == image
# return volume
#
#
# def wait_for_volume_replica_count(client, name, count):
# for i in range(RETRY_COUNTS):
# volume = client.by_id_volume(name)
# if len(volume["replicas"]) == count:
# break
# time.sleep(RETRY_ITERVAL)
# assert len(volume["replicas"]) == count
# return volume
#
#
# def wait_for_snapshot_purge(volume, *snaps):
# for i in range(RETRY_COUNTS):
# snapshots = volume.snapshotList(volume=volume["name"])
# snapMap = {}
# for snap in snapshots:
# snapMap[snap["name"]] = snap
# found = False
# for snap in snaps:
# if snap in snapMap:
# found = True
# break
# if not found:
# break
# time.sleep(RETRY_ITERVAL)
# assert not found
#
#
# def wait_for_engine_image_state(client, image_name, state):
# for i in range(RETRY_COUNTS):
# image = client.by_id_engine_image(image_name)
# if image["state"] == state:
# break
# time.sleep(RETRY_ITERVAL)
# assert image["state"] == state
# return image
#
#
# def wait_for_engine_image_ref_count(client, image_name, count):
# for i in range(RETRY_COUNTS):
# image = client.by_id_engine_image(image_name)
# if image["refCount"] == count:
# break
# time.sleep(RETRY_ITERVAL)
# assert image["refCount"] == count
# if count == 0:
# assert image["noRefSince"] != ""
# return image
#
#
# def k8s_delete_replica_pods_for_volume(volname):
# k8sclient.CoreV1Api().delete_collection_namespaced_pod(
# label_selector="longhorn-volume-replica=" + volname,
# namespace=LONGHORN_NAMESPACE,
# watch=False)
#
#
# @pytest.fixture
# def volume_name(request):
# return generate_volume_name()
#
#
# @pytest.fixture
# def csi_pvc_name(request):
# return generate_volume_name()
#
#
# def generate_volume_name():
# return VOLUME_NAME + "-" + \
# ''.join(random.choice(string.ascii_lowercase + string.digits)
# for _ in range(6))
#
#
# def get_default_engine_image(client):
# images = client.list_engine_image()
# for img in images:
# if img["default"]:
# return img
# assert False
#
#
# def get_compatibility_test_image(cli_v, cli_minv,
# ctl_v, ctl_minv,
# data_v, data_minv):
# return "%s.%d-%d.%d-%d.%d-%d" % (COMPATIBILTY_TEST_IMAGE_PREFIX,
# cli_v, cli_minv,
# ctl_v, ctl_minv,
# data_v, data_minv)
#
#
# def generate_random_data(count):
# return ''.join(random.choice(string.ascii_lowercase + string.digits)
# for _ in range(count))
#
#
# def volume_read(dev, start, count):
# r_data = ""
# fdev = open(dev, 'rb')
# if fdev is not None:
# fdev.seek(start)
# r_data = fdev.read(count)
# fdev.close()
# return r_data
#
#
# def volume_write(dev, start, data):
# w_length = 0
# fdev = open(dev, 'rb+')
# if fdev is not None:
# fdev.seek(start)
# fdev.write(data)
# fdev.close()
# w_length = len(data)
# return w_length
#
#
# def volume_valid(dev):
# return stat.S_ISBLK(os.stat(dev).st_mode)
#
#
# def parse_iscsi_endpoint(iscsi):
# iscsi_endpoint = iscsi[8:]
# return iscsi_endpoint.split('/')
#
#
# def get_iscsi_ip(iscsi):
# iscsi_endpoint = parse_iscsi_endpoint(iscsi)
# ip = iscsi_endpoint[0].split(':')
# return ip[0]
#
#
# def get_iscsi_port(iscsi):
# iscsi_endpoint = parse_iscsi_endpoint(iscsi)
# ip = iscsi_endpoint[0].split(':')
# return ip[1]
#
#
# def get_iscsi_target(iscsi):
# iscsi_endpoint = parse_iscsi_endpoint(iscsi)
# return iscsi_endpoint[1]
#
#
# def get_iscsi_lun(iscsi):
# iscsi_endpoint = parse_iscsi_endpoint(iscsi)
# return iscsi_endpoint[2]
#
#
# def exec_nsenter(cmd):
# exec_cmd = "nsenter --mount=/host/proc/1/ns/mnt \
# --net=/host/proc/1/ns/net bash -c \"" + cmd + "\""
# fp = os.popen(exec_cmd)
# ret = fp.read()
# fp.close()
# return ret
#
#
# def iscsi_login(iscsi_ep):
# ip = get_iscsi_ip(iscsi_ep)
# port = get_iscsi_port(iscsi_ep)
# target = get_iscsi_target(iscsi_ep)
# lun = get_iscsi_lun(iscsi_ep)
# # discovery
# cmd_discovery = "iscsiadm -m discovery -t st -p " + ip
# exec_nsenter(cmd_discovery)
# # login
# cmd_login = "iscsiadm -m node -T " + target + " -p " + ip + " --login"
# exec_nsenter(cmd_login)
# blk_name = "ip-%s:%s-iscsi-%s-lun-%s" % (ip, port, target, lun)
# wait_for_device_login(ISCSI_DEV_PATH, blk_name)
# dev = os.path.realpath(ISCSI_DEV_PATH + "/" + blk_name)
# return dev
#
#
# def iscsi_logout(iscsi_ep):
# ip = get_iscsi_ip(iscsi_ep)
# target = get_iscsi_target(iscsi_ep)
# cmd_logout = "iscsiadm -m node -T " + target + " -p " + ip + " --logout"
# exec_nsenter(cmd_logout)
# cmd_rm_discovery = "iscsiadm -m discovery -p " + ip + " -o delete"
# exec_nsenter(cmd_rm_discovery)
#
#
# def generate_random_pos(size, used={}):
# for i in range(RETRY_COUNTS):
# pos = 0
# if int(SIZE) != size:
# pos = random.randrange(0, int(SIZE) - size, 1)
# collided = False
# # it's [start, end) vs [pos, pos + size)
# for start, end in used.items():
# if pos + size <= start or pos >= end:
# continue
# collided = True
# break
# if not collided:
# break
# assert not collided
# used[pos] = pos + size
# return pos
#
#
# def get_upgrade_test_image(cli_v, cli_minv,
# ctl_v, ctl_minv,
# data_v, data_minv):
# return "%s.%d-%d.%d-%d.%d-%d" % (UPGRADE_TEST_IMAGE_PREFIX,
# cli_v, cli_minv,
# ctl_v, ctl_minv,
# data_v, data_minv)
| base_url = 'http://%ip%:9333/v1'
token = ''
fqdn = ''
create_param = {'fqdn': '', 'hosts': ['1.1.1.1', '2.2.2.2']}
update_param = {'fqdn': '', 'hosts': ['3.3.3.3']}
def set_token_fqdn(result):
global token, fqdn
token = result['token']
fqdn = result['data']['fqdn']
def get_token_fqdn():
return (token, fqdn) |
a, b, i = 0, 1, 2
fibo = [a, b]
while i < 100:
i = i + 1
a, b = b, a+b
fibo.append(b)
| (a, b, i) = (0, 1, 2)
fibo = [a, b]
while i < 100:
i = i + 1
(a, b) = (b, a + b)
fibo.append(b) |
# Recursive solution for permutation
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
result = []
self.permu_helper(nums, [], result)
return result
def permu_helper(self, new_list, temp, result):
if len(new_list) == 0:
result.append(temp)
return
for i in range(len(new_list)):
self.permu_helper(new_list[:i]+new_list[i+1:],temp+[new_list[i]], result ) | class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
result = []
self.permu_helper(nums, [], result)
return result
def permu_helper(self, new_list, temp, result):
if len(new_list) == 0:
result.append(temp)
return
for i in range(len(new_list)):
self.permu_helper(new_list[:i] + new_list[i + 1:], temp + [new_list[i]], result) |
rankDict = {
'1': 'A',
'11': 'J',
'12': 'Q',
'13': 'K'
}
class Rank:
def __init__(self, number):
if not (1 <= number <= 13):
raise Exception("number is out of range")
self.number = number
def __str__(self):
return rankDict.get(str(self.number), str(self.number))
| rank_dict = {'1': 'A', '11': 'J', '12': 'Q', '13': 'K'}
class Rank:
def __init__(self, number):
if not 1 <= number <= 13:
raise exception('number is out of range')
self.number = number
def __str__(self):
return rankDict.get(str(self.number), str(self.number)) |
def server(host, port, symmetricKey):
sockVanilla = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sockVanilla.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sockVanilla.bind((host, port))
sockVanilla.listen(5)
while True:
sockClientVanilla, source = sockVanilla.accept()
sock = EasySafeSocket(sockClientVanilla, symmetricKey)
threading.Thread(target=OnConnection, args=(sock, source[0], source[1])).start()
| def server(host, port, symmetricKey):
sock_vanilla = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sockVanilla.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sockVanilla.bind((host, port))
sockVanilla.listen(5)
while True:
(sock_client_vanilla, source) = sockVanilla.accept()
sock = easy_safe_socket(sockClientVanilla, symmetricKey)
threading.Thread(target=OnConnection, args=(sock, source[0], source[1])).start() |
name_list= ['Sharon','Mic','Josh','Hannah','Hansel']
height_list = [172,166,187,200,166]
weight_list = [59.5,65.6,49.8,64.2,47.5]
size_list = ['M','L','S','M','S']
bmi_list = []
for i in range(len(name_list)):
bmi = weight_list[i]/((height_list[i]/100)**2)
bmi_list.append('{:.2f}'.format(bmi))
print("{:<10} {:<8} {:<8} {:<8} {:<5}".format('Name','Weight','Height','BMI','Size'))
for i in range(len(name_list)):
print("{:<10} {:<8} {:<8} {:<8} {:<5}".format(name_list[i], weight_list[i],height_list[i],bmi_list[i],size_list[i])) | name_list = ['Sharon', 'Mic', 'Josh', 'Hannah', 'Hansel']
height_list = [172, 166, 187, 200, 166]
weight_list = [59.5, 65.6, 49.8, 64.2, 47.5]
size_list = ['M', 'L', 'S', 'M', 'S']
bmi_list = []
for i in range(len(name_list)):
bmi = weight_list[i] / (height_list[i] / 100) ** 2
bmi_list.append('{:.2f}'.format(bmi))
print('{:<10} {:<8} {:<8} {:<8} {:<5}'.format('Name', 'Weight', 'Height', 'BMI', 'Size'))
for i in range(len(name_list)):
print('{:<10} {:<8} {:<8} {:<8} {:<5}'.format(name_list[i], weight_list[i], height_list[i], bmi_list[i], size_list[i])) |
def get_fuel(fuel):
fuel = ((fuel // 3) - 2)
if fuel <= 0:
return 0
return fuel + get_fuel(fuel)
total = 0
with open("d1.txt", "r") as f:
for line in f:
total += get_fuel(int(line))
print(total)
| def get_fuel(fuel):
fuel = fuel // 3 - 2
if fuel <= 0:
return 0
return fuel + get_fuel(fuel)
total = 0
with open('d1.txt', 'r') as f:
for line in f:
total += get_fuel(int(line))
print(total) |
print("""
Note!
A matrix is said to be sparse matrix if most of the elements of that matrix are 0.
It implies that it contains very less non-zero elements.
""")
# To check whether the given matrix is the sparse matrix or not,
# we first count the number of zero elements present in the matrix.
# Then calculate the size of the matrix.
# For the matrix to be sparse, count of zero elements present in an array must be greater than size/2.
matrix=[]
row=int(input("Enter row size of the matrix: "))
column=int(input("Enter column size of the matrix: "))
for i in range(row):
a=[]
for j in range(column):
j=int(input(f"Enter elements of the matrix at poistion row({i})column({j}): "))
a.append(j)
print()
matrix.append(a)
print("Elements of the matrix: ")
for i in range(row):
for j in range(column):
print(matrix[i][j],end=" ")
print()
count =0
#Calculate the size of the array
size=row*column
#count all zero elements present in matrix
for i in range(row):
for j in range(column):
if matrix[i][j]==0:
count=count+1
if count>size/2:
print("Given matrix is a sparse matrix")
else:
print("Given matrix is not a sparse matrix")
| print('\nNote!\nA matrix is said to be sparse matrix if most of the elements of that matrix are 0.\nIt implies that it contains very less non-zero elements.\n')
matrix = []
row = int(input('Enter row size of the matrix: '))
column = int(input('Enter column size of the matrix: '))
for i in range(row):
a = []
for j in range(column):
j = int(input(f'Enter elements of the matrix at poistion row({i})column({j}): '))
a.append(j)
print()
matrix.append(a)
print('Elements of the matrix: ')
for i in range(row):
for j in range(column):
print(matrix[i][j], end=' ')
print()
count = 0
size = row * column
for i in range(row):
for j in range(column):
if matrix[i][j] == 0:
count = count + 1
if count > size / 2:
print('Given matrix is a sparse matrix')
else:
print('Given matrix is not a sparse matrix') |
"""
15740 : A+B - 9
URL : https://www.acmicpc.net/problem/15750
Input #1 :
1 2
Output #1 :
3
Input #2 :
-60 40
Output #2 :
-20
Input #3 :
-999999999 1000000000
Output #3 :
1
Input #4 :
1099511627776 1073741824
Output #4 :
1100585369600
Input #5 :
123456789123456789123456789 987654321987654321987654321
Output #5 :
1111111111111111111111111110
"""
a, b = map(int, input().split())
print(a + b)
| """
15740 : A+B - 9
URL : https://www.acmicpc.net/problem/15750
Input #1 :
1 2
Output #1 :
3
Input #2 :
-60 40
Output #2 :
-20
Input #3 :
-999999999 1000000000
Output #3 :
1
Input #4 :
1099511627776 1073741824
Output #4 :
1100585369600
Input #5 :
123456789123456789123456789 987654321987654321987654321
Output #5 :
1111111111111111111111111110
"""
(a, b) = map(int, input().split())
print(a + b) |
def impares_no_intervalo(intervalo: tuple, lista: list):
inicial, final = intervalo
return [numero for numero in lista if numero % 2 != 0 and inicial <= numero <= final]
limite = (0,10)
l = [-2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
# --- OUTPUT ---
# [1, 3, 5, 7, 9]
print(impares_no_intervalo(limite, l))
| def impares_no_intervalo(intervalo: tuple, lista: list):
(inicial, final) = intervalo
return [numero for numero in lista if numero % 2 != 0 and inicial <= numero <= final]
limite = (0, 10)
l = [-2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
print(impares_no_intervalo(limite, l)) |
# -- coding:utf-8--
class DL(object):
def __init__(self):
self.dlcs = 0
def q(self):
self.dlcs = self.dlcs + 1
print(str(self.dlcs))
def a(self):
self.dlcs = 0
print(str(self.dlcs))
hi = DL()
hi.q()
hi.q()
hi.q()
hi.q()
hi.q()
hi.a() | class Dl(object):
def __init__(self):
self.dlcs = 0
def q(self):
self.dlcs = self.dlcs + 1
print(str(self.dlcs))
def a(self):
self.dlcs = 0
print(str(self.dlcs))
hi = dl()
hi.q()
hi.q()
hi.q()
hi.q()
hi.q()
hi.a() |
#
# This file contains the Python code from Program 8.20 of
# "Data Structures and Algorithms
# with Object-Oriented Design Patterns in Python"
# by Bruno R. Preiss.
#
# Copyright (c) 2003 by Bruno R. Preiss, P.Eng. All rights reserved.
#
# http://www.brpreiss.com/books/opus7/programs/pgm08_20.txt
#
class OpenScatterTableV2(OpenScatterTable):
def withdraw(self, obj):
if self._count == 0:
raise ContainerEmpty
i = self.findInstance(obj)
if i < 0:
raise KeyError
while True:
j = (i + 1) % len(self)
while self._array[j]._state == self.OCCUPIED:
h = self.h(self._array[j]._obj)
if ((h <= i and i < j) or (i < j and j < h) or \
(j < h and h <= i)):
break
j = (j + 1) % len(self)
if self._array[j]._state == self.EMPTY:
break
self._array[i] = self._array[j]
i = j
self._array[i] = self.Entry(self.EMPTY, None)
self._count -= 1
# ...
| class Openscattertablev2(OpenScatterTable):
def withdraw(self, obj):
if self._count == 0:
raise ContainerEmpty
i = self.findInstance(obj)
if i < 0:
raise KeyError
while True:
j = (i + 1) % len(self)
while self._array[j]._state == self.OCCUPIED:
h = self.h(self._array[j]._obj)
if h <= i and i < j or (i < j and j < h) or (j < h and h <= i):
break
j = (j + 1) % len(self)
if self._array[j]._state == self.EMPTY:
break
self._array[i] = self._array[j]
i = j
self._array[i] = self.Entry(self.EMPTY, None)
self._count -= 1 |
# CodeWars Count_Of_Positives_/_Sum_Of_Negatives
def count_positives_sum_negatives(arr):
null_list = []
sum_of_positives = 0
sum_of_negatives = 0
if arr == [0, 0] or arr == []:
return null_list
for i in arr:
if i > 0:
sum_of_positives += 1
elif i < 0:
sum_of_negatives += i
else:
continue
return [sum_of_positives, sum_of_negatives]
| def count_positives_sum_negatives(arr):
null_list = []
sum_of_positives = 0
sum_of_negatives = 0
if arr == [0, 0] or arr == []:
return null_list
for i in arr:
if i > 0:
sum_of_positives += 1
elif i < 0:
sum_of_negatives += i
else:
continue
return [sum_of_positives, sum_of_negatives] |
"""
best time to use this times you're pretty sure list is almost sorted
o(n)
worst case(o(n^2))
"""
array = [99, 44, 6, 2, 1, 5, 63, 87, 283, 40]
def insertionSort(array):
count = 0
for i in range(1, len(array)):
first = array[i]
last = array[i-1] # store the last element which is sorted
count += 1
if first < last:
for j in range(i-1, -1, -1): # for every element we find in the sorted part which is greter than the current element, we shift them one place towards right to make room for the current element
count += 1
if first < array[j]:
if j == 0: # reach the beginning of array
array[j+1] = array[j]
array[j] = first
else:
array[j+1] = array[j]
else:
array[j+1] = first
break
return array
print(insertionSort(array))
| """
best time to use this times you're pretty sure list is almost sorted
o(n)
worst case(o(n^2))
"""
array = [99, 44, 6, 2, 1, 5, 63, 87, 283, 40]
def insertion_sort(array):
count = 0
for i in range(1, len(array)):
first = array[i]
last = array[i - 1]
count += 1
if first < last:
for j in range(i - 1, -1, -1):
count += 1
if first < array[j]:
if j == 0:
array[j + 1] = array[j]
array[j] = first
else:
array[j + 1] = array[j]
else:
array[j + 1] = first
break
return array
print(insertion_sort(array)) |
class Student:
email = 'default@redi-school.org'
def __init__(self, name, birthday, courses):
# class public attributes
self.full_name = name
self.first_name = name.split(' ')[0]
self.birthday = birthday
self.courses = courses
self.attendance = []
# Objects
john = Student('John Schneider', '2010-04-05', ['German', 'Arts', 'History'])
mary = Student('Mary von Neumann', '2010-05-06',
['German', 'Math', 'Geography', 'Science'])
lucy = Student('Lucy Schwarz', '2010-07-08', ['English', 'Math', 'Dance'])
# The class attribute can be changed for a single object
lucy.email = 'lucy@redi-school.org'
print(f'{lucy.first_name} can be contacted at {lucy.email}')
# Lucy can be contacted at lucy@redi-school.org
# But it didn't change the others
print(f'{john.first_name} can be contacted at {john.email}')
# John can be contacted at default@redi-school.org
# Or for all objects that didn't have changed it.
for student in [john, mary, lucy]:
print(f'{student.first_name}:{student.email}')
# John:default@redi.org
# Mary:default@redi.org
# Lucy:lucy@redi-school.org
# Changing the class attribute will be visible if the object does not have an
# attribute with the same name
Student.email = 'default@redi.org'
for student in [john, mary, lucy]:
# Note that there is no warning at email now.
print(f'{student.first_name}:{student.email}')
# John:default@redi.org
# Maria:default@redi.org
# Lucy:lucy@redi-school.org
# Changing the attribute for an object doesn't affect the class attribute.
john.email = 'john@redi.org'
for student in [john, mary, lucy]:
print(f'{student.first_name}:{student.email}')
# John:john@redi.org
# Maria:default@redi.org
# Lucy:lucy@redi-school.org
| class Student:
email = 'default@redi-school.org'
def __init__(self, name, birthday, courses):
self.full_name = name
self.first_name = name.split(' ')[0]
self.birthday = birthday
self.courses = courses
self.attendance = []
john = student('John Schneider', '2010-04-05', ['German', 'Arts', 'History'])
mary = student('Mary von Neumann', '2010-05-06', ['German', 'Math', 'Geography', 'Science'])
lucy = student('Lucy Schwarz', '2010-07-08', ['English', 'Math', 'Dance'])
lucy.email = 'lucy@redi-school.org'
print(f'{lucy.first_name} can be contacted at {lucy.email}')
print(f'{john.first_name} can be contacted at {john.email}')
for student in [john, mary, lucy]:
print(f'{student.first_name}:{student.email}')
Student.email = 'default@redi.org'
for student in [john, mary, lucy]:
print(f'{student.first_name}:{student.email}')
john.email = 'john@redi.org'
for student in [john, mary, lucy]:
print(f'{student.first_name}:{student.email}') |
"""
Creational :
Builder => every builders designed patterns has director class to attach
each side of objects
"""
class Director:
__builder = None
def set_builder(self, builder):
self.__builder = builder
def get_car(self):
car = Car()
body = self.__builder.get_body()
car.set_body(body)
wheel = self.__builder.get_wheel()
car.set_wheel(wheel)
engine = self.__builder.get_engine()
car.set_engine(engine)
return car
# ----------------------------------------
class Car:
def __init__(self):
self.__wheel = None
self.__engine = None
self.__body = None
def set_wheel(self, wheel):
self.__wheel = wheel
def set_body(self, body):
self.__body = body
def set_engine(self, engine):
self.__engine = engine
def detail(self):
print(f'Body: {self.__body.shape}')
print(f'Engine: {self.__engine.hp}')
print(f'Wheel: {self.__wheel.size}')
# ----------------------------------------
class Builder:
def get_engine(self):
pass
def get_wheel(self):
pass
def get_body(self):
pass
class Benz(Builder):
def get_body(self):
body = Body()
body.shape = 'Suv'
return body
def get_engine(self):
engine = Engine()
engine.hp = 500
return engine
def get_wheel(self):
wheel = Wheel()
wheel.size = 22
return wheel
class Bmw(Builder):
def get_body(self):
body = Body()
body.shape = 'Sedan'
return body
def get_engine(self):
engine = Engine()
engine.hp = 340
return engine
def get_wheel(self):
wheel = Wheel()
wheel.size = 18
return wheel
# ----------------------------------------
class Wheel:
size = None
class Body:
shape = None
class Engine:
hp = None
# ----------------------------------------
car1 = Bmw()
director = Director()
director.set_builder(car1)
b1 = director.get_car()
b1.detail()
| """
Creational :
Builder => every builders designed patterns has director class to attach
each side of objects
"""
class Director:
__builder = None
def set_builder(self, builder):
self.__builder = builder
def get_car(self):
car = car()
body = self.__builder.get_body()
car.set_body(body)
wheel = self.__builder.get_wheel()
car.set_wheel(wheel)
engine = self.__builder.get_engine()
car.set_engine(engine)
return car
class Car:
def __init__(self):
self.__wheel = None
self.__engine = None
self.__body = None
def set_wheel(self, wheel):
self.__wheel = wheel
def set_body(self, body):
self.__body = body
def set_engine(self, engine):
self.__engine = engine
def detail(self):
print(f'Body: {self.__body.shape}')
print(f'Engine: {self.__engine.hp}')
print(f'Wheel: {self.__wheel.size}')
class Builder:
def get_engine(self):
pass
def get_wheel(self):
pass
def get_body(self):
pass
class Benz(Builder):
def get_body(self):
body = body()
body.shape = 'Suv'
return body
def get_engine(self):
engine = engine()
engine.hp = 500
return engine
def get_wheel(self):
wheel = wheel()
wheel.size = 22
return wheel
class Bmw(Builder):
def get_body(self):
body = body()
body.shape = 'Sedan'
return body
def get_engine(self):
engine = engine()
engine.hp = 340
return engine
def get_wheel(self):
wheel = wheel()
wheel.size = 18
return wheel
class Wheel:
size = None
class Body:
shape = None
class Engine:
hp = None
car1 = bmw()
director = director()
director.set_builder(car1)
b1 = director.get_car()
b1.detail() |
class NumArray(object):
def __init__(self, nums):
"""
initialize your data structure here.
:type nums: List[int]
"""
self.nums = [0] * len(nums)
self.sums = [0] * (len(nums) + 1)
for i, num in enumerate(nums):
self.update(i, num)
def update(self, i, val):
"""
:type i: int
:type val: int
:rtype: int
"""
old = self.nums[i]
self.nums[i] = val
diff = val - old
i += 1
while i < len(self.sums):
self.sums[i] += diff
i += i & (-i)
def sum(self, i):
sum = 0
i += 1
while i != 0:
sum += self.sums[i]
i -= i & (-i)
return sum
def sumRange(self, i, j):
"""
sum of elements nums[i..j], inclusive.
:type i: int
:type j: int
:rtype: int
"""
return self.sum(j) - self.sum(i - 1)
# Your NumArray object will be instantiated and called as such:
# numArray = NumArray(nums)
# numArray.sumRange(0, 1)
# numArray.update(1, 10)
# numArray.sumRange(1, 2)
| class Numarray(object):
def __init__(self, nums):
"""
initialize your data structure here.
:type nums: List[int]
"""
self.nums = [0] * len(nums)
self.sums = [0] * (len(nums) + 1)
for (i, num) in enumerate(nums):
self.update(i, num)
def update(self, i, val):
"""
:type i: int
:type val: int
:rtype: int
"""
old = self.nums[i]
self.nums[i] = val
diff = val - old
i += 1
while i < len(self.sums):
self.sums[i] += diff
i += i & -i
def sum(self, i):
sum = 0
i += 1
while i != 0:
sum += self.sums[i]
i -= i & -i
return sum
def sum_range(self, i, j):
"""
sum of elements nums[i..j], inclusive.
:type i: int
:type j: int
:rtype: int
"""
return self.sum(j) - self.sum(i - 1) |
def get_ip_address(request):
"""use request object to fetch client machine's IP Address"""
x_forwarded_for = request.META.get("HTTP_X_FORWARDED_FOR")
if x_forwarded_for:
ip = x_forwarded_for.split(",")[0]
else:
ip = request.META.get("REMOTE_ADDR") ### Real IP address of client Machine
return ip
def phone_num_val(phone_number):
phone_number_list = list(phone_number)
phone_number_list[0] = "234"
p = "".join([str(elem) for elem in phone_number_list])
return p
| def get_ip_address(request):
"""use request object to fetch client machine's IP Address"""
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
if x_forwarded_for:
ip = x_forwarded_for.split(',')[0]
else:
ip = request.META.get('REMOTE_ADDR')
return ip
def phone_num_val(phone_number):
phone_number_list = list(phone_number)
phone_number_list[0] = '234'
p = ''.join([str(elem) for elem in phone_number_list])
return p |
# Task
# Given sets of integers, M and N, print their symmetric difference in ascending order.
# The term symmetric difference indicates those values that exist in either M or N but do not
# exist in both.
#
# Input Format
# The first line of input contains an integer, M.
# The second line contains M space-separated integers.
# The third line contains an integer, N.
# The fourth line contains N space-separated integers.
#
# Output Format
# Output the symmetric difference integers in ascending order, one per line.
#
# Sample Input
# 4
# 2 4 5 9
# 4
# 2 4 11 12
# Sample Output
# 5
# 9
# 11
# 12
m, m_set = int(input()), set(input().split())
n, n_set = int(input()), set(input().split())
values_in_m = m_set.difference(n_set)
values_in_n = n_set.difference(m_set)
m_union_n = values_in_m.union(values_in_n)
for number in sorted(int(i) for i in m_union_n):
print(number)
| (m, m_set) = (int(input()), set(input().split()))
(n, n_set) = (int(input()), set(input().split()))
values_in_m = m_set.difference(n_set)
values_in_n = n_set.difference(m_set)
m_union_n = values_in_m.union(values_in_n)
for number in sorted((int(i) for i in m_union_n)):
print(number) |
SOC_IRAM_LOW = 0x4037c000
SOC_IRAM_HIGH = 0x403e0000
SOC_DRAM_LOW = 0x3fc80000
SOC_DRAM_HIGH = 0x3fce0000
SOC_RTC_DRAM_LOW = 0x50000000
SOC_RTC_DRAM_HIGH = 0x50002000
SOC_RTC_DATA_LOW = 0x50000000
SOC_RTC_DATA_HIGH = 0x50002000
| soc_iram_low = 1077395456
soc_iram_high = 1077805056
soc_dram_low = 1070071808
soc_dram_high = 1070465024
soc_rtc_dram_low = 1342177280
soc_rtc_dram_high = 1342185472
soc_rtc_data_low = 1342177280
soc_rtc_data_high = 1342185472 |
class Node:
def __init__(self, data, next=None):
self.data = data
self.next = next
class LinkedList:
def __init__(self):
self.head = None
def insert_first(self, data):
node = Node(data, self.head)
self.head = node
def __repr__(self):
return str(self.head)
l = LinkedList()
l.insert_first(123)
print(l) | class Node:
def __init__(self, data, next=None):
self.data = data
self.next = next
class Linkedlist:
def __init__(self):
self.head = None
def insert_first(self, data):
node = node(data, self.head)
self.head = node
def __repr__(self):
return str(self.head)
l = linked_list()
l.insert_first(123)
print(l) |
"""Configuration Values"""
# DRIVER = 'mysql+pymysql://'
# URL_PARAMS = {
# 'username': 'root',
# 'password': 'root',
# 'host': 'localhost',
# 'port': '3306',
# 'database_name': 'hydro'
# }
# URL = DRIVER + '{username}:{password}@{host}:{port}/{database_name}'.format(
# **URL_PARAMS)
class Config(object):
# ENV = 'development'
# DEBUG = True
SECRET_KEY = ''.join(
'4ed2e994cba06266df65170068c57ae7227482ddac10cfbd49d35f8e28b5fa0b'
)
SEND_FILE_MAX_AGE_DEFAULT = 0
# SQLALCHEMY_DATABASE_URI = URL
# SQLALCHEMY_TRACK_MODIFICATIONS = False
# SQLALCHEMY_ECHO = True
| """Configuration Values"""
class Config(object):
secret_key = ''.join('4ed2e994cba06266df65170068c57ae7227482ddac10cfbd49d35f8e28b5fa0b')
send_file_max_age_default = 0 |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# Base exception class
class QlibException(Exception):
pass
class RecorderInitializationError(QlibException):
"""Error type for re-initialization when starting an experiment"""
class LoadObjectError(QlibException):
"""Error type for Recorder when can not load object"""
class ExpAlreadyExistError(Exception):
"""Experiment already exists"""
| class Qlibexception(Exception):
pass
class Recorderinitializationerror(QlibException):
"""Error type for re-initialization when starting an experiment"""
class Loadobjecterror(QlibException):
"""Error type for Recorder when can not load object"""
class Expalreadyexisterror(Exception):
"""Experiment already exists""" |
"""
Given an integer n and an integer start.
Define an array nums where nums[i] = start + 2*i (0-indexed) and
n == nums.length.
Return the bitwise XOR of all elements of nums.
Example:
Input: n = 5, start = 0
Output: 8
Explanation: Array nums is equal to [0, 2, 4, 6, 8]
where (0 ^ 2 ^ 4 ^ 6 ^ 8) = 8.
Where "^" corresponds to bitwise XOR operator.
Constraints:
- 1 <= n <= 1000
- 0 <= start <= 1000
- n == nums.length
"""
#Difficulty: Easy
#54 / 54 test cases passed.
#Runtime: 28 ms
#Memory Usage: 13.9 MB
#Runtime: 28 ms, faster than 85.34% of Python3 online submissions for XOR Operation in an Array.
#Memory Usage: 13.9 MB, less than 27.03% of Python3 online submissions for XOR Operation in an Array.
class Solution:
def xorOperation(self, n: int, start: int) -> int:
num = start
for i in range(1, n):
num ^= start + 2 * i
return num
| """
Given an integer n and an integer start.
Define an array nums where nums[i] = start + 2*i (0-indexed) and
n == nums.length.
Return the bitwise XOR of all elements of nums.
Example:
Input: n = 5, start = 0
Output: 8
Explanation: Array nums is equal to [0, 2, 4, 6, 8]
where (0 ^ 2 ^ 4 ^ 6 ^ 8) = 8.
Where "^" corresponds to bitwise XOR operator.
Constraints:
- 1 <= n <= 1000
- 0 <= start <= 1000
- n == nums.length
"""
class Solution:
def xor_operation(self, n: int, start: int) -> int:
num = start
for i in range(1, n):
num ^= start + 2 * i
return num |
#! /usr/bin/env python3
"""control the whitespaces in string"""
s = 'The Little Price'
# justify string to be at least width wide
# by adding whitespaces
width = 20
s1 = s.ljust(width)
s2 = s.rjust(width)
s3 = s.center(width)
print(s1) # 'The Little Price '
print(s2) # ' The Little Price'
print(s3) # ' The Little Price '
# strip whitespaces in two sides of string
print(s3.lstrip()) # 'The Little Price '
print(s3.rstrip()) # ' The Little Price'
print(s3.strip()) # 'The Little Price'
| """control the whitespaces in string"""
s = 'The Little Price'
width = 20
s1 = s.ljust(width)
s2 = s.rjust(width)
s3 = s.center(width)
print(s1)
print(s2)
print(s3)
print(s3.lstrip())
print(s3.rstrip())
print(s3.strip()) |
"""exercism armstrong numbers module."""
def is_armstrong_number(number):
"""
Determine if the number provided is an Armstrong Number.
An Armstrong Number is a number that is the sum of its own digits each raised to the power of the number of digits
:param number int - Number to check.
:return bool - Whether the provided number passes the check or not.
>>>is_armstrong_number(9)
True
# because `9 = 9^1 = 9`
>>>is_armstrong_number(10)
False
# because `10 != 1^2 + 0^2 = 1`
"""
number_string = list(str(number))
digit_sum = 0
power = len(number_string)
for digit in number_string:
digit_sum += int(digit) ** power
return digit_sum == number
| """exercism armstrong numbers module."""
def is_armstrong_number(number):
"""
Determine if the number provided is an Armstrong Number.
An Armstrong Number is a number that is the sum of its own digits each raised to the power of the number of digits
:param number int - Number to check.
:return bool - Whether the provided number passes the check or not.
>>>is_armstrong_number(9)
True
# because `9 = 9^1 = 9`
>>>is_armstrong_number(10)
False
# because `10 != 1^2 + 0^2 = 1`
"""
number_string = list(str(number))
digit_sum = 0
power = len(number_string)
for digit in number_string:
digit_sum += int(digit) ** power
return digit_sum == number |
"""Generic Models."""
class CaseInsensitiveString(str):
"""A case insensitive string to aid comparison."""
def __eq__(self, other: object) -> bool:
"""Determine whether this object and another object are equal.
Parameters:
other: The object to compare this one to.
Raises:
ValueError: When the object we are compared with is not of the same type.
"""
if not isinstance(other, (self.__class__, str)):
raise ValueError(f"Cannot compare {self.__class__.__name__} and {other.__class__.__name__}")
return self.lower() == other.lower()
def __hash__(self) -> int:
"""Compute the hash for this object."""
return hash(self.lower())
def __repr__(self) -> str:
"""Return an instantiable representation of this object."""
return f"{self.__class__.__name__}('{self}')"
| """Generic Models."""
class Caseinsensitivestring(str):
"""A case insensitive string to aid comparison."""
def __eq__(self, other: object) -> bool:
"""Determine whether this object and another object are equal.
Parameters:
other: The object to compare this one to.
Raises:
ValueError: When the object we are compared with is not of the same type.
"""
if not isinstance(other, (self.__class__, str)):
raise value_error(f'Cannot compare {self.__class__.__name__} and {other.__class__.__name__}')
return self.lower() == other.lower()
def __hash__(self) -> int:
"""Compute the hash for this object."""
return hash(self.lower())
def __repr__(self) -> str:
"""Return an instantiable representation of this object."""
return f"{self.__class__.__name__}('{self}')" |
def make_withdraw(balance):
"""Return a withdraw function with a starting balance."""
def withdraw(amount):
nonlocal balance
if amount > balance:
return 'Insufficient funds'
balance = balance - amount
return balance
return withdraw
def make_withdraw_list(balance):
b = [balance]
def withdraw(amount):
if amount > b[0]:
return 'Insufficient funds'
b[0] = b[0] - amount
return b[0]
return withdraw
def f(x):
x = 4
def g(y):
def h(z):
nonlocal x
x = x + 1
return x + y + z
return h
return g
a = f(1)
b = a(2)
b(3) + b(4)
| def make_withdraw(balance):
"""Return a withdraw function with a starting balance."""
def withdraw(amount):
nonlocal balance
if amount > balance:
return 'Insufficient funds'
balance = balance - amount
return balance
return withdraw
def make_withdraw_list(balance):
b = [balance]
def withdraw(amount):
if amount > b[0]:
return 'Insufficient funds'
b[0] = b[0] - amount
return b[0]
return withdraw
def f(x):
x = 4
def g(y):
def h(z):
nonlocal x
x = x + 1
return x + y + z
return h
return g
a = f(1)
b = a(2)
b(3) + b(4) |
#!/usr/bin/env python
class DataHelper:
"""
Helper to retrieve data from particular nodes
"""
@staticmethod
def get_bucket(root, parents):
"""Get bucket name from root and parent nodes"""
path = root.get("path", "")
if path:
# assume path like /pools/default
return path.split("/")[-1]
else:
return "default"
@staticmethod
def get_ip(root, parent):
"""
Get hostname or ip address from root and parent nodes
Carbon needs to know the originator of the fast changing data, \
for the purpose of contruct the metric info.
"""
return root.get("host", "127.0.0.1") | class Datahelper:
"""
Helper to retrieve data from particular nodes
"""
@staticmethod
def get_bucket(root, parents):
"""Get bucket name from root and parent nodes"""
path = root.get('path', '')
if path:
return path.split('/')[-1]
else:
return 'default'
@staticmethod
def get_ip(root, parent):
"""
Get hostname or ip address from root and parent nodes
Carbon needs to know the originator of the fast changing data, for the purpose of contruct the metric info.
"""
return root.get('host', '127.0.0.1') |
"""
You are given an m x n integer matrix heights representing the height of each unit cell in a continent.
The Pacific ocean touches the continent's left and top edges,
and the Atlantic ocean touches the continent's right and bottom edges.
Water can only flow in four directions: up, down, left, and right.
Water flows from a cell to an adjacent one with an equal or lower height.
Return a list of grid coordinates where water can flow to both the Pacific and Atlantic oceans.
Example 1:
Input: heights = [[1,2,2,3,5],[3,2,3,4,4],[2,4,5,3,1],[6,7,1,4,5],[5,1,1,2,4]]
Output: [[0,4],[1,3],[1,4],[2,2],[3,0],[3,1],[4,0]]
Example 2:
Input: heights = [[2,1],[1,2]]
Output: [[0,0],[0,1],[1,0],[1,1]]
Constraints:
m == heights.length
n == heights[i].length
1 <= m, n <= 200
1 <= heights[i][j] <= 105
"""
# V0
# IDEA : DFS + SET
class Solution:
def pacificAtlantic(self, matrix):
if not matrix: return []
pacific,atlantic = set(),set()
m,n = len(matrix),len(matrix[0])
for i in range(n):
# note : the reason why we need to iterate from both side : maybe the water flow gets stocked in one direction, but maybe it cas flow on the other side
# e.g. from 0 and from m - 1
self.dfs(0, i, matrix, pacific, 0)
self.dfs(m - 1, i, matrix, atlantic, 0)
for i in range(m):
# note : the reason why we need to iterate from both side : maybe the water flow gets stocked in one direction, but maybe it cas flow on the other side
# e.g. from 0 and from n - 1
self.dfs(i, 0, matrix, pacific, 0) # self.dfs(i, 0, matrix, pacific, -1 # (seems 0 is OK as well)
self.dfs(i, n - 1, matrix, atlantic, 0)
return list(pacific&atlantic)
def dfs(self, x, y, matrix, visit, height):
m,n = len(matrix),len(matrix[0])
if x < 0 or x >= m or y < 0 or y >= n or (x,y) in visit:
return
if matrix[x][y] < height:
return
visit.add((x,y))
moves = [[0,1], [0, -1], [1,0], [-1,0]]
for move in moves:
self.dfs( x + move[0], y + move[1], matrix, visit, matrix[x][y])
# V0'
class Solution:
def pacificAtlantic(self, matrix):
if not matrix: return []
pacific,atlantic = set(),set()
m,n = len(matrix),len(matrix[0])
for i in xrange(n):
self.dfs(0, i, matrix, pacific, 0)
self.dfs(m - 1, i, matrix, atlantic, 0)
for i in xrange(m):
self.dfs(i, 0, matrix, pacific, -1)
self.dfs(i, n - 1, matrix, atlantic, 0)
return list(pacific&atlantic)
def dfs(self, x, y, matrix, visit, height):
m,n = len(matrix),len(matrix[0])
if x < 0 or x >= m or y < 0 or y >= n or (x,y) in visit:
return
if matrix[x][y] < height:
return
visit.add((x,y))
self.dfs(x - 1, y, matrix, visit, matrix[x][y])
self.dfs(x + 1, y, matrix, visit, matrix[x][y])
self.dfs(x, y - 1, matrix, visit, matrix[x][y])
self.dfs(x, y + 1, matrix, visit, matrix[x][y])
# V1
# https://www.jiuzhang.com/solution/pacific-atlantic-water-flow/#tag-highlight-lang-python
# IDEA : DFS
class Solution:
"""
@param matrix: the given matrix
@return: The list of grid coordinates
"""
def pacificAtlantic(self, matrix):
if not matrix: return []
pacific,atlantic = set(),set()
m,n = len(matrix),len(matrix[0])
for i in xrange(n):
self.dfs(0, i, matrix, pacific, 0)
self.dfs(m - 1, i, matrix, atlantic, 0)
for i in xrange(m):
self.dfs(i, 0, matrix, pacific, -1)
self.dfs(i, n - 1, matrix, atlantic, 0)
return list(pacific&atlantic)
def dfs(self, x, y, matrix, visit, height):
m,n = len(matrix),len(matrix[0])
if x < 0 or x >= m or y < 0 or y >= n or (x,y) in visit:
return
if matrix[x][y] < height:
return
visit.add((x,y))
self.dfs(x - 1, y, matrix, visit, matrix[x][y])
self.dfs(x + 1, y, matrix, visit, matrix[x][y])
self.dfs(x, y - 1, matrix, visit, matrix[x][y])
self.dfs(x, y + 1, matrix, visit, matrix[x][y])
### Test case : dev
# V1'
# https://blog.csdn.net/fuxuemingzhu/article/details/82917037
class Solution(object):
def pacificAtlantic(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[List[int]]
"""
if not matrix or not matrix[0]: return []
m, n = len(matrix), len(matrix[0])
p_visited = [[False] * n for _ in range(m)]
a_visited = [[False] * n for _ in range(m)]
for i in range(m):
self.dfs(p_visited, matrix, m, n, i, 0)
self.dfs(a_visited, matrix, m, n, i, n -1)
for j in range(n):
self.dfs(p_visited, matrix, m, n, 0, j)
self.dfs(a_visited, matrix, m, n, m - 1, j)
res = []
for i in range(m):
for j in range(n):
if p_visited[i][j] and a_visited[i][j]:
res.append([i, j])
return res
def dfs(self, visited, matrix, m, n, i, j):
visited[i][j] = True
directions = [(-1, 0), (1, 0), (0, 1), (0, -1)]
for dire in directions:
x, y = i + dire[0], j + dire[1]
if x < 0 or x >= m or y < 0 or y >= n or visited[x][y] or matrix[x][y] < matrix[i][j]:
continue
self.dfs(visited, matrix, m, n, x, y)
# V1''
# https://leetcode.com/problems/pacific-atlantic-water-flow/discuss/90739/Python-DFS-bests-85.-Tips-for-all-DFS-in-matrix-question.
# IDEA : DFS
class Solution(object):
def pacificAtlantic(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[List[int]]
"""
if not matrix: return []
self.directions = [(1,0),(-1,0),(0,1),(0,-1)]
m = len(matrix)
n = len(matrix[0])
p_visited = [[False for _ in range(n)] for _ in range(m)]
a_visited = [[False for _ in range(n)] for _ in range(m)]
result = []
for i in range(m):
# p_visited[i][0] = True
# a_visited[i][n-1] = True
self.dfs(matrix, i, 0, p_visited, m, n)
self.dfs(matrix, i, n-1, a_visited, m, n)
for j in range(n):
# p_visited[0][j] = True
# a_visited[m-1][j] = True
self.dfs(matrix, 0, j, p_visited, m, n)
self.dfs(matrix, m-1, j, a_visited, m, n)
for i in range(m):
for j in range(n):
if p_visited[i][j] and a_visited[i][j]:
result.append([i,j])
return result
def dfs(self, matrix, i, j, visited, m, n):
# when dfs called, meaning its caller already verified this point
visited[i][j] = True
for dir in self.directions:
x, y = i + dir[0], j + dir[1]
if x < 0 or x >= m or y < 0 or y >= n or visited[x][y] or matrix[x][y] < matrix[i][j]:
continue
self.dfs(matrix, x, y, visited, m, n)
# V1'''
# https://leetcode.com/problems/pacific-atlantic-water-flow/discuss/90739/Python-DFS-bests-85.-Tips-for-all-DFS-in-matrix-question.
class Solution(object):
def longestIncreasingPath(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: int
"""
if not matrix: return 0
self.directions = [(1,0),(-1,0),(0,1),(0,-1)]
m = len(matrix)
n = len(matrix[0])
cache = [[-1 for _ in range(n)] for _ in range(m)]
res = 0
for i in range(m):
for j in range(n):
cur_len = self.dfs(i, j, matrix, cache, m, n)
res = max(res, cur_len)
return res
def dfs(self, i, j, matrix, cache, m, n):
if cache[i][j] != -1:
return cache[i][j]
res = 1
for direction in self.directions:
x, y = i + direction[0], j + direction[1]
if x < 0 or x >= m or y < 0 or y >= n or matrix[x][y] <= matrix[i][j]:
continue
length = 1 + self.dfs(x, y, matrix, cache, m, n)
res = max(length, res)
cache[i][j] = res
return res
# V1'''''
# https://leetcode.com/problems/pacific-atlantic-water-flow/discuss/90764/Python-solution-using-bfs-and-sets.
# IDEA : DFS + SET
class Solution(object):
def pacificAtlantic(self, matrix):
if not matrix: return []
m, n = len(matrix), len(matrix[0])
def bfs(reachable_ocean):
q = collections.deque(reachable_ocean)
while q:
(i, j) = q.popleft()
for (di, dj) in [(0,1), (0, -1), (1, 0), (-1, 0)]:
if 0 <= di+i < m and 0 <= dj+j < n and (di+i, dj+j) not in reachable_ocean \
and matrix[di+i][dj+j] >= matrix[i][j]:
q.append( (di+i,dj+j) )
reachable_ocean.add( (di+i, dj+j) )
return reachable_ocean
pacific =set ( [ (i, 0) for i in range(m)] + [(0, j) for j in range(1, n)])
atlantic =set ( [ (i, n-1) for i in range(m)] + [(m-1, j) for j in range(n-1)])
return list( bfs(pacific) & bfs(atlantic) )
# V2
# Time: O(m * n)
# Space: O(m * n)
class Solution(object):
def pacificAtlantic(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[List[int]]
"""
PACIFIC, ATLANTIC = 1, 2
def pacificAtlanticHelper(matrix, x, y, prev_height, prev_val, visited, res):
if (not 0 <= x < len(matrix)) or \
(not 0 <= y < len(matrix[0])) or \
matrix[x][y] < prev_height or \
(visited[x][y] | prev_val) == visited[x][y]:
return
visited[x][y] |= prev_val
if visited[x][y] == (PACIFIC | ATLANTIC):
res.append((x, y))
for d in [(0, -1), (0, 1), (-1, 0), (1, 0)]:
pacificAtlanticHelper(matrix, x + d[0], y + d[1], matrix[x][y], visited[x][y], visited, res)
if not matrix:
return []
res = []
m, n = len(matrix),len(matrix[0])
visited = [[0 for _ in range(n)] for _ in range(m)]
for i in range(m):
pacificAtlanticHelper(matrix, i, 0, float("-inf"), PACIFIC, visited, res)
pacificAtlanticHelper(matrix, i, n - 1, float("-inf"), ATLANTIC, visited, res)
for j in range(n):
pacificAtlanticHelper(matrix, 0, j, float("-inf"), PACIFIC, visited, res)
pacificAtlanticHelper(matrix, m - 1, j, float("-inf"), ATLANTIC, visited, res)
return res
| """
You are given an m x n integer matrix heights representing the height of each unit cell in a continent.
The Pacific ocean touches the continent's left and top edges,
and the Atlantic ocean touches the continent's right and bottom edges.
Water can only flow in four directions: up, down, left, and right.
Water flows from a cell to an adjacent one with an equal or lower height.
Return a list of grid coordinates where water can flow to both the Pacific and Atlantic oceans.
Example 1:
Input: heights = [[1,2,2,3,5],[3,2,3,4,4],[2,4,5,3,1],[6,7,1,4,5],[5,1,1,2,4]]
Output: [[0,4],[1,3],[1,4],[2,2],[3,0],[3,1],[4,0]]
Example 2:
Input: heights = [[2,1],[1,2]]
Output: [[0,0],[0,1],[1,0],[1,1]]
Constraints:
m == heights.length
n == heights[i].length
1 <= m, n <= 200
1 <= heights[i][j] <= 105
"""
class Solution:
def pacific_atlantic(self, matrix):
if not matrix:
return []
(pacific, atlantic) = (set(), set())
(m, n) = (len(matrix), len(matrix[0]))
for i in range(n):
self.dfs(0, i, matrix, pacific, 0)
self.dfs(m - 1, i, matrix, atlantic, 0)
for i in range(m):
self.dfs(i, 0, matrix, pacific, 0)
self.dfs(i, n - 1, matrix, atlantic, 0)
return list(pacific & atlantic)
def dfs(self, x, y, matrix, visit, height):
(m, n) = (len(matrix), len(matrix[0]))
if x < 0 or x >= m or y < 0 or (y >= n) or ((x, y) in visit):
return
if matrix[x][y] < height:
return
visit.add((x, y))
moves = [[0, 1], [0, -1], [1, 0], [-1, 0]]
for move in moves:
self.dfs(x + move[0], y + move[1], matrix, visit, matrix[x][y])
class Solution:
def pacific_atlantic(self, matrix):
if not matrix:
return []
(pacific, atlantic) = (set(), set())
(m, n) = (len(matrix), len(matrix[0]))
for i in xrange(n):
self.dfs(0, i, matrix, pacific, 0)
self.dfs(m - 1, i, matrix, atlantic, 0)
for i in xrange(m):
self.dfs(i, 0, matrix, pacific, -1)
self.dfs(i, n - 1, matrix, atlantic, 0)
return list(pacific & atlantic)
def dfs(self, x, y, matrix, visit, height):
(m, n) = (len(matrix), len(matrix[0]))
if x < 0 or x >= m or y < 0 or (y >= n) or ((x, y) in visit):
return
if matrix[x][y] < height:
return
visit.add((x, y))
self.dfs(x - 1, y, matrix, visit, matrix[x][y])
self.dfs(x + 1, y, matrix, visit, matrix[x][y])
self.dfs(x, y - 1, matrix, visit, matrix[x][y])
self.dfs(x, y + 1, matrix, visit, matrix[x][y])
class Solution:
"""
@param matrix: the given matrix
@return: The list of grid coordinates
"""
def pacific_atlantic(self, matrix):
if not matrix:
return []
(pacific, atlantic) = (set(), set())
(m, n) = (len(matrix), len(matrix[0]))
for i in xrange(n):
self.dfs(0, i, matrix, pacific, 0)
self.dfs(m - 1, i, matrix, atlantic, 0)
for i in xrange(m):
self.dfs(i, 0, matrix, pacific, -1)
self.dfs(i, n - 1, matrix, atlantic, 0)
return list(pacific & atlantic)
def dfs(self, x, y, matrix, visit, height):
(m, n) = (len(matrix), len(matrix[0]))
if x < 0 or x >= m or y < 0 or (y >= n) or ((x, y) in visit):
return
if matrix[x][y] < height:
return
visit.add((x, y))
self.dfs(x - 1, y, matrix, visit, matrix[x][y])
self.dfs(x + 1, y, matrix, visit, matrix[x][y])
self.dfs(x, y - 1, matrix, visit, matrix[x][y])
self.dfs(x, y + 1, matrix, visit, matrix[x][y])
class Solution(object):
def pacific_atlantic(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[List[int]]
"""
if not matrix or not matrix[0]:
return []
(m, n) = (len(matrix), len(matrix[0]))
p_visited = [[False] * n for _ in range(m)]
a_visited = [[False] * n for _ in range(m)]
for i in range(m):
self.dfs(p_visited, matrix, m, n, i, 0)
self.dfs(a_visited, matrix, m, n, i, n - 1)
for j in range(n):
self.dfs(p_visited, matrix, m, n, 0, j)
self.dfs(a_visited, matrix, m, n, m - 1, j)
res = []
for i in range(m):
for j in range(n):
if p_visited[i][j] and a_visited[i][j]:
res.append([i, j])
return res
def dfs(self, visited, matrix, m, n, i, j):
visited[i][j] = True
directions = [(-1, 0), (1, 0), (0, 1), (0, -1)]
for dire in directions:
(x, y) = (i + dire[0], j + dire[1])
if x < 0 or x >= m or y < 0 or (y >= n) or visited[x][y] or (matrix[x][y] < matrix[i][j]):
continue
self.dfs(visited, matrix, m, n, x, y)
class Solution(object):
def pacific_atlantic(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[List[int]]
"""
if not matrix:
return []
self.directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]
m = len(matrix)
n = len(matrix[0])
p_visited = [[False for _ in range(n)] for _ in range(m)]
a_visited = [[False for _ in range(n)] for _ in range(m)]
result = []
for i in range(m):
self.dfs(matrix, i, 0, p_visited, m, n)
self.dfs(matrix, i, n - 1, a_visited, m, n)
for j in range(n):
self.dfs(matrix, 0, j, p_visited, m, n)
self.dfs(matrix, m - 1, j, a_visited, m, n)
for i in range(m):
for j in range(n):
if p_visited[i][j] and a_visited[i][j]:
result.append([i, j])
return result
def dfs(self, matrix, i, j, visited, m, n):
visited[i][j] = True
for dir in self.directions:
(x, y) = (i + dir[0], j + dir[1])
if x < 0 or x >= m or y < 0 or (y >= n) or visited[x][y] or (matrix[x][y] < matrix[i][j]):
continue
self.dfs(matrix, x, y, visited, m, n)
class Solution(object):
def longest_increasing_path(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: int
"""
if not matrix:
return 0
self.directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]
m = len(matrix)
n = len(matrix[0])
cache = [[-1 for _ in range(n)] for _ in range(m)]
res = 0
for i in range(m):
for j in range(n):
cur_len = self.dfs(i, j, matrix, cache, m, n)
res = max(res, cur_len)
return res
def dfs(self, i, j, matrix, cache, m, n):
if cache[i][j] != -1:
return cache[i][j]
res = 1
for direction in self.directions:
(x, y) = (i + direction[0], j + direction[1])
if x < 0 or x >= m or y < 0 or (y >= n) or (matrix[x][y] <= matrix[i][j]):
continue
length = 1 + self.dfs(x, y, matrix, cache, m, n)
res = max(length, res)
cache[i][j] = res
return res
class Solution(object):
def pacific_atlantic(self, matrix):
if not matrix:
return []
(m, n) = (len(matrix), len(matrix[0]))
def bfs(reachable_ocean):
q = collections.deque(reachable_ocean)
while q:
(i, j) = q.popleft()
for (di, dj) in [(0, 1), (0, -1), (1, 0), (-1, 0)]:
if 0 <= di + i < m and 0 <= dj + j < n and ((di + i, dj + j) not in reachable_ocean) and (matrix[di + i][dj + j] >= matrix[i][j]):
q.append((di + i, dj + j))
reachable_ocean.add((di + i, dj + j))
return reachable_ocean
pacific = set([(i, 0) for i in range(m)] + [(0, j) for j in range(1, n)])
atlantic = set([(i, n - 1) for i in range(m)] + [(m - 1, j) for j in range(n - 1)])
return list(bfs(pacific) & bfs(atlantic))
class Solution(object):
def pacific_atlantic(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[List[int]]
"""
(pacific, atlantic) = (1, 2)
def pacific_atlantic_helper(matrix, x, y, prev_height, prev_val, visited, res):
if not 0 <= x < len(matrix) or not 0 <= y < len(matrix[0]) or matrix[x][y] < prev_height or (visited[x][y] | prev_val == visited[x][y]):
return
visited[x][y] |= prev_val
if visited[x][y] == PACIFIC | ATLANTIC:
res.append((x, y))
for d in [(0, -1), (0, 1), (-1, 0), (1, 0)]:
pacific_atlantic_helper(matrix, x + d[0], y + d[1], matrix[x][y], visited[x][y], visited, res)
if not matrix:
return []
res = []
(m, n) = (len(matrix), len(matrix[0]))
visited = [[0 for _ in range(n)] for _ in range(m)]
for i in range(m):
pacific_atlantic_helper(matrix, i, 0, float('-inf'), PACIFIC, visited, res)
pacific_atlantic_helper(matrix, i, n - 1, float('-inf'), ATLANTIC, visited, res)
for j in range(n):
pacific_atlantic_helper(matrix, 0, j, float('-inf'), PACIFIC, visited, res)
pacific_atlantic_helper(matrix, m - 1, j, float('-inf'), ATLANTIC, visited, res)
return res |
# [Grand Athenaeum]
sm.removeEscapeButton()
sm.flipDialoguePlayerAsSpeaker()
sm.sendNext("Supposedly the White Mage was last seen in Ellin Forest. If that's true, there must be evidence.")
sm.sendSay("Ephenia the Fairy Queen's dwelling is nearby. I'll see if she knows anything.")
sm.startQuest(parentID) | sm.removeEscapeButton()
sm.flipDialoguePlayerAsSpeaker()
sm.sendNext("Supposedly the White Mage was last seen in Ellin Forest. If that's true, there must be evidence.")
sm.sendSay("Ephenia the Fairy Queen's dwelling is nearby. I'll see if she knows anything.")
sm.startQuest(parentID) |
# reference.py
# This script is for image references
cookieurl = ["https://media1.tenor.com/images/45fe45f75ec523c2abf4e75ca2ac2fe2/tenor.gif?itemid=11797931",
"https://media1.tenor.com/images/de6a49b999216fbda779cd27a24919c3/tenor.gif?itemid=19073253"]
cookiesurl = ["https://media1.tenor.com/images/30c8ce96272fe73f58841164a179f6d1/tenor.gif?itemid=17729544",
"https://media1.tenor.com/images/54abaf4ed18aa4d5e2c71d6e03f82fea/tenor.gif?itemid=16659532"]
bonkurl = ["https://media1.tenor.com/images/dd3c08dbdb41ba9cb5d59c527e6d881a/tenor.gif?itemid=20472628",
"https://media1.tenor.com/images/0f145914d9e66a19829d7145daf9abcc/tenor.gif?itemid=19401897",
"https://media1.tenor.com/images/4dee992174206c66cb208bee31174b8d/tenor.gif?itemid=18805247"]
hugurl = ["https://media1.tenor.com/images/29a4aef07fde6e590aeaa3381324bbd1/tenor.gif?itemid=18630098",
"https://media1.tenor.com/images/f77657e4f9d454de399b7c8acb1b8735/tenor.gif?itemid=7939501",
"https://media1.tenor.com/images/24ac13447f9409d41c1aecb923aedf81/tenor.gif?itemid=3972670"]
kissurl = ["https://media1.tenor.com/images/4700f51c48d41104e541459743db42ae/tenor.gif?itemid=17947049"]
fistbumpurl = ["https://media2.giphy.com/media/l0HlL6XHioKD5Gsgg/giphy.gif?cid=ecf05e473oo7yozme81o170s0i9tjwxdb7pq69ba46acewt0&rid=giphy.gif"]
frickurl = ["https://media1.tenor.com/images/fa98b23ca1dba1925da62f834f27153f/tenor.gif?itemid=19355212"]
donuturl = ["https://media1.tenor.com/images/29a1be900e68a176097ff05eb51514b5/tenor.gif?itemid=8158743"] | cookieurl = ['https://media1.tenor.com/images/45fe45f75ec523c2abf4e75ca2ac2fe2/tenor.gif?itemid=11797931', 'https://media1.tenor.com/images/de6a49b999216fbda779cd27a24919c3/tenor.gif?itemid=19073253']
cookiesurl = ['https://media1.tenor.com/images/30c8ce96272fe73f58841164a179f6d1/tenor.gif?itemid=17729544', 'https://media1.tenor.com/images/54abaf4ed18aa4d5e2c71d6e03f82fea/tenor.gif?itemid=16659532']
bonkurl = ['https://media1.tenor.com/images/dd3c08dbdb41ba9cb5d59c527e6d881a/tenor.gif?itemid=20472628', 'https://media1.tenor.com/images/0f145914d9e66a19829d7145daf9abcc/tenor.gif?itemid=19401897', 'https://media1.tenor.com/images/4dee992174206c66cb208bee31174b8d/tenor.gif?itemid=18805247']
hugurl = ['https://media1.tenor.com/images/29a4aef07fde6e590aeaa3381324bbd1/tenor.gif?itemid=18630098', 'https://media1.tenor.com/images/f77657e4f9d454de399b7c8acb1b8735/tenor.gif?itemid=7939501', 'https://media1.tenor.com/images/24ac13447f9409d41c1aecb923aedf81/tenor.gif?itemid=3972670']
kissurl = ['https://media1.tenor.com/images/4700f51c48d41104e541459743db42ae/tenor.gif?itemid=17947049']
fistbumpurl = ['https://media2.giphy.com/media/l0HlL6XHioKD5Gsgg/giphy.gif?cid=ecf05e473oo7yozme81o170s0i9tjwxdb7pq69ba46acewt0&rid=giphy.gif']
frickurl = ['https://media1.tenor.com/images/fa98b23ca1dba1925da62f834f27153f/tenor.gif?itemid=19355212']
donuturl = ['https://media1.tenor.com/images/29a1be900e68a176097ff05eb51514b5/tenor.gif?itemid=8158743'] |
def D():
n = int(input())
neighbours = [None] #Asi puedo manejar numero de personas como index
for i in range(n):
neighbours.append([int(x) for x in input().split()])
visited = set()
ans = [None,1]
visited.add(1)
a , b = neighbours[1][0] , neighbours[1][1]
if(b in neighbours[a]):
ans+=[a,b]
else:
ans+=[b,a]
visited.add(a)
visited.add(b)
for i in range(1,n):
person = ans[i]
if(neighbours[person][0] not in visited):
ans.append(neighbours[person][0])
visited.add(neighbours[person][0])
if(neighbours[person][1] not in visited):
ans.append(neighbours[person][1])
visited.add(neighbours[person][1])
ans = ans[1:]
ans = [str(x) for x in ans]
print(" ".join(ans))
D() | def d():
n = int(input())
neighbours = [None]
for i in range(n):
neighbours.append([int(x) for x in input().split()])
visited = set()
ans = [None, 1]
visited.add(1)
(a, b) = (neighbours[1][0], neighbours[1][1])
if b in neighbours[a]:
ans += [a, b]
else:
ans += [b, a]
visited.add(a)
visited.add(b)
for i in range(1, n):
person = ans[i]
if neighbours[person][0] not in visited:
ans.append(neighbours[person][0])
visited.add(neighbours[person][0])
if neighbours[person][1] not in visited:
ans.append(neighbours[person][1])
visited.add(neighbours[person][1])
ans = ans[1:]
ans = [str(x) for x in ans]
print(' '.join(ans))
d() |
# Count total cars per company
# My Solution
df.groupby('company').count()
# Given Solution
df['company'].value_counts()
| df.groupby('company').count()
df['company'].value_counts() |
'''
Python Program to Remove the Duplicate Items from a List
'''
lst = [3,5,2,7,5,4,3,7,8,2,5,4,7,2,1]
print(lst)
def method():
new_lst = []
for item in lst:
if item not in new_lst:
new_lst.append(item)
print(new_lst)
method()
| """
Python Program to Remove the Duplicate Items from a List
"""
lst = [3, 5, 2, 7, 5, 4, 3, 7, 8, 2, 5, 4, 7, 2, 1]
print(lst)
def method():
new_lst = []
for item in lst:
if item not in new_lst:
new_lst.append(item)
print(new_lst)
method() |
# this module is the template of all environment in this project
# some basic and common features are listed in this class
class ENVError(Exception):
def __init__(self, value_):
self.__value = value_
def __str__(self):
print('Environment error occur: ' + self.__value)
class ENV:
def __init__(self):
pass
def reset(self):
raise ENVError('You have not defined the reset function of environment')
def step(self, action):
raise ENVError('You have not defined the step function of environment')
| class Enverror(Exception):
def __init__(self, value_):
self.__value = value_
def __str__(self):
print('Environment error occur: ' + self.__value)
class Env:
def __init__(self):
pass
def reset(self):
raise env_error('You have not defined the reset function of environment')
def step(self, action):
raise env_error('You have not defined the step function of environment') |
'''Identify whether the given input is polindrome'''
def is_polindrome_word(input_word):
"""Check whether the given word is polindrome or not"""
status = True
input_word = input_word.replace(' ', '').lower()
index = 0
while index < (len(input_word)/2):
if input_word[index] != input_word[(index*-1)-1]:
status = False
break
index += 1
return status
if __name__ == "__main__":
USER_INPUT = input("Enter a word to check whether it is Polindrome:")
if is_polindrome_word(USER_INPUT):
print('Yes "{0}" is Polindrome'.format(USER_INPUT))
else:
print('No "{0}" is NOT Polindrome'.format(USER_INPUT))
| """Identify whether the given input is polindrome"""
def is_polindrome_word(input_word):
"""Check whether the given word is polindrome or not"""
status = True
input_word = input_word.replace(' ', '').lower()
index = 0
while index < len(input_word) / 2:
if input_word[index] != input_word[index * -1 - 1]:
status = False
break
index += 1
return status
if __name__ == '__main__':
user_input = input('Enter a word to check whether it is Polindrome:')
if is_polindrome_word(USER_INPUT):
print('Yes "{0}" is Polindrome'.format(USER_INPUT))
else:
print('No "{0}" is NOT Polindrome'.format(USER_INPUT)) |
#Given two strings s and t, determine if they are isomorphic.
#
#Two strings are isomorphic if the characters in s can be replaced to get t.
#
#All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character but a character may map to itself.
class Solution(object):
def isIsomorphic(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
dict1={}
dict2={}
if len(s)!=len(t):
return False
for i in xrange(len(s)):
if s[i] in dict1 and dict1[s[i]]!=t[i]:
return False
if t[i] in dict2 and dict2[t[i]]!=s[i]:
return False
else:
dict1[s[i]]=t[i]
dict2[t[i]]=s[i]
return True | class Solution(object):
def is_isomorphic(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
dict1 = {}
dict2 = {}
if len(s) != len(t):
return False
for i in xrange(len(s)):
if s[i] in dict1 and dict1[s[i]] != t[i]:
return False
if t[i] in dict2 and dict2[t[i]] != s[i]:
return False
else:
dict1[s[i]] = t[i]
dict2[t[i]] = s[i]
return True |
C_ENDINGS = ('.c', '.i', )
CXX_ENDINGS = ('.cpp', '.cxx', '.cc', '.c++', '.CPP', '.CXX', '.C', '.CC', '.C++', '.ii', )
OBJC_ENDINGS = ('.m', '.mi', )
OBJCXX_ENDINGS = ('.mm', '.mii', )
FORTRAN_ENDINGS = ('.f', '.for', '.ftn', '.f77', '.f90', '.f95', '.f03', '.f08',
'.F', '.FOR', '.FTN', '.F77', '.F90', '.F95', '.F03', '.F08', )
SOURCE_ENDINGS = C_ENDINGS + CXX_ENDINGS + OBJC_ENDINGS + OBJCXX_ENDINGS + FORTRAN_ENDINGS
OBJ_ENDINGS = ('.o', )
BITCODE_ENDINGS = ('.bc', )
AR_ENDINGS = ('.a', )
SHARED_ENDINGS = ('.so', )
INPUT_ENDINGS = SOURCE_ENDINGS + OBJ_ENDINGS + BITCODE_ENDINGS + AR_ENDINGS + SHARED_ENDINGS
FORTRAN_COMPILE_FLAGS = ('-fall-intrinsics', '-fallow-argument-mismatch', '-fallow-invalid-boz',
'-fbackslash', '-fcray-pointer', '-fd-lines-as-code', '-fd-lines-as-comments',
'-fdec', '-fdec-char-conversions', '-fdec-structure', '-fdec-intrinsic-ints',
'-fdec-static', '-fdec-math', '-fdec-include', '-fdec-format-defaults',
'-fdec-blank-format-item', '-fdefault-double-8', '-fdefault-integer-8',
'-fdefault-real-8', '-fdefault-real-10', '-fdefault-real-16', '-fdollar-ok',
'-ffixed-line-length-n', '-ffixed-line-length-none', '-fpad-source',
'-ffree-form', '-ffree-line-length-n', '-ffree-line-length-none',
'-fimplicit-none', '-finteger-4-integer-8', '-fmax-identifier-length',
'-fmodule-private', '-ffixed-form', '-fno-range-check', '-fopenacc',
'-freal-4-real-10', '-freal-4-real-16', '-freal-4-real-8', '-freal-8-real-10',
'-freal-8-real-16', '-freal-8-real-4', '-std=', '-ftest-forall-temp', '-flarge-sizes',
'-flogical-abbreviations', '-fxor-operator','-fno-leading-underscore', '-funderscoring',
'-fno-underscoring', '-fsecond-underscore')
COMPILE_FLAGS = FORTRAN_COMPILE_FLAGS
LINK_FLAGS = ('-static', '-static-flang-libs', '-fno-fortran-main', '-noFlangLibs')
IGNORE_FLAGS = ('-Kieee')
ALIAS = {'-openmp':'-fopenmp', '-static-libgfortran':'-static-flang-libs',
'-Mbackslash': '-fbackslash', '-Mfixed':'-ffixed-form',
'-Mfreeform':'-ffree-form', '-Mrecursive':'-frecursive'}
class ParseArg:
def __init__(self, args):
self.args = []
for x in args[1:]:
if x in ALIAS:
self.args.append(ALIAS[x])
else:
self.args.append(x)
def hasFlag(self, flag, remove=False):
if flag in self.args:
if remove:
self.args.remove(flag)
return True
return False
def getOpt(self, flag, remove=False):
for i in range(0, len(self.args)):
if self.args[i].startswith(flag):
value = self.args[i+1]
if remove:
self.args.remove(value)
del self.args[i]
return value
return None
def getDef(self, flag, remove=False):
for i in range(0, len(self.args)):
if self.args[i].startswith(flag+"="):
value = self.args[i]
if remove:
self.args.remove(value)
return value[len(flag)+1:]
return None
def getInputFiles(self, endings, remove=False):
inputFiles = []
skip = False
for x in self.args:
if skip:
skip = False
continue
if not x.startswith('-'):
if x.endswith(endings):
inputFiles.append(x)
elif '=' in x:
skip = True
if remove:
for x in inputFiles:
self.args.remove(x)
return inputFiles
def get(self):
return self.args
def getCompile(self, warn=False):
argv = []
for x in self.args:
if x.startswith('-l') or x.startswith('-fuse-ld='):
if warn:
print(sys.argv[0]+": warning: argument unused during compilation: \""+x+"\"", file=sys.stderr)
elif x in LINK_FLAGS:
if warn:
print(sys.argv[0]+": warning: argument unused during compilation: \""+x+"\"", file=sys.stderr)
elif not x in IGNORE_FLAGS:
argv.append(x)
return argv
def getLink(self, warn=False):
argv = []
for x in self.args:
if x in COMPILE_FLAGS:
if warn:
print(sys.argv[0]+": warning: argument unused during linking: \""+x+"\"", file=sys.stderr)
elif not x in IGNORE_FLAGS:
argv.append(x)
return argv
| c_endings = ('.c', '.i')
cxx_endings = ('.cpp', '.cxx', '.cc', '.c++', '.CPP', '.CXX', '.C', '.CC', '.C++', '.ii')
objc_endings = ('.m', '.mi')
objcxx_endings = ('.mm', '.mii')
fortran_endings = ('.f', '.for', '.ftn', '.f77', '.f90', '.f95', '.f03', '.f08', '.F', '.FOR', '.FTN', '.F77', '.F90', '.F95', '.F03', '.F08')
source_endings = C_ENDINGS + CXX_ENDINGS + OBJC_ENDINGS + OBJCXX_ENDINGS + FORTRAN_ENDINGS
obj_endings = ('.o',)
bitcode_endings = ('.bc',)
ar_endings = ('.a',)
shared_endings = ('.so',)
input_endings = SOURCE_ENDINGS + OBJ_ENDINGS + BITCODE_ENDINGS + AR_ENDINGS + SHARED_ENDINGS
fortran_compile_flags = ('-fall-intrinsics', '-fallow-argument-mismatch', '-fallow-invalid-boz', '-fbackslash', '-fcray-pointer', '-fd-lines-as-code', '-fd-lines-as-comments', '-fdec', '-fdec-char-conversions', '-fdec-structure', '-fdec-intrinsic-ints', '-fdec-static', '-fdec-math', '-fdec-include', '-fdec-format-defaults', '-fdec-blank-format-item', '-fdefault-double-8', '-fdefault-integer-8', '-fdefault-real-8', '-fdefault-real-10', '-fdefault-real-16', '-fdollar-ok', '-ffixed-line-length-n', '-ffixed-line-length-none', '-fpad-source', '-ffree-form', '-ffree-line-length-n', '-ffree-line-length-none', '-fimplicit-none', '-finteger-4-integer-8', '-fmax-identifier-length', '-fmodule-private', '-ffixed-form', '-fno-range-check', '-fopenacc', '-freal-4-real-10', '-freal-4-real-16', '-freal-4-real-8', '-freal-8-real-10', '-freal-8-real-16', '-freal-8-real-4', '-std=', '-ftest-forall-temp', '-flarge-sizes', '-flogical-abbreviations', '-fxor-operator', '-fno-leading-underscore', '-funderscoring', '-fno-underscoring', '-fsecond-underscore')
compile_flags = FORTRAN_COMPILE_FLAGS
link_flags = ('-static', '-static-flang-libs', '-fno-fortran-main', '-noFlangLibs')
ignore_flags = '-Kieee'
alias = {'-openmp': '-fopenmp', '-static-libgfortran': '-static-flang-libs', '-Mbackslash': '-fbackslash', '-Mfixed': '-ffixed-form', '-Mfreeform': '-ffree-form', '-Mrecursive': '-frecursive'}
class Parsearg:
def __init__(self, args):
self.args = []
for x in args[1:]:
if x in ALIAS:
self.args.append(ALIAS[x])
else:
self.args.append(x)
def has_flag(self, flag, remove=False):
if flag in self.args:
if remove:
self.args.remove(flag)
return True
return False
def get_opt(self, flag, remove=False):
for i in range(0, len(self.args)):
if self.args[i].startswith(flag):
value = self.args[i + 1]
if remove:
self.args.remove(value)
del self.args[i]
return value
return None
def get_def(self, flag, remove=False):
for i in range(0, len(self.args)):
if self.args[i].startswith(flag + '='):
value = self.args[i]
if remove:
self.args.remove(value)
return value[len(flag) + 1:]
return None
def get_input_files(self, endings, remove=False):
input_files = []
skip = False
for x in self.args:
if skip:
skip = False
continue
if not x.startswith('-'):
if x.endswith(endings):
inputFiles.append(x)
elif '=' in x:
skip = True
if remove:
for x in inputFiles:
self.args.remove(x)
return inputFiles
def get(self):
return self.args
def get_compile(self, warn=False):
argv = []
for x in self.args:
if x.startswith('-l') or x.startswith('-fuse-ld='):
if warn:
print(sys.argv[0] + ': warning: argument unused during compilation: "' + x + '"', file=sys.stderr)
elif x in LINK_FLAGS:
if warn:
print(sys.argv[0] + ': warning: argument unused during compilation: "' + x + '"', file=sys.stderr)
elif not x in IGNORE_FLAGS:
argv.append(x)
return argv
def get_link(self, warn=False):
argv = []
for x in self.args:
if x in COMPILE_FLAGS:
if warn:
print(sys.argv[0] + ': warning: argument unused during linking: "' + x + '"', file=sys.stderr)
elif not x in IGNORE_FLAGS:
argv.append(x)
return argv |
#Python solution for AoC qn 2
f = open("2.txt","r")
strings = f.readlines()
#Part 1
freq_total = {
"2":0,
"3":0
}
for s in strings:
s = s.strip().lower()
freq_indv = {}
#Count how many of each letter is inside
for ch in s:
if ch in freq_indv:
freq_indv[ch]+=1
else:
freq_indv[ch]=1
#Check how many found
found = {
"2":False,
"3":False
}
for ch in freq_indv:
if (not found["2"]) and freq_indv[ch]==2:
found["2"] = True
freq_total["2"]+=1
elif (not found["3"]) and freq_indv[ch]==3:
found["3"] = True
freq_total["3"]+=1
if found["2"] and found["3"]:
break
continue
print("Checksum: "+str(freq_total["2"]*freq_total["3"]))
#Part 2
found = False
for i in range(len(strings)-1):
s1 = strings[i]
for j in range(i+1,len(strings)):
s2 = strings[j]
different = 0
found = True
common = ""
#Compare s1 and s2
for k in range(min(len(s1),len(s2))):
if s1[k] != s2[k]:
different+=1
else:
common+=s1[k]
if different>1:
found = False
break
if found:
print("Common Letters: "+common)
break
if found: break
| f = open('2.txt', 'r')
strings = f.readlines()
freq_total = {'2': 0, '3': 0}
for s in strings:
s = s.strip().lower()
freq_indv = {}
for ch in s:
if ch in freq_indv:
freq_indv[ch] += 1
else:
freq_indv[ch] = 1
found = {'2': False, '3': False}
for ch in freq_indv:
if not found['2'] and freq_indv[ch] == 2:
found['2'] = True
freq_total['2'] += 1
elif not found['3'] and freq_indv[ch] == 3:
found['3'] = True
freq_total['3'] += 1
if found['2'] and found['3']:
break
continue
print('Checksum: ' + str(freq_total['2'] * freq_total['3']))
found = False
for i in range(len(strings) - 1):
s1 = strings[i]
for j in range(i + 1, len(strings)):
s2 = strings[j]
different = 0
found = True
common = ''
for k in range(min(len(s1), len(s2))):
if s1[k] != s2[k]:
different += 1
else:
common += s1[k]
if different > 1:
found = False
break
if found:
print('Common Letters: ' + common)
break
if found:
break |
class Solution:
@staticmethod
def naive(prices):
maxReturn = 0
minVal = prices[0]
for i in range(1,len(prices)):
if prices[i]-minVal > maxReturn:
maxReturn = prices[i]-minVal
if prices[i]<minVal:
minVal = prices[i]
return maxReturn | class Solution:
@staticmethod
def naive(prices):
max_return = 0
min_val = prices[0]
for i in range(1, len(prices)):
if prices[i] - minVal > maxReturn:
max_return = prices[i] - minVal
if prices[i] < minVal:
min_val = prices[i]
return maxReturn |
'''
subsets and subarrays
subarrays:
a = [10,20,30]
=> [
[10], [20], [30]
[10,20], [10,20,30], [20,30],
]
subsets:
a = [10,20,30]
=> [
[], [10,20,30]
[10], [20], [30], [10, 20], [10, 30], [20, 30]
]
'''
def print_subsets(a):
limit = 2 ** len(a)
for i in range(limit):
for j in range(len(a)):
if(i & (1 << j) > 0):
print(a[j], end=" ")
print()
def print_subarray(a):
for i in range(len(a)):
for j in range(i, len(a)):
for k in range(i, j+1):
print(a[k], end=" ")
print()
print_subsets([10,20,30])
print_subarray([10,20,30])
| """
subsets and subarrays
subarrays:
a = [10,20,30]
=> [
[10], [20], [30]
[10,20], [10,20,30], [20,30],
]
subsets:
a = [10,20,30]
=> [
[], [10,20,30]
[10], [20], [30], [10, 20], [10, 30], [20, 30]
]
"""
def print_subsets(a):
limit = 2 ** len(a)
for i in range(limit):
for j in range(len(a)):
if i & 1 << j > 0:
print(a[j], end=' ')
print()
def print_subarray(a):
for i in range(len(a)):
for j in range(i, len(a)):
for k in range(i, j + 1):
print(a[k], end=' ')
print()
print_subsets([10, 20, 30])
print_subarray([10, 20, 30]) |
# -*- coding: utf-8 -*-
# blue to red diverging set
blue_to_red_diverging = ['#d7191c', '#fdae61', '#ffffbf', '#abd9e9', '#2c7bb6']
# red oragne sequential single hue:
orange_sequential = ['#fff5eb', '#fee6ce', '#fdd0a2', '#fdae6b', '#fd8d3c',
'#f16913', '#d94801', '#a63603', '#7f2704']
# blue sequential single hue:
blue_sequential = ['#f7fbff', '#deebf7', '#c6dbef', '#9ecae1', '#6baed6',
'#4292c6', '#2171b5', '#08519c', '#08306b']
mpl_default = ['b', 'r', 'g', 'c', 'm', 'y', 'k']
# Cynthia Brewer Set 1
categorical_1 = [ '#e41a1c', '#377eb8', '#4daf4a', '#ff7f00', '#a65628',
'#f781bf', '#999999', '#984ea3', '#ffff33']
# Cynthia Brewer Set 2
categorical_2 = ['#66c2a5', '#fc8d62', '#8da0cb', '#e78ac3', '#a6d854',
'#ffd92f', '#e5c494', '#b3b3b3' ]
# Dark Brewer Set 2
categorical_3 = ['#1b9e77', '#d95f02', '#7570b3', '#e7298a', '#66a61e',
'#e6ab02', '#a6761d', '#666666']
| blue_to_red_diverging = ['#d7191c', '#fdae61', '#ffffbf', '#abd9e9', '#2c7bb6']
orange_sequential = ['#fff5eb', '#fee6ce', '#fdd0a2', '#fdae6b', '#fd8d3c', '#f16913', '#d94801', '#a63603', '#7f2704']
blue_sequential = ['#f7fbff', '#deebf7', '#c6dbef', '#9ecae1', '#6baed6', '#4292c6', '#2171b5', '#08519c', '#08306b']
mpl_default = ['b', 'r', 'g', 'c', 'm', 'y', 'k']
categorical_1 = ['#e41a1c', '#377eb8', '#4daf4a', '#ff7f00', '#a65628', '#f781bf', '#999999', '#984ea3', '#ffff33']
categorical_2 = ['#66c2a5', '#fc8d62', '#8da0cb', '#e78ac3', '#a6d854', '#ffd92f', '#e5c494', '#b3b3b3']
categorical_3 = ['#1b9e77', '#d95f02', '#7570b3', '#e7298a', '#66a61e', '#e6ab02', '#a6761d', '#666666'] |
'''
Author : Hemant Rana
Date : 30th Aug 2020
link : https://leetcode.com/problems/container-with-most-water
'''
class Solution:
def maxArea(self, height: List[int]) -> int:
h_len=len(height)
max_area=0
b,e=0,h_len-1
while(b<e):
area=min(height[b],height[e])*(e-b)
max_area=max(area,max_area)
if(height[b]>height[e]):
e-=1
else:
b+=1
return max_area
| """
Author : Hemant Rana
Date : 30th Aug 2020
link : https://leetcode.com/problems/container-with-most-water
"""
class Solution:
def max_area(self, height: List[int]) -> int:
h_len = len(height)
max_area = 0
(b, e) = (0, h_len - 1)
while b < e:
area = min(height[b], height[e]) * (e - b)
max_area = max(area, max_area)
if height[b] > height[e]:
e -= 1
else:
b += 1
return max_area |
class Struct(object):
def __init__(self, data=None, **kwds):
if not data:
data = {}
for name, value in data.items():
if name:
setattr(self, name, self._wrap(value))
for name, value in kwds.items():
if name:
setattr(self, name, self._wrap(value))
def _wrap(self, value):
if isinstance(value, (tuple, list, set, frozenset)):
return type(value)([self._wrap(v) for v in value])
else:
return Struct(value) if isinstance(value, dict) else value
def clone(self, **kwds):
return Struct(self.__to_dict__(), **kwds)
def __repr__(self):
return "Struct: " + repr(self.__dict__)
def __len__(self):
return len(self.__dict__)
def __to_dict__(self):
res = {}
res.update(self.__dict__)
for k in res.keys():
if isinstance(res[k], Struct):
res[k] = res[k].__to_dict__()
elif isinstance(res[k], (tuple, list, set, frozenset)):
res[k] = [i.__to_dict__() if isinstance(i, Struct) else i for i in res[k]]
return res
class StructDefault(Struct):
def __getattr__(self, item):
return self._default_
| class Struct(object):
def __init__(self, data=None, **kwds):
if not data:
data = {}
for (name, value) in data.items():
if name:
setattr(self, name, self._wrap(value))
for (name, value) in kwds.items():
if name:
setattr(self, name, self._wrap(value))
def _wrap(self, value):
if isinstance(value, (tuple, list, set, frozenset)):
return type(value)([self._wrap(v) for v in value])
else:
return struct(value) if isinstance(value, dict) else value
def clone(self, **kwds):
return struct(self.__to_dict__(), **kwds)
def __repr__(self):
return 'Struct: ' + repr(self.__dict__)
def __len__(self):
return len(self.__dict__)
def __to_dict__(self):
res = {}
res.update(self.__dict__)
for k in res.keys():
if isinstance(res[k], Struct):
res[k] = res[k].__to_dict__()
elif isinstance(res[k], (tuple, list, set, frozenset)):
res[k] = [i.__to_dict__() if isinstance(i, Struct) else i for i in res[k]]
return res
class Structdefault(Struct):
def __getattr__(self, item):
return self._default_ |
"""
This includes constants that may be used in the connectivity_libs module.
"""
WEBTIMEOUT = 5
NUM_OF_WORKER_PROCESSES = 4
REGEX_IP = r'(?P<ip_address>(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))'
REGEX_EMAIL = r'[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})'
REGEX_PASSWORD = r'([\w!@#$%-]+)'
REGEX_HOSTNAME = r'((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|' \
r'[01]?[0-9][0-9]?)){3})$|^((([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])' \
r'\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9]))'
| """
This includes constants that may be used in the connectivity_libs module.
"""
webtimeout = 5
num_of_worker_processes = 4
regex_ip = '(?P<ip_address>(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))'
regex_email = '[_a-z0-9-]+(\\.[_a-z0-9-]+)*@[a-z0-9-]+(\\.[a-z0-9-]+)*(\\.[a-z]{2,4})'
regex_password = '([\\w!@#$%-]+)'
regex_hostname = '((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3})$|^((([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]*[a-zA-Z0-9])\\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\\-]*[A-Za-z0-9]))' |
##To find the kth maximum number in an array.
lst=[]
len=int(input("Enter the length of the array.\n"))
for i in range(0,len):
e=input("Enter the element.\n")
lst.append(e)
k=int(input("Enter the value of k\n"))
lst.sort(reverse=True)
f=k-1
print(lst[f])
| lst = []
len = int(input('Enter the length of the array.\n'))
for i in range(0, len):
e = input('Enter the element.\n')
lst.append(e)
k = int(input('Enter the value of k\n'))
lst.sort(reverse=True)
f = k - 1
print(lst[f]) |
__all__ = ['status_in_range', 'response_time_under',
'response_time_above', 'status_must_be']
def status_must_be(value: int = None, expected: int = 200) -> bool:
"""
Validates the status code of a HTTP call is as expected.
"""
return value == expected
def status_in_range(value: int, lower: int = 100,
upper: int = 600) -> bool:
"""
Validates the status code of a HTTP call is within the given boundary,
inclusive.
"""
return value in range(lower, upper+1)
def response_time_under(value: float = None, duration: float = 0) -> bool:
"""
Validates the response time value of a HTTP call falls below the
given duration in milliseconds.
"""
return value <= duration
def response_time_above(value: float = None, duration: float = 0) -> bool:
"""
Validates the response time value of a HTTP call is greater than the
given duration in milliseconds.
"""
return value >= duration
| __all__ = ['status_in_range', 'response_time_under', 'response_time_above', 'status_must_be']
def status_must_be(value: int=None, expected: int=200) -> bool:
"""
Validates the status code of a HTTP call is as expected.
"""
return value == expected
def status_in_range(value: int, lower: int=100, upper: int=600) -> bool:
"""
Validates the status code of a HTTP call is within the given boundary,
inclusive.
"""
return value in range(lower, upper + 1)
def response_time_under(value: float=None, duration: float=0) -> bool:
"""
Validates the response time value of a HTTP call falls below the
given duration in milliseconds.
"""
return value <= duration
def response_time_above(value: float=None, duration: float=0) -> bool:
"""
Validates the response time value of a HTTP call is greater than the
given duration in milliseconds.
"""
return value >= duration |
# create a list of movies
list_of_movies = None
list_of_movies = [
'Toy Story',
'Lion King',
'Coco'
]
# cycle through each movie title in the list of movies
# starting from the first item and ending at the last item
for movie_title in list_of_movies:
print('***{}***'.format(movie_title))
# create an empty variable called word
word = ''
# cycle through each letter in the movie title
for letter in movie_title:
print(' {}'.format(letter))
word += letter
print("The letters create the word variable >>{}".format(word))
print("The movie title is the same as the word variable: {}".format(movie_title == word))
print('\n\n')
word = ''
| list_of_movies = None
list_of_movies = ['Toy Story', 'Lion King', 'Coco']
for movie_title in list_of_movies:
print('***{}***'.format(movie_title))
word = ''
for letter in movie_title:
print(' {}'.format(letter))
word += letter
print('The letters create the word variable >>{}'.format(word))
print('The movie title is the same as the word variable: {}'.format(movie_title == word))
print('\n\n')
word = '' |
'''
Run through and ensure that all the required programs are installed on the system
and functioning
'''
| """
Run through and ensure that all the required programs are installed on the system
and functioning
""" |
def solution(n, computers):
def dfs(n, s, metrix, visited):
stack = [s]
visited.add(s)
while stack:
this = stack[-1]
remove = True
for i in range(n):
if this == i:
continue
if i in visited:
continue
if metrix[this][i]:
visited.add(i)
stack.append(i)
remove = False
break
if remove:
stack.pop()
answer = 0
visited = set()
for i in range(n):
if i not in visited:
dfs(n, i, computers, visited)
answer += 1
return answer
if __name__ == "__main__":
n = 3
c = [[1, 1, 0], [1, 1, 0], [0, 0, 1]]
print(solution(n, c))
| def solution(n, computers):
def dfs(n, s, metrix, visited):
stack = [s]
visited.add(s)
while stack:
this = stack[-1]
remove = True
for i in range(n):
if this == i:
continue
if i in visited:
continue
if metrix[this][i]:
visited.add(i)
stack.append(i)
remove = False
break
if remove:
stack.pop()
answer = 0
visited = set()
for i in range(n):
if i not in visited:
dfs(n, i, computers, visited)
answer += 1
return answer
if __name__ == '__main__':
n = 3
c = [[1, 1, 0], [1, 1, 0], [0, 0, 1]]
print(solution(n, c)) |
def is_paired(input_string: str) -> bool:
input_string = clean_input_string(input_string)
if len(input_string) % 2 != 0:
return False
while input_string:
if not remove_bracket(input_string[0], input_string):
return False
return True
def remove_bracket(bracket: str, input_string: list) -> bool:
pairs = {
'{': '}',
'[': ']',
'(': ')',
}
if bracket not in pairs:
return False
if input_string[1] == pairs[bracket]:
del input_string[1]
del input_string[0]
return True
elif input_string[-1] == pairs[bracket]:
del input_string[-1]
del input_string[0]
return True
def clean_input_string(input_string: str) -> list:
template = '[]{}()'
return [char for char in input_string if char in template] | def is_paired(input_string: str) -> bool:
input_string = clean_input_string(input_string)
if len(input_string) % 2 != 0:
return False
while input_string:
if not remove_bracket(input_string[0], input_string):
return False
return True
def remove_bracket(bracket: str, input_string: list) -> bool:
pairs = {'{': '}', '[': ']', '(': ')'}
if bracket not in pairs:
return False
if input_string[1] == pairs[bracket]:
del input_string[1]
del input_string[0]
return True
elif input_string[-1] == pairs[bracket]:
del input_string[-1]
del input_string[0]
return True
def clean_input_string(input_string: str) -> list:
template = '[]{}()'
return [char for char in input_string if char in template] |
def _(string):
"""Emulates gettext method"""
return string
__version__ = "0.8.2"
__description__ = _("EncFS GUI managing tool")
__generic_name__ = _("EncFS manager")
| def _(string):
"""Emulates gettext method"""
return string
__version__ = '0.8.2'
__description__ = _('EncFS GUI managing tool')
__generic_name__ = _('EncFS manager') |
def test_oops(client):
url = f'/fake-path'
response = client.get(url)
assert response.status_code == 404 | def test_oops(client):
url = f'/fake-path'
response = client.get(url)
assert response.status_code == 404 |
#-*- coding: utf-8 -*-
class ValueDefinition:
str_val_dict = {}
val_str_dict = {}
@classmethod
def get(cls, data):
if not cls.val_str_dict:
cls.val_str_dict = dict(zip(cls.str_val_dict.values(), cls.str_val_dict.keys()))
if type(data) == str:
return cls.str_val_dict.get(data)
else:
return cls.val_str_dict.get(data)
class SectionType(ValueDefinition):
str_val_dict = {
"name_section" : 0,
"type_section" : 1,
"import_section" : 2,
"function_section" : 3,
"table_section" : 4,
"memory_section" : 5,
"global_section" : 6,
"export_section" : 7,
"start_section" : 8,
"elem_section" : 9,
"code_section" : 10,
"data_section" : 11,
"invalid_section" : 12
}
class TypeOpcode(ValueDefinition):
str_val_dict = {
"i32": 0x7f,
'i64': 0x7e,
'f32': 0x7d,
'f64': 0x7c,
'anyfunc': 0x70,
'func': 0x60,
'empty_block_type': 0x40
}
class ExternalKind(ValueDefinition):
str_val_dict = {
"Function": 0,
'Table': 1,
'Memory': 2,
'Global': 3
}
class InitExprOp(ValueDefinition):
str_val_dict = {
"i32.const": 0x41,
"i64.const": 0x42,
"f32.const": 0x43,
"f64.const": 0x44,
"v128.const": 0xfd,
"get_global": 0x23,
"end": 0x0b
}
class NameType(ValueDefinition):
str_val_dict = {
'module': 0,
'function': 1,
'local': 2
} | class Valuedefinition:
str_val_dict = {}
val_str_dict = {}
@classmethod
def get(cls, data):
if not cls.val_str_dict:
cls.val_str_dict = dict(zip(cls.str_val_dict.values(), cls.str_val_dict.keys()))
if type(data) == str:
return cls.str_val_dict.get(data)
else:
return cls.val_str_dict.get(data)
class Sectiontype(ValueDefinition):
str_val_dict = {'name_section': 0, 'type_section': 1, 'import_section': 2, 'function_section': 3, 'table_section': 4, 'memory_section': 5, 'global_section': 6, 'export_section': 7, 'start_section': 8, 'elem_section': 9, 'code_section': 10, 'data_section': 11, 'invalid_section': 12}
class Typeopcode(ValueDefinition):
str_val_dict = {'i32': 127, 'i64': 126, 'f32': 125, 'f64': 124, 'anyfunc': 112, 'func': 96, 'empty_block_type': 64}
class Externalkind(ValueDefinition):
str_val_dict = {'Function': 0, 'Table': 1, 'Memory': 2, 'Global': 3}
class Initexprop(ValueDefinition):
str_val_dict = {'i32.const': 65, 'i64.const': 66, 'f32.const': 67, 'f64.const': 68, 'v128.const': 253, 'get_global': 35, 'end': 11}
class Nametype(ValueDefinition):
str_val_dict = {'module': 0, 'function': 1, 'local': 2} |
strip_words = [
'Kind',
'MAE',
'Pandemisch'
]
skip_names = [
'Water'
]
ignore_names = [
'alfalfa',
'ali',
'belladonna',
'cold',
'drank',
'gas',
'hot',
'linn',
'sepia',
'skin',
'slow',
'stol',
'ultra',
'vicks',
'vitamine',
'yasmin'
]
# require_implicit_certainty = [
# 'acid',
# 'agnus',
# 'allium',
# 'angelica',
# 'anti',
# 'apis',
# 'ben',
# 'bleu',
# 'buxus',
# 'cactus',
# 'cad',
# 'cat',
# 'china',
# 'citroenmelisse',
# 'code',
# 'diane',
# 'duivelsklauw',
# 'dry',
# 'eucalyptus',
# 'formule',
# 'flor',
# 'femke',
# 'getinte',
# 'glucose',
# 'glucosamine',
# 'hedera',
# 'hoest',
# 'humaan',
# 'indium',
# 'iris',
# 'lobelia',
# 'luis',
# 'muse',
# 'nol',
# 'red',
# 'robinia',
# 'sabina',
# 'saxen',
# 'senna',
# 'stadium',
# 'talia',
# 'thuja',
# 'timo',
# 'tobi',
# 'rectale'
# 'veronica',
# 'will'
# ]
# require_more_certainty = [
# 'adrenaline',
# 'allegra',
# 'ammonium',
# 'arum',
# 'belfor',
# 'calcium',
# 'digitalis',
# 'discus',
# 'formica',
# 'ginkgo',
# 'kalium',
# 'lac',
# 'lucht',
# 'maagzuur',
# 'melissa',
# 'mercurius',
# 'mono',
# 'myosotis',
# 'nicotine',
# 'nol',
# 'oblong',
# 'omega',
# 'plasma',
# 'platina',
# 'prick',
# 'rectale',
# 'ribes',
# 'selenium',
# 'terra',
# 'viola',
# 'zeel',
# 'zure',
# 'zuurstof'
# ] | strip_words = ['Kind', 'MAE', 'Pandemisch']
skip_names = ['Water']
ignore_names = ['alfalfa', 'ali', 'belladonna', 'cold', 'drank', 'gas', 'hot', 'linn', 'sepia', 'skin', 'slow', 'stol', 'ultra', 'vicks', 'vitamine', 'yasmin'] |
class Solution:
def canJump(self, nums) -> bool:
"""
nums: List[int]
Given an array of non-negative integers, you are initially
positioned at the first index of the array.
Each element in the array represents your maximum jump length at that
position.
Determine if you are able to reach the last index.
"""
#side case
if len(nums)==0:
return False
if len(nums)==1:
return True
#init
i=0
j=0
max_length=0
#code
for i in range(len(nums)):
if max_length<i:
return False
max_length=max(max_length,i+nums[i])
return True
if __name__=="__main__":
solu=Solution()
assert(solu.canJump([2,3,1,1,4]))
assert(solu.canJump([2,5,0,0]))
assert(not solu.canJump([3,2,1,0,4])) | class Solution:
def can_jump(self, nums) -> bool:
"""
nums: List[int]
Given an array of non-negative integers, you are initially
positioned at the first index of the array.
Each element in the array represents your maximum jump length at that
position.
Determine if you are able to reach the last index.
"""
if len(nums) == 0:
return False
if len(nums) == 1:
return True
i = 0
j = 0
max_length = 0
for i in range(len(nums)):
if max_length < i:
return False
max_length = max(max_length, i + nums[i])
return True
if __name__ == '__main__':
solu = solution()
assert solu.canJump([2, 3, 1, 1, 4])
assert solu.canJump([2, 5, 0, 0])
assert not solu.canJump([3, 2, 1, 0, 4]) |
#!/usr/bin/env python
esInputs = "/home/matthieu/.emulationstation/es_input.cfg"
esSettings = '/home/matthieu/.emulationstation/es_settings.cfg'
recalboxConf = "/home/matthieu/recalbox/recalbox.conf"
retroarchRoot = "/home/matthieu/recalbox/configs/retroarch"
retroarchCustom = retroarchRoot + '/retroarchcustom.cfg'
retroarchCustomOrigin = retroarchRoot + "/retroarchcustom.cfg.origin"
retroarchCoreCustom = retroarchRoot + "/cores/retroarch-core-options.cfg"
retroarchBin = "retroarch"
retroarchCores = "/usr/lib/libretro/"
shadersRoot = "/home/matthieu/recalbox/share_init/shaders/presets/"
shadersExt = '.gplsp'
libretroExt = '_libretro.so'
fbaRoot = '/home/matthieu/recalbox/configs/fba/'
fbaCustom = fbaRoot + 'fba2x.cfg'
fbaCustomOrigin = fbaRoot + 'fba2x.cfg.origin'
fba2xBin = '/usr/bin/fba2x'
mupenCustom = "/home/matthieu/recalbox/configs/mupen64/mupen64plus.cfg"
shaderPresetRoot = "/home/matthieu/recalbox/share/system/shadersets/"
kodiJoystick = '/home/matthieu/.kodi/userdata/keymaps/recalbox.xml'
kodiMappingUser = '/home/matthieu/recalbox/configs/kodi/input.xml'
kodiBin = '/usr/lib/kodi/kodi.bin'
logdir = '/home/matthieu/recalbox/logs/'
| es_inputs = '/home/matthieu/.emulationstation/es_input.cfg'
es_settings = '/home/matthieu/.emulationstation/es_settings.cfg'
recalbox_conf = '/home/matthieu/recalbox/recalbox.conf'
retroarch_root = '/home/matthieu/recalbox/configs/retroarch'
retroarch_custom = retroarchRoot + '/retroarchcustom.cfg'
retroarch_custom_origin = retroarchRoot + '/retroarchcustom.cfg.origin'
retroarch_core_custom = retroarchRoot + '/cores/retroarch-core-options.cfg'
retroarch_bin = 'retroarch'
retroarch_cores = '/usr/lib/libretro/'
shaders_root = '/home/matthieu/recalbox/share_init/shaders/presets/'
shaders_ext = '.gplsp'
libretro_ext = '_libretro.so'
fba_root = '/home/matthieu/recalbox/configs/fba/'
fba_custom = fbaRoot + 'fba2x.cfg'
fba_custom_origin = fbaRoot + 'fba2x.cfg.origin'
fba2x_bin = '/usr/bin/fba2x'
mupen_custom = '/home/matthieu/recalbox/configs/mupen64/mupen64plus.cfg'
shader_preset_root = '/home/matthieu/recalbox/share/system/shadersets/'
kodi_joystick = '/home/matthieu/.kodi/userdata/keymaps/recalbox.xml'
kodi_mapping_user = '/home/matthieu/recalbox/configs/kodi/input.xml'
kodi_bin = '/usr/lib/kodi/kodi.bin'
logdir = '/home/matthieu/recalbox/logs/' |
def set_timer():
# WIP
pass
| def set_timer():
pass |
def check_inputs(number_of_models, model_1_inputs, model_2_inputs=None):
"""Checks that the user inputs make logical sense
e.g. have they specified the number of models to be 2
but only given data for one model."""
# check model comparison information
# check model 2 is added if number of models is set to 2
if number_of_models == 2 and model_2_inputs is None:
raise ValueError("Expect model 2 data and got None. To fix either set number_of_models = 1 \
or enter data for Model 2")
# warning if number of models is set to 1 but data for model 2 exists
if number_of_models == 1 and model_2_inputs is not None:
print("Warning: model 2 data will not be used. \
To fix set number_of_models = 2.")
# check model 1 data
# warning if instantenous dose is specified
# but no times are given for the dose
if model_1_inputs["m1_instantaneous_dose_amount"] != 0 \
and model_1_inputs["m1_dose_times"] == []:
raise ValueError("Warning: enter times for instantenous dose \
or set m1_instantaneous_dose_amount to 0.")
# warning if times are given for the instantanous dose
# but no dose quantity is given
if model_1_inputs["m1_instantaneous_dose_amount"] == 0 \
and model_1_inputs["m1_dose_times"]:
print("Warning: no m1_instantenous_dose_amount entered")
# warnings if compartment volumes are zero or negative
if model_1_inputs["m1_volume_c"] <= 0:
raise ValueError("Set m1_volume_c to a positive value.")
if model_1_inputs["m1_volume_1"] <= 0:
raise ValueError("Set m1_volume_1 to a positive value.")
if model_1_inputs["m1_number_of_compartments"] == 2 \
and model_1_inputs["m1_volume_2"] <= 0:
raise ValueError("Set m1_volume_2 to a positive value \
or set m1_number_of_compartments to 1.")
# warning if size of second peripheral compartment is non-zero
# and number of compartments is set to 1
if model_1_inputs["m1_number_of_compartments"] == 1 \
and model_1_inputs["m1_volume_2"] != 0:
print("Warning: 2nd peripheral compartment won't be included. \
Set m1_number_of_compartments to 2 to include.")
# warning if dosing is set to subcutaneous but ka is 0
if model_1_inputs["m1_dose_entry"] == 'subcutaneous' \
and model_1_inputs["m1_k_a"] == 0:
print("Warning: Dosing is set to subcutaneous and ka = 0 \
so dose won't be absorbed.")
# warning if dosing is not subcutenous but ka is non-zero
if model_1_inputs["m1_dose_entry"] != 'subcutaneous' \
and model_1_inputs["m1_k_a"] != 0:
print("Warning: m1_dose_entry not subcutaneous \
so dose compartment won't be added.")
# check model 2 data
# warning if instantenous dose is specified
# but no times are given for the dose
if model_2_inputs["m2_instantaneous_dose_amount"] != 0 \
and model_2_inputs["m2_dose_times"] == []:
raise ValueError("Warning: enter times for instantenous dose \
or set m2_instantaneous_dose_amount to 0.")
# warning if times are given for the instantanous dose
# but no dose quantity is given
if model_2_inputs["m2_instantaneous_dose_amount"] == 0 \
and model_2_inputs["m2_dose_times"]:
print("Warning: no m2_instantenous_dose_amount entered")
# warnings if compartment volumes are zero or negative
if model_2_inputs["m2_volume_c"] <= 0:
raise ValueError("Set m2_volume_c to a positive value.")
if model_2_inputs["m2_volume_1"] <= 0:
raise ValueError("Set m2_volume_1 to a positive value.")
if model_2_inputs["m2_number_of_compartments"] == 2 \
and model_2_inputs["m2_volume_2"] <= 0:
raise ValueError("Set m2_volume_2 to a positive value \
or set m2_number_of_compartments to 1.")
# warning if size of second peripheral compartment is non-zero
# and number of compartments is set to 1
if model_2_inputs["m2_number_of_compartments"] == 1 \
and model_2_inputs["m2_volume_2"] != 0:
print("Warning: 2nd peripheral compartment won't be included. \
Set m2_number_of_compartments to 2 to include.")
# warning if dosing is set to subcutaneous but ka is 0
if model_2_inputs["m2_dose_entry"] == 'subcutaneous' \
and model_2_inputs["m2_k_a"] == 0:
print("Warning: Dosing is set to subcutaneous and ka = 0 \
so dose won't be absorbed.")
# warning if dosing is not subcutenous but ka is non-zero
if model_2_inputs["m2_dose_entry"] != 'subcutaneous' \
and model_2_inputs["m2_k_a"] != 0:
print("Warning: m2_dose_entry not subcutaneous \
so dose compartment won't be added.")
| def check_inputs(number_of_models, model_1_inputs, model_2_inputs=None):
"""Checks that the user inputs make logical sense
e.g. have they specified the number of models to be 2
but only given data for one model."""
if number_of_models == 2 and model_2_inputs is None:
raise value_error('Expect model 2 data and got None. To fix either set number_of_models = 1 or enter data for Model 2')
if number_of_models == 1 and model_2_inputs is not None:
print('Warning: model 2 data will not be used. To fix set number_of_models = 2.')
if model_1_inputs['m1_instantaneous_dose_amount'] != 0 and model_1_inputs['m1_dose_times'] == []:
raise value_error('Warning: enter times for instantenous dose or set m1_instantaneous_dose_amount to 0.')
if model_1_inputs['m1_instantaneous_dose_amount'] == 0 and model_1_inputs['m1_dose_times']:
print('Warning: no m1_instantenous_dose_amount entered')
if model_1_inputs['m1_volume_c'] <= 0:
raise value_error('Set m1_volume_c to a positive value.')
if model_1_inputs['m1_volume_1'] <= 0:
raise value_error('Set m1_volume_1 to a positive value.')
if model_1_inputs['m1_number_of_compartments'] == 2 and model_1_inputs['m1_volume_2'] <= 0:
raise value_error('Set m1_volume_2 to a positive value or set m1_number_of_compartments to 1.')
if model_1_inputs['m1_number_of_compartments'] == 1 and model_1_inputs['m1_volume_2'] != 0:
print("Warning: 2nd peripheral compartment won't be included. Set m1_number_of_compartments to 2 to include.")
if model_1_inputs['m1_dose_entry'] == 'subcutaneous' and model_1_inputs['m1_k_a'] == 0:
print("Warning: Dosing is set to subcutaneous and ka = 0 so dose won't be absorbed.")
if model_1_inputs['m1_dose_entry'] != 'subcutaneous' and model_1_inputs['m1_k_a'] != 0:
print("Warning: m1_dose_entry not subcutaneous so dose compartment won't be added.")
if model_2_inputs['m2_instantaneous_dose_amount'] != 0 and model_2_inputs['m2_dose_times'] == []:
raise value_error('Warning: enter times for instantenous dose or set m2_instantaneous_dose_amount to 0.')
if model_2_inputs['m2_instantaneous_dose_amount'] == 0 and model_2_inputs['m2_dose_times']:
print('Warning: no m2_instantenous_dose_amount entered')
if model_2_inputs['m2_volume_c'] <= 0:
raise value_error('Set m2_volume_c to a positive value.')
if model_2_inputs['m2_volume_1'] <= 0:
raise value_error('Set m2_volume_1 to a positive value.')
if model_2_inputs['m2_number_of_compartments'] == 2 and model_2_inputs['m2_volume_2'] <= 0:
raise value_error('Set m2_volume_2 to a positive value or set m2_number_of_compartments to 1.')
if model_2_inputs['m2_number_of_compartments'] == 1 and model_2_inputs['m2_volume_2'] != 0:
print("Warning: 2nd peripheral compartment won't be included. Set m2_number_of_compartments to 2 to include.")
if model_2_inputs['m2_dose_entry'] == 'subcutaneous' and model_2_inputs['m2_k_a'] == 0:
print("Warning: Dosing is set to subcutaneous and ka = 0 so dose won't be absorbed.")
if model_2_inputs['m2_dose_entry'] != 'subcutaneous' and model_2_inputs['m2_k_a'] != 0:
print("Warning: m2_dose_entry not subcutaneous so dose compartment won't be added.") |
class Stack:
def __init__(self):
self.data = []
def push(self, value):
self.data.append(value)
def pop(self):
return self.data.pop()
def peek(self):
if len(self.data) > 0:
return self.data[-1:][0]
else:
return None
def size(self):
return len(self.data)
| class Stack:
def __init__(self):
self.data = []
def push(self, value):
self.data.append(value)
def pop(self):
return self.data.pop()
def peek(self):
if len(self.data) > 0:
return self.data[-1:][0]
else:
return None
def size(self):
return len(self.data) |
class Ingredient():
def __init__(self, amount, unit, name):
self.amount = self.convert_to_decimal(amount)
self.unit = unit
self.name = name
def convert_to_decimal(self, amount):
try:
return float(amount)
except ValueError:
num, denom = amount.split('/')
return float(num) / float(denom)
def convert_to_grams(self):
pass | class Ingredient:
def __init__(self, amount, unit, name):
self.amount = self.convert_to_decimal(amount)
self.unit = unit
self.name = name
def convert_to_decimal(self, amount):
try:
return float(amount)
except ValueError:
(num, denom) = amount.split('/')
return float(num) / float(denom)
def convert_to_grams(self):
pass |
""" This is an AWS Lambda function to demonstrate the import of Lambda Layers
"""
# from lambdalayer import lambdalayer
def main(event, context):
"""Handler method for the AWS Lambda Function."""
print(f"*** Lambda 2: Execution of AWS Lambda function starts. ***")
print(f"*** Lambda 2: Trying to invoke Lambda Layer. ***")
# lambdalayer.import_layer()
print(f"*** Lambda 2: Invoked method from Lambda Layer. ***")
print(f"*** Lambda 2: Execution of AWS Lambda function ends. ***") | """ This is an AWS Lambda function to demonstrate the import of Lambda Layers
"""
def main(event, context):
"""Handler method for the AWS Lambda Function."""
print(f'*** Lambda 2: Execution of AWS Lambda function starts. ***')
print(f'*** Lambda 2: Trying to invoke Lambda Layer. ***')
print(f'*** Lambda 2: Invoked method from Lambda Layer. ***')
print(f'*** Lambda 2: Execution of AWS Lambda function ends. ***') |
"""Helper module to define static html outputs"""
__all__ = [
'add_header',
'row',
'rows',
'fig',
'card',
'card_deck',
'card_rows',
'title',
'div',
'table_from_df',
'hide',
'tabs',
'input'
]
def add_header(html:str, title="explainerdashboard")->str:
"""Turns a html snippet into a full html layout by adding <html>, <head> and <body> tags.
Loads bootstrap css and javascript and triggers a resize event in order to prevent
plotly figs from overflowing their div containers.
"""
return f"""
<!DOCTYPE html>
<html lang="en">
<head>
<title>{title}</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
</head>
<body>
<div class="container">
{html}
</div>
</body>
<script type="text/javascript">
window.dispatchEvent(new Event('resize'));
</script>
</html>
"""
def row(*cols)->str:
"""Turns a series of html snippets into a bootstrap row with equally sized
columns for each snippet.
Example:
to_html.row("<div>first snippet</div>", "<div>second snippet</div>")
"""
row = '<div class="row" style="margin-top: 20px;">'
for col in cols:
row += '<div class="col-sm">'
row += col
row += '</div>'
row += '</div>'
return row
def rows(*col_lists)->str:
"""Turns a list of lists of html snippets into a series of bootstrap rows
with equally sized columns for each snippet.
Example:
to_html.row(
["<div>first snippet</div>", "<div>second snippet</div>"],
["<div>second row snippet snippet</div>", "<div>second row snippet two</div>"]
)
"""
rows = [row(*cols) for cols in col_lists]
rows = "".join(rows)
return div(rows)
def fig(fig, include_plotlyjs='cdn', full_html:bool=False)->str:
"""Returns html for a plotly figure. By default the plotly javascript is not
included but imported from the plotly cdn, and the full html wrapper is not included.
Args:
include_plotlyjs (bool, str): how to import the necessary javascript for the plotly
fig. Defaults to 'cdn', which means the figure just links to javascript file
hosted by plotly. If set to True then a 3MB javascript snippet is included.
For other options check https://plotly.com/python-api-reference/generated/plotly.io.to_html.html
full_html (bool): include <html>, <head> and <body> tags. Defaults to False.
"""
return fig.to_html(include_plotlyjs=include_plotlyjs, full_html=full_html)
def card(html:str, title:str=None, subtitle:str=None)->str:
"""Wrap to html snippet in a bootstrap card. You can optionally add a title
and subtitle to the card.
"""
if title:
card_header = f"""<div class="card-header"><h3 class="card-title">{title}</h3>"""
if subtitle:
card_header += f"""<h6 class="card-subtitle">{subtitle}</h6></div>"""
else:
card_header += "</div>"
else:
card_header = ""
return f"""
<div class="card">
{card_header}
<div class="card-body">
<div class="w-100">
{row(html)}
</div>
</div>
</div>
"""
def card_deck(*cards)->str:
"""turn a list of bootstrap cards into an equally spaced card deck.
Example:
to_html.card_deck(to_html.card("card1"), to_html.card("card2"))
"""
cards = list(cards)
cards = "".join(cards)
return f"""
<div class="card-deck">
{cards}
</div>
"""
def card_rows(*card_lists)->str:
"""Turn a list of lists of bootstrap cards into a series of bootstrap rows
with card decks.
Example:
to_html.card_rows(
[to_html.card("card1"), to_html.card("card2")],
[to_html.card("card3"), to_html.card("card4")],
)
"""
card_decks = [[card_deck(*cards)] for cards in card_lists]
return rows(*card_decks)
def title(title:str)->str:
"""wrap a title string in div and <H1></H1>"""
return f"<div><H1>{title}</H1></div>"
def div(html:str)->str:
"""wrap an html snippet in a <div></div>"""
return f'<div>{html}</div>'
def table_from_df(df)->str:
"""Generate a html table from a pandas DataFrame"""
header_row = '\n'.join([f' <th scope="col">{col}</th>' for col in df.columns])
body_rows = ""
for i, row in df.iterrows():
body_rows += (' <tr>\n'+'\n'.join([" <td>"+str(val)+"</td>" for val in row.values])+'\n </tr>\n')
table = f"""
<table class="table">
<thead>
<tr>
{header_row}
</tr>
</thead>
<tbody>
{body_rows}
</tbody>
</table>
"""
return table
def hide(html:str, hide:bool=False)->str:
"""optionally hide an html snippet (return empty div) if parameter hide=True"""
if hide:
return "<div></div>"
return html
def tabs(tabs_dict:dict)->str:
"""Generate a series of bootstrap tabs for a dictionary tabs_dict with the
name of each tab as the dict key and the html contents of the tab as the dict value.
"""
html = '<ul class="nav nav-tabs" id="myTab" role="tablist">'
for i, tab_name in enumerate(tabs_dict.keys()):
if i == 0:
html += f"""
<li class="nav-item">
<a class="nav-link active" id="{tab_name}-tab" data-toggle="tab" href="#{tab_name}" role="tab" aria-controls="{tab_name}" aria-selected="true">{tab_name}</a>
</li>\n"""
else:
html += f"""
<li class="nav-item">
<a class="nav-link" id="{tab_name}-tab" data-toggle="tab" href="#{tab_name}" role="tab" aria-controls="{tab_name}" aria-selected="false">{tab_name}</a>
</li>\n"""
html += """\n</ul>\n\n"""
html += """<div class="tab-content">\n\n"""
for i, (tab_name, tab_contents) in enumerate(tabs_dict.items()):
if i == 0:
html += f"""<div class="tab-pane active" id="{tab_name}" role="tabpanel" aria-labelledby="{tab_name}-tab">\n {tab_contents} \n</div>\n"""
else:
html += f"""<div class="tab-pane" id="{tab_name}" role="tabpanel" aria-labelledby="{tab_name}-tab">\n {tab_contents} \n</div>\n"""
html += "\n</div>"
html += """
<script type="text/javascript">
$('#myTab a').on('click', function (e) {
e.preventDefault()
$(this).tab('show')
})
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
window.dispatchEvent(new Event('resize'));
})
</script>
"""
return html
def input(feature:str, value, disabled:bool=False)->str:
"""
Return a html feature input with a feature name and default value.
Args:
feature (str): name of feature
value (str): default value
disabled (bool): disable the input. Defaults to False.
"""
return f"""
<div style="display:flex;flex-direction:column;">
<label for="{feature}">{feature}</label>
<input id="{feature}" type="text" value="{value}" name="{feature}" {'disabled' if disabled else ''}>
</div>
""" | """Helper module to define static html outputs"""
__all__ = ['add_header', 'row', 'rows', 'fig', 'card', 'card_deck', 'card_rows', 'title', 'div', 'table_from_df', 'hide', 'tabs', 'input']
def add_header(html: str, title='explainerdashboard') -> str:
"""Turns a html snippet into a full html layout by adding <html>, <head> and <body> tags.
Loads bootstrap css and javascript and triggers a resize event in order to prevent
plotly figs from overflowing their div containers.
"""
return f"""\n<!DOCTYPE html>\n<html lang="en">\n<head>\n<title>{title}</title>\n<meta charset="utf-8">\n<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">\n<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">\n<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>\n<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>\n<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>\n</head>\n<body>\n\n<div class="container">\n{html}\n</div>\n\n</body>\n<script type="text/javascript">\nwindow.dispatchEvent(new Event('resize'));\n</script>\n</html>\n"""
def row(*cols) -> str:
"""Turns a series of html snippets into a bootstrap row with equally sized
columns for each snippet.
Example:
to_html.row("<div>first snippet</div>", "<div>second snippet</div>")
"""
row = '<div class="row" style="margin-top: 20px;">'
for col in cols:
row += '<div class="col-sm">'
row += col
row += '</div>'
row += '</div>'
return row
def rows(*col_lists) -> str:
"""Turns a list of lists of html snippets into a series of bootstrap rows
with equally sized columns for each snippet.
Example:
to_html.row(
["<div>first snippet</div>", "<div>second snippet</div>"],
["<div>second row snippet snippet</div>", "<div>second row snippet two</div>"]
)
"""
rows = [row(*cols) for cols in col_lists]
rows = ''.join(rows)
return div(rows)
def fig(fig, include_plotlyjs='cdn', full_html: bool=False) -> str:
"""Returns html for a plotly figure. By default the plotly javascript is not
included but imported from the plotly cdn, and the full html wrapper is not included.
Args:
include_plotlyjs (bool, str): how to import the necessary javascript for the plotly
fig. Defaults to 'cdn', which means the figure just links to javascript file
hosted by plotly. If set to True then a 3MB javascript snippet is included.
For other options check https://plotly.com/python-api-reference/generated/plotly.io.to_html.html
full_html (bool): include <html>, <head> and <body> tags. Defaults to False.
"""
return fig.to_html(include_plotlyjs=include_plotlyjs, full_html=full_html)
def card(html: str, title: str=None, subtitle: str=None) -> str:
"""Wrap to html snippet in a bootstrap card. You can optionally add a title
and subtitle to the card.
"""
if title:
card_header = f'<div class="card-header"><h3 class="card-title">{title}</h3>'
if subtitle:
card_header += f'<h6 class="card-subtitle">{subtitle}</h6></div>'
else:
card_header += '</div>'
else:
card_header = ''
return f'\n<div class="card">\n {card_header}\n <div class="card-body">\n <div class="w-100">\n {row(html)}\n </div>\n </div>\n</div>\n'
def card_deck(*cards) -> str:
"""turn a list of bootstrap cards into an equally spaced card deck.
Example:
to_html.card_deck(to_html.card("card1"), to_html.card("card2"))
"""
cards = list(cards)
cards = ''.join(cards)
return f'\n<div class="card-deck">\n {cards}\n</div>\n '
def card_rows(*card_lists) -> str:
"""Turn a list of lists of bootstrap cards into a series of bootstrap rows
with card decks.
Example:
to_html.card_rows(
[to_html.card("card1"), to_html.card("card2")],
[to_html.card("card3"), to_html.card("card4")],
)
"""
card_decks = [[card_deck(*cards)] for cards in card_lists]
return rows(*card_decks)
def title(title: str) -> str:
"""wrap a title string in div and <H1></H1>"""
return f'<div><H1>{title}</H1></div>'
def div(html: str) -> str:
"""wrap an html snippet in a <div></div>"""
return f'<div>{html}</div>'
def table_from_df(df) -> str:
"""Generate a html table from a pandas DataFrame"""
header_row = '\n'.join([f' <th scope="col">{col}</th>' for col in df.columns])
body_rows = ''
for (i, row) in df.iterrows():
body_rows += ' <tr>\n' + '\n'.join([' <td>' + str(val) + '</td>' for val in row.values]) + '\n </tr>\n'
table = f'\n<table class="table">\n <thead>\n <tr>\n{header_row}\n </tr>\n </thead>\n <tbody>\n{body_rows}\n </tbody>\n</table>\n '
return table
def hide(html: str, hide: bool=False) -> str:
"""optionally hide an html snippet (return empty div) if parameter hide=True"""
if hide:
return '<div></div>'
return html
def tabs(tabs_dict: dict) -> str:
"""Generate a series of bootstrap tabs for a dictionary tabs_dict with the
name of each tab as the dict key and the html contents of the tab as the dict value.
"""
html = '<ul class="nav nav-tabs" id="myTab" role="tablist">'
for (i, tab_name) in enumerate(tabs_dict.keys()):
if i == 0:
html += f'\n <li class="nav-item">\n <a class="nav-link active" id="{tab_name}-tab" data-toggle="tab" href="#{tab_name}" role="tab" aria-controls="{tab_name}" aria-selected="true">{tab_name}</a>\n </li>\n'
else:
html += f'\n <li class="nav-item">\n <a class="nav-link" id="{tab_name}-tab" data-toggle="tab" href="#{tab_name}" role="tab" aria-controls="{tab_name}" aria-selected="false">{tab_name}</a>\n </li>\n'
html += '\n</ul>\n\n'
html += '<div class="tab-content">\n\n'
for (i, (tab_name, tab_contents)) in enumerate(tabs_dict.items()):
if i == 0:
html += f'<div class="tab-pane active" id="{tab_name}" role="tabpanel" aria-labelledby="{tab_name}-tab">\n {tab_contents} \n</div>\n'
else:
html += f'<div class="tab-pane" id="{tab_name}" role="tabpanel" aria-labelledby="{tab_name}-tab">\n {tab_contents} \n</div>\n'
html += '\n</div>'
html += '\n<script type="text/javascript">\n\n$(\'#myTab a\').on(\'click\', function (e) {\n e.preventDefault()\n $(this).tab(\'show\')\n})\n\n$(\'a[data-toggle="tab"]\').on(\'shown.bs.tab\', function (e) {\n window.dispatchEvent(new Event(\'resize\'));\n})\n\n</script>\n'
return html
def input(feature: str, value, disabled: bool=False) -> str:
"""
Return a html feature input with a feature name and default value.
Args:
feature (str): name of feature
value (str): default value
disabled (bool): disable the input. Defaults to False.
"""
return f'''\n<div style="display:flex;flex-direction:column;">\n <label for="{feature}">{feature}</label>\n <input id="{feature}" type="text" value="{value}" name="{feature}" {('disabled' if disabled else '')}>\n</div>\n ''' |
# Return the Nth Even Number
# nthEven(1) //=> 0, the first even number is 0
# nthEven(3) //=> 4, the 3rd even number is 4 (0, 2, 4)
# nthEven(100) //=> 198
# nthEven(1298734) //=> 2597466
# The input will not be 0.
def nth_even(n):
return 2 * (n - 1)
def test_nth_even():
assert nth_even(1) == 0
assert nth_even(2) == 2
assert nth_even(3) == 4
assert nth_even(100) == 198
assert nth_even(1298734) == 2597466
| def nth_even(n):
return 2 * (n - 1)
def test_nth_even():
assert nth_even(1) == 0
assert nth_even(2) == 2
assert nth_even(3) == 4
assert nth_even(100) == 198
assert nth_even(1298734) == 2597466 |
# https://www.codechef.com/problems/GOODBAD
for T in range(int(input())):
l,k=map(int,input().split())
s,c,b=input(),0,0
for i in s:
if(i>='A' and i<='Z'): c+=1
if(i>='a' and i<='z'): b+=1
if(c<=k and b<=k): print("both")
elif(c<=k): print("chef")
elif(b<=k): print("brother")
else: print("none") | for t in range(int(input())):
(l, k) = map(int, input().split())
(s, c, b) = (input(), 0, 0)
for i in s:
if i >= 'A' and i <= 'Z':
c += 1
if i >= 'a' and i <= 'z':
b += 1
if c <= k and b <= k:
print('both')
elif c <= k:
print('chef')
elif b <= k:
print('brother')
else:
print('none') |
x = """
.loader {
position: absolute;
top: 50%;
left: 50%;
margin-left: -HALFWIDTHpx;
margin-top: -HALFWIDTHpx;
width: 0;
height: 0;
visibility: initial;
transition: all .3s ease;
color: #fff;
font-family: Helvetica, Arial, sans-serif;
font-size: 2rem;
background-color: white;
border-radius: 50%;
z-index: -10
box-shadow: 10px -5px 12.5px 3.125px rgba(0, 133, 255, 0.53), inset 2px -5px 12.5px 0px rgba(235, 255, 0, 0.54), 2px 10px 12.5px 6.25px rgba(22, 243, 3, 0.55);
}
.loader:before {
content: "";
display: block;
width: FULLWIDTHpx;
height: FULLWIDTHpx;
/* border-radius: 40% 60% 86%;
*/ background: rgba(190, 11, 224, 0.35);
filter: blur(5px);
box-shadow: 10px 10px 12.5px 0px rgba(0, 133, 255, 0.53), inset -7px -5px 12.5px 0px rgba(235, 255, 0, 0.54);
animation: spin 10s linear infinite;
visibility: initial;
z-index: -10
}
.loader:after {
content: "";
display: block;
width: FULLWIDTHpx;
height: FULLWIDTHpx;
/* border-radius: 60% 50% 75%;
*/ background: rgba(235, 255, 0, 0.54);
filter: blur(5px);
box-shadow: -10px -12px 12.5px 0px rgba(255, 0, 0, 0.25), inset 7px -2px 12.5px 0px rgba(253, 127, 11, 0.4);
position: absolute;
top: 0;
animation: spin-alt 5s linear infinite;
visibility: initial;
z-index: -10
}
.loader-message {
display: block;
text-align: center;
vertical-align: middle;
background: white;
/* background: #1d1d1d;
*/ width: MINUSTENpx;
height: MINUSTENpx;
line-height: 190px;
/* border-radius: 50%;
*/ border: 3px solid white;
box-shadow: 0px 0px 10px 10px white;
text-transform: uppercase;
font-size: 1rem;
font-weight: bold;
position: absolute;
top: 50%;
left: 50%;
margin: 100px;
transform: translate(-50%, -50%);
z-index: 0;
letter-spacing: 7.5px;
}
@keyframes spin {
0% {
transform: rotate(0deg) scale(1);
}
50% {
transform: rotate(180deg) scale(1.2);
}
100% {
transform: rotate(360deg) scale(1);
}
}
@keyframes spin-alt {
0% {
transform: rotate(0deg) scale(1);
}
50% {
transform: rotate(-180deg) scale(1.2);
}
100% {
transform: rotate(-360deg) scale(1);
}
}
"""
w = 160
print(x.replace("FULLWIDTH", str(w)).replace("HALFWIDTH", str(w//2)).replace("MINUSTEN", str(w-10)))
| x = '\n.loader {\n position: absolute;\n top: 50%;\n left: 50%;\n margin-left: -HALFWIDTHpx;\n margin-top: -HALFWIDTHpx;\n width: 0;\n height: 0;\n visibility: initial;\n transition: all .3s ease;\n color: #fff;\n font-family: Helvetica, Arial, sans-serif;\n font-size: 2rem;\n background-color: white;\n border-radius: 50%;\n z-index: -10\n box-shadow: 10px -5px 12.5px 3.125px rgba(0, 133, 255, 0.53), inset 2px -5px 12.5px 0px rgba(235, 255, 0, 0.54), 2px 10px 12.5px 6.25px rgba(22, 243, 3, 0.55);\n}\n.loader:before {\n content: "";\n display: block;\n width: FULLWIDTHpx;\n height: FULLWIDTHpx;\n/* border-radius: 40% 60% 86%;\n*/ background: rgba(190, 11, 224, 0.35);\n filter: blur(5px);\n box-shadow: 10px 10px 12.5px 0px rgba(0, 133, 255, 0.53), inset -7px -5px 12.5px 0px rgba(235, 255, 0, 0.54);\n animation: spin 10s linear infinite;\n visibility: initial;\n z-index: -10\n\n}\n.loader:after {\n content: "";\n display: block;\n width: FULLWIDTHpx;\n height: FULLWIDTHpx;\n/* border-radius: 60% 50% 75%;\n*/ background: rgba(235, 255, 0, 0.54);\n filter: blur(5px);\n box-shadow: -10px -12px 12.5px 0px rgba(255, 0, 0, 0.25), inset 7px -2px 12.5px 0px rgba(253, 127, 11, 0.4);\n position: absolute;\n top: 0;\n animation: spin-alt 5s linear infinite;\n visibility: initial;\n z-index: -10\n\n\n}\n.loader-message {\n display: block;\n text-align: center;\n vertical-align: middle;\n background: white;\n/* background: #1d1d1d;\n*/ width: MINUSTENpx;\n height: MINUSTENpx;\n line-height: 190px;\n/* border-radius: 50%;\n*/ border: 3px solid white;\n box-shadow: 0px 0px 10px 10px white;\n text-transform: uppercase;\n font-size: 1rem;\n font-weight: bold;\n position: absolute;\n top: 50%;\n left: 50%;\n margin: 100px;\n transform: translate(-50%, -50%);\n z-index: 0;\n letter-spacing: 7.5px;\n}\n\n@keyframes spin {\n 0% {\n transform: rotate(0deg) scale(1);\n }\n 50% {\n transform: rotate(180deg) scale(1.2);\n }\n 100% {\n transform: rotate(360deg) scale(1);\n }\n}\n@keyframes spin-alt {\n 0% {\n transform: rotate(0deg) scale(1);\n }\n 50% {\n transform: rotate(-180deg) scale(1.2);\n }\n 100% {\n transform: rotate(-360deg) scale(1);\n }\n}\n'
w = 160
print(x.replace('FULLWIDTH', str(w)).replace('HALFWIDTH', str(w // 2)).replace('MINUSTEN', str(w - 10))) |
# class Tree:
# def __init__(self, val, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
treeSum = 0
def solve(self, root):
def preOrder(root):
if root:
self.treeSum += root.val
preOrder(root.right)
preOrder(root.left)
return root
preOrder(root)
return self.treeSum
| class Solution:
tree_sum = 0
def solve(self, root):
def pre_order(root):
if root:
self.treeSum += root.val
pre_order(root.right)
pre_order(root.left)
return root
pre_order(root)
return self.treeSum |
# 2.3.4 Iterators
class SequenceIterator:
"""An iterator for any of Python's sequence types."""
def __init__(self,sequence):
"""Create an iterator for the given sequence."""
self._seq = sequence # keep a reference to the underlying data
self._k = -1 # will increment to 0 on first call to next
def __next__(self):
"""Return the next element, or else raise StopIteration error."""
self._k += 1 # advance to next index
if self._k < len(self._seq):
return(self._seq[self._k]) # return the data element
else:
raise StopIteration('End') # there are no more elements
def __iter__(self):
"""By convention, an iterator must return itself as an iterator."""
return self
#----------------------------- my main function -----------------------------
seq = [1,1,2,3,5,8] # seq is iterable object instance
seq_buildIn = [1,1,2,3,5,8] # seq_buildIn is the same with seq
print('0: ',seq)
s = SequenceIterator(seq)
s_buildIn = seq_buildIn.__iter__()
print('1: ',end='')
for i in range(6):
print(s.__next__(),' ',end='')
print('')
print('2: ',end='')
for i in range(6):
print(s_buildIn.__next__(),' ',end='')
print('')
s._k = -1
for i in range(6):
s._seq[i] += 2.718
print('3: ',seq)
print('4: ',end='')
s._k = -1
for i in range(6):
print(s.__next__(),' ',end='') | class Sequenceiterator:
"""An iterator for any of Python's sequence types."""
def __init__(self, sequence):
"""Create an iterator for the given sequence."""
self._seq = sequence
self._k = -1
def __next__(self):
"""Return the next element, or else raise StopIteration error."""
self._k += 1
if self._k < len(self._seq):
return self._seq[self._k]
else:
raise stop_iteration('End')
def __iter__(self):
"""By convention, an iterator must return itself as an iterator."""
return self
seq = [1, 1, 2, 3, 5, 8]
seq_build_in = [1, 1, 2, 3, 5, 8]
print('0: ', seq)
s = sequence_iterator(seq)
s_build_in = seq_buildIn.__iter__()
print('1: ', end='')
for i in range(6):
print(s.__next__(), ' ', end='')
print('')
print('2: ', end='')
for i in range(6):
print(s_buildIn.__next__(), ' ', end='')
print('')
s._k = -1
for i in range(6):
s._seq[i] += 2.718
print('3: ', seq)
print('4: ', end='')
s._k = -1
for i in range(6):
print(s.__next__(), ' ', end='') |
class Service:
def __init__(self, name, connector_func, state_processor_method=None,
batch_size=1, tags=None, names_previous_services=None,
names_required_previous_services=None,
workflow_formatter=None, dialog_formatter=None, response_formatter=None,
label=None):
self.name = name
self.batch_size = batch_size
self.state_processor_method = state_processor_method
self.names_previous_services = names_previous_services or set()
self.names_required_previous_services = names_required_previous_services or set()
self.tags = set(tags or [])
self.workflow_formatter = workflow_formatter
self.dialog_formatter = dialog_formatter
self.response_formatter = response_formatter
self.connector_func = connector_func
self.previous_services = set()
self.required_previous_services = set()
self.dependent_services = set()
self.next_services = set()
self.label = label or self.name
def is_sselector(self):
return 'selector' in self.tags
def is_responder(self):
return 'responder' in self.tags
def is_input(self):
return 'input' in self.tags
def is_last_chance(self):
return 'last_chance' in self.tags
def is_timeout(self):
return 'timeout' in self.tags
def apply_workflow_formatter(self, payload):
if not self.workflow_formatter:
return payload
return self.workflow_formatter(payload)
def apply_dialog_formatter(self, payload):
if not self.dialog_formatter:
return [self.apply_workflow_formatter(payload)]
return self.dialog_formatter(self.apply_workflow_formatter(payload))
def apply_response_formatter(self, payload):
if not self.response_formatter:
return payload
return self.response_formatter(payload)
def simple_workflow_formatter(workflow_record):
return workflow_record['dialog'].to_dict()
| class Service:
def __init__(self, name, connector_func, state_processor_method=None, batch_size=1, tags=None, names_previous_services=None, names_required_previous_services=None, workflow_formatter=None, dialog_formatter=None, response_formatter=None, label=None):
self.name = name
self.batch_size = batch_size
self.state_processor_method = state_processor_method
self.names_previous_services = names_previous_services or set()
self.names_required_previous_services = names_required_previous_services or set()
self.tags = set(tags or [])
self.workflow_formatter = workflow_formatter
self.dialog_formatter = dialog_formatter
self.response_formatter = response_formatter
self.connector_func = connector_func
self.previous_services = set()
self.required_previous_services = set()
self.dependent_services = set()
self.next_services = set()
self.label = label or self.name
def is_sselector(self):
return 'selector' in self.tags
def is_responder(self):
return 'responder' in self.tags
def is_input(self):
return 'input' in self.tags
def is_last_chance(self):
return 'last_chance' in self.tags
def is_timeout(self):
return 'timeout' in self.tags
def apply_workflow_formatter(self, payload):
if not self.workflow_formatter:
return payload
return self.workflow_formatter(payload)
def apply_dialog_formatter(self, payload):
if not self.dialog_formatter:
return [self.apply_workflow_formatter(payload)]
return self.dialog_formatter(self.apply_workflow_formatter(payload))
def apply_response_formatter(self, payload):
if not self.response_formatter:
return payload
return self.response_formatter(payload)
def simple_workflow_formatter(workflow_record):
return workflow_record['dialog'].to_dict() |
text = input()
command = input()
while command != 'Decode':
current_command = command.split('|')
action = current_command[0]
if action == 'Move':
num_of_letters = int(current_command[1])
substring = text[:num_of_letters]
text = text[num_of_letters:] + substring
elif action == 'Insert':
index = int(current_command[1])
new_value = current_command[2]
text = text[:index] + new_value + text[index:]
elif action == 'ChangeAll':
substring = current_command[1]
replacement = current_command[2]
text = text.replace(substring, replacement)
command = input()
print(f"The decrypted message is: {text}")
| text = input()
command = input()
while command != 'Decode':
current_command = command.split('|')
action = current_command[0]
if action == 'Move':
num_of_letters = int(current_command[1])
substring = text[:num_of_letters]
text = text[num_of_letters:] + substring
elif action == 'Insert':
index = int(current_command[1])
new_value = current_command[2]
text = text[:index] + new_value + text[index:]
elif action == 'ChangeAll':
substring = current_command[1]
replacement = current_command[2]
text = text.replace(substring, replacement)
command = input()
print(f'The decrypted message is: {text}') |
"""
Given a string that contains only digits 0-9 and a target value, return all possibilities to add binary operators (not
unary) +, -, or * between the digits so they evaluate to the target value.
Examples:
"123", 6 -> ["1+2+3", "1*2*3"]
"232", 8 -> ["2*3+2", "2+3*2"]
"105", 5 -> ["1*0+5","10-5"]
"00", 0 -> ["0+0", "0-0", "0*0"]
"3456237490", 9191 -> []
"""
__author__ = 'Daniel'
class Solution(object):
def addOperators(self, num, target):
"""
Adapted from https://leetcode.com/discuss/58614/java-standard-backtrace-ac-solutoin-short-and-clear
Algorithm:
1. DFS
2. Special handling for multiplication
3. Detect invalid number with leading 0's
:type num: str
:type target: int
:rtype: List[str]
"""
ret = []
self.dfs(num, target, 0, "", 0, 0, ret)
return ret
def dfs(self, num, target, pos, cur_str, cur_val, mul, ret):
if pos >= len(num):
if cur_val == target:
ret.append(cur_str)
else:
for i in xrange(pos, len(num)):
if i != pos and num[pos] == "0":
continue
nxt_val = int(num[pos:i+1])
if not cur_str:
self.dfs(num, target, i+1, "%d"%nxt_val, nxt_val, nxt_val, ret)
else:
self.dfs(num, target, i+1, cur_str+"+%d"%nxt_val, cur_val+nxt_val, nxt_val, ret)
self.dfs(num, target, i+1, cur_str+"-%d"%nxt_val, cur_val-nxt_val, -nxt_val, ret)
self.dfs(num, target, i+1, cur_str+"*%d"%nxt_val, cur_val-mul+mul*nxt_val, mul*nxt_val, ret)
if __name__ == "__main__":
assert Solution().addOperators("232", 8) == ["2+3*2", "2*3+2"]
| """
Given a string that contains only digits 0-9 and a target value, return all possibilities to add binary operators (not
unary) +, -, or * between the digits so they evaluate to the target value.
Examples:
"123", 6 -> ["1+2+3", "1*2*3"]
"232", 8 -> ["2*3+2", "2+3*2"]
"105", 5 -> ["1*0+5","10-5"]
"00", 0 -> ["0+0", "0-0", "0*0"]
"3456237490", 9191 -> []
"""
__author__ = 'Daniel'
class Solution(object):
def add_operators(self, num, target):
"""
Adapted from https://leetcode.com/discuss/58614/java-standard-backtrace-ac-solutoin-short-and-clear
Algorithm:
1. DFS
2. Special handling for multiplication
3. Detect invalid number with leading 0's
:type num: str
:type target: int
:rtype: List[str]
"""
ret = []
self.dfs(num, target, 0, '', 0, 0, ret)
return ret
def dfs(self, num, target, pos, cur_str, cur_val, mul, ret):
if pos >= len(num):
if cur_val == target:
ret.append(cur_str)
else:
for i in xrange(pos, len(num)):
if i != pos and num[pos] == '0':
continue
nxt_val = int(num[pos:i + 1])
if not cur_str:
self.dfs(num, target, i + 1, '%d' % nxt_val, nxt_val, nxt_val, ret)
else:
self.dfs(num, target, i + 1, cur_str + '+%d' % nxt_val, cur_val + nxt_val, nxt_val, ret)
self.dfs(num, target, i + 1, cur_str + '-%d' % nxt_val, cur_val - nxt_val, -nxt_val, ret)
self.dfs(num, target, i + 1, cur_str + '*%d' % nxt_val, cur_val - mul + mul * nxt_val, mul * nxt_val, ret)
if __name__ == '__main__':
assert solution().addOperators('232', 8) == ['2+3*2', '2*3+2'] |
# To implement a stack using a list
# Made by Nouman
stack=[]
def push(x):
stack.append(x)
print("Stack: ", stack)
print(x," pushed into stack")
def pop():
x=stack.pop()
print("\nPopped: ",x)
print("Stack :",stack)
size=int(input("Enter size of stack: "))
print("\nEnter elements into stack: ")
for i in range(size):
x=int(input("\nInput: "))
push(x)
for i in range(size):
pop() | stack = []
def push(x):
stack.append(x)
print('Stack: ', stack)
print(x, ' pushed into stack')
def pop():
x = stack.pop()
print('\nPopped: ', x)
print('Stack :', stack)
size = int(input('Enter size of stack: '))
print('\nEnter elements into stack: ')
for i in range(size):
x = int(input('\nInput: '))
push(x)
for i in range(size):
pop() |
class Solution:
def wordPattern(self, pattern: str, s: str) -> bool:
words = s.split(' ')
if len(pattern) != len(words): return False
w_to_p = {}
p_to_w = {}
for i, w in enumerate(words):
if pattern[i] not in p_to_w: p_to_w[pattern[i]] = w
if w not in w_to_p: w_to_p[w] = pattern[i]
if p_to_w[pattern[i]] != w or w_to_p[w] != pattern[i]: return False
return True
| class Solution:
def word_pattern(self, pattern: str, s: str) -> bool:
words = s.split(' ')
if len(pattern) != len(words):
return False
w_to_p = {}
p_to_w = {}
for (i, w) in enumerate(words):
if pattern[i] not in p_to_w:
p_to_w[pattern[i]] = w
if w not in w_to_p:
w_to_p[w] = pattern[i]
if p_to_w[pattern[i]] != w or w_to_p[w] != pattern[i]:
return False
return True |
class Solution:
@staticmethod
def naive(nums,target):
left,right = 0,len(nums)-1
while right>left+1:
mid = (left+right)//2
if nums[mid]>target:
right = mid
elif nums[mid]<target:
left = mid
else:
return mid
if target<=nums[right] and target<=nums[left]:
return left
if nums[left]<target<=nums[right]:
return right
if target>=nums[right] and target>nums[left]:
if target==nums[right]:
return right
else:
return right+1
| class Solution:
@staticmethod
def naive(nums, target):
(left, right) = (0, len(nums) - 1)
while right > left + 1:
mid = (left + right) // 2
if nums[mid] > target:
right = mid
elif nums[mid] < target:
left = mid
else:
return mid
if target <= nums[right] and target <= nums[left]:
return left
if nums[left] < target <= nums[right]:
return right
if target >= nums[right] and target > nums[left]:
if target == nums[right]:
return right
else:
return right + 1 |
"""Define mapping of litex components to generated zephyr output"""
class Mapping:
"""Mapping from litex component to generated zephyr output
:param name: Name of the mapping, only used during debugging
:type name: str
"""
def __init__(self, name):
self.name = name
| """Define mapping of litex components to generated zephyr output"""
class Mapping:
"""Mapping from litex component to generated zephyr output
:param name: Name of the mapping, only used during debugging
:type name: str
"""
def __init__(self, name):
self.name = name |
#
# PySNMP MIB module CISCO-WAN-MG-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-WAN-MG-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:02:23 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsIntersection, ValueSizeConstraint, SingleValueConstraint, ValueRangeConstraint, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ValueSizeConstraint", "SingleValueConstraint", "ValueRangeConstraint", "ConstraintsUnion")
ciscoWan, = mibBuilder.importSymbols("CISCOWAN-SMI", "ciscoWan")
SnmpAdminString, = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpAdminString")
ModuleCompliance, NotificationGroup, ObjectGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup", "ObjectGroup")
IpAddress, Counter32, TimeTicks, Gauge32, Unsigned32, MibIdentifier, Bits, iso, ObjectIdentity, Counter64, ModuleIdentity, NotificationType, MibScalar, MibTable, MibTableRow, MibTableColumn, Integer32 = mibBuilder.importSymbols("SNMPv2-SMI", "IpAddress", "Counter32", "TimeTicks", "Gauge32", "Unsigned32", "MibIdentifier", "Bits", "iso", "ObjectIdentity", "Counter64", "ModuleIdentity", "NotificationType", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Integer32")
TruthValue, RowStatus, DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "TruthValue", "RowStatus", "DisplayString", "TextualConvention")
ciscoWanMgMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 351, 150, 10))
ciscoWanMgMIB.setRevisions(('2005-05-27 00:00', '2004-01-20 00:00', '2002-06-14 00:00', '2001-05-25 00:00', '2000-07-19 15:00', '2000-03-27 00:00', '1999-11-27 00:00',))
if mibBuilder.loadTexts: ciscoWanMgMIB.setLastUpdated('200505270000Z')
if mibBuilder.loadTexts: ciscoWanMgMIB.setOrganization('Cisco Systems, Inc.')
ciscoWanMgMIBObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 351, 150, 10, 1))
mediaGateway = MibIdentifier((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 1))
mediaGatewayController = MibIdentifier((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 2))
mediaGatewayEndpoint = MibIdentifier((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 3))
mediaGatewayLine = MibIdentifier((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 4))
mediaGatewayControllerResolution = MibIdentifier((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 5))
mediaGatewayDomainName = MibIdentifier((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 6))
mgName = MibScalar((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 1, 1), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 64))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: mgName.setStatus('current')
mgAdministrativeState = MibScalar((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("inService", 1), ("commandedOutOfService", 2), ("pendingOutOfService", 3))).clone('commandedOutOfService')).setMaxAccess("readonly")
if mibBuilder.loadTexts: mgAdministrativeState.setStatus('current')
mgAdministrativeStateControl = MibScalar((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("inService", 1), ("forcefulOutOfService", 2), ("gracefulOutOfService", 3))).clone('forcefulOutOfService')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: mgAdministrativeStateControl.setStatus('current')
mgShutdownGraceTime = MibScalar((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 65535))).setUnits('seconds').setMaxAccess("readwrite")
if mibBuilder.loadTexts: mgShutdownGraceTime.setStatus('current')
mgSupportedProtocolTable = MibTable((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 1, 7), )
if mibBuilder.loadTexts: mgSupportedProtocolTable.setStatus('current')
mgSupportedProtocolEntry = MibTableRow((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 1, 7, 1), ).setIndexNames((0, "CISCO-WAN-MG-MIB", "mgProtocolNumber"))
if mibBuilder.loadTexts: mgSupportedProtocolEntry.setStatus('current')
mgProtocolNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 1, 7, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535)))
if mibBuilder.loadTexts: mgProtocolNumber.setStatus('current')
mgProtocolName = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 1, 7, 1, 2), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 64))).setMaxAccess("readonly")
if mibBuilder.loadTexts: mgProtocolName.setStatus('current')
maxConcurrentMgcs = MibScalar((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 2, 3), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setUnits('controllers').setMaxAccess("readonly")
if mibBuilder.loadTexts: maxConcurrentMgcs.setStatus('current')
mgcTable = MibTable((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 2, 1), )
if mibBuilder.loadTexts: mgcTable.setStatus('current')
mgcEntry = MibTableRow((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 2, 1, 1), ).setIndexNames((0, "CISCO-WAN-MG-MIB", "mgcNumber"))
if mibBuilder.loadTexts: mgcEntry.setStatus('current')
mgcNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 2, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535)))
if mibBuilder.loadTexts: mgcNumber.setStatus('current')
mgcName = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 2, 1, 1, 2), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 64))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: mgcName.setStatus('current')
mgcDnsResolution = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 2, 1, 1, 3), TruthValue().clone('false')).setMaxAccess("readonly")
if mibBuilder.loadTexts: mgcDnsResolution.setStatus('deprecated')
mgcAssociationState = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 2, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("mgcUnassociated", 1), ("mgcAssociated", 2), ("mgcAssociatedCommLoss", 3)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: mgcAssociationState.setStatus('deprecated')
mgcAssociationStateControl = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 2, 1, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("mgcUnassociate", 1), ("mgcAssociate", 2), ("mgcClear", 3))).clone('mgcUnassociate')).setMaxAccess("readcreate")
if mibBuilder.loadTexts: mgcAssociationStateControl.setStatus('deprecated')
mgcUnassociationPolicy = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 2, 1, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("mgcNoAction", 1), ("mgcRelease", 2))).clone('mgcNoAction')).setMaxAccess("readcreate")
if mibBuilder.loadTexts: mgcUnassociationPolicy.setStatus('deprecated')
mgcCommLossUnassociationTimeout = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 2, 1, 1, 7), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 65535)).clone(-1)).setUnits('seconds').setMaxAccess("readcreate")
if mibBuilder.loadTexts: mgcCommLossUnassociationTimeout.setStatus('deprecated')
mgcRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 2, 1, 1, 8), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: mgcRowStatus.setStatus('current')
mgcProtocolTable = MibTable((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 2, 2), )
if mibBuilder.loadTexts: mgcProtocolTable.setStatus('deprecated')
mgcProtocolEntry = MibTableRow((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 2, 2, 1), ).setIndexNames((0, "CISCO-WAN-MG-MIB", "mgcNumber"), (0, "CISCO-WAN-MG-MIB", "mgProtocolNumber"))
if mibBuilder.loadTexts: mgcProtocolEntry.setStatus('deprecated')
mgcProtocolRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 2, 2, 1, 1), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: mgcProtocolRowStatus.setStatus('deprecated')
mgEndpointCreationPolicy = MibScalar((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 3, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("dynamic", 1), ("strictDynamic", 2), ("static", 3))).clone('static')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: mgEndpointCreationPolicy.setStatus('current')
mgEndpointTable = MibTable((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 3, 1), )
if mibBuilder.loadTexts: mgEndpointTable.setStatus('current')
mgEndpointEntry = MibTableRow((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 3, 1, 1), ).setIndexNames((0, "CISCO-WAN-MG-MIB", "mgEndpointNumber"))
if mibBuilder.loadTexts: mgEndpointEntry.setStatus('current')
mgEndpointNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 3, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535)))
if mibBuilder.loadTexts: mgEndpointNumber.setStatus('current')
mgEndpointLineNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 3, 1, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: mgEndpointLineNumber.setStatus('current')
mgEndpointName = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 3, 1, 1, 3), SnmpAdminString()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: mgEndpointName.setStatus('current')
mgEndpointSpeed = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 3, 1, 1, 4), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setUnits('Kbps').setMaxAccess("readonly")
if mibBuilder.loadTexts: mgEndpointSpeed.setStatus('current')
mgEndpointState = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 3, 1, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("mgEndpointActive", 1), ("mgEndpointFailed", 2), ("mgEndpointDegraded", 3)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: mgEndpointState.setStatus('current')
mgEndpointChannelMap = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 3, 1, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 2147483647))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: mgEndpointChannelMap.setStatus('current')
mgEndpointRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 3, 1, 1, 7), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: mgEndpointRowStatus.setStatus('current')
lineAssignmentTable = MibTable((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 4, 1), )
if mibBuilder.loadTexts: lineAssignmentTable.setStatus('current')
lineAssignmentEntry = MibTableRow((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 4, 1, 1), ).setIndexNames((0, "CISCO-WAN-MG-MIB", "lineNumber"))
if mibBuilder.loadTexts: lineAssignmentEntry.setStatus('current')
lineNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 4, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535)))
if mibBuilder.loadTexts: lineNumber.setStatus('current')
channelAssignment = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 4, 1, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 2147483647))).setMaxAccess("readonly")
if mibBuilder.loadTexts: channelAssignment.setStatus('current')
lineName = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 4, 1, 1, 3), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 64))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: lineName.setStatus('current')
mgcResolutionTable = MibTable((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 5, 1), )
if mibBuilder.loadTexts: mgcResolutionTable.setStatus('current')
mgcResolutionEntry = MibTableRow((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 5, 1, 1), ).setIndexNames((0, "CISCO-WAN-MG-MIB", "mgcResolutionIndex"))
if mibBuilder.loadTexts: mgcResolutionEntry.setStatus('current')
mgcResolutionIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 5, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535)))
if mibBuilder.loadTexts: mgcResolutionIndex.setStatus('current')
mgcResolutionName = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 5, 1, 1, 2), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 64))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: mgcResolutionName.setStatus('current')
mgcResolutionIpAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 5, 1, 1, 3), IpAddress()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: mgcResolutionIpAddress.setStatus('current')
mgcResolutionCommState = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 5, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("csActive", 1), ("csInactive", 2))).clone('csInactive')).setMaxAccess("readonly")
if mibBuilder.loadTexts: mgcResolutionCommState.setStatus('current')
mgcResolutionPreference = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 5, 1, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: mgcResolutionPreference.setStatus('current')
mgcResolutionRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 5, 1, 1, 6), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: mgcResolutionRowStatus.setStatus('current')
mgcDnsResolutionFlag = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 5, 1, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("internal", 1), ("external", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: mgcDnsResolutionFlag.setStatus('current')
mgDomainNameTable = MibTable((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 6, 1), )
if mibBuilder.loadTexts: mgDomainNameTable.setStatus('current')
mgDomainNameEntry = MibTableRow((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 6, 1, 1), ).setIndexNames((0, "CISCO-WAN-MG-MIB", "mgDomainNameIndex"))
if mibBuilder.loadTexts: mgDomainNameEntry.setStatus('current')
mgDomainNameIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 6, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535)))
if mibBuilder.loadTexts: mgDomainNameIndex.setStatus('current')
mgDomainName = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 6, 1, 1, 2), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 64))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: mgDomainName.setStatus('current')
mgDnsResolutionType = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 6, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("internalOnly", 1), ("externalOnly", 2), ("internalFirst", 3), ("externalFirst", 4))).clone('internalOnly')).setMaxAccess("readcreate")
if mibBuilder.loadTexts: mgDnsResolutionType.setStatus('current')
mgDomainNameRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 6, 1, 1, 4), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: mgDomainNameRowStatus.setStatus('current')
mgEndpointExtTable = MibTable((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 3, 3), )
if mibBuilder.loadTexts: mgEndpointExtTable.setStatus('current')
mgEndpointExtEntry = MibTableRow((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 3, 3, 1), )
mgEndpointEntry.registerAugmentions(("CISCO-WAN-MG-MIB", "mgEndpointExtEntry"))
mgEndpointExtEntry.setIndexNames(*mgEndpointEntry.getIndexNames())
if mibBuilder.loadTexts: mgEndpointExtEntry.setStatus('current')
mgEndpointRepetition = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 3, 3, 1, 1), Unsigned32().clone(1)).setMaxAccess("readcreate")
if mibBuilder.loadTexts: mgEndpointRepetition.setStatus('current')
mgMIBConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 351, 150, 10, 3))
mgMIBCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 351, 150, 10, 3, 1))
mgMIBGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 351, 150, 10, 3, 2))
mgMIBCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 351, 150, 10, 3, 1, 1)).setObjects(("CISCO-WAN-MG-MIB", "mediaGatewayGroup"), ("CISCO-WAN-MG-MIB", "mediaGatewayControllerGroup"), ("CISCO-WAN-MG-MIB", "mediaGatewayEndpointGroup"), ("CISCO-WAN-MG-MIB", "mediaGatewayLineGroup"), ("CISCO-WAN-MG-MIB", "mediaGatewayControllerResolutionGroup"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
mgMIBCompliance = mgMIBCompliance.setStatus('deprecated')
mgMIBCompliance1 = ModuleCompliance((1, 3, 6, 1, 4, 1, 351, 150, 10, 3, 1, 2)).setObjects(("CISCO-WAN-MG-MIB", "mediaGatewayGroup"), ("CISCO-WAN-MG-MIB", "mediaGatewayControllerGroup1"), ("CISCO-WAN-MG-MIB", "mediaGatewayEndpointGroup"), ("CISCO-WAN-MG-MIB", "mediaGatewayLineGroup"), ("CISCO-WAN-MG-MIB", "mediaGatewayDomainNameGroup"), ("CISCO-WAN-MG-MIB", "mediaGatewayControllerResolutionGroup1"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
mgMIBCompliance1 = mgMIBCompliance1.setStatus('deprecated')
mgMIBCompliance2 = ModuleCompliance((1, 3, 6, 1, 4, 1, 351, 150, 10, 3, 1, 3)).setObjects(("CISCO-WAN-MG-MIB", "mediaGatewayGroup"), ("CISCO-WAN-MG-MIB", "mediaGatewayControllerGroup2"), ("CISCO-WAN-MG-MIB", "mediaGatewayEndpointGroup"), ("CISCO-WAN-MG-MIB", "mediaGatewayLineGroup"), ("CISCO-WAN-MG-MIB", "mediaGatewayDomainNameGroup"), ("CISCO-WAN-MG-MIB", "mediaGatewayControllerResolutionGroup1"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
mgMIBCompliance2 = mgMIBCompliance2.setStatus('deprecated')
mgMIBCompliance3 = ModuleCompliance((1, 3, 6, 1, 4, 1, 351, 150, 10, 3, 1, 4)).setObjects(("CISCO-WAN-MG-MIB", "mediaGatewayGroup"), ("CISCO-WAN-MG-MIB", "mediaGatewayControllerGroup2"), ("CISCO-WAN-MG-MIB", "mediaGatewayEndpointGroup"), ("CISCO-WAN-MG-MIB", "mediaGatewayLineGroup"), ("CISCO-WAN-MG-MIB", "mediaGatewayDomainNameGroup"), ("CISCO-WAN-MG-MIB", "mediaGatewayControllerResolutionGroup1"), ("CISCO-WAN-MG-MIB", "mediaGatewayEndptRepetitionGroup"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
mgMIBCompliance3 = mgMIBCompliance3.setStatus('current')
mediaGatewayGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 351, 150, 10, 3, 2, 1)).setObjects(("CISCO-WAN-MG-MIB", "mgName"), ("CISCO-WAN-MG-MIB", "mgAdministrativeState"), ("CISCO-WAN-MG-MIB", "mgAdministrativeStateControl"), ("CISCO-WAN-MG-MIB", "mgShutdownGraceTime"), ("CISCO-WAN-MG-MIB", "mgProtocolName"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
mediaGatewayGroup = mediaGatewayGroup.setStatus('current')
mediaGatewayControllerGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 351, 150, 10, 3, 2, 2)).setObjects(("CISCO-WAN-MG-MIB", "maxConcurrentMgcs"), ("CISCO-WAN-MG-MIB", "mgcName"), ("CISCO-WAN-MG-MIB", "mgcDnsResolution"), ("CISCO-WAN-MG-MIB", "mgcAssociationState"), ("CISCO-WAN-MG-MIB", "mgcAssociationStateControl"), ("CISCO-WAN-MG-MIB", "mgcUnassociationPolicy"), ("CISCO-WAN-MG-MIB", "mgcCommLossUnassociationTimeout"), ("CISCO-WAN-MG-MIB", "mgcRowStatus"), ("CISCO-WAN-MG-MIB", "mgcProtocolRowStatus"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
mediaGatewayControllerGroup = mediaGatewayControllerGroup.setStatus('deprecated')
mediaGatewayEndpointGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 351, 150, 10, 3, 2, 3)).setObjects(("CISCO-WAN-MG-MIB", "mgEndpointCreationPolicy"), ("CISCO-WAN-MG-MIB", "mgEndpointName"), ("CISCO-WAN-MG-MIB", "mgEndpointLineNumber"), ("CISCO-WAN-MG-MIB", "mgEndpointSpeed"), ("CISCO-WAN-MG-MIB", "mgEndpointState"), ("CISCO-WAN-MG-MIB", "mgEndpointChannelMap"), ("CISCO-WAN-MG-MIB", "mgEndpointRowStatus"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
mediaGatewayEndpointGroup = mediaGatewayEndpointGroup.setStatus('current')
mediaGatewayLineGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 351, 150, 10, 3, 2, 4)).setObjects(("CISCO-WAN-MG-MIB", "channelAssignment"), ("CISCO-WAN-MG-MIB", "lineName"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
mediaGatewayLineGroup = mediaGatewayLineGroup.setStatus('current')
mediaGatewayControllerResolutionGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 351, 150, 10, 3, 2, 5)).setObjects(("CISCO-WAN-MG-MIB", "mgcResolutionName"), ("CISCO-WAN-MG-MIB", "mgcResolutionIpAddress"), ("CISCO-WAN-MG-MIB", "mgcResolutionCommState"), ("CISCO-WAN-MG-MIB", "mgcResolutionPreference"), ("CISCO-WAN-MG-MIB", "mgcResolutionRowStatus"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
mediaGatewayControllerResolutionGroup = mediaGatewayControllerResolutionGroup.setStatus('deprecated')
mediaGatewayControllerGroup1 = ObjectGroup((1, 3, 6, 1, 4, 1, 351, 150, 10, 3, 2, 6)).setObjects(("CISCO-WAN-MG-MIB", "maxConcurrentMgcs"), ("CISCO-WAN-MG-MIB", "mgcName"), ("CISCO-WAN-MG-MIB", "mgcAssociationState"), ("CISCO-WAN-MG-MIB", "mgcAssociationStateControl"), ("CISCO-WAN-MG-MIB", "mgcUnassociationPolicy"), ("CISCO-WAN-MG-MIB", "mgcCommLossUnassociationTimeout"), ("CISCO-WAN-MG-MIB", "mgcRowStatus"), ("CISCO-WAN-MG-MIB", "mgcProtocolRowStatus"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
mediaGatewayControllerGroup1 = mediaGatewayControllerGroup1.setStatus('deprecated')
mediaGatewayControllerResolutionGroup1 = ObjectGroup((1, 3, 6, 1, 4, 1, 351, 150, 10, 3, 2, 7)).setObjects(("CISCO-WAN-MG-MIB", "mgcResolutionName"), ("CISCO-WAN-MG-MIB", "mgcResolutionIpAddress"), ("CISCO-WAN-MG-MIB", "mgcResolutionCommState"), ("CISCO-WAN-MG-MIB", "mgcResolutionPreference"), ("CISCO-WAN-MG-MIB", "mgcResolutionRowStatus"), ("CISCO-WAN-MG-MIB", "mgcDnsResolutionFlag"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
mediaGatewayControllerResolutionGroup1 = mediaGatewayControllerResolutionGroup1.setStatus('current')
mediaGatewayDomainNameGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 351, 150, 10, 3, 2, 8)).setObjects(("CISCO-WAN-MG-MIB", "mgDomainName"), ("CISCO-WAN-MG-MIB", "mgDnsResolutionType"), ("CISCO-WAN-MG-MIB", "mgDomainNameRowStatus"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
mediaGatewayDomainNameGroup = mediaGatewayDomainNameGroup.setStatus('current')
mediaGatewayControllerGroup2 = ObjectGroup((1, 3, 6, 1, 4, 1, 351, 150, 10, 3, 2, 9)).setObjects(("CISCO-WAN-MG-MIB", "maxConcurrentMgcs"), ("CISCO-WAN-MG-MIB", "mgcName"), ("CISCO-WAN-MG-MIB", "mgcRowStatus"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
mediaGatewayControllerGroup2 = mediaGatewayControllerGroup2.setStatus('current')
mediaGatewayEndptRepetitionGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 351, 150, 10, 3, 2, 10)).setObjects(("CISCO-WAN-MG-MIB", "mgEndpointRepetition"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
mediaGatewayEndptRepetitionGroup = mediaGatewayEndptRepetitionGroup.setStatus('current')
mibBuilder.exportSymbols("CISCO-WAN-MG-MIB", mgEndpointCreationPolicy=mgEndpointCreationPolicy, mgProtocolNumber=mgProtocolNumber, mgcNumber=mgcNumber, mediaGatewayGroup=mediaGatewayGroup, mgcResolutionIpAddress=mgcResolutionIpAddress, mgEndpointSpeed=mgEndpointSpeed, mgcDnsResolution=mgcDnsResolution, mgAdministrativeStateControl=mgAdministrativeStateControl, mgMIBConformance=mgMIBConformance, mgName=mgName, mgDomainNameTable=mgDomainNameTable, mgMIBCompliance3=mgMIBCompliance3, mgMIBCompliance=mgMIBCompliance, lineAssignmentEntry=lineAssignmentEntry, mgcTable=mgcTable, mediaGatewayControllerResolutionGroup=mediaGatewayControllerResolutionGroup, mgEndpointExtTable=mgEndpointExtTable, mgEndpointExtEntry=mgEndpointExtEntry, mgcProtocolRowStatus=mgcProtocolRowStatus, mgcAssociationState=mgcAssociationState, mgcDnsResolutionFlag=mgcDnsResolutionFlag, mediaGateway=mediaGateway, mediaGatewayEndpoint=mediaGatewayEndpoint, mgSupportedProtocolTable=mgSupportedProtocolTable, mgDomainName=mgDomainName, ciscoWanMgMIBObjects=ciscoWanMgMIBObjects, mgEndpointLineNumber=mgEndpointLineNumber, mgMIBCompliance2=mgMIBCompliance2, channelAssignment=channelAssignment, mgMIBCompliance1=mgMIBCompliance1, mediaGatewayDomainNameGroup=mediaGatewayDomainNameGroup, mgcResolutionPreference=mgcResolutionPreference, mgcProtocolEntry=mgcProtocolEntry, mediaGatewayLine=mediaGatewayLine, mgcResolutionName=mgcResolutionName, mediaGatewayLineGroup=mediaGatewayLineGroup, mediaGatewayControllerGroup=mediaGatewayControllerGroup, mgEndpointRowStatus=mgEndpointRowStatus, mgDomainNameEntry=mgDomainNameEntry, mediaGatewayDomainName=mediaGatewayDomainName, mgEndpointRepetition=mgEndpointRepetition, mgDomainNameIndex=mgDomainNameIndex, mgShutdownGraceTime=mgShutdownGraceTime, mgcEntry=mgcEntry, mgcAssociationStateControl=mgcAssociationStateControl, mgAdministrativeState=mgAdministrativeState, mgcRowStatus=mgcRowStatus, mgEndpointChannelMap=mgEndpointChannelMap, mgDomainNameRowStatus=mgDomainNameRowStatus, mgcUnassociationPolicy=mgcUnassociationPolicy, mediaGatewayControllerGroup1=mediaGatewayControllerGroup1, ciscoWanMgMIB=ciscoWanMgMIB, mediaGatewayEndpointGroup=mediaGatewayEndpointGroup, mediaGatewayController=mediaGatewayController, mediaGatewayControllerResolution=mediaGatewayControllerResolution, mgcResolutionCommState=mgcResolutionCommState, mgcResolutionRowStatus=mgcResolutionRowStatus, mediaGatewayControllerGroup2=mediaGatewayControllerGroup2, mgProtocolName=mgProtocolName, mgSupportedProtocolEntry=mgSupportedProtocolEntry, mgEndpointEntry=mgEndpointEntry, mgDnsResolutionType=mgDnsResolutionType, mgEndpointName=mgEndpointName, mgcResolutionTable=mgcResolutionTable, mgEndpointState=mgEndpointState, mediaGatewayControllerResolutionGroup1=mediaGatewayControllerResolutionGroup1, mgcProtocolTable=mgcProtocolTable, lineAssignmentTable=lineAssignmentTable, PYSNMP_MODULE_ID=ciscoWanMgMIB, mgcResolutionIndex=mgcResolutionIndex, mgcCommLossUnassociationTimeout=mgcCommLossUnassociationTimeout, mgcResolutionEntry=mgcResolutionEntry, mgMIBGroups=mgMIBGroups, mgEndpointNumber=mgEndpointNumber, mgcName=mgcName, mgMIBCompliances=mgMIBCompliances, mediaGatewayEndptRepetitionGroup=mediaGatewayEndptRepetitionGroup, mgEndpointTable=mgEndpointTable, maxConcurrentMgcs=maxConcurrentMgcs, lineName=lineName, lineNumber=lineNumber)
| (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, value_size_constraint, single_value_constraint, value_range_constraint, constraints_union) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsIntersection', 'ValueSizeConstraint', 'SingleValueConstraint', 'ValueRangeConstraint', 'ConstraintsUnion')
(cisco_wan,) = mibBuilder.importSymbols('CISCOWAN-SMI', 'ciscoWan')
(snmp_admin_string,) = mibBuilder.importSymbols('SNMP-FRAMEWORK-MIB', 'SnmpAdminString')
(module_compliance, notification_group, object_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'NotificationGroup', 'ObjectGroup')
(ip_address, counter32, time_ticks, gauge32, unsigned32, mib_identifier, bits, iso, object_identity, counter64, module_identity, notification_type, mib_scalar, mib_table, mib_table_row, mib_table_column, integer32) = mibBuilder.importSymbols('SNMPv2-SMI', 'IpAddress', 'Counter32', 'TimeTicks', 'Gauge32', 'Unsigned32', 'MibIdentifier', 'Bits', 'iso', 'ObjectIdentity', 'Counter64', 'ModuleIdentity', 'NotificationType', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'Integer32')
(truth_value, row_status, display_string, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'TruthValue', 'RowStatus', 'DisplayString', 'TextualConvention')
cisco_wan_mg_mib = module_identity((1, 3, 6, 1, 4, 1, 351, 150, 10))
ciscoWanMgMIB.setRevisions(('2005-05-27 00:00', '2004-01-20 00:00', '2002-06-14 00:00', '2001-05-25 00:00', '2000-07-19 15:00', '2000-03-27 00:00', '1999-11-27 00:00'))
if mibBuilder.loadTexts:
ciscoWanMgMIB.setLastUpdated('200505270000Z')
if mibBuilder.loadTexts:
ciscoWanMgMIB.setOrganization('Cisco Systems, Inc.')
cisco_wan_mg_mib_objects = mib_identifier((1, 3, 6, 1, 4, 1, 351, 150, 10, 1))
media_gateway = mib_identifier((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 1))
media_gateway_controller = mib_identifier((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 2))
media_gateway_endpoint = mib_identifier((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 3))
media_gateway_line = mib_identifier((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 4))
media_gateway_controller_resolution = mib_identifier((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 5))
media_gateway_domain_name = mib_identifier((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 6))
mg_name = mib_scalar((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 1, 1), snmp_admin_string().subtype(subtypeSpec=value_size_constraint(1, 64))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
mgName.setStatus('current')
mg_administrative_state = mib_scalar((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 1, 2), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('inService', 1), ('commandedOutOfService', 2), ('pendingOutOfService', 3))).clone('commandedOutOfService')).setMaxAccess('readonly')
if mibBuilder.loadTexts:
mgAdministrativeState.setStatus('current')
mg_administrative_state_control = mib_scalar((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 1, 3), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('inService', 1), ('forcefulOutOfService', 2), ('gracefulOutOfService', 3))).clone('forcefulOutOfService')).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
mgAdministrativeStateControl.setStatus('current')
mg_shutdown_grace_time = mib_scalar((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 1, 4), integer32().subtype(subtypeSpec=value_range_constraint(-1, 65535))).setUnits('seconds').setMaxAccess('readwrite')
if mibBuilder.loadTexts:
mgShutdownGraceTime.setStatus('current')
mg_supported_protocol_table = mib_table((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 1, 7))
if mibBuilder.loadTexts:
mgSupportedProtocolTable.setStatus('current')
mg_supported_protocol_entry = mib_table_row((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 1, 7, 1)).setIndexNames((0, 'CISCO-WAN-MG-MIB', 'mgProtocolNumber'))
if mibBuilder.loadTexts:
mgSupportedProtocolEntry.setStatus('current')
mg_protocol_number = mib_table_column((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 1, 7, 1, 1), integer32().subtype(subtypeSpec=value_range_constraint(1, 65535)))
if mibBuilder.loadTexts:
mgProtocolNumber.setStatus('current')
mg_protocol_name = mib_table_column((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 1, 7, 1, 2), snmp_admin_string().subtype(subtypeSpec=value_size_constraint(1, 64))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
mgProtocolName.setStatus('current')
max_concurrent_mgcs = mib_scalar((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 2, 3), unsigned32().subtype(subtypeSpec=value_range_constraint(0, 65535))).setUnits('controllers').setMaxAccess('readonly')
if mibBuilder.loadTexts:
maxConcurrentMgcs.setStatus('current')
mgc_table = mib_table((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 2, 1))
if mibBuilder.loadTexts:
mgcTable.setStatus('current')
mgc_entry = mib_table_row((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 2, 1, 1)).setIndexNames((0, 'CISCO-WAN-MG-MIB', 'mgcNumber'))
if mibBuilder.loadTexts:
mgcEntry.setStatus('current')
mgc_number = mib_table_column((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 2, 1, 1, 1), integer32().subtype(subtypeSpec=value_range_constraint(1, 65535)))
if mibBuilder.loadTexts:
mgcNumber.setStatus('current')
mgc_name = mib_table_column((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 2, 1, 1, 2), snmp_admin_string().subtype(subtypeSpec=value_size_constraint(1, 64))).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
mgcName.setStatus('current')
mgc_dns_resolution = mib_table_column((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 2, 1, 1, 3), truth_value().clone('false')).setMaxAccess('readonly')
if mibBuilder.loadTexts:
mgcDnsResolution.setStatus('deprecated')
mgc_association_state = mib_table_column((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 2, 1, 1, 4), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('mgcUnassociated', 1), ('mgcAssociated', 2), ('mgcAssociatedCommLoss', 3)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
mgcAssociationState.setStatus('deprecated')
mgc_association_state_control = mib_table_column((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 2, 1, 1, 5), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('mgcUnassociate', 1), ('mgcAssociate', 2), ('mgcClear', 3))).clone('mgcUnassociate')).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
mgcAssociationStateControl.setStatus('deprecated')
mgc_unassociation_policy = mib_table_column((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 2, 1, 1, 6), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('mgcNoAction', 1), ('mgcRelease', 2))).clone('mgcNoAction')).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
mgcUnassociationPolicy.setStatus('deprecated')
mgc_comm_loss_unassociation_timeout = mib_table_column((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 2, 1, 1, 7), integer32().subtype(subtypeSpec=value_range_constraint(-1, 65535)).clone(-1)).setUnits('seconds').setMaxAccess('readcreate')
if mibBuilder.loadTexts:
mgcCommLossUnassociationTimeout.setStatus('deprecated')
mgc_row_status = mib_table_column((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 2, 1, 1, 8), row_status()).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
mgcRowStatus.setStatus('current')
mgc_protocol_table = mib_table((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 2, 2))
if mibBuilder.loadTexts:
mgcProtocolTable.setStatus('deprecated')
mgc_protocol_entry = mib_table_row((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 2, 2, 1)).setIndexNames((0, 'CISCO-WAN-MG-MIB', 'mgcNumber'), (0, 'CISCO-WAN-MG-MIB', 'mgProtocolNumber'))
if mibBuilder.loadTexts:
mgcProtocolEntry.setStatus('deprecated')
mgc_protocol_row_status = mib_table_column((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 2, 2, 1, 1), row_status()).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
mgcProtocolRowStatus.setStatus('deprecated')
mg_endpoint_creation_policy = mib_scalar((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 3, 2), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('dynamic', 1), ('strictDynamic', 2), ('static', 3))).clone('static')).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
mgEndpointCreationPolicy.setStatus('current')
mg_endpoint_table = mib_table((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 3, 1))
if mibBuilder.loadTexts:
mgEndpointTable.setStatus('current')
mg_endpoint_entry = mib_table_row((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 3, 1, 1)).setIndexNames((0, 'CISCO-WAN-MG-MIB', 'mgEndpointNumber'))
if mibBuilder.loadTexts:
mgEndpointEntry.setStatus('current')
mg_endpoint_number = mib_table_column((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 3, 1, 1, 1), integer32().subtype(subtypeSpec=value_range_constraint(1, 65535)))
if mibBuilder.loadTexts:
mgEndpointNumber.setStatus('current')
mg_endpoint_line_number = mib_table_column((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 3, 1, 1, 2), integer32().subtype(subtypeSpec=value_range_constraint(1, 65535))).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
mgEndpointLineNumber.setStatus('current')
mg_endpoint_name = mib_table_column((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 3, 1, 1, 3), snmp_admin_string()).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
mgEndpointName.setStatus('current')
mg_endpoint_speed = mib_table_column((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 3, 1, 1, 4), unsigned32().subtype(subtypeSpec=value_range_constraint(0, 65535))).setUnits('Kbps').setMaxAccess('readonly')
if mibBuilder.loadTexts:
mgEndpointSpeed.setStatus('current')
mg_endpoint_state = mib_table_column((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 3, 1, 1, 5), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('mgEndpointActive', 1), ('mgEndpointFailed', 2), ('mgEndpointDegraded', 3)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
mgEndpointState.setStatus('current')
mg_endpoint_channel_map = mib_table_column((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 3, 1, 1, 6), integer32().subtype(subtypeSpec=value_range_constraint(0, 2147483647))).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
mgEndpointChannelMap.setStatus('current')
mg_endpoint_row_status = mib_table_column((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 3, 1, 1, 7), row_status()).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
mgEndpointRowStatus.setStatus('current')
line_assignment_table = mib_table((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 4, 1))
if mibBuilder.loadTexts:
lineAssignmentTable.setStatus('current')
line_assignment_entry = mib_table_row((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 4, 1, 1)).setIndexNames((0, 'CISCO-WAN-MG-MIB', 'lineNumber'))
if mibBuilder.loadTexts:
lineAssignmentEntry.setStatus('current')
line_number = mib_table_column((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 4, 1, 1, 1), integer32().subtype(subtypeSpec=value_range_constraint(1, 65535)))
if mibBuilder.loadTexts:
lineNumber.setStatus('current')
channel_assignment = mib_table_column((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 4, 1, 1, 2), integer32().subtype(subtypeSpec=value_range_constraint(0, 2147483647))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
channelAssignment.setStatus('current')
line_name = mib_table_column((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 4, 1, 1, 3), snmp_admin_string().subtype(subtypeSpec=value_size_constraint(1, 64))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
lineName.setStatus('current')
mgc_resolution_table = mib_table((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 5, 1))
if mibBuilder.loadTexts:
mgcResolutionTable.setStatus('current')
mgc_resolution_entry = mib_table_row((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 5, 1, 1)).setIndexNames((0, 'CISCO-WAN-MG-MIB', 'mgcResolutionIndex'))
if mibBuilder.loadTexts:
mgcResolutionEntry.setStatus('current')
mgc_resolution_index = mib_table_column((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 5, 1, 1, 1), integer32().subtype(subtypeSpec=value_range_constraint(1, 65535)))
if mibBuilder.loadTexts:
mgcResolutionIndex.setStatus('current')
mgc_resolution_name = mib_table_column((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 5, 1, 1, 2), snmp_admin_string().subtype(subtypeSpec=value_size_constraint(1, 64))).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
mgcResolutionName.setStatus('current')
mgc_resolution_ip_address = mib_table_column((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 5, 1, 1, 3), ip_address()).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
mgcResolutionIpAddress.setStatus('current')
mgc_resolution_comm_state = mib_table_column((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 5, 1, 1, 4), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('csActive', 1), ('csInactive', 2))).clone('csInactive')).setMaxAccess('readonly')
if mibBuilder.loadTexts:
mgcResolutionCommState.setStatus('current')
mgc_resolution_preference = mib_table_column((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 5, 1, 1, 5), integer32().subtype(subtypeSpec=value_range_constraint(1, 65535))).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
mgcResolutionPreference.setStatus('current')
mgc_resolution_row_status = mib_table_column((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 5, 1, 1, 6), row_status()).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
mgcResolutionRowStatus.setStatus('current')
mgc_dns_resolution_flag = mib_table_column((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 5, 1, 1, 7), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('internal', 1), ('external', 2)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
mgcDnsResolutionFlag.setStatus('current')
mg_domain_name_table = mib_table((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 6, 1))
if mibBuilder.loadTexts:
mgDomainNameTable.setStatus('current')
mg_domain_name_entry = mib_table_row((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 6, 1, 1)).setIndexNames((0, 'CISCO-WAN-MG-MIB', 'mgDomainNameIndex'))
if mibBuilder.loadTexts:
mgDomainNameEntry.setStatus('current')
mg_domain_name_index = mib_table_column((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 6, 1, 1, 1), integer32().subtype(subtypeSpec=value_range_constraint(1, 65535)))
if mibBuilder.loadTexts:
mgDomainNameIndex.setStatus('current')
mg_domain_name = mib_table_column((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 6, 1, 1, 2), snmp_admin_string().subtype(subtypeSpec=value_size_constraint(1, 64))).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
mgDomainName.setStatus('current')
mg_dns_resolution_type = mib_table_column((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 6, 1, 1, 3), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4))).clone(namedValues=named_values(('internalOnly', 1), ('externalOnly', 2), ('internalFirst', 3), ('externalFirst', 4))).clone('internalOnly')).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
mgDnsResolutionType.setStatus('current')
mg_domain_name_row_status = mib_table_column((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 6, 1, 1, 4), row_status()).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
mgDomainNameRowStatus.setStatus('current')
mg_endpoint_ext_table = mib_table((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 3, 3))
if mibBuilder.loadTexts:
mgEndpointExtTable.setStatus('current')
mg_endpoint_ext_entry = mib_table_row((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 3, 3, 1))
mgEndpointEntry.registerAugmentions(('CISCO-WAN-MG-MIB', 'mgEndpointExtEntry'))
mgEndpointExtEntry.setIndexNames(*mgEndpointEntry.getIndexNames())
if mibBuilder.loadTexts:
mgEndpointExtEntry.setStatus('current')
mg_endpoint_repetition = mib_table_column((1, 3, 6, 1, 4, 1, 351, 150, 10, 1, 3, 3, 1, 1), unsigned32().clone(1)).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
mgEndpointRepetition.setStatus('current')
mg_mib_conformance = mib_identifier((1, 3, 6, 1, 4, 1, 351, 150, 10, 3))
mg_mib_compliances = mib_identifier((1, 3, 6, 1, 4, 1, 351, 150, 10, 3, 1))
mg_mib_groups = mib_identifier((1, 3, 6, 1, 4, 1, 351, 150, 10, 3, 2))
mg_mib_compliance = module_compliance((1, 3, 6, 1, 4, 1, 351, 150, 10, 3, 1, 1)).setObjects(('CISCO-WAN-MG-MIB', 'mediaGatewayGroup'), ('CISCO-WAN-MG-MIB', 'mediaGatewayControllerGroup'), ('CISCO-WAN-MG-MIB', 'mediaGatewayEndpointGroup'), ('CISCO-WAN-MG-MIB', 'mediaGatewayLineGroup'), ('CISCO-WAN-MG-MIB', 'mediaGatewayControllerResolutionGroup'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
mg_mib_compliance = mgMIBCompliance.setStatus('deprecated')
mg_mib_compliance1 = module_compliance((1, 3, 6, 1, 4, 1, 351, 150, 10, 3, 1, 2)).setObjects(('CISCO-WAN-MG-MIB', 'mediaGatewayGroup'), ('CISCO-WAN-MG-MIB', 'mediaGatewayControllerGroup1'), ('CISCO-WAN-MG-MIB', 'mediaGatewayEndpointGroup'), ('CISCO-WAN-MG-MIB', 'mediaGatewayLineGroup'), ('CISCO-WAN-MG-MIB', 'mediaGatewayDomainNameGroup'), ('CISCO-WAN-MG-MIB', 'mediaGatewayControllerResolutionGroup1'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
mg_mib_compliance1 = mgMIBCompliance1.setStatus('deprecated')
mg_mib_compliance2 = module_compliance((1, 3, 6, 1, 4, 1, 351, 150, 10, 3, 1, 3)).setObjects(('CISCO-WAN-MG-MIB', 'mediaGatewayGroup'), ('CISCO-WAN-MG-MIB', 'mediaGatewayControllerGroup2'), ('CISCO-WAN-MG-MIB', 'mediaGatewayEndpointGroup'), ('CISCO-WAN-MG-MIB', 'mediaGatewayLineGroup'), ('CISCO-WAN-MG-MIB', 'mediaGatewayDomainNameGroup'), ('CISCO-WAN-MG-MIB', 'mediaGatewayControllerResolutionGroup1'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
mg_mib_compliance2 = mgMIBCompliance2.setStatus('deprecated')
mg_mib_compliance3 = module_compliance((1, 3, 6, 1, 4, 1, 351, 150, 10, 3, 1, 4)).setObjects(('CISCO-WAN-MG-MIB', 'mediaGatewayGroup'), ('CISCO-WAN-MG-MIB', 'mediaGatewayControllerGroup2'), ('CISCO-WAN-MG-MIB', 'mediaGatewayEndpointGroup'), ('CISCO-WAN-MG-MIB', 'mediaGatewayLineGroup'), ('CISCO-WAN-MG-MIB', 'mediaGatewayDomainNameGroup'), ('CISCO-WAN-MG-MIB', 'mediaGatewayControllerResolutionGroup1'), ('CISCO-WAN-MG-MIB', 'mediaGatewayEndptRepetitionGroup'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
mg_mib_compliance3 = mgMIBCompliance3.setStatus('current')
media_gateway_group = object_group((1, 3, 6, 1, 4, 1, 351, 150, 10, 3, 2, 1)).setObjects(('CISCO-WAN-MG-MIB', 'mgName'), ('CISCO-WAN-MG-MIB', 'mgAdministrativeState'), ('CISCO-WAN-MG-MIB', 'mgAdministrativeStateControl'), ('CISCO-WAN-MG-MIB', 'mgShutdownGraceTime'), ('CISCO-WAN-MG-MIB', 'mgProtocolName'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
media_gateway_group = mediaGatewayGroup.setStatus('current')
media_gateway_controller_group = object_group((1, 3, 6, 1, 4, 1, 351, 150, 10, 3, 2, 2)).setObjects(('CISCO-WAN-MG-MIB', 'maxConcurrentMgcs'), ('CISCO-WAN-MG-MIB', 'mgcName'), ('CISCO-WAN-MG-MIB', 'mgcDnsResolution'), ('CISCO-WAN-MG-MIB', 'mgcAssociationState'), ('CISCO-WAN-MG-MIB', 'mgcAssociationStateControl'), ('CISCO-WAN-MG-MIB', 'mgcUnassociationPolicy'), ('CISCO-WAN-MG-MIB', 'mgcCommLossUnassociationTimeout'), ('CISCO-WAN-MG-MIB', 'mgcRowStatus'), ('CISCO-WAN-MG-MIB', 'mgcProtocolRowStatus'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
media_gateway_controller_group = mediaGatewayControllerGroup.setStatus('deprecated')
media_gateway_endpoint_group = object_group((1, 3, 6, 1, 4, 1, 351, 150, 10, 3, 2, 3)).setObjects(('CISCO-WAN-MG-MIB', 'mgEndpointCreationPolicy'), ('CISCO-WAN-MG-MIB', 'mgEndpointName'), ('CISCO-WAN-MG-MIB', 'mgEndpointLineNumber'), ('CISCO-WAN-MG-MIB', 'mgEndpointSpeed'), ('CISCO-WAN-MG-MIB', 'mgEndpointState'), ('CISCO-WAN-MG-MIB', 'mgEndpointChannelMap'), ('CISCO-WAN-MG-MIB', 'mgEndpointRowStatus'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
media_gateway_endpoint_group = mediaGatewayEndpointGroup.setStatus('current')
media_gateway_line_group = object_group((1, 3, 6, 1, 4, 1, 351, 150, 10, 3, 2, 4)).setObjects(('CISCO-WAN-MG-MIB', 'channelAssignment'), ('CISCO-WAN-MG-MIB', 'lineName'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
media_gateway_line_group = mediaGatewayLineGroup.setStatus('current')
media_gateway_controller_resolution_group = object_group((1, 3, 6, 1, 4, 1, 351, 150, 10, 3, 2, 5)).setObjects(('CISCO-WAN-MG-MIB', 'mgcResolutionName'), ('CISCO-WAN-MG-MIB', 'mgcResolutionIpAddress'), ('CISCO-WAN-MG-MIB', 'mgcResolutionCommState'), ('CISCO-WAN-MG-MIB', 'mgcResolutionPreference'), ('CISCO-WAN-MG-MIB', 'mgcResolutionRowStatus'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
media_gateway_controller_resolution_group = mediaGatewayControllerResolutionGroup.setStatus('deprecated')
media_gateway_controller_group1 = object_group((1, 3, 6, 1, 4, 1, 351, 150, 10, 3, 2, 6)).setObjects(('CISCO-WAN-MG-MIB', 'maxConcurrentMgcs'), ('CISCO-WAN-MG-MIB', 'mgcName'), ('CISCO-WAN-MG-MIB', 'mgcAssociationState'), ('CISCO-WAN-MG-MIB', 'mgcAssociationStateControl'), ('CISCO-WAN-MG-MIB', 'mgcUnassociationPolicy'), ('CISCO-WAN-MG-MIB', 'mgcCommLossUnassociationTimeout'), ('CISCO-WAN-MG-MIB', 'mgcRowStatus'), ('CISCO-WAN-MG-MIB', 'mgcProtocolRowStatus'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
media_gateway_controller_group1 = mediaGatewayControllerGroup1.setStatus('deprecated')
media_gateway_controller_resolution_group1 = object_group((1, 3, 6, 1, 4, 1, 351, 150, 10, 3, 2, 7)).setObjects(('CISCO-WAN-MG-MIB', 'mgcResolutionName'), ('CISCO-WAN-MG-MIB', 'mgcResolutionIpAddress'), ('CISCO-WAN-MG-MIB', 'mgcResolutionCommState'), ('CISCO-WAN-MG-MIB', 'mgcResolutionPreference'), ('CISCO-WAN-MG-MIB', 'mgcResolutionRowStatus'), ('CISCO-WAN-MG-MIB', 'mgcDnsResolutionFlag'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
media_gateway_controller_resolution_group1 = mediaGatewayControllerResolutionGroup1.setStatus('current')
media_gateway_domain_name_group = object_group((1, 3, 6, 1, 4, 1, 351, 150, 10, 3, 2, 8)).setObjects(('CISCO-WAN-MG-MIB', 'mgDomainName'), ('CISCO-WAN-MG-MIB', 'mgDnsResolutionType'), ('CISCO-WAN-MG-MIB', 'mgDomainNameRowStatus'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
media_gateway_domain_name_group = mediaGatewayDomainNameGroup.setStatus('current')
media_gateway_controller_group2 = object_group((1, 3, 6, 1, 4, 1, 351, 150, 10, 3, 2, 9)).setObjects(('CISCO-WAN-MG-MIB', 'maxConcurrentMgcs'), ('CISCO-WAN-MG-MIB', 'mgcName'), ('CISCO-WAN-MG-MIB', 'mgcRowStatus'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
media_gateway_controller_group2 = mediaGatewayControllerGroup2.setStatus('current')
media_gateway_endpt_repetition_group = object_group((1, 3, 6, 1, 4, 1, 351, 150, 10, 3, 2, 10)).setObjects(('CISCO-WAN-MG-MIB', 'mgEndpointRepetition'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
media_gateway_endpt_repetition_group = mediaGatewayEndptRepetitionGroup.setStatus('current')
mibBuilder.exportSymbols('CISCO-WAN-MG-MIB', mgEndpointCreationPolicy=mgEndpointCreationPolicy, mgProtocolNumber=mgProtocolNumber, mgcNumber=mgcNumber, mediaGatewayGroup=mediaGatewayGroup, mgcResolutionIpAddress=mgcResolutionIpAddress, mgEndpointSpeed=mgEndpointSpeed, mgcDnsResolution=mgcDnsResolution, mgAdministrativeStateControl=mgAdministrativeStateControl, mgMIBConformance=mgMIBConformance, mgName=mgName, mgDomainNameTable=mgDomainNameTable, mgMIBCompliance3=mgMIBCompliance3, mgMIBCompliance=mgMIBCompliance, lineAssignmentEntry=lineAssignmentEntry, mgcTable=mgcTable, mediaGatewayControllerResolutionGroup=mediaGatewayControllerResolutionGroup, mgEndpointExtTable=mgEndpointExtTable, mgEndpointExtEntry=mgEndpointExtEntry, mgcProtocolRowStatus=mgcProtocolRowStatus, mgcAssociationState=mgcAssociationState, mgcDnsResolutionFlag=mgcDnsResolutionFlag, mediaGateway=mediaGateway, mediaGatewayEndpoint=mediaGatewayEndpoint, mgSupportedProtocolTable=mgSupportedProtocolTable, mgDomainName=mgDomainName, ciscoWanMgMIBObjects=ciscoWanMgMIBObjects, mgEndpointLineNumber=mgEndpointLineNumber, mgMIBCompliance2=mgMIBCompliance2, channelAssignment=channelAssignment, mgMIBCompliance1=mgMIBCompliance1, mediaGatewayDomainNameGroup=mediaGatewayDomainNameGroup, mgcResolutionPreference=mgcResolutionPreference, mgcProtocolEntry=mgcProtocolEntry, mediaGatewayLine=mediaGatewayLine, mgcResolutionName=mgcResolutionName, mediaGatewayLineGroup=mediaGatewayLineGroup, mediaGatewayControllerGroup=mediaGatewayControllerGroup, mgEndpointRowStatus=mgEndpointRowStatus, mgDomainNameEntry=mgDomainNameEntry, mediaGatewayDomainName=mediaGatewayDomainName, mgEndpointRepetition=mgEndpointRepetition, mgDomainNameIndex=mgDomainNameIndex, mgShutdownGraceTime=mgShutdownGraceTime, mgcEntry=mgcEntry, mgcAssociationStateControl=mgcAssociationStateControl, mgAdministrativeState=mgAdministrativeState, mgcRowStatus=mgcRowStatus, mgEndpointChannelMap=mgEndpointChannelMap, mgDomainNameRowStatus=mgDomainNameRowStatus, mgcUnassociationPolicy=mgcUnassociationPolicy, mediaGatewayControllerGroup1=mediaGatewayControllerGroup1, ciscoWanMgMIB=ciscoWanMgMIB, mediaGatewayEndpointGroup=mediaGatewayEndpointGroup, mediaGatewayController=mediaGatewayController, mediaGatewayControllerResolution=mediaGatewayControllerResolution, mgcResolutionCommState=mgcResolutionCommState, mgcResolutionRowStatus=mgcResolutionRowStatus, mediaGatewayControllerGroup2=mediaGatewayControllerGroup2, mgProtocolName=mgProtocolName, mgSupportedProtocolEntry=mgSupportedProtocolEntry, mgEndpointEntry=mgEndpointEntry, mgDnsResolutionType=mgDnsResolutionType, mgEndpointName=mgEndpointName, mgcResolutionTable=mgcResolutionTable, mgEndpointState=mgEndpointState, mediaGatewayControllerResolutionGroup1=mediaGatewayControllerResolutionGroup1, mgcProtocolTable=mgcProtocolTable, lineAssignmentTable=lineAssignmentTable, PYSNMP_MODULE_ID=ciscoWanMgMIB, mgcResolutionIndex=mgcResolutionIndex, mgcCommLossUnassociationTimeout=mgcCommLossUnassociationTimeout, mgcResolutionEntry=mgcResolutionEntry, mgMIBGroups=mgMIBGroups, mgEndpointNumber=mgEndpointNumber, mgcName=mgcName, mgMIBCompliances=mgMIBCompliances, mediaGatewayEndptRepetitionGroup=mediaGatewayEndptRepetitionGroup, mgEndpointTable=mgEndpointTable, maxConcurrentMgcs=maxConcurrentMgcs, lineName=lineName, lineNumber=lineNumber) |
#!/usr/local/bin/python3.3
def echo(message):
print(message)
return
echo('Direct Call')
x = echo
x('Indirect Call')
def indirect(func, arg):
func(arg)
indirect(echo, "Argument Call")
schedule = [(echo, 'Spam'), (echo, 'Ham')]
for (func, arg) in schedule:
func(arg)
def make(label):
def echo(message):
print(label + ': ' + message)
return echo
F = make('Spam')
F('Eggs')
F('Ham')
def func(a):
b = 'spam'
return b * a
print(func(8))
print(dir(func))
func.handles = 'Bottom-Press'
func.count = 0
print(dir(func))
def func(a: 'spam', b: (1, 10), c: float) -> int:
return a+b+c
print(func.__annotations__)
| def echo(message):
print(message)
return
echo('Direct Call')
x = echo
x('Indirect Call')
def indirect(func, arg):
func(arg)
indirect(echo, 'Argument Call')
schedule = [(echo, 'Spam'), (echo, 'Ham')]
for (func, arg) in schedule:
func(arg)
def make(label):
def echo(message):
print(label + ': ' + message)
return echo
f = make('Spam')
f('Eggs')
f('Ham')
def func(a):
b = 'spam'
return b * a
print(func(8))
print(dir(func))
func.handles = 'Bottom-Press'
func.count = 0
print(dir(func))
def func(a: 'spam', b: (1, 10), c: float) -> int:
return a + b + c
print(func.__annotations__) |
class SqlQueries:
address_table_insert = ("""
SELECT DISTINCT address1 AS address1
, address2 AS address2
, address3 AS address3
, city AS city
, zip_code AS zip_code
, country AS country
, state AS state
FROM staging_restaurants
WHERE address1 IS NOT NULL
""")
restaurant_table_insert = ("""
SELECT DISTINCT id AS restaurant_id
, name AS name
, image_url AS image_url
, yelp_url AS yelp_url
, review_count AS review_count
, latitude AS latitude
, longitude AS longitude
, price AS price
, ( SELECT at.address_id
FROM address_table AS at
WHERE sr.address1=at.address1
AND sr.zip_code=at.zip_code
ORDER BY at.address_id
LIMIT 1) AS address_id
, phone AS phone
, ( SELECT qt.quadrant_id
FROM quadrant_table AS qt
WHERE sr.latitude BETWEEN qt.lat_from AND qt.lat_to
AND sr.longitude BETWEEN qt.lon_from AND qt.lon_to
LIMIT 1) AS quadrant_id
FROM staging_restaurants AS sr
WHERE sr.id IS NOT NULL
AND sr.address1 IS NOT NULL
""")
pickup_table_insert = ("""
SELECT DISTINCT datetime AS datetime
, latitude AS latitude
, longitude AS longitude
, ( SELECT qt.quadrant_id
FROM quadrant_table AS qt
WHERE st.latitude BETWEEN qt.lat_from AND qt.lat_to
AND st.longitude BETWEEN qt.lon_from AND qt.lon_to
LIMIT 1) AS quadrant_id
, base AS base
FROM staging_trips AS st
WHERE datetime IS NOT NULL
""")
time_table_insert = ("""
SELECT DISTINCT datetime AS datetime
, extract(hour from datetime) AS hour
, extract(day from datetime) AS day
, extract(week from datetime) AS week
, extract(month from datetime) AS month
, extract(year from datetime) AS year
, extract(dayofweek from datetime) AS weekday
FROM staging_trips
""")
| class Sqlqueries:
address_table_insert = '\n SELECT DISTINCT address1 AS address1\n , address2 AS address2\n , address3 AS address3\n , city AS city\n , zip_code AS zip_code\n , country AS country\n , state AS state\n FROM staging_restaurants\n WHERE address1 IS NOT NULL\n '
restaurant_table_insert = '\n SELECT DISTINCT id AS restaurant_id\n , name AS name\n , image_url AS image_url\n , yelp_url AS yelp_url\n , review_count AS review_count\n , latitude AS latitude\n , longitude AS longitude\n , price AS price\n , ( SELECT at.address_id\n FROM address_table AS at\n WHERE sr.address1=at.address1\n AND sr.zip_code=at.zip_code\n ORDER BY at.address_id\n LIMIT 1) AS address_id\n , phone AS phone\n , ( SELECT qt.quadrant_id\n FROM quadrant_table AS qt\n WHERE sr.latitude BETWEEN qt.lat_from AND qt.lat_to\n AND sr.longitude BETWEEN qt.lon_from AND qt.lon_to\n LIMIT 1) AS quadrant_id\n FROM staging_restaurants AS sr\n WHERE sr.id IS NOT NULL\n AND sr.address1 IS NOT NULL\n\n '
pickup_table_insert = '\n SELECT DISTINCT datetime AS datetime\n , latitude AS latitude\n , longitude AS longitude\n , ( SELECT qt.quadrant_id\n FROM quadrant_table AS qt\n WHERE st.latitude BETWEEN qt.lat_from AND qt.lat_to\n AND st.longitude BETWEEN qt.lon_from AND qt.lon_to\n LIMIT 1) AS quadrant_id\n , base AS base\n FROM staging_trips AS st\n WHERE datetime IS NOT NULL\n '
time_table_insert = '\n SELECT DISTINCT datetime AS datetime\n , extract(hour from datetime) AS hour\n , extract(day from datetime) AS day\n , extract(week from datetime) AS week\n , extract(month from datetime) AS month\n , extract(year from datetime) AS year\n , extract(dayofweek from datetime) AS weekday\n FROM staging_trips\n ' |
"""
Unittests
=========
Tests are built for usage with **py.test**.
In data fixtures, not all settings and Sass sources will compile with
libsass. Some of them contains some errors for test needs.
* ``boussole.txt``: Is not an usable settings file, just a dummy file for base
backend tests;
* ``boussole.json``: Is not an usable settings file, its values are dummy
pointing to path and files that does not exists;
* ``boussole_polluted.json``: Is almost equivalent of ``boussole_custom.json``
but polluted with invalid setting names;
* ``boussole_custom.json``: Contain only valid settings, will compile;
For Sass sources, they should all contains a comment when it contains errors.
"""
| """
Unittests
=========
Tests are built for usage with **py.test**.
In data fixtures, not all settings and Sass sources will compile with
libsass. Some of them contains some errors for test needs.
* ``boussole.txt``: Is not an usable settings file, just a dummy file for base
backend tests;
* ``boussole.json``: Is not an usable settings file, its values are dummy
pointing to path and files that does not exists;
* ``boussole_polluted.json``: Is almost equivalent of ``boussole_custom.json``
but polluted with invalid setting names;
* ``boussole_custom.json``: Contain only valid settings, will compile;
For Sass sources, they should all contains a comment when it contains errors.
""" |
class SketchGalleryOptions(Enum, IComparable, IFormattable, IConvertible):
"""
Enumerates all the sketch options.
enum SketchGalleryOptions,values: SGO_Arc3Point (6),SGO_ArcCenterEnds (7),SGO_ArcFillet (9),SGO_ArcTanEnd (8),SGO_Circle (5),SGO_CircumscribedPolygon (4),SGO_Default (0),SGO_FullEllipse (12),SGO_InscribedPolygon (3),SGO_LandingSquare (25),SGO_LandingWithTwoRuns (30),SGO_Line (1),SGO_PartialEllipse (13),SGO_PickFaces (15),SGO_PickLines (14),SGO_PickPoints (20),SGO_PickRoofs (18),SGO_PickSupports (17),SGO_PickWalls (16),SGO_Point (19),SGO_PointElement (21),SGO_Rect (2),SGO_RunArcCenterEnds (24),SGO_RunArcFullStep (23),SGO_RunLine (22),SGO_SketchLanding (32),SGO_SketchRun (31),SGO_Spline (10),SGO_SplineByPoints (11),SGO_SupportPickLine (28),SGO_WinderLShape (26),SGO_WinderPattern (27),SGO_WinderUShape (29)
"""
def __eq__(self, *args):
""" x.__eq__(y) <==> x==yx.__eq__(y) <==> x==yx.__eq__(y) <==> x==y """
pass
def __format__(self, *args):
""" __format__(formattable: IFormattable,format: str) -> str """
pass
def __ge__(self, *args):
pass
def __gt__(self, *args):
pass
def __init__(self, *args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
def __le__(self, *args):
pass
def __lt__(self, *args):
pass
def __ne__(self, *args):
pass
def __reduce_ex__(self, *args):
pass
def __str__(self, *args):
pass
SGO_Arc3Point = None
SGO_ArcCenterEnds = None
SGO_ArcFillet = None
SGO_ArcTanEnd = None
SGO_Circle = None
SGO_CircumscribedPolygon = None
SGO_Default = None
SGO_FullEllipse = None
SGO_InscribedPolygon = None
SGO_LandingSquare = None
SGO_LandingWithTwoRuns = None
SGO_Line = None
SGO_PartialEllipse = None
SGO_PickFaces = None
SGO_PickLines = None
SGO_PickPoints = None
SGO_PickRoofs = None
SGO_PickSupports = None
SGO_PickWalls = None
SGO_Point = None
SGO_PointElement = None
SGO_Rect = None
SGO_RunArcCenterEnds = None
SGO_RunArcFullStep = None
SGO_RunLine = None
SGO_SketchLanding = None
SGO_SketchRun = None
SGO_Spline = None
SGO_SplineByPoints = None
SGO_SupportPickLine = None
SGO_WinderLShape = None
SGO_WinderPattern = None
SGO_WinderUShape = None
value__ = None
| class Sketchgalleryoptions(Enum, IComparable, IFormattable, IConvertible):
"""
Enumerates all the sketch options.
enum SketchGalleryOptions,values: SGO_Arc3Point (6),SGO_ArcCenterEnds (7),SGO_ArcFillet (9),SGO_ArcTanEnd (8),SGO_Circle (5),SGO_CircumscribedPolygon (4),SGO_Default (0),SGO_FullEllipse (12),SGO_InscribedPolygon (3),SGO_LandingSquare (25),SGO_LandingWithTwoRuns (30),SGO_Line (1),SGO_PartialEllipse (13),SGO_PickFaces (15),SGO_PickLines (14),SGO_PickPoints (20),SGO_PickRoofs (18),SGO_PickSupports (17),SGO_PickWalls (16),SGO_Point (19),SGO_PointElement (21),SGO_Rect (2),SGO_RunArcCenterEnds (24),SGO_RunArcFullStep (23),SGO_RunLine (22),SGO_SketchLanding (32),SGO_SketchRun (31),SGO_Spline (10),SGO_SplineByPoints (11),SGO_SupportPickLine (28),SGO_WinderLShape (26),SGO_WinderPattern (27),SGO_WinderUShape (29)
"""
def __eq__(self, *args):
""" x.__eq__(y) <==> x==yx.__eq__(y) <==> x==yx.__eq__(y) <==> x==y """
pass
def __format__(self, *args):
""" __format__(formattable: IFormattable,format: str) -> str """
pass
def __ge__(self, *args):
pass
def __gt__(self, *args):
pass
def __init__(self, *args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
def __le__(self, *args):
pass
def __lt__(self, *args):
pass
def __ne__(self, *args):
pass
def __reduce_ex__(self, *args):
pass
def __str__(self, *args):
pass
sgo__arc3_point = None
sgo__arc_center_ends = None
sgo__arc_fillet = None
sgo__arc_tan_end = None
sgo__circle = None
sgo__circumscribed_polygon = None
sgo__default = None
sgo__full_ellipse = None
sgo__inscribed_polygon = None
sgo__landing_square = None
sgo__landing_with_two_runs = None
sgo__line = None
sgo__partial_ellipse = None
sgo__pick_faces = None
sgo__pick_lines = None
sgo__pick_points = None
sgo__pick_roofs = None
sgo__pick_supports = None
sgo__pick_walls = None
sgo__point = None
sgo__point_element = None
sgo__rect = None
sgo__run_arc_center_ends = None
sgo__run_arc_full_step = None
sgo__run_line = None
sgo__sketch_landing = None
sgo__sketch_run = None
sgo__spline = None
sgo__spline_by_points = None
sgo__support_pick_line = None
sgo__winder_l_shape = None
sgo__winder_pattern = None
sgo__winder_u_shape = None
value__ = None |
def generateHTML(colors):
print(colors)
node1 = f"""id: '1',
label: 'Theme 1',
x: 7,
y: 1,
size: 1,
color: '{colors[0]}'"""
node2 = f"""id: '2',
label: 'Theme 2',
x: 12,
y: 1,
size: 1,
color: '{colors[1]}'"""
node3 = f"""id: '3',
label: 'Constituant de la phrase',
x: 5,
y: 3,
size: 1,
color: '{colors[2]}'"""
node4 = f"""id: '4',
label: 'Types de phrase et accord du verbe',
x: 9,
y: 3,
size: 1,
color: '{colors[3]}'"""
node5 = f"""id: '5',
label: 'Homophone',
x: 14,
y: 3,
size: 1,
color: '{colors[4]}'"""
node6 = f"""id: '6',
label: 'Apprentissage',
x: 4,
y: 5,
size: 1,
color: '{colors[5]}'"""
node7 = f"""id: '7',
label: 'Appronfondissement',
x: 6,
y: 5,
size: 1,
color: '{colors[6]}'"""
node8 = f"""id: '8',
label: 'Type de phrase',
x: 8,
y: 5,
size: 1,
color: '{colors[7]}'"""
node9 = f"""id: '9',
label: 'Accord du verbe',
x: 10,
y: 5,
size: 1,
color: '{colors[8]}'"""
node10 = f"""id: '10',
label: 'Homonyme',
x: 13,
y: 5,
size: 1,
color: '{colors[9]}'"""
node11 = f"""id: '11',
label: 'Autre Cas',
x: 15,
y: 5,
size: 1,
color: '{colors[10]}'"""
html = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<!-- START SIGMA IMPORTS -->
<script src="./src/sigma.core.js"></script>
<script src="./src/conrad.js"></script>
<script src="./src/utils/sigma.utils.js"></script>
<script src="./src/utils/sigma.polyfills.js"></script>
<script src="./src/sigma.settings.js"></script>
<script src="./src/classes/sigma.classes.dispatcher.js"></script>
<script src="./src/classes/sigma.classes.configurable.js"></script>
<script src="./src/classes/sigma.classes.graph.js"></script>
<script src="./src/classes/sigma.classes.camera.js"></script>
<script src="./src/classes/sigma.classes.quad.js"></script>
<script src="./src/classes/sigma.classes.edgequad.js"></script>
<script src="./src/captors/sigma.captors.mouse.js"></script>
<script src="./src/captors/sigma.captors.touch.js"></script>
<script src="./src/renderers/sigma.renderers.canvas.js"></script>
<script src="./src/renderers/sigma.renderers.webgl.js"></script>
<script src="./src/renderers/sigma.renderers.svg.js"></script>
<script src="./src/renderers/sigma.renderers.def.js"></script>
<script src="./src/renderers/webgl/sigma.webgl.nodes.def.js"></script>
<script src="./src/renderers/webgl/sigma.webgl.nodes.fast.js"></script>
<script src="./src/renderers/webgl/sigma.webgl.edges.def.js"></script>
<script src="./src/renderers/webgl/sigma.webgl.edges.fast.js"></script>
<script src="./src/renderers/webgl/sigma.webgl.edges.arrow.js"></script>
<script src="./src/renderers/canvas/sigma.canvas.labels.def.js"></script>
<script src="./src/renderers/canvas/sigma.canvas.hovers.def.js"></script>
<script src="./src/renderers/canvas/sigma.canvas.nodes.def.js"></script>
<script src="./src/renderers/canvas/sigma.canvas.edges.def.js"></script>
<script src="./src/renderers/canvas/sigma.canvas.edges.curve.js"></script>
<script src="./src/renderers/canvas/sigma.canvas.edges.arrow.js"></script>
<script src="./src/renderers/canvas/sigma.canvas.edges.curvedArrow.js"></script>
<script src="./src/renderers/canvas/sigma.canvas.edgehovers.def.js"></script>
<script src="./src/renderers/canvas/sigma.canvas.edgehovers.curve.js"></script>
<script src="./src/renderers/canvas/sigma.canvas.edgehovers.arrow.js"></script>
<script src="./src/renderers/canvas/sigma.canvas.edgehovers.curvedArrow.js"></script>
<script src="./src/renderers/canvas/sigma.canvas.extremities.def.js"></script>
<script src="./src/renderers/svg/sigma.svg.utils.js"></script>
<script src="./src/renderers/svg/sigma.svg.nodes.def.js"></script>
<script src="./src/renderers/svg/sigma.svg.edges.def.js"></script>
<script src="./src/renderers/svg/sigma.svg.edges.curve.js"></script>
<script src="./src/renderers/svg/sigma.svg.labels.def.js"></script>
<script src="./src/renderers/svg/sigma.svg.hovers.def.js"></script>
<script src="./src/middlewares/sigma.middlewares.rescale.js"></script>
<script src="./src/middlewares/sigma.middlewares.copy.js"></script>
<script src="./src/misc/sigma.misc.animation.js"></script>
<script src="./src/misc/sigma.misc.bindEvents.js"></script>
<script src="./src/misc/sigma.misc.bindDOMEvents.js"></script>
<script src="./src/misc/sigma.misc.drawHovers.js"></script>
<!-- END SIGMA IMPORTS -->
<title>Visualisation prototype</title>
<link rel="stylesheet" href="https://unpkg.com/sakura.css/css/sakura.css" type="text/css">
</head>
<body>
<div id="container">
<style>
#graph-container {
top: 50px;
bottom: 50px;
left: 50px;
right: 50px;
position: absolute;
}
</style>
<div id="legend">
<div class="class">
<div class="color" id="_0"></div>
<span class="spanner">Graduation 0</span>
</div>
<div class="class">
<div class="color" id="_1"></div>
<span class="spanner">Graduation 1</span>
</div>
<div class="class">
<div class="color" id="_2"></div>
<span class="spanner">Graduation 2</span>
</div>
<div class="class">
<div class="color" id="_3"></div>
<span class="spanner">Graduation 3</span>
</div>
<div class="class">
<div class="color" id="_4"></div>
<span class="spanner">Graduation 4</span>
</div>
</div>
<style>
body{
height: 100vh;
width: 100vw;
}
#legend{
display: flex;
flex-direction: column;
max-width: 20vw;
}
.class{
display: flex;
flex-direction: row;
justify-content: flex-start;
margin-top: 10px;
border-bottom: 2px solid black;
max-width: 10vw;
}
.color {
width: 40px;
height: 20px;
}
#_0{
background-color: #999966;
}
#_1{
background-color: #cc0000;
}
#_2{
background-color: #ff6600;
}
#_3{
background-color: #ffff00;
}
#_4{
background-color: #00ff00;
}
.spanner {
margin-left: 10px;
}
html { overflow-y: hidden; overflow-x: hidden;}
</style>
<div id="graph-container"></div>
</div>
<script>
/**
* This is a basic example on how to instantiate sigma. A random graph is
* generated and stored in the "graph" variable, and then sigma is instantiated
* directly with the graph.
*
* The simple instance of sigma is enough to make it render the graph on the on
* the screen, since the graph is given directly to the constructor.
*/
var i,
s,
N = 2,
E = 1,
g = {
nodes: [{"""+node1+"""
},{"""+node2+"""
},{"""+node3+"""
},{"""+node4+"""
},{"""+node5+"""
},{"""+node6+"""
},{"""+node7+"""
},{"""+node8+"""
},{"""+node9+"""
},{"""+node10+"""
},{"""+node11+"""
}],
edges: [{
id: '1',
source: 1,
target: 2,
size: 1,
color: '#000000'
},{
id: '2',
source: '3',
target: '1',
size: 1,
color: '#000000'
},{
id: '4',
source: '6',
target: '3',
size: 1,
color: '#000000'
},{
id: '5',
source: '7',
target: '3',
size: 1,
color: '#000000'
},{
id: '6',
source: '8',
target: '4',
size: 1,
color: '#000000'
},{
id: '7',
source: '9',
target: '4',
size: 1,
color: '#000000'
},{
id: '8',
source: '5',
target: '2',
size: 1,
color: '#000000'
},{
id: '9',
source: '10',
target: '5',
size: 1,
color: '#000000'
},{
id: '10',
source: '11',
target: '5',
size: 1,
color: '#000000'
},{
id: '11',
source: '4',
target: '1',
size: 1,
color: '#000000'
}]
};
// Instantiate sigma:
s = new sigma({
graph: g,
container: 'graph-container',
settings: {
sideMargin: 1,
defaultLabelSize: 16,
labelThreshold: 2
}
});
</script>
</body>
</html>
"""
return html | def generate_html(colors):
print(colors)
node1 = f"id: '1',\n label: 'Theme 1',\n x: 7,\n y: 1,\n size: 1,\n color: '{colors[0]}'"
node2 = f"id: '2',\n label: 'Theme 2',\n x: 12,\n y: 1,\n size: 1,\n color: '{colors[1]}'"
node3 = f"id: '3',\n label: 'Constituant de la phrase',\n x: 5,\n y: 3,\n size: 1,\n color: '{colors[2]}'"
node4 = f"id: '4',\n label: 'Types de phrase et accord du verbe',\n x: 9,\n y: 3,\n size: 1,\n color: '{colors[3]}'"
node5 = f"id: '5',\n label: 'Homophone',\n x: 14,\n y: 3,\n size: 1,\n color: '{colors[4]}'"
node6 = f"id: '6',\n label: 'Apprentissage',\n x: 4,\n y: 5,\n size: 1,\n color: '{colors[5]}'"
node7 = f"id: '7',\n label: 'Appronfondissement',\n x: 6,\n y: 5,\n size: 1,\n color: '{colors[6]}'"
node8 = f"id: '8',\n label: 'Type de phrase',\n x: 8,\n y: 5,\n size: 1,\n color: '{colors[7]}'"
node9 = f"id: '9',\n label: 'Accord du verbe',\n x: 10,\n y: 5,\n size: 1,\n color: '{colors[8]}'"
node10 = f"id: '10',\n label: 'Homonyme',\n x: 13,\n y: 5,\n size: 1,\n color: '{colors[9]}'"
node11 = f"id: '11',\n label: 'Autre Cas',\n x: 15,\n y: 5,\n size: 1,\n color: '{colors[10]}'"
html = '\n<!DOCTYPE html>\n<html lang="en">\n\n<head>\n <meta charset="UTF-8">\n <meta name="viewport" content="width=device-width, initial-scale=1.0">\n <meta http-equiv="X-UA-Compatible" content="ie=edge">\n <!-- START SIGMA IMPORTS -->\n <script src="./src/sigma.core.js"></script>\n <script src="./src/conrad.js"></script>\n <script src="./src/utils/sigma.utils.js"></script>\n <script src="./src/utils/sigma.polyfills.js"></script>\n <script src="./src/sigma.settings.js"></script>\n <script src="./src/classes/sigma.classes.dispatcher.js"></script>\n <script src="./src/classes/sigma.classes.configurable.js"></script>\n <script src="./src/classes/sigma.classes.graph.js"></script>\n <script src="./src/classes/sigma.classes.camera.js"></script>\n <script src="./src/classes/sigma.classes.quad.js"></script>\n <script src="./src/classes/sigma.classes.edgequad.js"></script>\n <script src="./src/captors/sigma.captors.mouse.js"></script>\n <script src="./src/captors/sigma.captors.touch.js"></script>\n <script src="./src/renderers/sigma.renderers.canvas.js"></script>\n <script src="./src/renderers/sigma.renderers.webgl.js"></script>\n <script src="./src/renderers/sigma.renderers.svg.js"></script>\n <script src="./src/renderers/sigma.renderers.def.js"></script>\n <script src="./src/renderers/webgl/sigma.webgl.nodes.def.js"></script>\n <script src="./src/renderers/webgl/sigma.webgl.nodes.fast.js"></script>\n <script src="./src/renderers/webgl/sigma.webgl.edges.def.js"></script>\n <script src="./src/renderers/webgl/sigma.webgl.edges.fast.js"></script>\n <script src="./src/renderers/webgl/sigma.webgl.edges.arrow.js"></script>\n <script src="./src/renderers/canvas/sigma.canvas.labels.def.js"></script>\n <script src="./src/renderers/canvas/sigma.canvas.hovers.def.js"></script>\n <script src="./src/renderers/canvas/sigma.canvas.nodes.def.js"></script>\n <script src="./src/renderers/canvas/sigma.canvas.edges.def.js"></script>\n <script src="./src/renderers/canvas/sigma.canvas.edges.curve.js"></script>\n <script src="./src/renderers/canvas/sigma.canvas.edges.arrow.js"></script>\n <script src="./src/renderers/canvas/sigma.canvas.edges.curvedArrow.js"></script>\n <script src="./src/renderers/canvas/sigma.canvas.edgehovers.def.js"></script>\n <script src="./src/renderers/canvas/sigma.canvas.edgehovers.curve.js"></script>\n <script src="./src/renderers/canvas/sigma.canvas.edgehovers.arrow.js"></script>\n <script src="./src/renderers/canvas/sigma.canvas.edgehovers.curvedArrow.js"></script>\n <script src="./src/renderers/canvas/sigma.canvas.extremities.def.js"></script>\n <script src="./src/renderers/svg/sigma.svg.utils.js"></script>\n <script src="./src/renderers/svg/sigma.svg.nodes.def.js"></script>\n <script src="./src/renderers/svg/sigma.svg.edges.def.js"></script>\n <script src="./src/renderers/svg/sigma.svg.edges.curve.js"></script>\n <script src="./src/renderers/svg/sigma.svg.labels.def.js"></script>\n <script src="./src/renderers/svg/sigma.svg.hovers.def.js"></script>\n <script src="./src/middlewares/sigma.middlewares.rescale.js"></script>\n <script src="./src/middlewares/sigma.middlewares.copy.js"></script>\n <script src="./src/misc/sigma.misc.animation.js"></script>\n <script src="./src/misc/sigma.misc.bindEvents.js"></script>\n <script src="./src/misc/sigma.misc.bindDOMEvents.js"></script>\n <script src="./src/misc/sigma.misc.drawHovers.js"></script>\n <!-- END SIGMA IMPORTS -->\n <title>Visualisation prototype</title>\n <link rel="stylesheet" href="https://unpkg.com/sakura.css/css/sakura.css" type="text/css">\n </head>\n\n <body>\n <div id="container">\n <style>\n #graph-container {\n top: 50px;\n bottom: 50px;\n left: 50px;\n right: 50px;\n position: absolute;\n }\n </style>\n <div id="legend">\n <div class="class">\n <div class="color" id="_0"></div>\n <span class="spanner">Graduation 0</span>\n </div>\n <div class="class">\n <div class="color" id="_1"></div>\n <span class="spanner">Graduation 1</span>\n </div>\n <div class="class">\n <div class="color" id="_2"></div>\n <span class="spanner">Graduation 2</span>\n </div>\n <div class="class">\n <div class="color" id="_3"></div>\n <span class="spanner">Graduation 3</span>\n </div>\n <div class="class">\n <div class="color" id="_4"></div>\n <span class="spanner">Graduation 4</span>\n </div>\n \n </div>\n <style>\n body{\n height: 100vh;\n width: 100vw;\n }\n #legend{\n display: flex;\n flex-direction: column;\n max-width: 20vw;\n }\n .class{\n display: flex;\n flex-direction: row;\n justify-content: flex-start;\n margin-top: 10px;\n border-bottom: 2px solid black;\n max-width: 10vw;\n }\n .color {\n width: 40px;\n height: 20px;\n }\n #_0{\n background-color: #999966;\n }\n #_1{\n background-color: #cc0000;\n }\n #_2{\n background-color: #ff6600;\n }\n #_3{\n background-color: #ffff00;\n }\n #_4{\n background-color: #00ff00;\n }\n \n .spanner {\n margin-left: 10px;\n }\n html { overflow-y: hidden; overflow-x: hidden;}\n </style>\n <div id="graph-container"></div>\n </div>\n <script>\n /**\n * This is a basic example on how to instantiate sigma. A random graph is\n * generated and stored in the "graph" variable, and then sigma is instantiated\n * directly with the graph.\n *\n * The simple instance of sigma is enough to make it render the graph on the on\n * the screen, since the graph is given directly to the constructor.\n */\n var i,\n s,\n N = 2,\n E = 1,\n g = {\n nodes: [{' + node1 + '\n },{' + node2 + '\n },{' + node3 + '\n },{' + node4 + '\n },{' + node5 + '\n },{' + node6 + '\n },{' + node7 + '\n },{' + node8 + '\n },{' + node9 + '\n },{' + node10 + '\n },{' + node11 + "\n }],\n edges: [{\n id: '1',\n source: 1,\n target: 2,\n size: 1,\n color: '#000000'\n },{\n id: '2',\n source: '3',\n target: '1',\n size: 1,\n color: '#000000'\n },{\n id: '4',\n source: '6',\n target: '3',\n size: 1,\n color: '#000000'\n },{\n id: '5',\n source: '7',\n target: '3',\n size: 1,\n color: '#000000'\n },{\n id: '6',\n source: '8',\n target: '4',\n size: 1,\n color: '#000000'\n },{\n id: '7',\n source: '9',\n target: '4',\n size: 1,\n color: '#000000'\n },{\n id: '8',\n source: '5',\n target: '2',\n size: 1,\n color: '#000000'\n },{\n id: '9',\n source: '10',\n target: '5',\n size: 1,\n color: '#000000'\n },{\n id: '10',\n source: '11',\n target: '5',\n size: 1,\n color: '#000000'\n },{\n id: '11',\n source: '4',\n target: '1',\n size: 1,\n color: '#000000'\n }]\n };\n\n // Instantiate sigma:\n s = new sigma({\n graph: g,\n container: 'graph-container',\n settings: {\n sideMargin: 1,\n defaultLabelSize: 16,\n labelThreshold: 2\n }\n });\n </script>\n </body>\n\n </html>\n "
return html |
def for_S():
""" Upper case Alphabet letter 'S' pattern using Python for loop"""
for row in range(7):
for col in range(5):
if row%3==0 and col>0 and col<4 or col==0 and row%3!=0 and row<3 or col==4 and row%3!=0 and row>3:
print('*', end = ' ')
else:
print(' ', end = ' ')
print()
def while_S():
""" Upper case Alphabet letter 'S' pattern using Python while loop"""
row = 0
while row<7:
col = 0
while col<5:
if row%3==0 and col>0 and col<4 or col==0 and row%3!=0 and row<3 or col==4 and row%3!=0 and row>3:
print('*', end = ' ')
else:
print(' ', end = ' ')
col += 1
print()
row += 1
| def for_s():
""" Upper case Alphabet letter 'S' pattern using Python for loop"""
for row in range(7):
for col in range(5):
if row % 3 == 0 and col > 0 and (col < 4) or (col == 0 and row % 3 != 0 and (row < 3)) or (col == 4 and row % 3 != 0 and (row > 3)):
print('*', end=' ')
else:
print(' ', end=' ')
print()
def while_s():
""" Upper case Alphabet letter 'S' pattern using Python while loop"""
row = 0
while row < 7:
col = 0
while col < 5:
if row % 3 == 0 and col > 0 and (col < 4) or (col == 0 and row % 3 != 0 and (row < 3)) or (col == 4 and row % 3 != 0 and (row > 3)):
print('*', end=' ')
else:
print(' ', end=' ')
col += 1
print()
row += 1 |
# DROP TABLES
arrivals_drop = "DROP TABLE IF EXISTS arrivals;"
airports_drop = "DROP TABLE IF EXISTS airports;"
countries_drop = "DROP TABLE IF EXISTS countries;"
temp_drop = "DROP TABLE IF EXISTS temp;"
# CREATE TABLES
arrivals_create = ("""CREATE TABLE IF NOT EXISTS arrivals (
arrival_id serial PRIMARY KEY,
country_id int,
visa_type int,
count int,
year int NOT NULL,
month int NOT NULL,
port varchar
);
""")
airports_create = ("""CREATE TABLE IF NOT EXISTS airports (
port varchar PRIMARY KEY,
municipality varchar,
country_id int,
region varchar
);
""")
countries_create = ("""CREATE TABLE IF NOT EXISTS countries (
country_id int PRIMARY KEY,
country_name varchar
);
""")
temp_create = ("""CREATE TABLE IF NOT EXISTS temp (
temp_id serial PRIMARY KEY,
country_id int,
year int NOT NULL,
month int NOT NULL,
avg_temp float,
avg_tempF float
);
""")
# INSERT RECORDS
arrivals_insert = """INSERT INTO arrivals
(
country_id,
visa_type,
count,
month,
year,
port
) \
VALUES (%s, %s, %s, %s, %s, %s)
"""
airports_insert = """INSERT INTO airports
(
port,
municipality,
country_id,
region
) \
VALUES (%s, %s, %s, %s)
"""
countries_insert = """INSERT INTO countries
(
country_id,
country_name
) \
VALUES (%s, %s)
"""
temp_insert = """INSERT INTO temp
(
country_id,
year,
month,
avg_temp,
avg_tempF
) \
VALUES (%s, %s, %s, %s, %s)
"""
# QUERY LISTS
drop_table_queries = [arrivals_drop, airports_drop, countries_drop, temp_drop]
create_table_queries = [arrivals_create, airports_create, countries_create, temp_create]
| arrivals_drop = 'DROP TABLE IF EXISTS arrivals;'
airports_drop = 'DROP TABLE IF EXISTS airports;'
countries_drop = 'DROP TABLE IF EXISTS countries;'
temp_drop = 'DROP TABLE IF EXISTS temp;'
arrivals_create = 'CREATE TABLE IF NOT EXISTS arrivals (\narrival_id serial PRIMARY KEY,\ncountry_id int,\nvisa_type int,\ncount int,\nyear int NOT NULL,\nmonth int NOT NULL,\nport varchar\n);\n'
airports_create = 'CREATE TABLE IF NOT EXISTS airports (\nport varchar PRIMARY KEY,\nmunicipality varchar,\ncountry_id int,\nregion varchar\n);\n'
countries_create = 'CREATE TABLE IF NOT EXISTS countries (\ncountry_id int PRIMARY KEY,\ncountry_name varchar\n);\n'
temp_create = 'CREATE TABLE IF NOT EXISTS temp (\ntemp_id serial PRIMARY KEY,\ncountry_id int,\nyear int NOT NULL,\nmonth int NOT NULL,\navg_temp float,\navg_tempF float\n);\n'
arrivals_insert = 'INSERT INTO arrivals \n(\ncountry_id,\nvisa_type,\ncount,\nmonth,\nyear,\nport\n) VALUES (%s, %s, %s, %s, %s, %s)\n'
airports_insert = 'INSERT INTO airports \n(\nport,\nmunicipality,\ncountry_id,\nregion\n) VALUES (%s, %s, %s, %s)\n'
countries_insert = 'INSERT INTO countries \n(\ncountry_id,\ncountry_name\n) VALUES (%s, %s)\n'
temp_insert = 'INSERT INTO temp \n(\ncountry_id,\nyear,\nmonth,\navg_temp,\navg_tempF\n) VALUES (%s, %s, %s, %s, %s)\n'
drop_table_queries = [arrivals_drop, airports_drop, countries_drop, temp_drop]
create_table_queries = [arrivals_create, airports_create, countries_create, temp_create] |
command = input()
numbers = [int(x) for x in input().split()]
parity = 0 if command == 'Even' else 1
result = sum(filter(lambda x: x % 2 == parity, numbers))
print(result * len(numbers))
| command = input()
numbers = [int(x) for x in input().split()]
parity = 0 if command == 'Even' else 1
result = sum(filter(lambda x: x % 2 == parity, numbers))
print(result * len(numbers)) |
class ListNode:
def __init__(self, data, link=None):
self.data = data
self.link = link
| class Listnode:
def __init__(self, data, link=None):
self.data = data
self.link = link |
temperature =int(input("Enter Temperature: "))
if temperature > 30:
print("It's a hot day")
elif temperature < 10:
print("It's a cold day")
else:
print("it's neither hot nor cold")
| temperature = int(input('Enter Temperature: '))
if temperature > 30:
print("It's a hot day")
elif temperature < 10:
print("It's a cold day")
else:
print("it's neither hot nor cold") |
TRACKS = 'tracks'
STUDIES = 'studies'
EXPERIMENTS = 'experiments'
SAMPLES = 'samples'
SCHEMA_URL_PART1 = 'https://raw.githubusercontent.com/fairtracks/fairtracks_standard/'
SCHEMA_URL_PART2 = '/current/json/schema/fairtracks.schema.json'
TOP_SCHEMA_FN = 'fairtracks.schema.json'
TERM_ID = 'term_id'
ONTOLOGY = 'ontology'
TERM_LABEL = 'term_label'
DOC_ONTOLOGY_VERSIONS_NAMES = {'doc_info': 'doc_ontology_versions',
'document': 'ontology_versions'}
HAS_AUGMENTED_METADATA = {'doc_info': 'has_augmented_metadata',
'document': 'has_augmented_metadata'}
FILE_NAME = 'file_name'
FILE_URL = 'file_url'
ITEMS = 'items'
PROPERTIES = 'properties'
VERSION_IRI = '<owl:versionIRI rdf:resource="'
DOAP_VERSION = '<doap:Version>'
EDAM_ONTOLOGY = 'http://edamontology.org/'
IDENTIFIERS_API_URL = 'http://resolver.api.identifiers.org/'
NCBI_TAXONOMY_RESOLVER_URL = 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?db=taxonomy&retmode=json'
SAMPLE_TYPE_MAPPING = {'http://purl.obolibrary.org/obo/NCIT_C12508':['sample_type', 'cell_type'],
'http://purl.obolibrary.org/obo/NCIT_C12913':['sample_type', 'abnormal_cell_type'],
'http://purl.obolibrary.org/obo/NCIT_C16403':['sample_type', 'cell_line'],
'http://purl.obolibrary.org/obo/NCIT_C103199':['sample_type', 'organism_part']}
SAMPLE_ORGANISM_PART_PATH = ['sample_type', 'organism_part', 'term_label']
SAMPLE_DETAILS_PATH = ['sample_type', 'details']
BIOSPECIMEN_CLASS_PATH = ['biospecimen_class', 'term_id']
SAMPLE_TYPE_SUMMARY_PATH = ['sample_type', 'summary']
EXPERIMENT_TARGET_PATHS = [['target', 'sequence_feature', 'term_label'], ['target', 'gene_id'],
['target', 'gene_product_type', 'term_label'],
['target', 'macromolecular_structure', 'term_label'],
['target', 'phenotype', 'term_label']]
TARGET_DETAILS_PATH = ['target', 'details']
TARGET_SUMMARY_PATH = ['target', 'summary']
TRACK_FILE_URL_PATH = ['file_url']
SPECIES_ID_PATH = ['species_id']
SPECIES_NAME_PATH = ['species_name']
ONTOLOGY_FOLDER_PATH = 'ontologies'
RESOLVED_RESOURCES = 'resolvedResources'
| tracks = 'tracks'
studies = 'studies'
experiments = 'experiments'
samples = 'samples'
schema_url_part1 = 'https://raw.githubusercontent.com/fairtracks/fairtracks_standard/'
schema_url_part2 = '/current/json/schema/fairtracks.schema.json'
top_schema_fn = 'fairtracks.schema.json'
term_id = 'term_id'
ontology = 'ontology'
term_label = 'term_label'
doc_ontology_versions_names = {'doc_info': 'doc_ontology_versions', 'document': 'ontology_versions'}
has_augmented_metadata = {'doc_info': 'has_augmented_metadata', 'document': 'has_augmented_metadata'}
file_name = 'file_name'
file_url = 'file_url'
items = 'items'
properties = 'properties'
version_iri = '<owl:versionIRI rdf:resource="'
doap_version = '<doap:Version>'
edam_ontology = 'http://edamontology.org/'
identifiers_api_url = 'http://resolver.api.identifiers.org/'
ncbi_taxonomy_resolver_url = 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?db=taxonomy&retmode=json'
sample_type_mapping = {'http://purl.obolibrary.org/obo/NCIT_C12508': ['sample_type', 'cell_type'], 'http://purl.obolibrary.org/obo/NCIT_C12913': ['sample_type', 'abnormal_cell_type'], 'http://purl.obolibrary.org/obo/NCIT_C16403': ['sample_type', 'cell_line'], 'http://purl.obolibrary.org/obo/NCIT_C103199': ['sample_type', 'organism_part']}
sample_organism_part_path = ['sample_type', 'organism_part', 'term_label']
sample_details_path = ['sample_type', 'details']
biospecimen_class_path = ['biospecimen_class', 'term_id']
sample_type_summary_path = ['sample_type', 'summary']
experiment_target_paths = [['target', 'sequence_feature', 'term_label'], ['target', 'gene_id'], ['target', 'gene_product_type', 'term_label'], ['target', 'macromolecular_structure', 'term_label'], ['target', 'phenotype', 'term_label']]
target_details_path = ['target', 'details']
target_summary_path = ['target', 'summary']
track_file_url_path = ['file_url']
species_id_path = ['species_id']
species_name_path = ['species_name']
ontology_folder_path = 'ontologies'
resolved_resources = 'resolvedResources' |
class Constant():
def __init__(self, value):
self._value = value
def __call__(self):
return self._value
y = Constant(5)
print((y()))
| class Constant:
def __init__(self, value):
self._value = value
def __call__(self):
return self._value
y = constant(5)
print(y()) |
print(2, type(2))
print(3.5, type(3.5))
print([], type([]))
print(True, type(True))
print(None, type(None))
# code to put in a for-each loop for the Pattern Loop Exercise
| print(2, type(2))
print(3.5, type(3.5))
print([], type([]))
print(True, type(True))
print(None, type(None)) |
def create_dimension_competitors(cursor):
cursor.execute('''CREATE TABLE dimension_competitors
( company_name text,
company_permalink text,
competitor_name text,
competitor_permalink text,
extracted_at text
)''') | def create_dimension_competitors(cursor):
cursor.execute('CREATE TABLE dimension_competitors\n ( company_name text,\n company_permalink text,\n competitor_name text,\n competitor_permalink text,\n extracted_at text\n )') |
name_1 = input()
name_2 = input()
delimiter = input()
print(f"{name_1}{delimiter}{name_2}") | name_1 = input()
name_2 = input()
delimiter = input()
print(f'{name_1}{delimiter}{name_2}') |
def f(x):
for i in reversed([20, 19, 18, 17, 16, 15, 14, 13, 12, 11]):
if x % i != 0:
return False
return True
i = 20
while f(i) == False:
i += 20
print(i)
| def f(x):
for i in reversed([20, 19, 18, 17, 16, 15, 14, 13, 12, 11]):
if x % i != 0:
return False
return True
i = 20
while f(i) == False:
i += 20
print(i) |
a=int(input("Enter any number "))
for x in range(1,a+1):
print(x)
| a = int(input('Enter any number '))
for x in range(1, a + 1):
print(x) |
class String:
"""Javascript methods for strings."""
def char_at(string, index):
"""Returns the character at a specified index in a string."""
return string[index]
def trim(string):
"""Removes whitespace from both sides of a string."""
return string.strip()
def includes(string, value):
"""Checks if a string contains a specified value."""
temp_bool = string.find(value)
if temp_bool == -1:
return False
else:
return True
def starts_with(string, char):
"""Checks if a string starts with a specified charactor."""
return string.startswith(char)
def ends_with(string, char):
"""Checks if a string ends with a specified charactor."""
return string.endswith(char)
def multiline(*strings, end):
"""Takes lines of string and returns a multiline string.
end: The lastest line of the string.
"""
temp_string = ''
for string in strings:
temp_string += string + '\n'
temp_string += end
return temp_string
| class String:
"""Javascript methods for strings."""
def char_at(string, index):
"""Returns the character at a specified index in a string."""
return string[index]
def trim(string):
"""Removes whitespace from both sides of a string."""
return string.strip()
def includes(string, value):
"""Checks if a string contains a specified value."""
temp_bool = string.find(value)
if temp_bool == -1:
return False
else:
return True
def starts_with(string, char):
"""Checks if a string starts with a specified charactor."""
return string.startswith(char)
def ends_with(string, char):
"""Checks if a string ends with a specified charactor."""
return string.endswith(char)
def multiline(*strings, end):
"""Takes lines of string and returns a multiline string.
end: The lastest line of the string.
"""
temp_string = ''
for string in strings:
temp_string += string + '\n'
temp_string += end
return temp_string |
def pre_order(root):
ret = []
stack, node = [], root
while stack or node:
if node:
ret.append(node.val)
stack.append(node)
node = node.left
else:
node = stack.pop()
node = node.right
return ret
def in_order(root):
ret = []
stack, node = [], root
while stack or node:
if node:
stack.append(node)
node = node.left
else:
node = stack.pop()
ret.append(node.val)
node = node.right
return ret
def post_order(root):
ret = []
stack, node = [], root
while stack or node:
if node:
ret.append(node.val)
stack.append(node)
# move to right first, then reverse its result
node = node.right
else:
node = stack.pop()
node = node.left
return ret[::-1]
| def pre_order(root):
ret = []
(stack, node) = ([], root)
while stack or node:
if node:
ret.append(node.val)
stack.append(node)
node = node.left
else:
node = stack.pop()
node = node.right
return ret
def in_order(root):
ret = []
(stack, node) = ([], root)
while stack or node:
if node:
stack.append(node)
node = node.left
else:
node = stack.pop()
ret.append(node.val)
node = node.right
return ret
def post_order(root):
ret = []
(stack, node) = ([], root)
while stack or node:
if node:
ret.append(node.val)
stack.append(node)
node = node.right
else:
node = stack.pop()
node = node.left
return ret[::-1] |
# Keep a dictionary that has items ordered in a deque structure
class DequeDict:
# Entry that holds the key, value
class DequeEntry:
def __init__(self, key, value):
self.key = key
self.value = value
self.prev = None
self.next = None
# Helpful for debugging, print key and value
def __repr__(self):
return "(k={}, v={})".format(self.key, self.value)
def __init__(self):
self.htbl = {}
self.head = None
self.tail = None
# Helpful for debugging, print out entire Deque
def __repr__(self):
entries = []
entry = self.head
while entry:
entries.append(entry)
entry = entry.next
return "<DequeDict({})>".format(entries)
# Iterator
def __iter__(self):
self.current = self.head
return self
# Next for iterator
def __next__(self):
if self.current == None:
raise StopIteration
value = self.current.value
self.current = self.current.next
return value
# For Python2
next = __next__
def __contains__(self, key):
return key in self.htbl
def __len__(self):
return len(self.htbl)
# value = dequeDict[key]
def __getitem__(self, key):
return self.htbl[key].value
# dequeDict[key] = value
# NOTE: pushes a new item, updates an old item in the Deque
def __setitem__(self, key, value):
if key in self.htbl:
self.__update(key, value)
else:
self.__push(key, value)
# del dequeDict[key]
# Just removes the item completely as expected
def __delitem__(self, key):
self.__remove(key)
# Get first item
# NOTE: LRU since queue is FIFO
def first(self):
return self.head.value
# Push (key, value) as first in deque
def pushFirst(self, key, value):
assert (key not in self.htbl)
entry = self.DequeEntry(key, value)
self.htbl[key] = entry
headEntry = self.head
if headEntry:
headEntry.prev = entry
entry.next = headEntry
else:
self.tail = entry
self.head = entry
# Remove and return first item
# NOTE: LRU since queue is FIFO
def popFirst(self):
first = self.head
self.__remove(first.key)
return first.value
# Get last item
# NOTE: MRU since queue is FIFO
def last(self):
return self.tail.value
# Remove and return last item
# NOTE: MRU since queue is FIFO
def popLast(self):
last = self.tail
self.__remove(last.key)
return last.value
# Remove the entry with the given key completely from DequeDict
def __remove(self, key):
assert (key in self.htbl)
entry = self.htbl[key]
prevEntry = entry.prev
nextEntry = entry.next
if prevEntry:
prevEntry.next = nextEntry
else:
self.head = nextEntry
if nextEntry:
nextEntry.prev = prevEntry
else:
self.tail = prevEntry
del self.htbl[key]
# Insert a new item into the DequeDict
def __push(self, key, value):
assert (key not in self.htbl)
entry = self.DequeEntry(key, value)
self.htbl[key] = entry
tailEntry = self.tail
if tailEntry:
tailEntry.next = entry
entry.prev = tailEntry
else:
self.head = entry
self.tail = entry
# Update an item that currently exists in the DequeDict
def __update(self, key, value):
# Just remove and push since it should be very fast anyways
self.__remove(key)
self.__push(key, value)
# Some quick test code to make sure this works
if __name__ == '__main__':
dd = DequeDict()
l = [1, 2, 3, 4, 5, 6]
for e in l:
dd[len(l) - e] = e
for e, f in zip(l, dd):
assert (e == f)
for e in l:
f = dd.popFirst()
assert (e == f)
for e in l:
dd[len(l) - e] = e
for e in l[::-1]:
f = dd.popLast()
assert (e == f)
for e in l:
dd[len(l) - e] = e
dd[3] = -1
dd[5] = 7
del dd[1]
assert (dd.popFirst() == 2)
assert (dd.popFirst() == 4)
assert (dd.popFirst() == 6)
assert (dd.popFirst() == -1)
assert (dd.popFirst() == 7)
| class Dequedict:
class Dequeentry:
def __init__(self, key, value):
self.key = key
self.value = value
self.prev = None
self.next = None
def __repr__(self):
return '(k={}, v={})'.format(self.key, self.value)
def __init__(self):
self.htbl = {}
self.head = None
self.tail = None
def __repr__(self):
entries = []
entry = self.head
while entry:
entries.append(entry)
entry = entry.next
return '<DequeDict({})>'.format(entries)
def __iter__(self):
self.current = self.head
return self
def __next__(self):
if self.current == None:
raise StopIteration
value = self.current.value
self.current = self.current.next
return value
next = __next__
def __contains__(self, key):
return key in self.htbl
def __len__(self):
return len(self.htbl)
def __getitem__(self, key):
return self.htbl[key].value
def __setitem__(self, key, value):
if key in self.htbl:
self.__update(key, value)
else:
self.__push(key, value)
def __delitem__(self, key):
self.__remove(key)
def first(self):
return self.head.value
def push_first(self, key, value):
assert key not in self.htbl
entry = self.DequeEntry(key, value)
self.htbl[key] = entry
head_entry = self.head
if headEntry:
headEntry.prev = entry
entry.next = headEntry
else:
self.tail = entry
self.head = entry
def pop_first(self):
first = self.head
self.__remove(first.key)
return first.value
def last(self):
return self.tail.value
def pop_last(self):
last = self.tail
self.__remove(last.key)
return last.value
def __remove(self, key):
assert key in self.htbl
entry = self.htbl[key]
prev_entry = entry.prev
next_entry = entry.next
if prevEntry:
prevEntry.next = nextEntry
else:
self.head = nextEntry
if nextEntry:
nextEntry.prev = prevEntry
else:
self.tail = prevEntry
del self.htbl[key]
def __push(self, key, value):
assert key not in self.htbl
entry = self.DequeEntry(key, value)
self.htbl[key] = entry
tail_entry = self.tail
if tailEntry:
tailEntry.next = entry
entry.prev = tailEntry
else:
self.head = entry
self.tail = entry
def __update(self, key, value):
self.__remove(key)
self.__push(key, value)
if __name__ == '__main__':
dd = deque_dict()
l = [1, 2, 3, 4, 5, 6]
for e in l:
dd[len(l) - e] = e
for (e, f) in zip(l, dd):
assert e == f
for e in l:
f = dd.popFirst()
assert e == f
for e in l:
dd[len(l) - e] = e
for e in l[::-1]:
f = dd.popLast()
assert e == f
for e in l:
dd[len(l) - e] = e
dd[3] = -1
dd[5] = 7
del dd[1]
assert dd.popFirst() == 2
assert dd.popFirst() == 4
assert dd.popFirst() == 6
assert dd.popFirst() == -1
assert dd.popFirst() == 7 |
#
# Copyright (C) 2000-2005 by Yasushi Saito (yasushi.saito@gmail.com)
#
# Jockey is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2, or (at your option) any
# later version.
#
# Jockey is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
# for more details.
#
def generate_doc(name, suffix="", append = 0):
if append:
fp = open(name + "_doc.py", "a+")
else:
fp = open(name + "_doc.py", "w")
fp.write("# automatically generated by generate_docs.py.\n")
fp.write("doc" + suffix + "=\" \"\n")
fp.close()
generate_doc( "area")
generate_doc( "arrow")
generate_doc( "axis", "_x")
generate_doc( "axis", "_y", 1)
generate_doc( "bar_plot")
generate_doc( "color")
generate_doc( "error_bar","_1")
generate_doc( "error_bar", "_2", 1)
generate_doc( "error_bar", "_3", 1)
generate_doc( "error_bar", "_4", 1)
generate_doc( "error_bar", "_5", 1)
generate_doc( "error_bar", "_6", 1)
generate_doc( "fill_style")
generate_doc("line_plot")
generate_doc("pie_plot")
generate_doc("text_box")
generate_doc("range_plot")
generate_doc("legend")
generate_doc("legend", "_entry", 1)
generate_doc("line_style")
generate_doc("tick_mark")
| def generate_doc(name, suffix='', append=0):
if append:
fp = open(name + '_doc.py', 'a+')
else:
fp = open(name + '_doc.py', 'w')
fp.write('# automatically generated by generate_docs.py.\n')
fp.write('doc' + suffix + '=" "\n')
fp.close()
generate_doc('area')
generate_doc('arrow')
generate_doc('axis', '_x')
generate_doc('axis', '_y', 1)
generate_doc('bar_plot')
generate_doc('color')
generate_doc('error_bar', '_1')
generate_doc('error_bar', '_2', 1)
generate_doc('error_bar', '_3', 1)
generate_doc('error_bar', '_4', 1)
generate_doc('error_bar', '_5', 1)
generate_doc('error_bar', '_6', 1)
generate_doc('fill_style')
generate_doc('line_plot')
generate_doc('pie_plot')
generate_doc('text_box')
generate_doc('range_plot')
generate_doc('legend')
generate_doc('legend', '_entry', 1)
generate_doc('line_style')
generate_doc('tick_mark') |
class Solution:
def minTimeToVisitAllPoints(self, points: List[List[int]]) -> int:
if not points or len(points) == 1:
return 0
time = 0
for index,cur_point in enumerate(points):
if index == len(points) - 1:
return time
next_point = points[index+1]
cross_path = min(abs(cur_point[0] - next_point[0]),abs(cur_point[1] - next_point[1]))
straight_path = max(abs(cur_point[0] - next_point[0]),abs(cur_point[1] - next_point[1])) - cross_path
time += cross_path +straight_path
| class Solution:
def min_time_to_visit_all_points(self, points: List[List[int]]) -> int:
if not points or len(points) == 1:
return 0
time = 0
for (index, cur_point) in enumerate(points):
if index == len(points) - 1:
return time
next_point = points[index + 1]
cross_path = min(abs(cur_point[0] - next_point[0]), abs(cur_point[1] - next_point[1]))
straight_path = max(abs(cur_point[0] - next_point[0]), abs(cur_point[1] - next_point[1])) - cross_path
time += cross_path + straight_path |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.