content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
'''Soma Simples'''
A = int(input())
B = int(input())
def CalculaSomaSimples(a: int, b: int):
resultado = int(a+b)
return('SOMA = {}'.format(resultado))
print(CalculaSomaSimples(A,B))
| """Soma Simples"""
a = int(input())
b = int(input())
def calcula_soma_simples(a: int, b: int):
resultado = int(a + b)
return 'SOMA = {}'.format(resultado)
print(calcula_soma_simples(A, B)) |
pkgname = "libgpg-error"
pkgver = "1.43"
pkgrel = 0
build_style = "gnu_configure"
hostmakedepends = ["pkgconf"]
pkgdesc = "Library for error values used by GnuPG components"
maintainer = "q66 <q66@chimera-linux.org>"
license = "LGPL-2.1-or-later"
url = "https://www.gnupg.org"
source = f"{url}/ftp/gcrypt/{pkgname}/{pkgname}-{pkgver}.tar.bz2"
sha256 = "a9ab83ca7acc442a5bd846a75b920285ff79bdb4e3d34aa382be88ed2c3aebaf"
# needs qemu and patching
options = ["!cross"]
def post_install(self):
self.rm(self.destdir / "usr/share/common-lisp", recursive = True)
@subpackage("libgpg-error-devel")
def _devel(self):
return self.default_devel()
@subpackage("libgpg-error-progs")
def _progs(self):
return self.default_progs()
| pkgname = 'libgpg-error'
pkgver = '1.43'
pkgrel = 0
build_style = 'gnu_configure'
hostmakedepends = ['pkgconf']
pkgdesc = 'Library for error values used by GnuPG components'
maintainer = 'q66 <q66@chimera-linux.org>'
license = 'LGPL-2.1-or-later'
url = 'https://www.gnupg.org'
source = f'{url}/ftp/gcrypt/{pkgname}/{pkgname}-{pkgver}.tar.bz2'
sha256 = 'a9ab83ca7acc442a5bd846a75b920285ff79bdb4e3d34aa382be88ed2c3aebaf'
options = ['!cross']
def post_install(self):
self.rm(self.destdir / 'usr/share/common-lisp', recursive=True)
@subpackage('libgpg-error-devel')
def _devel(self):
return self.default_devel()
@subpackage('libgpg-error-progs')
def _progs(self):
return self.default_progs() |
class Person:
name = None
age = 0
gender = None
def __init__(self, n, a, g):
self.name = n
self.age = a
self.gender = g
def walk(self):
print('I am walking')
def eat(self):
print('I am eating :)')
def __str__(self): # string representation of the object
return 'name: {}\tage: {}\tgender: {}'.format(self.name, self.age, self.gender)
p1 = Person('Ahmed', 20, 'm')
p2 = Person('Attia', 25, 'm')
p1.walk()
p2.eat()
print(p1)
print(p2)
| class Person:
name = None
age = 0
gender = None
def __init__(self, n, a, g):
self.name = n
self.age = a
self.gender = g
def walk(self):
print('I am walking')
def eat(self):
print('I am eating :)')
def __str__(self):
return 'name: {}\tage: {}\tgender: {}'.format(self.name, self.age, self.gender)
p1 = person('Ahmed', 20, 'm')
p2 = person('Attia', 25, 'm')
p1.walk()
p2.eat()
print(p1)
print(p2) |
list=input().split()
re=[int(e) for e in input().split()]
new=[]
for i in re:
new.append(list[i])
for l in new:
print(l,end=" ")
| list = input().split()
re = [int(e) for e in input().split()]
new = []
for i in re:
new.append(list[i])
for l in new:
print(l, end=' ') |
shopping_list = []
def show_help():
print("Enter the items/amount for your shopping list")
print("Enter DONE once you have completed the list, Enter Help if you require assistance")
def add_to_list(item):
shopping_list.append(item)
print("Added! List has {} items.".format(len(shopping_list)))
def show_list():
print("Here is your list")
for item in shopping_list:
print(item)
show_help()
while True:
new_item = input("item>")
if new_item == 'DONE':
break
elif new_item == 'HELP':
show_help()
continue
elif new_item == 'SHOW':
show_list()
continue
else:
add_to_list(new_item)
continue
show_list() | shopping_list = []
def show_help():
print('Enter the items/amount for your shopping list')
print('Enter DONE once you have completed the list, Enter Help if you require assistance')
def add_to_list(item):
shopping_list.append(item)
print('Added! List has {} items.'.format(len(shopping_list)))
def show_list():
print('Here is your list')
for item in shopping_list:
print(item)
show_help()
while True:
new_item = input('item>')
if new_item == 'DONE':
break
elif new_item == 'HELP':
show_help()
continue
elif new_item == 'SHOW':
show_list()
continue
else:
add_to_list(new_item)
continue
show_list() |
GET_HOSTS = [
{
'device_id': '00000000000000000000000000000000',
'cid': '11111111111111111111111111111111',
'agent_load_flags': '0',
'agent_local_time': '2021-12-08T15:16:24.360Z',
'agent_version': '6.30.14406.0',
'bios_manufacturer': 'Amazon EC2',
'bios_version': '1.0',
'build_number': '11111',
'config_id_base': '11111111',
'config_id_build': '11111',
'config_id_platform': '1',
'cpu_signature': '111111',
'external_ip': '10.0.0.1',
'mac_address': '00-00-00-00-00-00',
'instance_id': 'i-01',
'service_provider': 'AWS_EC2',
'service_provider_account_id': '000000000000',
'hostname': 'test',
'first_seen': '2022-03-14T04:13:28Z',
'last_seen': '2022-03-15T07:42:07Z',
'local_ip': '10.0.0.1',
'machine_domain': 'example.com',
'major_version': '4',
'minor_version': '14',
'os_version': 'Amazon Linux 2',
'os_build': '241',
'ou': ['test'],
'platform_id': '3',
'platform_name': 'Linux',
'policies': [],
'reduced_functionality_mode': 'no',
'device_policies': {},
'groups': ['00000000000000000000000000000001'],
'group_hash': '0000000000000000000000000000000000000000000000000000000000000000',
'product_type': '3',
'product_type_desc': 'Server',
'provision_status': 'Provisioned',
'serial_number': '00000000-0000-0000-0000-000000000000',
'service_pack_major': '0',
'service_pack_minor': '0',
'pointer_size': '8',
'site_name': 'Default-First-Site-Name',
'status': 'normal',
'system_manufacturer': 'Amazon EC2',
'system_product_name': 't3.small',
'tags': ['SensorGroupingTags/test'],
'modified_timestamp': '2022-03-15T07:42:10Z',
'slow_changing_modified_timestamp': '2022-03-15T06:16:42Z',
'meta': {'version': '6433'},
'zone_group': 'us-east-1a',
'kernel_version': '4.14.241-184.433.amzn2.x86_64',
},
]
| get_hosts = [{'device_id': '00000000000000000000000000000000', 'cid': '11111111111111111111111111111111', 'agent_load_flags': '0', 'agent_local_time': '2021-12-08T15:16:24.360Z', 'agent_version': '6.30.14406.0', 'bios_manufacturer': 'Amazon EC2', 'bios_version': '1.0', 'build_number': '11111', 'config_id_base': '11111111', 'config_id_build': '11111', 'config_id_platform': '1', 'cpu_signature': '111111', 'external_ip': '10.0.0.1', 'mac_address': '00-00-00-00-00-00', 'instance_id': 'i-01', 'service_provider': 'AWS_EC2', 'service_provider_account_id': '000000000000', 'hostname': 'test', 'first_seen': '2022-03-14T04:13:28Z', 'last_seen': '2022-03-15T07:42:07Z', 'local_ip': '10.0.0.1', 'machine_domain': 'example.com', 'major_version': '4', 'minor_version': '14', 'os_version': 'Amazon Linux 2', 'os_build': '241', 'ou': ['test'], 'platform_id': '3', 'platform_name': 'Linux', 'policies': [], 'reduced_functionality_mode': 'no', 'device_policies': {}, 'groups': ['00000000000000000000000000000001'], 'group_hash': '0000000000000000000000000000000000000000000000000000000000000000', 'product_type': '3', 'product_type_desc': 'Server', 'provision_status': 'Provisioned', 'serial_number': '00000000-0000-0000-0000-000000000000', 'service_pack_major': '0', 'service_pack_minor': '0', 'pointer_size': '8', 'site_name': 'Default-First-Site-Name', 'status': 'normal', 'system_manufacturer': 'Amazon EC2', 'system_product_name': 't3.small', 'tags': ['SensorGroupingTags/test'], 'modified_timestamp': '2022-03-15T07:42:10Z', 'slow_changing_modified_timestamp': '2022-03-15T06:16:42Z', 'meta': {'version': '6433'}, 'zone_group': 'us-east-1a', 'kernel_version': '4.14.241-184.433.amzn2.x86_64'}] |
# *****************************************************************************
# Copyright (c) 2020, Intel Corporation All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
# EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# *****************************************************************************
def knn_python(
train,
train_labels,
test,
k,
classes_num,
train_size,
test_size,
predictions,
queue_neighbors_lst,
votes_to_classes_lst,
data_dim,
):
for i in range(test_size):
queue_neighbors = queue_neighbors_lst[i]
for j in range(k):
# dist = euclidean_dist(train[j], test[i])
x1 = train[j]
x2 = test[i]
distance = 0.0
for jj in range(data_dim):
diff = x1[jj] - x2[jj]
distance += diff * diff
dist = distance ** 0.5
queue_neighbors[j, 0] = dist
queue_neighbors[j, 1] = train_labels[j]
# sort_queue(queue_neighbors)
for j in range(len(queue_neighbors)):
# push_queue(queue_neighbors, queue_neighbors[i], i)
new_distance = queue_neighbors[j, 0]
new_neighbor_label = queue_neighbors[j, 1]
index = j
while index > 0 and new_distance < queue_neighbors[index - 1, 0]:
queue_neighbors[index, 0] = queue_neighbors[index - 1, 0]
queue_neighbors[index, 1] = queue_neighbors[index - 1, 1]
index = index - 1
queue_neighbors[index, 0] = new_distance
queue_neighbors[index, 1] = new_neighbor_label
for j in range(k, train_size):
# dist = euclidean_dist(train[j], test[i])
x1 = train[j]
x2 = test[i]
distance = 0.0
for jj in range(data_dim):
diff = x1[jj] - x2[jj]
distance += diff * diff
dist = distance ** 0.5
if dist < queue_neighbors[k - 1][0]:
# queue_neighbors[k - 1] = new_neighbor
queue_neighbors[k - 1][0] = dist
queue_neighbors[k - 1][1] = train_labels[j]
# push_queue(queue_neighbors, queue_neighbors[k - 1])
new_distance = queue_neighbors[k - 1, 0]
new_neighbor_label = queue_neighbors[k - 1, 1]
index = k - 1
while index > 0 and new_distance < queue_neighbors[index - 1, 0]:
queue_neighbors[index, 0] = queue_neighbors[index - 1, 0]
queue_neighbors[index, 1] = queue_neighbors[index - 1, 1]
index = index - 1
queue_neighbors[index, 0] = new_distance
queue_neighbors[index, 1] = new_neighbor_label
votes_to_classes = votes_to_classes_lst[i]
for j in range(len(queue_neighbors)):
votes_to_classes[int(queue_neighbors[j, 1])] += 1
max_ind = 0
max_value = 0
for j in range(classes_num):
if votes_to_classes[j] > max_value:
max_value = votes_to_classes[j]
max_ind = j
predictions[i] = max_ind
| def knn_python(train, train_labels, test, k, classes_num, train_size, test_size, predictions, queue_neighbors_lst, votes_to_classes_lst, data_dim):
for i in range(test_size):
queue_neighbors = queue_neighbors_lst[i]
for j in range(k):
x1 = train[j]
x2 = test[i]
distance = 0.0
for jj in range(data_dim):
diff = x1[jj] - x2[jj]
distance += diff * diff
dist = distance ** 0.5
queue_neighbors[j, 0] = dist
queue_neighbors[j, 1] = train_labels[j]
for j in range(len(queue_neighbors)):
new_distance = queue_neighbors[j, 0]
new_neighbor_label = queue_neighbors[j, 1]
index = j
while index > 0 and new_distance < queue_neighbors[index - 1, 0]:
queue_neighbors[index, 0] = queue_neighbors[index - 1, 0]
queue_neighbors[index, 1] = queue_neighbors[index - 1, 1]
index = index - 1
queue_neighbors[index, 0] = new_distance
queue_neighbors[index, 1] = new_neighbor_label
for j in range(k, train_size):
x1 = train[j]
x2 = test[i]
distance = 0.0
for jj in range(data_dim):
diff = x1[jj] - x2[jj]
distance += diff * diff
dist = distance ** 0.5
if dist < queue_neighbors[k - 1][0]:
queue_neighbors[k - 1][0] = dist
queue_neighbors[k - 1][1] = train_labels[j]
new_distance = queue_neighbors[k - 1, 0]
new_neighbor_label = queue_neighbors[k - 1, 1]
index = k - 1
while index > 0 and new_distance < queue_neighbors[index - 1, 0]:
queue_neighbors[index, 0] = queue_neighbors[index - 1, 0]
queue_neighbors[index, 1] = queue_neighbors[index - 1, 1]
index = index - 1
queue_neighbors[index, 0] = new_distance
queue_neighbors[index, 1] = new_neighbor_label
votes_to_classes = votes_to_classes_lst[i]
for j in range(len(queue_neighbors)):
votes_to_classes[int(queue_neighbors[j, 1])] += 1
max_ind = 0
max_value = 0
for j in range(classes_num):
if votes_to_classes[j] > max_value:
max_value = votes_to_classes[j]
max_ind = j
predictions[i] = max_ind |
class WordWithTag:
word = ""
tag = ""
separator = ''
def __init__(self, separator):
self.separator = separator
| class Wordwithtag:
word = ''
tag = ''
separator = ''
def __init__(self, separator):
self.separator = separator |
class Solution:
def minOperations(self, n: int) -> int:
num_ops = 0
for i in range(0, n // 2, 1):
num_ops += n - (2 * i + 1)
return num_ops | class Solution:
def min_operations(self, n: int) -> int:
num_ops = 0
for i in range(0, n // 2, 1):
num_ops += n - (2 * i + 1)
return num_ops |
'''
Largest Continuous Sum Problem
Given an array of integers (positive and negative) find the largest continous sum
'''
def large_cont_sum(arr):
#if array is all positive we return the result as summ of all numbers
#the negative numbers int he array will cause us to need to begin checkin sequences
## Check to see if array is Length 0
if len(arr) == 0:
return 0
max_sum = current_sum = arr[0] #equal to first element
for num in arr[1:]: #We check each number in array not including the first num arr[0]
current_sum = max(current_sum+num, num) #find out which one is larger: current sum + num or the num
max_sum = max(current_sum,max_sum) #we keep track of which one is larger
return max_sum
print(large_cont_sum([1,2,-1,3,4,10,10,-10,-1])) | """
Largest Continuous Sum Problem
Given an array of integers (positive and negative) find the largest continous sum
"""
def large_cont_sum(arr):
if len(arr) == 0:
return 0
max_sum = current_sum = arr[0]
for num in arr[1:]:
current_sum = max(current_sum + num, num)
max_sum = max(current_sum, max_sum)
return max_sum
print(large_cont_sum([1, 2, -1, 3, 4, 10, 10, -10, -1])) |
data = (
's', # 0x00
't', # 0x01
'u', # 0x02
'v', # 0x03
'w', # 0x04
'x', # 0x05
'y', # 0x06
'z', # 0x07
'A', # 0x08
'B', # 0x09
'C', # 0x0a
'D', # 0x0b
'E', # 0x0c
'F', # 0x0d
'G', # 0x0e
'H', # 0x0f
'I', # 0x10
'J', # 0x11
'K', # 0x12
'L', # 0x13
'M', # 0x14
'N', # 0x15
'O', # 0x16
'P', # 0x17
'Q', # 0x18
'R', # 0x19
'S', # 0x1a
'T', # 0x1b
'U', # 0x1c
'V', # 0x1d
'W', # 0x1e
'X', # 0x1f
'Y', # 0x20
'Z', # 0x21
'a', # 0x22
'b', # 0x23
'c', # 0x24
'd', # 0x25
'e', # 0x26
'f', # 0x27
'g', # 0x28
'h', # 0x29
'i', # 0x2a
'j', # 0x2b
'k', # 0x2c
'l', # 0x2d
'm', # 0x2e
'n', # 0x2f
'o', # 0x30
'p', # 0x31
'q', # 0x32
'r', # 0x33
's', # 0x34
't', # 0x35
'u', # 0x36
'v', # 0x37
'w', # 0x38
'x', # 0x39
'y', # 0x3a
'z', # 0x3b
'A', # 0x3c
'B', # 0x3d
'C', # 0x3e
'D', # 0x3f
'E', # 0x40
'F', # 0x41
'G', # 0x42
'H', # 0x43
'I', # 0x44
'J', # 0x45
'K', # 0x46
'L', # 0x47
'M', # 0x48
'N', # 0x49
'O', # 0x4a
'P', # 0x4b
'Q', # 0x4c
'R', # 0x4d
'S', # 0x4e
'T', # 0x4f
'U', # 0x50
'V', # 0x51
'W', # 0x52
'X', # 0x53
'Y', # 0x54
'Z', # 0x55
'a', # 0x56
'b', # 0x57
'c', # 0x58
'd', # 0x59
'e', # 0x5a
'f', # 0x5b
'g', # 0x5c
'h', # 0x5d
'i', # 0x5e
'j', # 0x5f
'k', # 0x60
'l', # 0x61
'm', # 0x62
'n', # 0x63
'o', # 0x64
'p', # 0x65
'q', # 0x66
'r', # 0x67
's', # 0x68
't', # 0x69
'u', # 0x6a
'v', # 0x6b
'w', # 0x6c
'x', # 0x6d
'y', # 0x6e
'z', # 0x6f
'A', # 0x70
'B', # 0x71
'C', # 0x72
'D', # 0x73
'E', # 0x74
'F', # 0x75
'G', # 0x76
'H', # 0x77
'I', # 0x78
'J', # 0x79
'K', # 0x7a
'L', # 0x7b
'M', # 0x7c
'N', # 0x7d
'O', # 0x7e
'P', # 0x7f
'Q', # 0x80
'R', # 0x81
'S', # 0x82
'T', # 0x83
'U', # 0x84
'V', # 0x85
'W', # 0x86
'X', # 0x87
'Y', # 0x88
'Z', # 0x89
'a', # 0x8a
'b', # 0x8b
'c', # 0x8c
'd', # 0x8d
'e', # 0x8e
'f', # 0x8f
'g', # 0x90
'h', # 0x91
'i', # 0x92
'j', # 0x93
'k', # 0x94
'l', # 0x95
'm', # 0x96
'n', # 0x97
'o', # 0x98
'p', # 0x99
'q', # 0x9a
'r', # 0x9b
's', # 0x9c
't', # 0x9d
'u', # 0x9e
'v', # 0x9f
'w', # 0xa0
'x', # 0xa1
'y', # 0xa2
'z', # 0xa3
'i', # 0xa4
'j', # 0xa5
'', # 0xa6
'', # 0xa7
'Alpha', # 0xa8
'Beta', # 0xa9
'Gamma', # 0xaa
'Delta', # 0xab
'Epsilon', # 0xac
'Zeta', # 0xad
'Eta', # 0xae
'Theta', # 0xaf
'Iota', # 0xb0
'Kappa', # 0xb1
'Lamda', # 0xb2
'Mu', # 0xb3
'Nu', # 0xb4
'Xi', # 0xb5
'Omicron', # 0xb6
'Pi', # 0xb7
'Rho', # 0xb8
'Theta', # 0xb9
'Sigma', # 0xba
'Tau', # 0xbb
'Upsilon', # 0xbc
'Phi', # 0xbd
'Chi', # 0xbe
'Psi', # 0xbf
'Omega', # 0xc0
'nabla', # 0xc1
'alpha', # 0xc2
'beta', # 0xc3
'gamma', # 0xc4
'delta', # 0xc5
'epsilon', # 0xc6
'zeta', # 0xc7
'eta', # 0xc8
'theta', # 0xc9
'iota', # 0xca
'kappa', # 0xcb
'lamda', # 0xcc
'mu', # 0xcd
'nu', # 0xce
'xi', # 0xcf
'omicron', # 0xd0
'pi', # 0xd1
'rho', # 0xd2
'sigma', # 0xd3
'sigma', # 0xd4
'tai', # 0xd5
'upsilon', # 0xd6
'phi', # 0xd7
'chi', # 0xd8
'psi', # 0xd9
'omega', # 0xda
'', # 0xdb
'', # 0xdc
'', # 0xdd
'', # 0xde
'', # 0xdf
'', # 0xe0
'', # 0xe1
'', # 0xe2
'', # 0xe3
'', # 0xe4
'', # 0xe5
'', # 0xe6
'', # 0xe7
'', # 0xe8
'', # 0xe9
'', # 0xea
'', # 0xeb
'', # 0xec
'', # 0xed
'', # 0xee
'', # 0xef
'', # 0xf0
'', # 0xf1
'', # 0xf2
'', # 0xf3
'', # 0xf4
'', # 0xf5
'', # 0xf6
'', # 0xf7
'', # 0xf8
'', # 0xf9
'', # 0xfa
'', # 0xfb
'', # 0xfc
'', # 0xfd
'', # 0xfe
'', # 0xff
)
| data = ('s', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'i', 'j', '', '', 'Alpha', 'Beta', 'Gamma', 'Delta', 'Epsilon', 'Zeta', 'Eta', 'Theta', 'Iota', 'Kappa', 'Lamda', 'Mu', 'Nu', 'Xi', 'Omicron', 'Pi', 'Rho', 'Theta', 'Sigma', 'Tau', 'Upsilon', 'Phi', 'Chi', 'Psi', 'Omega', 'nabla', 'alpha', 'beta', 'gamma', 'delta', 'epsilon', 'zeta', 'eta', 'theta', 'iota', 'kappa', 'lamda', 'mu', 'nu', 'xi', 'omicron', 'pi', 'rho', 'sigma', 'sigma', 'tai', 'upsilon', 'phi', 'chi', 'psi', 'omega', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '') |
# MIT licensed
# Copyright (c) 2013-2020 lilydjwg <lilydjwg@gmail.com>, et al.
GEMS_URL = 'https://rubygems.org/api/v1/versions/%s.json'
async def get_version(name, conf, *, cache, **kwargs):
key = conf.get('gems', name)
data = await cache.get_json(GEMS_URL % key)
return data[0]['number']
| gems_url = 'https://rubygems.org/api/v1/versions/%s.json'
async def get_version(name, conf, *, cache, **kwargs):
key = conf.get('gems', name)
data = await cache.get_json(GEMS_URL % key)
return data[0]['number'] |
def msgme(*names):
for i in names:
print(i)
msgme("abc")
msgme("xyz",100)
msgme("apple","mango",1,2,3,7)
| def msgme(*names):
for i in names:
print(i)
msgme('abc')
msgme('xyz', 100)
msgme('apple', 'mango', 1, 2, 3, 7) |
class Dog:
species = 'caniche'
def __init__(self, name, age):
self.name = name
self.age = age
bambi = Dog("Bambi", 5)
mikey = Dog("Rufus", 6)
blacky = Dog("Fosca", 9)
coco = Dog("Coco", 13)
perla = Dog("Neska", 3)
print("{} is {} and {} is {}.". format(bambi.name, bambi.age, mikey.name, mikey.age))
if bambi.species == "caniche":
print("{0} is a {1}!".format(bambi.name, bambi.species))
def get_biggest_number (*argument):
max=0
for i in argument:
if (type(i) is int) == False:
return ("Error: Arguments must be integers")
if i>max:
max=i
return (max)
print('The biggest number among the given is: ' , get_biggest_number(1 , 4 , 5 , -4 , 6 , 123 , 0)) | class Dog:
species = 'caniche'
def __init__(self, name, age):
self.name = name
self.age = age
bambi = dog('Bambi', 5)
mikey = dog('Rufus', 6)
blacky = dog('Fosca', 9)
coco = dog('Coco', 13)
perla = dog('Neska', 3)
print('{} is {} and {} is {}.'.format(bambi.name, bambi.age, mikey.name, mikey.age))
if bambi.species == 'caniche':
print('{0} is a {1}!'.format(bambi.name, bambi.species))
def get_biggest_number(*argument):
max = 0
for i in argument:
if (type(i) is int) == False:
return 'Error: Arguments must be integers'
if i > max:
max = i
return max
print('The biggest number among the given is: ', get_biggest_number(1, 4, 5, -4, 6, 123, 0)) |
def getBuiltinTargs():
return {
"1": {
"name": "1",
"ptype": "maven2",
"patterns": [".*"],
"defincpat": ["**"],
"defexcpat": []
},
"2": {
"name": "2",
"ptype": "maven1",
"patterns": [".*"],
"defincpat": ["**"],
"defexcpat": []
},
"3": {
"name": "3",
"ptype": "maven2",
"patterns": ["(?!.*-sources.*).*"],
"defincpat": ["**"],
"defexcpat": ["**/*-sources.*/**"]
},
"4": {
"name": "4",
"ptype": "maven2",
"patterns": [".*maven-metadata\.xml.*"],
"defincpat": ["**/*maven-metadata.xml*"],
"defexcpat": []
},
"any": {
"name": "any",
"ptype": "any",
"patterns": [".*"],
"defincpat": ["**"],
"defexcpat": []
},
"site": {
"name": "site",
"ptype": "site",
"patterns": [".*"],
"defincpat": ["**"],
"defexcpat": []
},
"npm": {
"name": "npm",
"ptype": "npm",
"patterns": [".*"],
"defincpat": ["**"],
"defexcpat": []
},
"nuget": {
"name": "nuget",
"ptype": "nuget",
"patterns": [".*"],
"defincpat": ["**"],
"defexcpat": []
},
"rubygems": {
"name": "rubygems",
"ptype": "rubygems",
"patterns": [".*"],
"defincpat": ["**"],
"defexcpat": []
}
}
def getBuiltinPrivs(targs):
return {
"All M1 Repositories": {
"name": "All M1 Repositories",
"target": targs["2"],
"repo": "*",
"builtin": True
},
"All M2 Repositories": {
"name": "All M2 Repositories",
"target": targs["1"],
"repo": "*",
"builtin": True
},
"All npm Repositories": {
"name": "All npm Repositories",
"target": targs["npm"],
"repo": "*",
"builtin": True
},
"All NuGet Repositories": {
"name": "All NuGet Repositories",
"target": targs["nuget"],
"repo": "*",
"builtin": True
},
"All Repositories": {
"name": "All Repositories",
"target": targs["any"],
"repo": "*",
"builtin": True
},
"All Rubygems Repositories": {
"name": "All Rubygems Repositories",
"target": targs["rubygems"],
"repo": "*",
"builtin": True
},
"All Site Repositories": {
"name": "All Site Repositories",
"target": targs["site"],
"repo": "*",
"builtin": True
}
}
def getBuiltinPrivmap(privs):
return {
"repository-all": {
"id": "repository-all",
"repo": "*",
"type": "view",
"needadmin": False
},
"T6": {
"id": "T6",
"method": "create",
"priv": privs["All M1 Repositories"],
"type": "target",
"needadmin": False
},
"T8": {
"id": "T8",
"method": "delete",
"priv": privs["All M1 Repositories"],
"type": "target",
"needadmin": False
},
"T2": {
"id": "T2",
"method": "read",
"priv": privs["All M1 Repositories"],
"type": "target",
"needadmin": False
},
"T4": {
"id": "T4",
"method": "update",
"priv": privs["All M1 Repositories"],
"type": "target",
"needadmin": False
},
"T5": {
"id": "T5",
"method": "create",
"priv": privs["All M2 Repositories"],
"type": "target",
"needadmin": False
},
"T7": {
"id": "T7",
"method": "delete",
"priv": privs["All M2 Repositories"],
"type": "target",
"needadmin": False
},
"T1": {
"id": "T1",
"method": "read",
"priv": privs["All M2 Repositories"],
"type": "target",
"needadmin": False
},
"T3": {
"id": "T3",
"method": "update",
"priv": privs["All M2 Repositories"],
"type": "target",
"needadmin": False
},
"npm-create": {
"id": "npm-create",
"method": "create",
"priv": privs["All npm Repositories"],
"type": "target",
"needadmin": False
},
"npm-delete": {
"id": "npm-delete",
"method": "delete",
"priv": privs["All npm Repositories"],
"type": "target",
"needadmin": False
},
"npm-read": {
"id": "npm-read",
"method": "read",
"priv": privs["All npm Repositories"],
"type": "target",
"needadmin": False
},
"npm-update": {
"id": "npm-update",
"method": "update",
"priv": privs["All npm Repositories"],
"type": "target",
"needadmin": False
},
"nuget-create": {
"id": "nuget-create",
"method": "create",
"priv": privs["All NuGet Repositories"],
"type": "target",
"needadmin": False
},
"nuget-delete": {
"id": "nuget-delete",
"method": "delete",
"priv": privs["All NuGet Repositories"],
"type": "target",
"needadmin": False
},
"nuget-read": {
"id": "nuget-read",
"method": "read",
"priv": privs["All NuGet Repositories"],
"type": "target",
"needadmin": False
},
"nuget-update": {
"id": "nuget-update",
"method": "update",
"priv": privs["All NuGet Repositories"],
"type": "target",
"needadmin": False
},
"T11": {
"id": "T11",
"method": "create",
"priv": privs["All Repositories"],
"type": "target",
"needadmin": False
},
"T12": {
"id": "T12",
"method": "delete",
"priv": privs["All Repositories"],
"type": "target",
"needadmin": False
},
"T9": {
"id": "T9",
"method": "read",
"priv": privs["All Repositories"],
"type": "target",
"needadmin": False
},
"T10": {
"id": "T10",
"method": "update",
"priv": privs["All Repositories"],
"type": "target",
"needadmin": False
},
"rubygems-create": {
"id": "rubygems-create",
"method": "create",
"priv": privs["All Rubygems Repositories"],
"type": "target",
"needadmin": False
},
"rubygems-delete": {
"id": "rubygems-delete",
"method": "delete",
"priv": privs["All Rubygems Repositories"],
"type": "target",
"needadmin": False
},
"rubygems-read": {
"id": "rubygems-read",
"method": "read",
"priv": privs["All Rubygems Repositories"],
"type": "target",
"needadmin": False
},
"rubygems-update": {
"id": "rubygems-update",
"method": "update",
"priv": privs["All Rubygems Repositories"],
"type": "target",
"needadmin": False
},
"site-create": {
"id": "site-create",
"method": "create",
"priv": privs["All Site Repositories"],
"type": "target",
"needadmin": False
},
"site-delete": {
"id": "site-delete",
"method": "delete",
"priv": privs["All Site Repositories"],
"type": "target",
"needadmin": False
},
"site-read": {
"id": "site-read",
"method": "read",
"priv": privs["All Site Repositories"],
"type": "target",
"needadmin": False
},
"site-update": {
"id": "site-update",
"method": "update",
"priv": privs["All Site Repositories"],
"type": "target",
"needadmin": False
},
"1000": {
"id": "1000",
"method": "*",
"permission": "nexus:*",
"type": "application",
"needadmin": True
},
"analytics-all": {
"id": "analytics-all",
"method": "*",
"permission": "nexus:analytics",
"type": "application",
"needadmin": False
},
"83": {
"id": "83",
"method": "*",
"permission": "apikey:access",
"type": "application",
"needadmin": False
},
"54": {
"id": "54",
"method": "read",
"permission": "nexus:artifact",
"type": "application",
"needadmin": False
},
"65": {
"id": "65",
"method": "create,read",
"permission": "nexus:artifact",
"type": "application",
"needadmin": False
},
"atlas-all": {
"id": "atlas-all",
"method": "*",
"permission": "nexus:atlas",
"type": "application",
"needadmin": False
},
"browse-remote-repo": {
"id": "browse-remote-repo",
"method": "read",
"permission": "nexus:browseremote",
"type": "application",
"needadmin": False
},
"capabilities-create-read": {
"id": "capabilities-create-read",
"method": "create,read",
"permission": "nexus:capabilities",
"type": "application",
"needadmin": False
},
"capabilities-delete-read": {
"id": "capabilities-delete-read",
"method": "delete,read",
"permission": "nexus:capabilities",
"type": "application",
"needadmin": False
},
"capabilities-read": {
"id": "capabilities-read",
"method": "read",
"permission": "nexus:capabilities",
"type": "application",
"needadmin": False
},
"capabilities-update-read": {
"id": "capabilities-update-read",
"method": "update,read",
"permission": "nexus:capabilities",
"type": "application",
"needadmin": False
},
"capability-types-read": {
"id": "capability-types-read",
"method": "read",
"permission": "nexus:capabilityTypes",
"type": "application",
"needadmin": False
},
"19": {
"id": "19",
"method": "read",
"permission": "nexus:identify",
"type": "application",
"needadmin": False
},
"21": {
"id": "21",
"method": "delete,read",
"permission": "nexus:cache",
"type": "application",
"needadmin": True
},
"43": {
"id": "43",
"method": "read",
"permission": "nexus:configuration",
"type": "application",
"needadmin": False
},
"nexus-healthcheck-read": {
"id": "nexus-healthcheck-read",
"method": "read",
"permission": "nexus:healthcheck",
"type": "application",
"needadmin": False
},
"nexus-healthcheck-update": {
"id": "nexus-healthcheck-update",
"method": "update",
"permission": "nexus:healthcheck",
"type": "application",
"needadmin": False
},
"nexus-healthcheck-summary-read": {
"id": "nexus-healthcheck-summary-read",
"method": "read",
"permission": "nexus:healthchecksummary",
"type": "application",
"needadmin": False
},
"ldap-conn-read": {
"id": "ldap-conn-read",
"method": "read",
"permission": "nexus:ldapconninfo",
"type": "application",
"needadmin": False
},
"ldap-conn-update": {
"id": "ldap-conn-update",
"method": "update",
"permission": "nexus:ldapconninfo",
"type": "application",
"needadmin": True
},
"ldap-test-auth-conf": {
"id": "ldap-test-auth-conf",
"method": "update",
"permission": "nexus:ldaptestauth",
"type": "application",
"needadmin": True
},
"ldap-test-user-group-conf": {
"id": "ldap-test-user-group-conf",
"method": "update",
"permission": "nexus:ldaptestuserconf",
"type": "application",
"needadmin": True
},
"ldap-user-group-conf-read": {
"id": "ldap-user-group-conf-read",
"method": "read",
"permission": "nexus:ldapusergroupconf",
"type": "application",
"needadmin": False
},
"ldap-user-group-conf-update": {
"id": "ldap-user-group-conf-update",
"method": "update",
"permission": "nexus:ldapusergroupconf",
"type": "application",
"needadmin": True
},
"ldap-user-role-map-create": {
"id": "ldap-user-role-map-create",
"method": "create",
"permission": "nexus:ldapuserrolemap",
"type": "application",
"needadmin": True
},
"ldap-user-role-map-delete": {
"id": "ldap-user-role-map-delete",
"method": "delete,read",
"permission": "nexus:ldapuserrolemap",
"type": "application",
"needadmin": True
},
"ldap-user-role-map-read": {
"id": "ldap-user-role-map-read",
"method": "read",
"permission": "nexus:ldapuserrolemap",
"type": "application",
"needadmin": False
},
"ldap-user-role-map-update": {
"id": "ldap-user-role-map-update",
"method": "update",
"permission": "nexus:ldapuserrolemap",
"type": "application",
"needadmin": True
},
"77": {
"id": "77",
"method": "read,update",
"permission": "nexus:logconfig",
"type": "application",
"needadmin": False
},
"2": {
"id": "2",
"method": "read",
"permission": "nexus:authentication",
"type": "application",
"needadmin": False
},
"42": {
"id": "42",
"method": "read",
"permission": "nexus:logs",
"type": "application",
"needadmin": False
},
"metrics-endpoints": {
"id": "metrics-endpoints",
"method": "*",
"permission": "nexus:metrics-endpoints",
"type": "application",
"needadmin": False
},
"66": {
"id": "66",
"method": "update,read",
"permission": "nexus:command",
"type": "application",
"needadmin": False
},
"plugin-infos-read": {
"id": "plugin-infos-read",
"method": "read",
"permission": "nexus:pluginconsoleplugininfos",
"type": "application",
"needadmin": False
},
"55": {
"id": "55",
"method": "read",
"permission": "nexus:repostatus",
"type": "application",
"needadmin": False
},
"73": {
"id": "73",
"method": "read",
"permission": "nexus:componentrealmtypes",
"type": "application",
"needadmin": False
},
"76": {
"id": "76",
"method": "delete,read",
"permission": "nexus:metadata",
"type": "application",
"needadmin": False
},
"20": {
"id": "20",
"method": "delete,read",
"permission": "nexus:attributes",
"type": "application",
"needadmin": False
},
"18": {
"id": "18",
"method": "delete,read",
"permission": "nexus:index",
"type": "application",
"needadmin": False
},
"5": {
"id": "5",
"method": "create,read",
"permission": "nexus:repositories",
"type": "application",
"needadmin": True
},
"8": {
"id": "8",
"method": "delete,read",
"permission": "nexus:repositories",
"type": "application",
"needadmin": True
},
"6": {
"id": "6",
"method": "read",
"permission": "nexus:repositories",
"type": "application",
"needadmin": False
},
"7": {
"id": "7",
"method": "update,read",
"permission": "nexus:repositories",
"type": "application",
"needadmin": True
},
"70": {
"id": "70",
"method": "read",
"permission": "nexus:componentscontentclasses",
"type": "application",
"needadmin": False
},
"13": {
"id": "13",
"method": "create,read",
"permission": "nexus:repogroups",
"type": "application",
"needadmin": True
},
"16": {
"id": "16",
"method": "delete,read",
"permission": "nexus:repogroups",
"type": "application",
"needadmin": True
},
"14": {
"id": "14",
"method": "read",
"permission": "nexus:repogroups",
"type": "application",
"needadmin": False
},
"15": {
"id": "15",
"method": "update,read",
"permission": "nexus:repogroups",
"type": "application",
"needadmin": True
},
"79": {
"id": "79",
"method": "create,read",
"permission": "nexus:repositorymirrors",
"type": "application",
"needadmin": False
},
"78": {
"id": "78",
"method": "read",
"permission": "nexus:repositorymirrors",
"type": "application",
"needadmin": False
},
"82": {
"id": "82",
"method": "read",
"permission": "nexus:repositorymirrorsstatus",
"type": "application",
"needadmin": False
},
"81": {
"id": "81",
"method": "read",
"permission": "nexus:repositorypredefinedmirrors",
"type": "application",
"needadmin": False
},
"22": {
"id": "22",
"method": "create,read",
"permission": "nexus:routes",
"type": "application",
"needadmin": False
},
"25": {
"id": "25",
"method": "delete,read",
"permission": "nexus:routes",
"type": "application",
"needadmin": False
},
"23": {
"id": "23",
"method": "read",
"permission": "nexus:routes",
"type": "application",
"needadmin": False
},
"24": {
"id": "24",
"method": "update,read",
"permission": "nexus:routes",
"type": "application",
"needadmin": False
},
"67": {
"id": "67",
"method": "read",
"permission": "nexus:repometa",
"type": "application",
"needadmin": False
},
"45": {
"id": "45",
"method": "create,read",
"permission": "nexus:targets",
"type": "application",
"needadmin": True
},
"48": {
"id": "48",
"method": "delete,read",
"permission": "nexus:targets",
"type": "application",
"needadmin": True
},
"46": {
"id": "46",
"method": "read",
"permission": "nexus:targets",
"type": "application",
"needadmin": False
},
"47": {
"id": "47",
"method": "update,read",
"permission": "nexus:targets",
"type": "application",
"needadmin": True
},
"9": {
"id": "9",
"method": "create,read",
"permission": "nexus:repotemplates",
"type": "application",
"needadmin": False
},
"12": {
"id": "12",
"method": "delete,read",
"permission": "nexus:repotemplates",
"type": "application",
"needadmin": False
},
"10": {
"id": "10",
"method": "read",
"permission": "nexus:repotemplates",
"type": "application",
"needadmin": False
},
"11": {
"id": "11",
"method": "update,read",
"permission": "nexus:repotemplates",
"type": "application",
"needadmin": False
},
"74": {
"id": "74",
"method": "read",
"permission": "nexus:componentsrepotypes",
"type": "application",
"needadmin": False
},
"44": {
"id": "44",
"method": "read",
"permission": "nexus:feeds",
"type": "application",
"needadmin": False
},
"69": {
"id": "69",
"method": "read",
"permission": "nexus:tasktypes",
"type": "application",
"needadmin": False
},
"71": {
"id": "71",
"method": "read",
"permission": "nexus:componentscheduletypes",
"type": "application",
"needadmin": False
},
"26": {
"id": "26",
"method": "create,read",
"permission": "nexus:tasks",
"type": "application",
"needadmin": True
},
"29": {
"id": "29",
"method": "delete,read",
"permission": "nexus:tasks",
"type": "application",
"needadmin": True
},
"27": {
"id": "27",
"method": "read",
"permission": "nexus:tasks",
"type": "application",
"needadmin": False
},
"68": {
"id": "68",
"method": "read,delete",
"permission": "nexus:tasksrun",
"type": "application",
"needadmin": True
},
"28": {
"id": "28",
"method": "update,read",
"permission": "nexus:tasks",
"type": "application",
"needadmin": True
},
"17": {
"id": "17",
"method": "read",
"permission": "nexus:index",
"type": "application",
"needadmin": False
},
"1001": {
"id": "1001",
"method": "*",
"permission": "security:*",
"type": "application",
"needadmin": True
},
"3": {
"id": "3",
"method": "read",
"permission": "nexus:settings",
"type": "application",
"needadmin": False
},
"4": {
"id": "4",
"method": "update,read",
"permission": "nexus:settings",
"type": "application",
"needadmin": True
},
"49": {
"id": "49",
"method": "update,read",
"permission": "nexus:status",
"type": "application",
"needadmin": True
},
"1": {
"id": "1",
"method": "read",
"permission": "nexus:status",
"type": "application",
"needadmin": False
},
"56": {
"id": "56",
"method": "update",
"permission": "nexus:repostatus",
"type": "application",
"needadmin": True
},
"64": {
"id": "64",
"method": "create,read",
"permission": "security:userschangepw",
"type": "application",
"needadmin": False
},
"57": {
"id": "57",
"method": "create,read",
"permission": "security:usersforgotpw",
"type": "application",
"needadmin": False
},
"58": {
"id": "58",
"method": "create,read",
"permission": "security:usersforgotid",
"type": "application",
"needadmin": False
},
"75": {
"id": "75",
"method": "read",
"permission": "security:componentsuserlocatortypes",
"type": "application",
"needadmin": False
},
"80": {
"id": "80",
"method": "read",
"permission": "security:privilegetypes",
"type": "application",
"needadmin": False
},
"30": {
"id": "30",
"method": "create,read",
"permission": "security:privileges",
"type": "application",
"needadmin": True
},
"33": {
"id": "33",
"method": "delete,read",
"permission": "security:privileges",
"type": "application",
"needadmin": True
},
"31": {
"id": "31",
"method": "read",
"permission": "security:privileges",
"type": "application",
"needadmin": False
},
"32": {
"id": "32",
"method": "update,read",
"permission": "security:privileges",
"type": "application",
"needadmin": True
},
"59": {
"id": "59",
"method": "delete,read",
"permission": "security:usersreset",
"type": "application",
"needadmin": True
},
"34": {
"id": "34",
"method": "create,read",
"permission": "security:roles",
"type": "application",
"needadmin": True
},
"37": {
"id": "37",
"method": "delete,read",
"permission": "security:roles",
"type": "application",
"needadmin": True
},
"35": {
"id": "35",
"method": "read",
"permission": "security:roles",
"type": "application",
"needadmin": False
},
"36": {
"id": "36",
"method": "update,read",
"permission": "security:roles",
"type": "application",
"needadmin": True
},
"72": {
"id": "72",
"method": "create,read",
"permission": "security:userssetpw",
"type": "application",
"needadmin": True
},
"38": {
"id": "38",
"method": "create,read",
"permission": "security:users",
"type": "application",
"needadmin": True
},
"41": {
"id": "41",
"method": "delete,read",
"permission": "security:users",
"type": "application",
"needadmin": True
},
"39": {
"id": "39",
"method": "read",
"permission": "security:users",
"type": "application",
"needadmin": False
},
"40": {
"id": "40",
"method": "update,read",
"permission": "security:users",
"type": "application",
"needadmin": True
},
"51": {
"id": "51",
"method": "delete,read",
"permission": "nexus:wastebasket",
"type": "application",
"needadmin": False
},
"50": {
"id": "50",
"method": "read",
"permission": "nexus:wastebasket",
"type": "application",
"needadmin": False
},
"wonderland-all": {
"id": "wonderland-all",
"method": "*",
"permission": "nexus:wonderland",
"type": "application",
"needadmin": False
},
"yum-alias-read": {
"id": "yum-alias-read",
"method": "read",
"permission": "nexus:yumAlias",
"type": "application",
"needadmin": False
},
"yum-alias-create-read": {
"id": "yum-alias-create-read",
"method": "create,update,read",
"permission": "nexus:yumAlias",
"type": "application",
"needadmin": False
},
"yum-repository-read": {
"id": "yum-repository-read",
"method": "read",
"permission": "nexus:yumVersionedRepositories",
"type": "application",
"needadmin": False
}
}
def getBuiltinRoles(privmap):
return {
"analytics": {
"groupName": "analytics",
"description": "Gives access to Analytics",
"privileges": [
privmap["analytics-all"]
],
"roles": [],
"admin": False,
"builtin": True
},
"atlas": {
"groupName": "atlas",
"description": "Gives access to Atlas support tools",
"privileges": [
privmap["atlas-all"]
],
"roles": [],
"admin": False,
"builtin": True
},
"metrics-endpoints": {
"groupName": "metrics-endpoints",
"description": "Allows access to metrics endpoints.",
"privileges": [
privmap["metrics-endpoints"]
],
"roles": [],
"admin": False,
"builtin": True
},
"nx-admin": {
"groupName": "nx-admin",
"description": "Administration role for Nexus",
"privileges": [
privmap["1001"],
privmap["1000"],
privmap["83"]
],
"roles": [],
"admin": True,
"builtin": True
},
"anonymous": {
"groupName": "anonymous",
"description": "Anonymous role for Nexus",
"privileges": [
privmap["1"],
privmap["57"],
privmap["58"],
privmap["70"],
privmap["74"],
privmap["54"]
],
"roles": [
"ui-healthcheck-read",
"ui-search",
"ui-repo-browser",
],
"admin": False,
"builtin": True
},
"nx-apikey-access": {
"groupName": "nx-apikey-access",
"description": "API-Key Access role for Nexus.",
"privileges": [
privmap["83"]
],
"roles": [],
"admin": False,
"builtin": True
},
"nx-deployment": {
"groupName": "nx-deployment",
"description": "Deployment role for Nexus",
"privileges": [
privmap["83"]
],
"roles": [
"ui-basic",
"anonymous",
],
"admin": False,
"builtin": True
},
"nx-developer": {
"groupName": "nx-developer",
"description": "Developer role for Nexus",
"privileges": [],
"roles": [
"ui-basic",
"nx-deployment",
],
"admin": False,
"builtin": True
},
"nexus-yum-admin": {
"groupName": "nexus-yum-admin",
"description": "Gives access to read versioned yum repositories and administrate version aliases",
"privileges": [
privmap["yum-repository-read"],
privmap["yum-alias-create-read"],
privmap["yum-alias-read"]
],
"roles": [],
"admin": False,
"builtin": True
},
"nexus-yum-user": {
"groupName": "nexus-yum-user",
"description": "Gives access to read versioned yum repositories",
"privileges": [
privmap["yum-repository-read"]
],
"roles": [],
"admin": False,
"builtin": True
},
"any-all-view": {
"groupName": "any-all-view",
"description": "Gives access to view ALL Repositories in Nexus.",
"privileges": [],
"roles": [],
"admin": False,
"builtin": True
},
"repo-all-full": {
"groupName": "repo-all-full",
"description": "Gives access to create/read/update/delete ALL content of ALL Maven1 and Maven2 repositories in Nexus.",
"privileges": [
privmap["T4"],
privmap["T5"],
privmap["T6"],
privmap["T7"],
privmap["T8"],
privmap["repository-all"],
privmap["T1"],
privmap["T2"],
privmap["T3"]
],
"roles": [],
"admin": False,
"builtin": True
},
"repo-all-read": {
"groupName": "repo-all-read",
"description": "Gives access to read ALL content of ALL Maven1 and Maven2 repositories in Nexus.",
"privileges": [
privmap["repository-all"],
privmap["T1"],
privmap["T2"]
],
"roles": [],
"admin": False,
"builtin": True
},
"maven1-all-view": {
"groupName": "maven1-all-view",
"description": "Gives access to view ALL Maven1 Repositories in Nexus.",
"privileges": [],
"roles": [],
"admin": False,
"builtin": True
},
"maven2-all-view": {
"groupName": "maven2-all-view",
"description": "Gives access to view ALL Maven2 Repositories in Nexus.",
"privileges": [],
"roles": [],
"admin": False,
"builtin": True
},
"npm-all-full": {
"groupName": "npm-all-full",
"description": "Gives access to create/read/update/delete ALL content of ALL npm Repositories in Nexus.",
"privileges": [
privmap["npm-read"],
privmap["npm-create"],
privmap["npm-delete"],
privmap["npm-update"]
],
"roles": [
"npm-all-view",
],
"admin": False,
"builtin": True
},
"npm-all-read": {
"groupName": "npm-all-read",
"description": "Gives access to read ALL content of ALL npm Repositories in Nexus.",
"privileges": [
privmap["npm-read"]
],
"roles": [
"npm-all-view",
],
"admin": False,
"builtin": True
},
"npm-all-view": {
"groupName": "npm-all-view",
"description": "Gives access to view ALL npm Repositories in Nexus.",
"privileges": [],
"roles": [],
"admin": False,
"builtin": True
},
"nuget-all-full": {
"groupName": "nuget-all-full",
"description": "Gives access to create/read/update/delete ALL content of ALL NuGet Repositories in Nexus.",
"privileges": [
privmap["nuget-read"],
privmap["nuget-create"],
privmap["nuget-delete"],
privmap["nuget-update"]
],
"roles": [
"nuget-all-view",
],
"admin": False,
"builtin": True
},
"nuget-all-read": {
"groupName": "nuget-all-read",
"description": "Gives access to read ALL content of ALL NuGet Repositories in Nexus.",
"privileges": [
privmap["nuget-read"]
],
"roles": [
"nuget-all-view",
],
"admin": False,
"builtin": True
},
"nuget-all-view": {
"groupName": "nuget-all-view",
"description": "Gives access to view ALL NuGet Repositories in Nexus.",
"privileges": [],
"roles": [],
"admin": False,
"builtin": True
},
"repository-any-full": {
"groupName": "repository-any-full",
"description": "Gives access to create/read/update/delete ALL content of ALL repositories in Nexus.",
"privileges": [
privmap["T10"],
privmap["T12"],
privmap["repository-all"],
privmap["T9"],
privmap["T11"]
],
"roles": [],
"admin": False,
"builtin": True
},
"repository-any-read": {
"groupName": "repository-any-read",
"description": "Gives access to read ALL content of ALL repositories in Nexus.",
"privileges": [
privmap["repository-all"],
privmap["T9"]
],
"roles": [],
"admin": False,
"builtin": True
},
"rubygems-all-full": {
"groupName": "rubygems-all-full",
"description": "Gives access to create/read/update/delete ALL content of ALL Rubygems Repositories in Nexus.",
"privileges": [
privmap["rubygems-create"],
privmap["rubygems-delete"],
privmap["rubygems-read"],
privmap["rubygems-update"]
],
"roles": [
"rubygems-all-view",
],
"admin": False,
"builtin": True
},
"rubygems-all-read": {
"groupName": "rubygems-all-read",
"description": "Gives access to read ALL content of ALL Rubygems Repositories in Nexus.",
"privileges": [
privmap["rubygems-read"]
],
"roles": [
"rubygems-all-view",
],
"admin": False,
"builtin": True
},
"rubygems-all-view": {
"groupName": "rubygems-all-view",
"description": "Gives access to view ALL Rubygems Repositories in Nexus.",
"privileges": [],
"roles": [],
"admin": False,
"builtin": True
},
"site-all-full": {
"groupName": "site-all-full",
"description": "Gives access to create/read/update/delete ALL content of ALL Site Repositories in Nexus.",
"privileges": [
privmap["site-create"],
privmap["site-update"],
privmap["site-delete"],
privmap["repository-all"],
privmap["site-read"]
],
"roles": [],
"admin": False,
"builtin": True
},
"site-all-read": {
"groupName": "site-all-read",
"description": "Gives access to read ALL content of ALL Site Repositories in Nexus.",
"privileges": [
privmap["repository-all"],
privmap["site-read"]
],
"roles": [],
"admin": False,
"builtin": True
},
"site-all-view": {
"groupName": "site-all-view",
"description": "Gives access to view ALL Site Repositories in Nexus.",
"privileges": [],
"roles": [],
"admin": False,
"builtin": True
},
"ui-basic": {
"groupName": "ui-basic",
"description": "Generic privileges for users in the Nexus UI",
"privileges": [
privmap["1"],
privmap["2"],
privmap["64"]
],
"roles": [],
"admin": False,
"builtin": True
},
"ui-capabilities-admin": {
"groupName": "ui-capabilities-admin",
"description": "Gives access to Capabilities Administration screen in Nexus UI",
"privileges": [
privmap["capabilities-read"],
privmap["capability-types-read"],
privmap["14"],
privmap["capabilities-update-read"],
privmap["6"],
privmap["capabilities-delete-read"],
privmap["capabilities-create-read"]
],
"roles": [],
"admin": False,
"builtin": True
},
"ui-group-admin": {
"groupName": "ui-group-admin",
"description": "Gives access to the Group Administration screen in Nexus UI",
"privileges": [
privmap["13"],
privmap["14"],
privmap["15"],
privmap["repository-all"],
privmap["16"],
privmap["6"]
],
"roles": [
"ui-repo-browser",
],
"admin": False,
"builtin": True
},
"ui-healthcheck-full": {
"groupName": "ui-healthcheck-full",
"description": "Gives access to view and enable/disable the health check for repositories, along with some additional artifact data",
"privileges": [
privmap["nexus-healthcheck-update"]
],
"roles": [
"ui-healthcheck-read",
],
"admin": False,
"builtin": True
},
"ui-healthcheck-read": {
"groupName": "ui-healthcheck-read",
"description": "Gives access to view the health check summary for repositories",
"privileges": [
privmap["nexus-healthcheck-summary-read"],
privmap["nexus-healthcheck-read"]
],
"roles": [],
"admin": False,
"builtin": True
},
"ui-ldap-admin": {
"groupName": "ui-ldap-admin",
"description": "Gives access to configure the LDAP server used for authentication.",
"privileges": [
privmap["ldap-conn-read"],
privmap["ldap-user-group-conf-update"],
privmap["ldap-user-role-map-create"],
privmap["ldap-conn-update"],
privmap["ldap-test-auth-conf"],
privmap["ldap-user-role-map-update"],
privmap["ldap-user-role-map-read"],
privmap["ldap-user-role-map-delete"],
privmap["ldap-user-group-conf-read"],
privmap["ldap-test-user-group-conf"]
],
"roles": [
"ui-server-admin",
],
"admin": False,
"builtin": True
},
"ui-logs-config-files": {
"groupName": "ui-logs-config-files",
"description": "Gives access to the Logs and Config Files screen in Nexus UI",
"privileges": [
privmap["42"],
privmap["43"]
],
"roles": [],
"admin": False,
"builtin": True
},
"ui-plugin-console": {
"groupName": "ui-plugin-console",
"description": "Gives access to the Plugin Console screen in Nexus UI.",
"privileges": [
privmap["plugin-infos-read"]
],
"roles": [],
"admin": False,
"builtin": True
},
"ui-privileges-admin": {
"groupName": "ui-privileges-admin",
"description": "Gives access to the Privilege Administration screen in Nexus UI",
"privileges": [
privmap["33"],
privmap["46"],
privmap["14"],
privmap["6"],
privmap["80"],
privmap["30"],
privmap["31"],
privmap["32"]
],
"roles": [],
"admin": False,
"builtin": True
},
"ui-repository-admin": {
"groupName": "ui-repository-admin",
"description": "Gives access to the Repository Administration screen in Nexus UI",
"privileges": [
privmap["78"],
privmap["79"],
privmap["repository-all"],
privmap["5"],
privmap["6"],
privmap["7"],
privmap["8"],
privmap["81"],
privmap["82"],
privmap["74"],
privmap["10"]
],
"roles": [
"ui-repo-browser",
],
"admin": False,
"builtin": True
},
"ui-repo-browser": {
"groupName": "ui-repo-browser",
"description": "Gives access to the Repository Browser screen in Nexus UI",
"privileges": [
privmap["55"],
privmap["14"],
privmap["6"],
privmap["browse-remote-repo"]
],
"roles": [],
"admin": False,
"builtin": True
},
"ui-repository-targets-admin": {
"groupName": "ui-repository-targets-admin",
"description": "Gives access to the Repository Target Administration screen in Nexus UI",
"privileges": [
privmap["45"],
privmap["46"],
privmap["47"],
privmap["48"],
privmap["70"],
privmap["74"]
],
"roles": [],
"admin": False,
"builtin": True
},
"ui-roles-admin": {
"groupName": "ui-roles-admin",
"description": "Gives access to the Role Administration screen in Nexus UI",
"privileges": [
privmap["34"],
privmap["35"],
privmap["36"],
privmap["37"],
privmap["31"]
],
"roles": [],
"admin": False,
"builtin": True
},
"ui-routing-admin": {
"groupName": "ui-routing-admin",
"description": "Gives access to the Routing Administration screen in Nexus UI",
"privileges": [
privmap["22"],
privmap["23"],
privmap["24"],
privmap["14"],
privmap["25"],
privmap["6"]
],
"roles": [],
"admin": False,
"builtin": True
},
"ui-scheduled-tasks-admin": {
"groupName": "ui-scheduled-tasks-admin",
"description": "Gives access to the Scheduled Task Administration screen in Nexus UI",
"privileges": [
privmap["68"],
privmap["14"],
privmap["69"],
privmap["26"],
privmap["27"],
privmap["6"],
privmap["28"],
privmap["29"],
privmap["71"]
],
"roles": [],
"admin": False,
"builtin": True
},
"ui-search": {
"groupName": "ui-search",
"description": "Gives access to the Search screen in Nexus UI",
"privileges": [
privmap["17"],
privmap["19"],
privmap["54"]
],
"roles": [],
"admin": False,
"builtin": True
},
"ui-server-admin": {
"groupName": "ui-server-admin",
"description": "Gives access to the Server Administration screen in Nexus UI",
"privileges": [
privmap["3"],
privmap["4"],
privmap["73"]
],
"roles": [],
"admin": False,
"builtin": True
},
"ui-system-feeds": {
"groupName": "ui-system-feeds",
"description": "Gives access to the System Feeds screen in Nexus UI",
"privileges": [
privmap["44"]
],
"roles": [],
"admin": False,
"builtin": True
},
"ui-users-admin": {
"groupName": "ui-users-admin",
"description": "Gives access to the User Administration screen in Nexus UI",
"privileges": [
privmap["35"],
privmap["38"],
privmap["39"],
privmap["72"],
privmap["40"],
privmap["41"],
privmap["75"]
],
"roles": [],
"admin": False,
"builtin": True
},
"wonderland": {
"groupName": "wonderland",
"description": "Gives access to Wonderland",
"privileges": [
privmap["wonderland-all"]
],
"roles": [],
"admin": False,
"builtin": True
}
}
| def get_builtin_targs():
return {'1': {'name': '1', 'ptype': 'maven2', 'patterns': ['.*'], 'defincpat': ['**'], 'defexcpat': []}, '2': {'name': '2', 'ptype': 'maven1', 'patterns': ['.*'], 'defincpat': ['**'], 'defexcpat': []}, '3': {'name': '3', 'ptype': 'maven2', 'patterns': ['(?!.*-sources.*).*'], 'defincpat': ['**'], 'defexcpat': ['**/*-sources.*/**']}, '4': {'name': '4', 'ptype': 'maven2', 'patterns': ['.*maven-metadata\\.xml.*'], 'defincpat': ['**/*maven-metadata.xml*'], 'defexcpat': []}, 'any': {'name': 'any', 'ptype': 'any', 'patterns': ['.*'], 'defincpat': ['**'], 'defexcpat': []}, 'site': {'name': 'site', 'ptype': 'site', 'patterns': ['.*'], 'defincpat': ['**'], 'defexcpat': []}, 'npm': {'name': 'npm', 'ptype': 'npm', 'patterns': ['.*'], 'defincpat': ['**'], 'defexcpat': []}, 'nuget': {'name': 'nuget', 'ptype': 'nuget', 'patterns': ['.*'], 'defincpat': ['**'], 'defexcpat': []}, 'rubygems': {'name': 'rubygems', 'ptype': 'rubygems', 'patterns': ['.*'], 'defincpat': ['**'], 'defexcpat': []}}
def get_builtin_privs(targs):
return {'All M1 Repositories': {'name': 'All M1 Repositories', 'target': targs['2'], 'repo': '*', 'builtin': True}, 'All M2 Repositories': {'name': 'All M2 Repositories', 'target': targs['1'], 'repo': '*', 'builtin': True}, 'All npm Repositories': {'name': 'All npm Repositories', 'target': targs['npm'], 'repo': '*', 'builtin': True}, 'All NuGet Repositories': {'name': 'All NuGet Repositories', 'target': targs['nuget'], 'repo': '*', 'builtin': True}, 'All Repositories': {'name': 'All Repositories', 'target': targs['any'], 'repo': '*', 'builtin': True}, 'All Rubygems Repositories': {'name': 'All Rubygems Repositories', 'target': targs['rubygems'], 'repo': '*', 'builtin': True}, 'All Site Repositories': {'name': 'All Site Repositories', 'target': targs['site'], 'repo': '*', 'builtin': True}}
def get_builtin_privmap(privs):
return {'repository-all': {'id': 'repository-all', 'repo': '*', 'type': 'view', 'needadmin': False}, 'T6': {'id': 'T6', 'method': 'create', 'priv': privs['All M1 Repositories'], 'type': 'target', 'needadmin': False}, 'T8': {'id': 'T8', 'method': 'delete', 'priv': privs['All M1 Repositories'], 'type': 'target', 'needadmin': False}, 'T2': {'id': 'T2', 'method': 'read', 'priv': privs['All M1 Repositories'], 'type': 'target', 'needadmin': False}, 'T4': {'id': 'T4', 'method': 'update', 'priv': privs['All M1 Repositories'], 'type': 'target', 'needadmin': False}, 'T5': {'id': 'T5', 'method': 'create', 'priv': privs['All M2 Repositories'], 'type': 'target', 'needadmin': False}, 'T7': {'id': 'T7', 'method': 'delete', 'priv': privs['All M2 Repositories'], 'type': 'target', 'needadmin': False}, 'T1': {'id': 'T1', 'method': 'read', 'priv': privs['All M2 Repositories'], 'type': 'target', 'needadmin': False}, 'T3': {'id': 'T3', 'method': 'update', 'priv': privs['All M2 Repositories'], 'type': 'target', 'needadmin': False}, 'npm-create': {'id': 'npm-create', 'method': 'create', 'priv': privs['All npm Repositories'], 'type': 'target', 'needadmin': False}, 'npm-delete': {'id': 'npm-delete', 'method': 'delete', 'priv': privs['All npm Repositories'], 'type': 'target', 'needadmin': False}, 'npm-read': {'id': 'npm-read', 'method': 'read', 'priv': privs['All npm Repositories'], 'type': 'target', 'needadmin': False}, 'npm-update': {'id': 'npm-update', 'method': 'update', 'priv': privs['All npm Repositories'], 'type': 'target', 'needadmin': False}, 'nuget-create': {'id': 'nuget-create', 'method': 'create', 'priv': privs['All NuGet Repositories'], 'type': 'target', 'needadmin': False}, 'nuget-delete': {'id': 'nuget-delete', 'method': 'delete', 'priv': privs['All NuGet Repositories'], 'type': 'target', 'needadmin': False}, 'nuget-read': {'id': 'nuget-read', 'method': 'read', 'priv': privs['All NuGet Repositories'], 'type': 'target', 'needadmin': False}, 'nuget-update': {'id': 'nuget-update', 'method': 'update', 'priv': privs['All NuGet Repositories'], 'type': 'target', 'needadmin': False}, 'T11': {'id': 'T11', 'method': 'create', 'priv': privs['All Repositories'], 'type': 'target', 'needadmin': False}, 'T12': {'id': 'T12', 'method': 'delete', 'priv': privs['All Repositories'], 'type': 'target', 'needadmin': False}, 'T9': {'id': 'T9', 'method': 'read', 'priv': privs['All Repositories'], 'type': 'target', 'needadmin': False}, 'T10': {'id': 'T10', 'method': 'update', 'priv': privs['All Repositories'], 'type': 'target', 'needadmin': False}, 'rubygems-create': {'id': 'rubygems-create', 'method': 'create', 'priv': privs['All Rubygems Repositories'], 'type': 'target', 'needadmin': False}, 'rubygems-delete': {'id': 'rubygems-delete', 'method': 'delete', 'priv': privs['All Rubygems Repositories'], 'type': 'target', 'needadmin': False}, 'rubygems-read': {'id': 'rubygems-read', 'method': 'read', 'priv': privs['All Rubygems Repositories'], 'type': 'target', 'needadmin': False}, 'rubygems-update': {'id': 'rubygems-update', 'method': 'update', 'priv': privs['All Rubygems Repositories'], 'type': 'target', 'needadmin': False}, 'site-create': {'id': 'site-create', 'method': 'create', 'priv': privs['All Site Repositories'], 'type': 'target', 'needadmin': False}, 'site-delete': {'id': 'site-delete', 'method': 'delete', 'priv': privs['All Site Repositories'], 'type': 'target', 'needadmin': False}, 'site-read': {'id': 'site-read', 'method': 'read', 'priv': privs['All Site Repositories'], 'type': 'target', 'needadmin': False}, 'site-update': {'id': 'site-update', 'method': 'update', 'priv': privs['All Site Repositories'], 'type': 'target', 'needadmin': False}, '1000': {'id': '1000', 'method': '*', 'permission': 'nexus:*', 'type': 'application', 'needadmin': True}, 'analytics-all': {'id': 'analytics-all', 'method': '*', 'permission': 'nexus:analytics', 'type': 'application', 'needadmin': False}, '83': {'id': '83', 'method': '*', 'permission': 'apikey:access', 'type': 'application', 'needadmin': False}, '54': {'id': '54', 'method': 'read', 'permission': 'nexus:artifact', 'type': 'application', 'needadmin': False}, '65': {'id': '65', 'method': 'create,read', 'permission': 'nexus:artifact', 'type': 'application', 'needadmin': False}, 'atlas-all': {'id': 'atlas-all', 'method': '*', 'permission': 'nexus:atlas', 'type': 'application', 'needadmin': False}, 'browse-remote-repo': {'id': 'browse-remote-repo', 'method': 'read', 'permission': 'nexus:browseremote', 'type': 'application', 'needadmin': False}, 'capabilities-create-read': {'id': 'capabilities-create-read', 'method': 'create,read', 'permission': 'nexus:capabilities', 'type': 'application', 'needadmin': False}, 'capabilities-delete-read': {'id': 'capabilities-delete-read', 'method': 'delete,read', 'permission': 'nexus:capabilities', 'type': 'application', 'needadmin': False}, 'capabilities-read': {'id': 'capabilities-read', 'method': 'read', 'permission': 'nexus:capabilities', 'type': 'application', 'needadmin': False}, 'capabilities-update-read': {'id': 'capabilities-update-read', 'method': 'update,read', 'permission': 'nexus:capabilities', 'type': 'application', 'needadmin': False}, 'capability-types-read': {'id': 'capability-types-read', 'method': 'read', 'permission': 'nexus:capabilityTypes', 'type': 'application', 'needadmin': False}, '19': {'id': '19', 'method': 'read', 'permission': 'nexus:identify', 'type': 'application', 'needadmin': False}, '21': {'id': '21', 'method': 'delete,read', 'permission': 'nexus:cache', 'type': 'application', 'needadmin': True}, '43': {'id': '43', 'method': 'read', 'permission': 'nexus:configuration', 'type': 'application', 'needadmin': False}, 'nexus-healthcheck-read': {'id': 'nexus-healthcheck-read', 'method': 'read', 'permission': 'nexus:healthcheck', 'type': 'application', 'needadmin': False}, 'nexus-healthcheck-update': {'id': 'nexus-healthcheck-update', 'method': 'update', 'permission': 'nexus:healthcheck', 'type': 'application', 'needadmin': False}, 'nexus-healthcheck-summary-read': {'id': 'nexus-healthcheck-summary-read', 'method': 'read', 'permission': 'nexus:healthchecksummary', 'type': 'application', 'needadmin': False}, 'ldap-conn-read': {'id': 'ldap-conn-read', 'method': 'read', 'permission': 'nexus:ldapconninfo', 'type': 'application', 'needadmin': False}, 'ldap-conn-update': {'id': 'ldap-conn-update', 'method': 'update', 'permission': 'nexus:ldapconninfo', 'type': 'application', 'needadmin': True}, 'ldap-test-auth-conf': {'id': 'ldap-test-auth-conf', 'method': 'update', 'permission': 'nexus:ldaptestauth', 'type': 'application', 'needadmin': True}, 'ldap-test-user-group-conf': {'id': 'ldap-test-user-group-conf', 'method': 'update', 'permission': 'nexus:ldaptestuserconf', 'type': 'application', 'needadmin': True}, 'ldap-user-group-conf-read': {'id': 'ldap-user-group-conf-read', 'method': 'read', 'permission': 'nexus:ldapusergroupconf', 'type': 'application', 'needadmin': False}, 'ldap-user-group-conf-update': {'id': 'ldap-user-group-conf-update', 'method': 'update', 'permission': 'nexus:ldapusergroupconf', 'type': 'application', 'needadmin': True}, 'ldap-user-role-map-create': {'id': 'ldap-user-role-map-create', 'method': 'create', 'permission': 'nexus:ldapuserrolemap', 'type': 'application', 'needadmin': True}, 'ldap-user-role-map-delete': {'id': 'ldap-user-role-map-delete', 'method': 'delete,read', 'permission': 'nexus:ldapuserrolemap', 'type': 'application', 'needadmin': True}, 'ldap-user-role-map-read': {'id': 'ldap-user-role-map-read', 'method': 'read', 'permission': 'nexus:ldapuserrolemap', 'type': 'application', 'needadmin': False}, 'ldap-user-role-map-update': {'id': 'ldap-user-role-map-update', 'method': 'update', 'permission': 'nexus:ldapuserrolemap', 'type': 'application', 'needadmin': True}, '77': {'id': '77', 'method': 'read,update', 'permission': 'nexus:logconfig', 'type': 'application', 'needadmin': False}, '2': {'id': '2', 'method': 'read', 'permission': 'nexus:authentication', 'type': 'application', 'needadmin': False}, '42': {'id': '42', 'method': 'read', 'permission': 'nexus:logs', 'type': 'application', 'needadmin': False}, 'metrics-endpoints': {'id': 'metrics-endpoints', 'method': '*', 'permission': 'nexus:metrics-endpoints', 'type': 'application', 'needadmin': False}, '66': {'id': '66', 'method': 'update,read', 'permission': 'nexus:command', 'type': 'application', 'needadmin': False}, 'plugin-infos-read': {'id': 'plugin-infos-read', 'method': 'read', 'permission': 'nexus:pluginconsoleplugininfos', 'type': 'application', 'needadmin': False}, '55': {'id': '55', 'method': 'read', 'permission': 'nexus:repostatus', 'type': 'application', 'needadmin': False}, '73': {'id': '73', 'method': 'read', 'permission': 'nexus:componentrealmtypes', 'type': 'application', 'needadmin': False}, '76': {'id': '76', 'method': 'delete,read', 'permission': 'nexus:metadata', 'type': 'application', 'needadmin': False}, '20': {'id': '20', 'method': 'delete,read', 'permission': 'nexus:attributes', 'type': 'application', 'needadmin': False}, '18': {'id': '18', 'method': 'delete,read', 'permission': 'nexus:index', 'type': 'application', 'needadmin': False}, '5': {'id': '5', 'method': 'create,read', 'permission': 'nexus:repositories', 'type': 'application', 'needadmin': True}, '8': {'id': '8', 'method': 'delete,read', 'permission': 'nexus:repositories', 'type': 'application', 'needadmin': True}, '6': {'id': '6', 'method': 'read', 'permission': 'nexus:repositories', 'type': 'application', 'needadmin': False}, '7': {'id': '7', 'method': 'update,read', 'permission': 'nexus:repositories', 'type': 'application', 'needadmin': True}, '70': {'id': '70', 'method': 'read', 'permission': 'nexus:componentscontentclasses', 'type': 'application', 'needadmin': False}, '13': {'id': '13', 'method': 'create,read', 'permission': 'nexus:repogroups', 'type': 'application', 'needadmin': True}, '16': {'id': '16', 'method': 'delete,read', 'permission': 'nexus:repogroups', 'type': 'application', 'needadmin': True}, '14': {'id': '14', 'method': 'read', 'permission': 'nexus:repogroups', 'type': 'application', 'needadmin': False}, '15': {'id': '15', 'method': 'update,read', 'permission': 'nexus:repogroups', 'type': 'application', 'needadmin': True}, '79': {'id': '79', 'method': 'create,read', 'permission': 'nexus:repositorymirrors', 'type': 'application', 'needadmin': False}, '78': {'id': '78', 'method': 'read', 'permission': 'nexus:repositorymirrors', 'type': 'application', 'needadmin': False}, '82': {'id': '82', 'method': 'read', 'permission': 'nexus:repositorymirrorsstatus', 'type': 'application', 'needadmin': False}, '81': {'id': '81', 'method': 'read', 'permission': 'nexus:repositorypredefinedmirrors', 'type': 'application', 'needadmin': False}, '22': {'id': '22', 'method': 'create,read', 'permission': 'nexus:routes', 'type': 'application', 'needadmin': False}, '25': {'id': '25', 'method': 'delete,read', 'permission': 'nexus:routes', 'type': 'application', 'needadmin': False}, '23': {'id': '23', 'method': 'read', 'permission': 'nexus:routes', 'type': 'application', 'needadmin': False}, '24': {'id': '24', 'method': 'update,read', 'permission': 'nexus:routes', 'type': 'application', 'needadmin': False}, '67': {'id': '67', 'method': 'read', 'permission': 'nexus:repometa', 'type': 'application', 'needadmin': False}, '45': {'id': '45', 'method': 'create,read', 'permission': 'nexus:targets', 'type': 'application', 'needadmin': True}, '48': {'id': '48', 'method': 'delete,read', 'permission': 'nexus:targets', 'type': 'application', 'needadmin': True}, '46': {'id': '46', 'method': 'read', 'permission': 'nexus:targets', 'type': 'application', 'needadmin': False}, '47': {'id': '47', 'method': 'update,read', 'permission': 'nexus:targets', 'type': 'application', 'needadmin': True}, '9': {'id': '9', 'method': 'create,read', 'permission': 'nexus:repotemplates', 'type': 'application', 'needadmin': False}, '12': {'id': '12', 'method': 'delete,read', 'permission': 'nexus:repotemplates', 'type': 'application', 'needadmin': False}, '10': {'id': '10', 'method': 'read', 'permission': 'nexus:repotemplates', 'type': 'application', 'needadmin': False}, '11': {'id': '11', 'method': 'update,read', 'permission': 'nexus:repotemplates', 'type': 'application', 'needadmin': False}, '74': {'id': '74', 'method': 'read', 'permission': 'nexus:componentsrepotypes', 'type': 'application', 'needadmin': False}, '44': {'id': '44', 'method': 'read', 'permission': 'nexus:feeds', 'type': 'application', 'needadmin': False}, '69': {'id': '69', 'method': 'read', 'permission': 'nexus:tasktypes', 'type': 'application', 'needadmin': False}, '71': {'id': '71', 'method': 'read', 'permission': 'nexus:componentscheduletypes', 'type': 'application', 'needadmin': False}, '26': {'id': '26', 'method': 'create,read', 'permission': 'nexus:tasks', 'type': 'application', 'needadmin': True}, '29': {'id': '29', 'method': 'delete,read', 'permission': 'nexus:tasks', 'type': 'application', 'needadmin': True}, '27': {'id': '27', 'method': 'read', 'permission': 'nexus:tasks', 'type': 'application', 'needadmin': False}, '68': {'id': '68', 'method': 'read,delete', 'permission': 'nexus:tasksrun', 'type': 'application', 'needadmin': True}, '28': {'id': '28', 'method': 'update,read', 'permission': 'nexus:tasks', 'type': 'application', 'needadmin': True}, '17': {'id': '17', 'method': 'read', 'permission': 'nexus:index', 'type': 'application', 'needadmin': False}, '1001': {'id': '1001', 'method': '*', 'permission': 'security:*', 'type': 'application', 'needadmin': True}, '3': {'id': '3', 'method': 'read', 'permission': 'nexus:settings', 'type': 'application', 'needadmin': False}, '4': {'id': '4', 'method': 'update,read', 'permission': 'nexus:settings', 'type': 'application', 'needadmin': True}, '49': {'id': '49', 'method': 'update,read', 'permission': 'nexus:status', 'type': 'application', 'needadmin': True}, '1': {'id': '1', 'method': 'read', 'permission': 'nexus:status', 'type': 'application', 'needadmin': False}, '56': {'id': '56', 'method': 'update', 'permission': 'nexus:repostatus', 'type': 'application', 'needadmin': True}, '64': {'id': '64', 'method': 'create,read', 'permission': 'security:userschangepw', 'type': 'application', 'needadmin': False}, '57': {'id': '57', 'method': 'create,read', 'permission': 'security:usersforgotpw', 'type': 'application', 'needadmin': False}, '58': {'id': '58', 'method': 'create,read', 'permission': 'security:usersforgotid', 'type': 'application', 'needadmin': False}, '75': {'id': '75', 'method': 'read', 'permission': 'security:componentsuserlocatortypes', 'type': 'application', 'needadmin': False}, '80': {'id': '80', 'method': 'read', 'permission': 'security:privilegetypes', 'type': 'application', 'needadmin': False}, '30': {'id': '30', 'method': 'create,read', 'permission': 'security:privileges', 'type': 'application', 'needadmin': True}, '33': {'id': '33', 'method': 'delete,read', 'permission': 'security:privileges', 'type': 'application', 'needadmin': True}, '31': {'id': '31', 'method': 'read', 'permission': 'security:privileges', 'type': 'application', 'needadmin': False}, '32': {'id': '32', 'method': 'update,read', 'permission': 'security:privileges', 'type': 'application', 'needadmin': True}, '59': {'id': '59', 'method': 'delete,read', 'permission': 'security:usersreset', 'type': 'application', 'needadmin': True}, '34': {'id': '34', 'method': 'create,read', 'permission': 'security:roles', 'type': 'application', 'needadmin': True}, '37': {'id': '37', 'method': 'delete,read', 'permission': 'security:roles', 'type': 'application', 'needadmin': True}, '35': {'id': '35', 'method': 'read', 'permission': 'security:roles', 'type': 'application', 'needadmin': False}, '36': {'id': '36', 'method': 'update,read', 'permission': 'security:roles', 'type': 'application', 'needadmin': True}, '72': {'id': '72', 'method': 'create,read', 'permission': 'security:userssetpw', 'type': 'application', 'needadmin': True}, '38': {'id': '38', 'method': 'create,read', 'permission': 'security:users', 'type': 'application', 'needadmin': True}, '41': {'id': '41', 'method': 'delete,read', 'permission': 'security:users', 'type': 'application', 'needadmin': True}, '39': {'id': '39', 'method': 'read', 'permission': 'security:users', 'type': 'application', 'needadmin': False}, '40': {'id': '40', 'method': 'update,read', 'permission': 'security:users', 'type': 'application', 'needadmin': True}, '51': {'id': '51', 'method': 'delete,read', 'permission': 'nexus:wastebasket', 'type': 'application', 'needadmin': False}, '50': {'id': '50', 'method': 'read', 'permission': 'nexus:wastebasket', 'type': 'application', 'needadmin': False}, 'wonderland-all': {'id': 'wonderland-all', 'method': '*', 'permission': 'nexus:wonderland', 'type': 'application', 'needadmin': False}, 'yum-alias-read': {'id': 'yum-alias-read', 'method': 'read', 'permission': 'nexus:yumAlias', 'type': 'application', 'needadmin': False}, 'yum-alias-create-read': {'id': 'yum-alias-create-read', 'method': 'create,update,read', 'permission': 'nexus:yumAlias', 'type': 'application', 'needadmin': False}, 'yum-repository-read': {'id': 'yum-repository-read', 'method': 'read', 'permission': 'nexus:yumVersionedRepositories', 'type': 'application', 'needadmin': False}}
def get_builtin_roles(privmap):
return {'analytics': {'groupName': 'analytics', 'description': 'Gives access to Analytics', 'privileges': [privmap['analytics-all']], 'roles': [], 'admin': False, 'builtin': True}, 'atlas': {'groupName': 'atlas', 'description': 'Gives access to Atlas support tools', 'privileges': [privmap['atlas-all']], 'roles': [], 'admin': False, 'builtin': True}, 'metrics-endpoints': {'groupName': 'metrics-endpoints', 'description': 'Allows access to metrics endpoints.', 'privileges': [privmap['metrics-endpoints']], 'roles': [], 'admin': False, 'builtin': True}, 'nx-admin': {'groupName': 'nx-admin', 'description': 'Administration role for Nexus', 'privileges': [privmap['1001'], privmap['1000'], privmap['83']], 'roles': [], 'admin': True, 'builtin': True}, 'anonymous': {'groupName': 'anonymous', 'description': 'Anonymous role for Nexus', 'privileges': [privmap['1'], privmap['57'], privmap['58'], privmap['70'], privmap['74'], privmap['54']], 'roles': ['ui-healthcheck-read', 'ui-search', 'ui-repo-browser'], 'admin': False, 'builtin': True}, 'nx-apikey-access': {'groupName': 'nx-apikey-access', 'description': 'API-Key Access role for Nexus.', 'privileges': [privmap['83']], 'roles': [], 'admin': False, 'builtin': True}, 'nx-deployment': {'groupName': 'nx-deployment', 'description': 'Deployment role for Nexus', 'privileges': [privmap['83']], 'roles': ['ui-basic', 'anonymous'], 'admin': False, 'builtin': True}, 'nx-developer': {'groupName': 'nx-developer', 'description': 'Developer role for Nexus', 'privileges': [], 'roles': ['ui-basic', 'nx-deployment'], 'admin': False, 'builtin': True}, 'nexus-yum-admin': {'groupName': 'nexus-yum-admin', 'description': 'Gives access to read versioned yum repositories and administrate version aliases', 'privileges': [privmap['yum-repository-read'], privmap['yum-alias-create-read'], privmap['yum-alias-read']], 'roles': [], 'admin': False, 'builtin': True}, 'nexus-yum-user': {'groupName': 'nexus-yum-user', 'description': 'Gives access to read versioned yum repositories', 'privileges': [privmap['yum-repository-read']], 'roles': [], 'admin': False, 'builtin': True}, 'any-all-view': {'groupName': 'any-all-view', 'description': 'Gives access to view ALL Repositories in Nexus.', 'privileges': [], 'roles': [], 'admin': False, 'builtin': True}, 'repo-all-full': {'groupName': 'repo-all-full', 'description': 'Gives access to create/read/update/delete ALL content of ALL Maven1 and Maven2 repositories in Nexus.', 'privileges': [privmap['T4'], privmap['T5'], privmap['T6'], privmap['T7'], privmap['T8'], privmap['repository-all'], privmap['T1'], privmap['T2'], privmap['T3']], 'roles': [], 'admin': False, 'builtin': True}, 'repo-all-read': {'groupName': 'repo-all-read', 'description': 'Gives access to read ALL content of ALL Maven1 and Maven2 repositories in Nexus.', 'privileges': [privmap['repository-all'], privmap['T1'], privmap['T2']], 'roles': [], 'admin': False, 'builtin': True}, 'maven1-all-view': {'groupName': 'maven1-all-view', 'description': 'Gives access to view ALL Maven1 Repositories in Nexus.', 'privileges': [], 'roles': [], 'admin': False, 'builtin': True}, 'maven2-all-view': {'groupName': 'maven2-all-view', 'description': 'Gives access to view ALL Maven2 Repositories in Nexus.', 'privileges': [], 'roles': [], 'admin': False, 'builtin': True}, 'npm-all-full': {'groupName': 'npm-all-full', 'description': 'Gives access to create/read/update/delete ALL content of ALL npm Repositories in Nexus.', 'privileges': [privmap['npm-read'], privmap['npm-create'], privmap['npm-delete'], privmap['npm-update']], 'roles': ['npm-all-view'], 'admin': False, 'builtin': True}, 'npm-all-read': {'groupName': 'npm-all-read', 'description': 'Gives access to read ALL content of ALL npm Repositories in Nexus.', 'privileges': [privmap['npm-read']], 'roles': ['npm-all-view'], 'admin': False, 'builtin': True}, 'npm-all-view': {'groupName': 'npm-all-view', 'description': 'Gives access to view ALL npm Repositories in Nexus.', 'privileges': [], 'roles': [], 'admin': False, 'builtin': True}, 'nuget-all-full': {'groupName': 'nuget-all-full', 'description': 'Gives access to create/read/update/delete ALL content of ALL NuGet Repositories in Nexus.', 'privileges': [privmap['nuget-read'], privmap['nuget-create'], privmap['nuget-delete'], privmap['nuget-update']], 'roles': ['nuget-all-view'], 'admin': False, 'builtin': True}, 'nuget-all-read': {'groupName': 'nuget-all-read', 'description': 'Gives access to read ALL content of ALL NuGet Repositories in Nexus.', 'privileges': [privmap['nuget-read']], 'roles': ['nuget-all-view'], 'admin': False, 'builtin': True}, 'nuget-all-view': {'groupName': 'nuget-all-view', 'description': 'Gives access to view ALL NuGet Repositories in Nexus.', 'privileges': [], 'roles': [], 'admin': False, 'builtin': True}, 'repository-any-full': {'groupName': 'repository-any-full', 'description': 'Gives access to create/read/update/delete ALL content of ALL repositories in Nexus.', 'privileges': [privmap['T10'], privmap['T12'], privmap['repository-all'], privmap['T9'], privmap['T11']], 'roles': [], 'admin': False, 'builtin': True}, 'repository-any-read': {'groupName': 'repository-any-read', 'description': 'Gives access to read ALL content of ALL repositories in Nexus.', 'privileges': [privmap['repository-all'], privmap['T9']], 'roles': [], 'admin': False, 'builtin': True}, 'rubygems-all-full': {'groupName': 'rubygems-all-full', 'description': 'Gives access to create/read/update/delete ALL content of ALL Rubygems Repositories in Nexus.', 'privileges': [privmap['rubygems-create'], privmap['rubygems-delete'], privmap['rubygems-read'], privmap['rubygems-update']], 'roles': ['rubygems-all-view'], 'admin': False, 'builtin': True}, 'rubygems-all-read': {'groupName': 'rubygems-all-read', 'description': 'Gives access to read ALL content of ALL Rubygems Repositories in Nexus.', 'privileges': [privmap['rubygems-read']], 'roles': ['rubygems-all-view'], 'admin': False, 'builtin': True}, 'rubygems-all-view': {'groupName': 'rubygems-all-view', 'description': 'Gives access to view ALL Rubygems Repositories in Nexus.', 'privileges': [], 'roles': [], 'admin': False, 'builtin': True}, 'site-all-full': {'groupName': 'site-all-full', 'description': 'Gives access to create/read/update/delete ALL content of ALL Site Repositories in Nexus.', 'privileges': [privmap['site-create'], privmap['site-update'], privmap['site-delete'], privmap['repository-all'], privmap['site-read']], 'roles': [], 'admin': False, 'builtin': True}, 'site-all-read': {'groupName': 'site-all-read', 'description': 'Gives access to read ALL content of ALL Site Repositories in Nexus.', 'privileges': [privmap['repository-all'], privmap['site-read']], 'roles': [], 'admin': False, 'builtin': True}, 'site-all-view': {'groupName': 'site-all-view', 'description': 'Gives access to view ALL Site Repositories in Nexus.', 'privileges': [], 'roles': [], 'admin': False, 'builtin': True}, 'ui-basic': {'groupName': 'ui-basic', 'description': 'Generic privileges for users in the Nexus UI', 'privileges': [privmap['1'], privmap['2'], privmap['64']], 'roles': [], 'admin': False, 'builtin': True}, 'ui-capabilities-admin': {'groupName': 'ui-capabilities-admin', 'description': 'Gives access to Capabilities Administration screen in Nexus UI', 'privileges': [privmap['capabilities-read'], privmap['capability-types-read'], privmap['14'], privmap['capabilities-update-read'], privmap['6'], privmap['capabilities-delete-read'], privmap['capabilities-create-read']], 'roles': [], 'admin': False, 'builtin': True}, 'ui-group-admin': {'groupName': 'ui-group-admin', 'description': 'Gives access to the Group Administration screen in Nexus UI', 'privileges': [privmap['13'], privmap['14'], privmap['15'], privmap['repository-all'], privmap['16'], privmap['6']], 'roles': ['ui-repo-browser'], 'admin': False, 'builtin': True}, 'ui-healthcheck-full': {'groupName': 'ui-healthcheck-full', 'description': 'Gives access to view and enable/disable the health check for repositories, along with some additional artifact data', 'privileges': [privmap['nexus-healthcheck-update']], 'roles': ['ui-healthcheck-read'], 'admin': False, 'builtin': True}, 'ui-healthcheck-read': {'groupName': 'ui-healthcheck-read', 'description': 'Gives access to view the health check summary for repositories', 'privileges': [privmap['nexus-healthcheck-summary-read'], privmap['nexus-healthcheck-read']], 'roles': [], 'admin': False, 'builtin': True}, 'ui-ldap-admin': {'groupName': 'ui-ldap-admin', 'description': 'Gives access to configure the LDAP server used for authentication.', 'privileges': [privmap['ldap-conn-read'], privmap['ldap-user-group-conf-update'], privmap['ldap-user-role-map-create'], privmap['ldap-conn-update'], privmap['ldap-test-auth-conf'], privmap['ldap-user-role-map-update'], privmap['ldap-user-role-map-read'], privmap['ldap-user-role-map-delete'], privmap['ldap-user-group-conf-read'], privmap['ldap-test-user-group-conf']], 'roles': ['ui-server-admin'], 'admin': False, 'builtin': True}, 'ui-logs-config-files': {'groupName': 'ui-logs-config-files', 'description': 'Gives access to the Logs and Config Files screen in Nexus UI', 'privileges': [privmap['42'], privmap['43']], 'roles': [], 'admin': False, 'builtin': True}, 'ui-plugin-console': {'groupName': 'ui-plugin-console', 'description': 'Gives access to the Plugin Console screen in Nexus UI.', 'privileges': [privmap['plugin-infos-read']], 'roles': [], 'admin': False, 'builtin': True}, 'ui-privileges-admin': {'groupName': 'ui-privileges-admin', 'description': 'Gives access to the Privilege Administration screen in Nexus UI', 'privileges': [privmap['33'], privmap['46'], privmap['14'], privmap['6'], privmap['80'], privmap['30'], privmap['31'], privmap['32']], 'roles': [], 'admin': False, 'builtin': True}, 'ui-repository-admin': {'groupName': 'ui-repository-admin', 'description': 'Gives access to the Repository Administration screen in Nexus UI', 'privileges': [privmap['78'], privmap['79'], privmap['repository-all'], privmap['5'], privmap['6'], privmap['7'], privmap['8'], privmap['81'], privmap['82'], privmap['74'], privmap['10']], 'roles': ['ui-repo-browser'], 'admin': False, 'builtin': True}, 'ui-repo-browser': {'groupName': 'ui-repo-browser', 'description': 'Gives access to the Repository Browser screen in Nexus UI', 'privileges': [privmap['55'], privmap['14'], privmap['6'], privmap['browse-remote-repo']], 'roles': [], 'admin': False, 'builtin': True}, 'ui-repository-targets-admin': {'groupName': 'ui-repository-targets-admin', 'description': 'Gives access to the Repository Target Administration screen in Nexus UI', 'privileges': [privmap['45'], privmap['46'], privmap['47'], privmap['48'], privmap['70'], privmap['74']], 'roles': [], 'admin': False, 'builtin': True}, 'ui-roles-admin': {'groupName': 'ui-roles-admin', 'description': 'Gives access to the Role Administration screen in Nexus UI', 'privileges': [privmap['34'], privmap['35'], privmap['36'], privmap['37'], privmap['31']], 'roles': [], 'admin': False, 'builtin': True}, 'ui-routing-admin': {'groupName': 'ui-routing-admin', 'description': 'Gives access to the Routing Administration screen in Nexus UI', 'privileges': [privmap['22'], privmap['23'], privmap['24'], privmap['14'], privmap['25'], privmap['6']], 'roles': [], 'admin': False, 'builtin': True}, 'ui-scheduled-tasks-admin': {'groupName': 'ui-scheduled-tasks-admin', 'description': 'Gives access to the Scheduled Task Administration screen in Nexus UI', 'privileges': [privmap['68'], privmap['14'], privmap['69'], privmap['26'], privmap['27'], privmap['6'], privmap['28'], privmap['29'], privmap['71']], 'roles': [], 'admin': False, 'builtin': True}, 'ui-search': {'groupName': 'ui-search', 'description': 'Gives access to the Search screen in Nexus UI', 'privileges': [privmap['17'], privmap['19'], privmap['54']], 'roles': [], 'admin': False, 'builtin': True}, 'ui-server-admin': {'groupName': 'ui-server-admin', 'description': 'Gives access to the Server Administration screen in Nexus UI', 'privileges': [privmap['3'], privmap['4'], privmap['73']], 'roles': [], 'admin': False, 'builtin': True}, 'ui-system-feeds': {'groupName': 'ui-system-feeds', 'description': 'Gives access to the System Feeds screen in Nexus UI', 'privileges': [privmap['44']], 'roles': [], 'admin': False, 'builtin': True}, 'ui-users-admin': {'groupName': 'ui-users-admin', 'description': 'Gives access to the User Administration screen in Nexus UI', 'privileges': [privmap['35'], privmap['38'], privmap['39'], privmap['72'], privmap['40'], privmap['41'], privmap['75']], 'roles': [], 'admin': False, 'builtin': True}, 'wonderland': {'groupName': 'wonderland', 'description': 'Gives access to Wonderland', 'privileges': [privmap['wonderland-all']], 'roles': [], 'admin': False, 'builtin': True}} |
EXT_STANDARD = 1
INT_STANDARD = 2
EXT_HQ = 3
INT_HQ = 4
EXT_HOUSE = 5
INT_HOUSE = 6
EXT_COGHQ = 7
INT_COGHQ = 8
EXT_KS = 9
INT_KS = 10
| ext_standard = 1
int_standard = 2
ext_hq = 3
int_hq = 4
ext_house = 5
int_house = 6
ext_coghq = 7
int_coghq = 8
ext_ks = 9
int_ks = 10 |
# Leo colorizer control file for dart mode.
# This file is in the public domain.
# Properties for dart mode.
properties = {
"commentEnd": "*/",
"commentStart": "/*",
"electricKeys": ":",
"indentCloseBrackets": "]}",
"indentNextLine": "\\s*(((if|while)\\s*\\(|else\\s*|else\\s+if\\s*\\(|for\\s*\\(.*\\))[^{;]*)",
"indentOpenBrackets": "{[",
"lineComment": "//",
"unalignedCloseBrackets": ")",
"unalignedOpenBrackets": "(",
"unindentThisLine": "^.*(default:\\s*|case.*:.*)$",
"wordBreakChars": ",+-=<>/?^&*",
}
dart_main_attributes_dict = {
# From python.py
"default": "null",
"digit_re": "",
"escape": "\\",
"highlight_digits": "true",
"ignore_case": "false",
"no_word_sep": "",
}
# Dictionary of attributes dictionaries for dart mode.
attributesDictDict = {
"dart_main": dart_main_attributes_dict,
}
# Keywords dict for dart_expression ruleset.
dart_main_keywords_dict = {
# keywords3 and keywords4.
"assertionerror": "keyword4",
"badnumberformatexception": "keyword4",
"bool": "keyword3",
"clock": "keyword4",
"closureargumentmismatchexception": "keyword4",
"collection": "keyword4",
"comparable": "keyword4",
"const": "keyword1",
"date": "keyword4",
"dispatcher": "keyword4",
"double": "keyword3",
"duration": "keyword4",
"emptyqueueexception": "keyword4",
"exception": "keyword4",
"expect": "keyword4",
"expectexception": "keyword4",
"fallthrougherror": "keyword4",
"false": "literal2",
"function": "keyword4",
"hashable": "keyword4",
"hashmap": "keyword4",
"hashset": "keyword4",
"illegalaccessexception": "keyword4",
"illegalargumentexception": "keyword4",
"illegaljsregexpexception": "keyword4",
"implements": "keyword1",
"indexoutofrangeexception": "keyword4",
"int": "keyword3",
"integerdivisionbyzeroexception": "keyword4",
"is": "keyword1",
"isolate": "keyword4",
"iterable": "keyword4",
"iterator": "keyword4",
"linkedhashmap": "keyword4",
"list": "keyword4",
"map": "keyword4",
"match": "keyword4",
"math": "keyword4",
"new": "keyword1",
"nomoreelementsexception": "keyword4",
"nosuchmethodexception": "keyword4",
"notimplementedexception": "keyword4",
"null": "literal2",
"nullpointerexception": "keyword4",
"num": "keyword3",
"object": "keyword4",
"objectnotclosureexception": "keyword4",
"outofmemoryexception": "keyword4",
"pattern": "keyword4",
"promise": "keyword4",
"proxy": "keyword4",
"queue": "keyword4",
"receiveport": "keyword4",
"regexp": "keyword4",
"sendport": "keyword4",
### "set": "keyword4",
"stackoverflowexception": "keyword4",
"stopwatch": "keyword4",
"string": "keyword4",
"stringbuffer": "keyword4",
"strings": "keyword4",
"super": "literal2",
"this": "literal2",
"timezone": "keyword4",
"true": "literal2",
"typeerror": "keyword4",
"unsupportedoperationexception": "keyword4",
"void": "keyword3",
"wrongargumentcountexception": "keyword4",
# keyword1
"abstract": "keyword1",
"assert": "keyword1",
"break": "keyword1",
"case": "keyword1",
"catch": "keyword1",
"class": "keyword1",
"continue": "keyword1",
"default": "keyword1",
"do": "keyword1",
"else": "keyword1",
"extends": "keyword1",
"factory": "keyword1",
"final": "keyword1",
"finally": "keyword1",
"for": "keyword1",
"get": "keyword1",
"if": "keyword1",
"import": "keyword1",
"in": "keyword1",
"interface": "keyword1",
"library": "keyword1",
"negate": "keyword1",
"operator": "keyword1",
"return": "keyword1",
"set": "keyword1",
"source": "keyword1",
"static": "keyword1",
"switch": "keyword1",
"throw": "keyword1",
"try": "keyword1",
"typedef": "keyword1",
"var": "keyword1",
"while": "keyword1",
}
# Dictionary of keywords dictionaries for dart mode.
keywordsDictDict = {
"dart_main": dart_main_keywords_dict,
}
# Rules for main ruleset.
def dart_rule2(colorer, s, i):
return colorer.match_span(s, i, kind="comment3", begin="/**", end="*/",
at_line_start=False, at_whitespace_end=False, at_word_start=False,
delegate="",exclude_match=False,
no_escape=False, no_line_break=False, no_word_break=False)
def dart_rule3(colorer, s, i):
return colorer.match_span(s, i, kind="comment1", begin="/*", end="*/",
at_line_start=False, at_whitespace_end=False, at_word_start=False,
delegate="",exclude_match=False,
no_escape=False, no_line_break=False, no_word_break=False)
def dart_rule4(colorer, s, i):
return colorer.match_span(s, i, kind="literal1", begin="@\"\"\"", end="\"\"\"",
at_line_start=False, at_whitespace_end=False, at_word_start=False,
delegate="",exclude_match=False,
no_escape=False, no_line_break=False, no_word_break=False)
def dart_rule5(colorer, s, i):
return colorer.match_span(s, i, kind="literal1", begin="@'''", end="'''",
at_line_start=False, at_whitespace_end=False, at_word_start=False,
delegate="",exclude_match=False,
no_escape=False, no_line_break=False, no_word_break=False)
def dart_rule6(colorer, s, i):
return colorer.match_span(s, i, kind="literal1", begin="@\"", end="\"",
at_line_start=False, at_whitespace_end=False, at_word_start=False,
delegate="",exclude_match=False,
no_escape=False, no_line_break=True, no_word_break=False)
def dart_rule7(colorer, s, i):
return colorer.match_span(s, i, kind="literal1", begin="@'", end="'",
at_line_start=False, at_whitespace_end=False, at_word_start=False,
delegate="",exclude_match=False,
no_escape=False, no_line_break=True, no_word_break=False)
def dart_rule8(colorer, s, i):
return colorer.match_span(s, i, kind="literal1", begin="\"\"\"", end="\"\"\"",
at_line_start=False, at_whitespace_end=False, at_word_start=False,
delegate="dart::dart_literal1",exclude_match=False,
no_escape=False, no_line_break=False, no_word_break=False)
def dart_rule9(colorer, s, i):
return colorer.match_span(s, i, kind="literal1", begin="'''", end="'''",
at_line_start=False, at_whitespace_end=False, at_word_start=False,
delegate="dart::dart_literal1",exclude_match=False,
no_escape=False, no_line_break=False, no_word_break=False)
def dart_rule10(colorer, s, i):
return colorer.match_span(s, i, kind="literal1", begin="\"", end="\"",
at_line_start=False, at_whitespace_end=False, at_word_start=False,
delegate="dart::dart_literal1",exclude_match=False,
no_escape=False, no_line_break=True, no_word_break=False)
def dart_rule11(colorer, s, i):
return colorer.match_span(s, i, kind="literal1", begin="'", end="'",
at_line_start=False, at_whitespace_end=False, at_word_start=False,
delegate="dart::dart_literal1",exclude_match=False,
no_escape=False, no_line_break=True, no_word_break=False)
def dart_rule12(colorer, s, i):
return colorer.match_seq(s, i, kind="operator", seq="=",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def dart_rule13(colorer, s, i):
return colorer.match_seq(s, i, kind="operator", seq="!",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def dart_rule14(colorer, s, i):
return colorer.match_seq(s, i, kind="operator", seq=">=",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def dart_rule15(colorer, s, i):
return colorer.match_seq(s, i, kind="operator", seq="<=",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def dart_rule16(colorer, s, i):
return colorer.match_seq(s, i, kind="operator", seq="+",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def dart_rule17(colorer, s, i):
return colorer.match_seq(s, i, kind="operator", seq="-",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def dart_rule18(colorer, s, i):
return colorer.match_seq(s, i, kind="operator", seq="/",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def dart_rule19(colorer, s, i):
return colorer.match_seq(s, i, kind="operator", seq="*",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def dart_rule20(colorer, s, i):
return colorer.match_seq(s, i, kind="operator", seq=">",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def dart_rule21(colorer, s, i):
return colorer.match_seq(s, i, kind="operator", seq="<",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def dart_rule22(colorer, s, i):
return colorer.match_seq(s, i, kind="operator", seq="%",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def dart_rule23(colorer, s, i):
return colorer.match_seq(s, i, kind="operator", seq="&",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def dart_rule24(colorer, s, i):
return colorer.match_seq(s, i, kind="operator", seq="|",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def dart_rule25(colorer, s, i):
return colorer.match_seq(s, i, kind="operator", seq="^",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def dart_rule26(colorer, s, i):
return colorer.match_seq(s, i, kind="operator", seq="<<",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def dart_rule27(colorer, s, i):
return colorer.match_seq(s, i, kind="operator", seq=">>>",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def dart_rule28(colorer, s, i):
return colorer.match_seq(s, i, kind="operator", seq=">>",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def dart_rule29(colorer, s, i):
return colorer.match_seq(s, i, kind="operator", seq="~/",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def dart_rule30(colorer, s, i):
return colorer.match_seq(s, i, kind="operator", seq=".",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def dart_rule31(colorer, s, i):
return colorer.match_seq(s, i, kind="operator", seq=";",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def dart_rule32(colorer, s, i):
return colorer.match_seq(s, i, kind="operator", seq="]",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def dart_rule33(colorer, s, i):
return colorer.match_seq(s, i, kind="operator", seq="[",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def dart_rule34(colorer, s, i):
return colorer.match_seq(s, i, kind="operator", seq="}",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def dart_rule35(colorer, s, i):
return colorer.match_seq(s, i, kind="operator", seq="{",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
# def dart_rule36(colorer, s, i):
# return colorer.match_mark_previous(s, i, kind="function", pattern="(",
# at_line_start=False, at_whitespace_end=False, at_word_start=False, exclude_match=False)
def dart_rule37(colorer, s, i):
return colorer.match_seq(s, i, kind="operator", seq=")",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def dart_rule38(colorer, s, i):
return colorer.match_keywords(s, i)
# Rules formerly in expression ruleset.
def dart_rule39(colorer, s, i):
return colorer.match_seq(s, i, kind="comment2", seq="//-->",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def dart_rule40(colorer, s, i):
return colorer.match_eol_span(s, i, kind="comment2", seq="//",
at_line_start=False, at_whitespace_end=False, at_word_start=False,
delegate="", exclude_match=False)
def dart_rule41(colorer, s, i):
return colorer.match_eol_span(s, i, kind="keyword2", seq="#!",
at_line_start=False, at_whitespace_end=False, at_word_start=False,
delegate="", exclude_match=False)
def dart_rule42(colorer, s, i):
return colorer.match_seq(s, i, kind="keyword2", seq="#library",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def dart_rule43(colorer, s, i):
return colorer.match_seq(s, i, kind="keyword2", seq="#import",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def dart_rule44(colorer, s, i):
return colorer.match_seq(s, i, kind="keyword2", seq="#source",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def dart_rule45(colorer, s, i):
return colorer.match_seq(s, i, kind="keyword2", seq="#resource",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def dart_rule46(colorer, s, i):
return colorer.match_keywords(s, i)
# Rules dict for main ruleset.
rulesDict1 = {
"#": [dart_rule41,dart_rule42,dart_rule43,dart_rule44,dart_rule45,],
"@": [dart_rule4,dart_rule5,dart_rule6,dart_rule7,dart_rule38,], # Added.
"/": [dart_rule39,dart_rule40,
dart_rule2,dart_rule3,dart_rule18,], # Added.
"'": [dart_rule9,dart_rule11,], # Added.
'"': [dart_rule8,dart_rule10,], # Added.
# "@": [dart_rule46,],
# "0": [dart_rule46,],
# "1": [dart_rule46,],
# "2": [dart_rule46,],
# "3": [dart_rule46,],
# "4": [dart_rule46,],
# "5": [dart_rule46,],
# "6": [dart_rule46,],
# "7": [dart_rule46,],
# "8": [dart_rule46,],
# "9": [dart_rule46,],
"A": [dart_rule46,],
"B": [dart_rule46,],
"C": [dart_rule46,],
"D": [dart_rule46,],
"E": [dart_rule46,],
"F": [dart_rule46,],
"G": [dart_rule46,],
"H": [dart_rule46,],
"I": [dart_rule46,],
"J": [dart_rule46,],
"K": [dart_rule46,],
"L": [dart_rule46,],
"M": [dart_rule46,],
"N": [dart_rule46,],
"O": [dart_rule46,],
"P": [dart_rule46,],
"Q": [dart_rule46,],
"R": [dart_rule46,],
"S": [dart_rule46,],
"T": [dart_rule46,],
"U": [dart_rule46,],
"V": [dart_rule46,],
"W": [dart_rule46,],
"X": [dart_rule46,],
"Y": [dart_rule46,],
"Z": [dart_rule46,],
"a": [dart_rule46,],
"b": [dart_rule46,],
"c": [dart_rule46,],
"d": [dart_rule46,],
"e": [dart_rule46,],
"f": [dart_rule46,],
"g": [dart_rule46,],
"h": [dart_rule46,],
"i": [dart_rule46,],
"j": [dart_rule46,],
"k": [dart_rule46,],
"l": [dart_rule46,],
"m": [dart_rule46,],
"n": [dart_rule46,],
"o": [dart_rule46,],
"p": [dart_rule46,],
"q": [dart_rule46,],
"r": [dart_rule46,],
"s": [dart_rule46,],
"t": [dart_rule46,],
"u": [dart_rule46,],
"v": [dart_rule46,],
"w": [dart_rule46,],
"x": [dart_rule46,],
"y": [dart_rule46,],
"z": [dart_rule46,],
}
# x.rulesDictDict for dart mode.
rulesDictDict = {
"dart_main": rulesDict1,
}
# Import dict for dart mode.
importDict = {}
| properties = {'commentEnd': '*/', 'commentStart': '/*', 'electricKeys': ':', 'indentCloseBrackets': ']}', 'indentNextLine': '\\s*(((if|while)\\s*\\(|else\\s*|else\\s+if\\s*\\(|for\\s*\\(.*\\))[^{;]*)', 'indentOpenBrackets': '{[', 'lineComment': '//', 'unalignedCloseBrackets': ')', 'unalignedOpenBrackets': '(', 'unindentThisLine': '^.*(default:\\s*|case.*:.*)$', 'wordBreakChars': ',+-=<>/?^&*'}
dart_main_attributes_dict = {'default': 'null', 'digit_re': '', 'escape': '\\', 'highlight_digits': 'true', 'ignore_case': 'false', 'no_word_sep': ''}
attributes_dict_dict = {'dart_main': dart_main_attributes_dict}
dart_main_keywords_dict = {'assertionerror': 'keyword4', 'badnumberformatexception': 'keyword4', 'bool': 'keyword3', 'clock': 'keyword4', 'closureargumentmismatchexception': 'keyword4', 'collection': 'keyword4', 'comparable': 'keyword4', 'const': 'keyword1', 'date': 'keyword4', 'dispatcher': 'keyword4', 'double': 'keyword3', 'duration': 'keyword4', 'emptyqueueexception': 'keyword4', 'exception': 'keyword4', 'expect': 'keyword4', 'expectexception': 'keyword4', 'fallthrougherror': 'keyword4', 'false': 'literal2', 'function': 'keyword4', 'hashable': 'keyword4', 'hashmap': 'keyword4', 'hashset': 'keyword4', 'illegalaccessexception': 'keyword4', 'illegalargumentexception': 'keyword4', 'illegaljsregexpexception': 'keyword4', 'implements': 'keyword1', 'indexoutofrangeexception': 'keyword4', 'int': 'keyword3', 'integerdivisionbyzeroexception': 'keyword4', 'is': 'keyword1', 'isolate': 'keyword4', 'iterable': 'keyword4', 'iterator': 'keyword4', 'linkedhashmap': 'keyword4', 'list': 'keyword4', 'map': 'keyword4', 'match': 'keyword4', 'math': 'keyword4', 'new': 'keyword1', 'nomoreelementsexception': 'keyword4', 'nosuchmethodexception': 'keyword4', 'notimplementedexception': 'keyword4', 'null': 'literal2', 'nullpointerexception': 'keyword4', 'num': 'keyword3', 'object': 'keyword4', 'objectnotclosureexception': 'keyword4', 'outofmemoryexception': 'keyword4', 'pattern': 'keyword4', 'promise': 'keyword4', 'proxy': 'keyword4', 'queue': 'keyword4', 'receiveport': 'keyword4', 'regexp': 'keyword4', 'sendport': 'keyword4', 'stackoverflowexception': 'keyword4', 'stopwatch': 'keyword4', 'string': 'keyword4', 'stringbuffer': 'keyword4', 'strings': 'keyword4', 'super': 'literal2', 'this': 'literal2', 'timezone': 'keyword4', 'true': 'literal2', 'typeerror': 'keyword4', 'unsupportedoperationexception': 'keyword4', 'void': 'keyword3', 'wrongargumentcountexception': 'keyword4', 'abstract': 'keyword1', 'assert': 'keyword1', 'break': 'keyword1', 'case': 'keyword1', 'catch': 'keyword1', 'class': 'keyword1', 'continue': 'keyword1', 'default': 'keyword1', 'do': 'keyword1', 'else': 'keyword1', 'extends': 'keyword1', 'factory': 'keyword1', 'final': 'keyword1', 'finally': 'keyword1', 'for': 'keyword1', 'get': 'keyword1', 'if': 'keyword1', 'import': 'keyword1', 'in': 'keyword1', 'interface': 'keyword1', 'library': 'keyword1', 'negate': 'keyword1', 'operator': 'keyword1', 'return': 'keyword1', 'set': 'keyword1', 'source': 'keyword1', 'static': 'keyword1', 'switch': 'keyword1', 'throw': 'keyword1', 'try': 'keyword1', 'typedef': 'keyword1', 'var': 'keyword1', 'while': 'keyword1'}
keywords_dict_dict = {'dart_main': dart_main_keywords_dict}
def dart_rule2(colorer, s, i):
return colorer.match_span(s, i, kind='comment3', begin='/**', end='*/', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='', exclude_match=False, no_escape=False, no_line_break=False, no_word_break=False)
def dart_rule3(colorer, s, i):
return colorer.match_span(s, i, kind='comment1', begin='/*', end='*/', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='', exclude_match=False, no_escape=False, no_line_break=False, no_word_break=False)
def dart_rule4(colorer, s, i):
return colorer.match_span(s, i, kind='literal1', begin='@"""', end='"""', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='', exclude_match=False, no_escape=False, no_line_break=False, no_word_break=False)
def dart_rule5(colorer, s, i):
return colorer.match_span(s, i, kind='literal1', begin="@'''", end="'''", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='', exclude_match=False, no_escape=False, no_line_break=False, no_word_break=False)
def dart_rule6(colorer, s, i):
return colorer.match_span(s, i, kind='literal1', begin='@"', end='"', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='', exclude_match=False, no_escape=False, no_line_break=True, no_word_break=False)
def dart_rule7(colorer, s, i):
return colorer.match_span(s, i, kind='literal1', begin="@'", end="'", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='', exclude_match=False, no_escape=False, no_line_break=True, no_word_break=False)
def dart_rule8(colorer, s, i):
return colorer.match_span(s, i, kind='literal1', begin='"""', end='"""', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='dart::dart_literal1', exclude_match=False, no_escape=False, no_line_break=False, no_word_break=False)
def dart_rule9(colorer, s, i):
return colorer.match_span(s, i, kind='literal1', begin="'''", end="'''", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='dart::dart_literal1', exclude_match=False, no_escape=False, no_line_break=False, no_word_break=False)
def dart_rule10(colorer, s, i):
return colorer.match_span(s, i, kind='literal1', begin='"', end='"', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='dart::dart_literal1', exclude_match=False, no_escape=False, no_line_break=True, no_word_break=False)
def dart_rule11(colorer, s, i):
return colorer.match_span(s, i, kind='literal1', begin="'", end="'", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='dart::dart_literal1', exclude_match=False, no_escape=False, no_line_break=True, no_word_break=False)
def dart_rule12(colorer, s, i):
return colorer.match_seq(s, i, kind='operator', seq='=', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='')
def dart_rule13(colorer, s, i):
return colorer.match_seq(s, i, kind='operator', seq='!', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='')
def dart_rule14(colorer, s, i):
return colorer.match_seq(s, i, kind='operator', seq='>=', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='')
def dart_rule15(colorer, s, i):
return colorer.match_seq(s, i, kind='operator', seq='<=', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='')
def dart_rule16(colorer, s, i):
return colorer.match_seq(s, i, kind='operator', seq='+', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='')
def dart_rule17(colorer, s, i):
return colorer.match_seq(s, i, kind='operator', seq='-', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='')
def dart_rule18(colorer, s, i):
return colorer.match_seq(s, i, kind='operator', seq='/', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='')
def dart_rule19(colorer, s, i):
return colorer.match_seq(s, i, kind='operator', seq='*', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='')
def dart_rule20(colorer, s, i):
return colorer.match_seq(s, i, kind='operator', seq='>', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='')
def dart_rule21(colorer, s, i):
return colorer.match_seq(s, i, kind='operator', seq='<', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='')
def dart_rule22(colorer, s, i):
return colorer.match_seq(s, i, kind='operator', seq='%', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='')
def dart_rule23(colorer, s, i):
return colorer.match_seq(s, i, kind='operator', seq='&', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='')
def dart_rule24(colorer, s, i):
return colorer.match_seq(s, i, kind='operator', seq='|', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='')
def dart_rule25(colorer, s, i):
return colorer.match_seq(s, i, kind='operator', seq='^', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='')
def dart_rule26(colorer, s, i):
return colorer.match_seq(s, i, kind='operator', seq='<<', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='')
def dart_rule27(colorer, s, i):
return colorer.match_seq(s, i, kind='operator', seq='>>>', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='')
def dart_rule28(colorer, s, i):
return colorer.match_seq(s, i, kind='operator', seq='>>', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='')
def dart_rule29(colorer, s, i):
return colorer.match_seq(s, i, kind='operator', seq='~/', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='')
def dart_rule30(colorer, s, i):
return colorer.match_seq(s, i, kind='operator', seq='.', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='')
def dart_rule31(colorer, s, i):
return colorer.match_seq(s, i, kind='operator', seq=';', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='')
def dart_rule32(colorer, s, i):
return colorer.match_seq(s, i, kind='operator', seq=']', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='')
def dart_rule33(colorer, s, i):
return colorer.match_seq(s, i, kind='operator', seq='[', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='')
def dart_rule34(colorer, s, i):
return colorer.match_seq(s, i, kind='operator', seq='}', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='')
def dart_rule35(colorer, s, i):
return colorer.match_seq(s, i, kind='operator', seq='{', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='')
def dart_rule37(colorer, s, i):
return colorer.match_seq(s, i, kind='operator', seq=')', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='')
def dart_rule38(colorer, s, i):
return colorer.match_keywords(s, i)
def dart_rule39(colorer, s, i):
return colorer.match_seq(s, i, kind='comment2', seq='//-->', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='')
def dart_rule40(colorer, s, i):
return colorer.match_eol_span(s, i, kind='comment2', seq='//', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='', exclude_match=False)
def dart_rule41(colorer, s, i):
return colorer.match_eol_span(s, i, kind='keyword2', seq='#!', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='', exclude_match=False)
def dart_rule42(colorer, s, i):
return colorer.match_seq(s, i, kind='keyword2', seq='#library', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='')
def dart_rule43(colorer, s, i):
return colorer.match_seq(s, i, kind='keyword2', seq='#import', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='')
def dart_rule44(colorer, s, i):
return colorer.match_seq(s, i, kind='keyword2', seq='#source', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='')
def dart_rule45(colorer, s, i):
return colorer.match_seq(s, i, kind='keyword2', seq='#resource', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='')
def dart_rule46(colorer, s, i):
return colorer.match_keywords(s, i)
rules_dict1 = {'#': [dart_rule41, dart_rule42, dart_rule43, dart_rule44, dart_rule45], '@': [dart_rule4, dart_rule5, dart_rule6, dart_rule7, dart_rule38], '/': [dart_rule39, dart_rule40, dart_rule2, dart_rule3, dart_rule18], "'": [dart_rule9, dart_rule11], '"': [dart_rule8, dart_rule10], 'A': [dart_rule46], 'B': [dart_rule46], 'C': [dart_rule46], 'D': [dart_rule46], 'E': [dart_rule46], 'F': [dart_rule46], 'G': [dart_rule46], 'H': [dart_rule46], 'I': [dart_rule46], 'J': [dart_rule46], 'K': [dart_rule46], 'L': [dart_rule46], 'M': [dart_rule46], 'N': [dart_rule46], 'O': [dart_rule46], 'P': [dart_rule46], 'Q': [dart_rule46], 'R': [dart_rule46], 'S': [dart_rule46], 'T': [dart_rule46], 'U': [dart_rule46], 'V': [dart_rule46], 'W': [dart_rule46], 'X': [dart_rule46], 'Y': [dart_rule46], 'Z': [dart_rule46], 'a': [dart_rule46], 'b': [dart_rule46], 'c': [dart_rule46], 'd': [dart_rule46], 'e': [dart_rule46], 'f': [dart_rule46], 'g': [dart_rule46], 'h': [dart_rule46], 'i': [dart_rule46], 'j': [dart_rule46], 'k': [dart_rule46], 'l': [dart_rule46], 'm': [dart_rule46], 'n': [dart_rule46], 'o': [dart_rule46], 'p': [dart_rule46], 'q': [dart_rule46], 'r': [dart_rule46], 's': [dart_rule46], 't': [dart_rule46], 'u': [dart_rule46], 'v': [dart_rule46], 'w': [dart_rule46], 'x': [dart_rule46], 'y': [dart_rule46], 'z': [dart_rule46]}
rules_dict_dict = {'dart_main': rulesDict1}
import_dict = {} |
ACCOUNT_ID = "1234567890"
def parameter_arn(region, parameter_name):
if parameter_name[0] == "/":
parameter_name = parameter_name[1:]
return "arn:aws:ssm:{0}:{1}:parameter/{2}".format(
region, ACCOUNT_ID, parameter_name
)
| account_id = '1234567890'
def parameter_arn(region, parameter_name):
if parameter_name[0] == '/':
parameter_name = parameter_name[1:]
return 'arn:aws:ssm:{0}:{1}:parameter/{2}'.format(region, ACCOUNT_ID, parameter_name) |
#!/bin/python
# Enter your code here. Read input from STDIN. Print output to STDOUT
N = int(raw_input())
n= N
w = 'Weird'
nw = 'Not Weird'
if n % 2 == 1:
print(w)
elif n % 2 == 0 and (n>=2 and n<5):
print(nw)
elif n % 2 == 0 and (n>=6 and n<=20):
print(w)
elif n % 2 == 0 and (n>20):
print(nw)
| n = int(raw_input())
n = N
w = 'Weird'
nw = 'Not Weird'
if n % 2 == 1:
print(w)
elif n % 2 == 0 and (n >= 2 and n < 5):
print(nw)
elif n % 2 == 0 and (n >= 6 and n <= 20):
print(w)
elif n % 2 == 0 and n > 20:
print(nw) |
# Sage version information for Python scripts
# This file is auto-generated by the sage-update-version script, do not edit!
version = '9.3.rc0'
date = '2021-03-23'
banner = 'SageMath version 9.3.rc0, Release Date: 2021-03-23'
| version = '9.3.rc0'
date = '2021-03-23'
banner = 'SageMath version 9.3.rc0, Release Date: 2021-03-23' |
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def __str__(self):
return str(self.val)
def print_list(head: ListNode):
cur = head
while cur is not None:
print(cur.val, end=' ')
cur = cur.next
if cur is not None:
print('->', end=' ')
print()
def build_list(values):
head = None
prev = None
for i, v in enumerate(values):
if i == 0:
head = ListNode(v)
prev = head
continue
cur = ListNode(v)
prev.next = cur
prev = cur
return head
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
if head is None or head.next is None:
return head
cur = head
next_node = head.next
cur.next = next_node.next
next_node.next = cur
cur.next = Solution().swapPairs(cur.next)
return next_node
# tests
head = build_list([1, 2, 3, 4, 5])
print_list(head)
head = Solution().swapPairs(head)
print_list(head)
head = build_list([])
print_list(head)
head = Solution().swapPairs(head)
print_list(head)
head = build_list([1])
print_list(head)
head = Solution().swapPairs(head)
print_list(head)
| class Listnode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def __str__(self):
return str(self.val)
def print_list(head: ListNode):
cur = head
while cur is not None:
print(cur.val, end=' ')
cur = cur.next
if cur is not None:
print('->', end=' ')
print()
def build_list(values):
head = None
prev = None
for (i, v) in enumerate(values):
if i == 0:
head = list_node(v)
prev = head
continue
cur = list_node(v)
prev.next = cur
prev = cur
return head
class Solution:
def swap_pairs(self, head: ListNode) -> ListNode:
if head is None or head.next is None:
return head
cur = head
next_node = head.next
cur.next = next_node.next
next_node.next = cur
cur.next = solution().swapPairs(cur.next)
return next_node
head = build_list([1, 2, 3, 4, 5])
print_list(head)
head = solution().swapPairs(head)
print_list(head)
head = build_list([])
print_list(head)
head = solution().swapPairs(head)
print_list(head)
head = build_list([1])
print_list(head)
head = solution().swapPairs(head)
print_list(head) |
REDFIN_TABLE_SCHEMA = {
'SCHEMA': {
'SALE_TYPE': 'VARCHAR(50)',
'SOLD_DATE': 'DATE',
'PROPERTY_TYPE': 'VARCHAR(50)',
'ADDRESS': 'VARCHAR(100) NOT NULL',
'CITY': 'VARCHAR(50) NOT NULL',
'STATE': 'VARCHAR(50) NOT NULL',
'ZIPCODE': 'BIGINT',
'PRICE': 'BIGINT',
'BEDS': 'BIGINT',
'BATHS': 'DOUBLE PRECISION',
'SQFT': 'BIGINT',
'LOT_SIZE': 'BIGINT',
'YEAR_BUILT': 'BIGINT',
'DAYS_ON_MARKET': 'BIGINT',
'DOLLAR_PER_SQFT': 'BIGINT',
'HOA_MONTHLY': 'BIGINT',
'STATUS': 'VARCHAR(50)',
'URL': 'VARCHAR(100)',
'MLS_NUM': 'VARCHAR(50)',
'LATITUDE': 'DOUBLE PRECISION',
'LONGITUDE': 'DOUBLE PRECISION'},
'PRIMARY_KEY': 'ADDRESS, CITY, STATE, ZIPCODE',
'POSITION': ['SALE_TYPE', 'SOLD_DATE', 'PROPERTY_TYPE', 'ADDRESS', 'CITY', 'STATE', 'ZIPCODE', 'PRICE', 'BEDS', 'BATHS', 'SQFT', 'LOT_SIZE', 'YEAR_BUILT', 'DAYS_ON_MARKET', 'DOLLAR_PER_SQFT', 'HOA_MONTHLY', 'STATUS', 'URL', 'MLS_NUM', 'LATITUDE', 'LONGITUDE']
}
| redfin_table_schema = {'SCHEMA': {'SALE_TYPE': 'VARCHAR(50)', 'SOLD_DATE': 'DATE', 'PROPERTY_TYPE': 'VARCHAR(50)', 'ADDRESS': 'VARCHAR(100) NOT NULL', 'CITY': 'VARCHAR(50) NOT NULL', 'STATE': 'VARCHAR(50) NOT NULL', 'ZIPCODE': 'BIGINT', 'PRICE': 'BIGINT', 'BEDS': 'BIGINT', 'BATHS': 'DOUBLE PRECISION', 'SQFT': 'BIGINT', 'LOT_SIZE': 'BIGINT', 'YEAR_BUILT': 'BIGINT', 'DAYS_ON_MARKET': 'BIGINT', 'DOLLAR_PER_SQFT': 'BIGINT', 'HOA_MONTHLY': 'BIGINT', 'STATUS': 'VARCHAR(50)', 'URL': 'VARCHAR(100)', 'MLS_NUM': 'VARCHAR(50)', 'LATITUDE': 'DOUBLE PRECISION', 'LONGITUDE': 'DOUBLE PRECISION'}, 'PRIMARY_KEY': 'ADDRESS, CITY, STATE, ZIPCODE', 'POSITION': ['SALE_TYPE', 'SOLD_DATE', 'PROPERTY_TYPE', 'ADDRESS', 'CITY', 'STATE', 'ZIPCODE', 'PRICE', 'BEDS', 'BATHS', 'SQFT', 'LOT_SIZE', 'YEAR_BUILT', 'DAYS_ON_MARKET', 'DOLLAR_PER_SQFT', 'HOA_MONTHLY', 'STATUS', 'URL', 'MLS_NUM', 'LATITUDE', 'LONGITUDE']} |
message = 'My name is ' 'Tom'
print(message)
| message = 'My name is Tom'
print(message) |
list1 = ["apple", "banana", "cherry"]
list2 = list1.copy()
print(list2)
list3 = list(list1)
print(list3)
list4 = list('T am a list')
print(list4)
# join 2 lists
list5 = list1 + list4
print(list5)
for x in list4:
list1.append(x)
print(list1)
list2.extend(list4)
print(list2)
# list constructor
list7 = list(("apple", "banana", "cherry")) # note the double round-brackets
print(list7)
print(list4.count(' '))
# reverse list
list7.reverse()
print(list7)
# sort list
cars = ['Ford', 'BMW', 'Volvo', 'Kia', 'Hyundai', 'Toyota', 'Honda', 'Mazda', 'Mitsubishi', 'Nissan']
cars.sort()
print(cars)
cars.sort(key=lambda e: len(e), reverse=True)
print(cars)
| list1 = ['apple', 'banana', 'cherry']
list2 = list1.copy()
print(list2)
list3 = list(list1)
print(list3)
list4 = list('T am a list')
print(list4)
list5 = list1 + list4
print(list5)
for x in list4:
list1.append(x)
print(list1)
list2.extend(list4)
print(list2)
list7 = list(('apple', 'banana', 'cherry'))
print(list7)
print(list4.count(' '))
list7.reverse()
print(list7)
cars = ['Ford', 'BMW', 'Volvo', 'Kia', 'Hyundai', 'Toyota', 'Honda', 'Mazda', 'Mitsubishi', 'Nissan']
cars.sort()
print(cars)
cars.sort(key=lambda e: len(e), reverse=True)
print(cars) |
_MODELS = dict()
def register(fn):
global _MODELS
_MODELS[fn.__name__] = fn
return fn
def get_model(args=None):
if args.model is None:
return _MODELS
return _MODELS[args.model](args.num_classes)
| _models = dict()
def register(fn):
global _MODELS
_MODELS[fn.__name__] = fn
return fn
def get_model(args=None):
if args.model is None:
return _MODELS
return _MODELS[args.model](args.num_classes) |
#Lists Challenge 9: Basketball Roster Program
print("Welcome to the Basketball Roster Program")
#Get user input and define our roster
roster = []
player = input("\nWho is your point guard: ").title()
roster.append(player)
player = input("Who is your shooting guard: ").title()
roster.append(player)
player = input("Who is your small forward: ").title()
roster.append(player)
player = input("Who is your power forward: ").title()
roster.append(player)
player = input("Who is your center: ").title()
roster.append(player)
#Display roster
print("\n\tYour starting 5 for the upcoming basketball season")
print("\t\tPoint Guard:\t\t" + roster[0])
print("\t\tShooting Guard:\t\t" + roster[1])
print("\t\tSmall Forward:\t\t" + roster[2])
print("\t\tPower Forward:\t\t" + roster[3])
print("\t\tCenter:\t\t\t" + roster[4])
#Remove an injured player
injured_player = roster.pop(2)
print("\nOh no, " + injured_player + " is injured.")
roster_length = len(roster)
print("Your roster only has " + str(roster_length) + " players.")
#Add a new player
added_player = input("Who will take " + injured_player + "'s spot: ").title()
roster.insert(2, added_player)
#Display roster
print("\n\tYour starting 5 for the upcoming basketball season")
print("\t\tPoint Guard:\t\t" + roster[0])
print("\t\tShooting Guard:\t\t" + roster[1])
print("\t\tSmall Forward:\t\t" + roster[2])
print("\t\tPower Forward:\t\t" + roster[3])
print("\t\tCenter:\t\t\t" + roster[4])
print("\nGood luck " + roster[2] + " you will do great!")
roster_length = len(roster)
print("Your roster now has " + str(roster_length) + " players.")
| print('Welcome to the Basketball Roster Program')
roster = []
player = input('\nWho is your point guard: ').title()
roster.append(player)
player = input('Who is your shooting guard: ').title()
roster.append(player)
player = input('Who is your small forward: ').title()
roster.append(player)
player = input('Who is your power forward: ').title()
roster.append(player)
player = input('Who is your center: ').title()
roster.append(player)
print('\n\tYour starting 5 for the upcoming basketball season')
print('\t\tPoint Guard:\t\t' + roster[0])
print('\t\tShooting Guard:\t\t' + roster[1])
print('\t\tSmall Forward:\t\t' + roster[2])
print('\t\tPower Forward:\t\t' + roster[3])
print('\t\tCenter:\t\t\t' + roster[4])
injured_player = roster.pop(2)
print('\nOh no, ' + injured_player + ' is injured.')
roster_length = len(roster)
print('Your roster only has ' + str(roster_length) + ' players.')
added_player = input('Who will take ' + injured_player + "'s spot: ").title()
roster.insert(2, added_player)
print('\n\tYour starting 5 for the upcoming basketball season')
print('\t\tPoint Guard:\t\t' + roster[0])
print('\t\tShooting Guard:\t\t' + roster[1])
print('\t\tSmall Forward:\t\t' + roster[2])
print('\t\tPower Forward:\t\t' + roster[3])
print('\t\tCenter:\t\t\t' + roster[4])
print('\nGood luck ' + roster[2] + ' you will do great!')
roster_length = len(roster)
print('Your roster now has ' + str(roster_length) + ' players.') |
# Helper merge sort function
def mergeSort(arr):
# Clone the array for the merge later
arrClone = arr.clone()
mergeSortAux(arr, arrClone, 0, len(arr) - 1)
# Actual merge sort
def mergeSortAux(arr, arrClone, low, high):
if low < high:
mid = (low + high) / 2
# Sort left
mergeSortAux(arr, arrClone, low, mid)
# Sort right
mergeSortAux(arr, arrClone, mid + 1, high)
# Merge
merge(arr, arrClone, low, mid, high)
# Merge definition that sorts two sub arrays
def merge(arr, arrClone, low, mid, high):
i = low
j = mid + 1
# Copy the clone array parts over
for k in range(low, high):
arrClone[k] = arr[k]
for k in range(low, high):
if i > mid:
arr[k] = arrClone[j]
j += 1
elif j > high:
arr[k] = arrClone[i]
i += 1
elif arrClone[i] > arrClone[j]:
arr[k] = arrClone[j]
j += 1
else:
arr[k] = arrClone[i]
i += 1 | def merge_sort(arr):
arr_clone = arr.clone()
merge_sort_aux(arr, arrClone, 0, len(arr) - 1)
def merge_sort_aux(arr, arrClone, low, high):
if low < high:
mid = (low + high) / 2
merge_sort_aux(arr, arrClone, low, mid)
merge_sort_aux(arr, arrClone, mid + 1, high)
merge(arr, arrClone, low, mid, high)
def merge(arr, arrClone, low, mid, high):
i = low
j = mid + 1
for k in range(low, high):
arrClone[k] = arr[k]
for k in range(low, high):
if i > mid:
arr[k] = arrClone[j]
j += 1
elif j > high:
arr[k] = arrClone[i]
i += 1
elif arrClone[i] > arrClone[j]:
arr[k] = arrClone[j]
j += 1
else:
arr[k] = arrClone[i]
i += 1 |
# You can comment by putting # in front of a text.
#First off we will start off with the humble while loop.
#Now notice the syntax: first we declare our variable,
#while condition is followed with a colon,
#in order to concenate a string with a number
#we must turn it into a string as well.
#Finally don't forget the incremental counter which will allow us
#to actually exit the file!!!!
n = 0
while n <= 5:
print ("While is now " + str(n))
n = n+1
#Now we will move on to the for loop.
#range will give us a collection of numbers. For now, the old fella
#will explain the real things later on.
#range syntax: range(start, stop, step)
for n in range(5):
print (n)
mySum = 1
for i in range(1, 12, 1):
print("i is now " + str(i))
if i == 11:
print("Oh snap we are now over 11!")
break
#Note that it will always stop one step before the stop value in the range.
#Also check this little loop out.
varA = 200
varB = 100
if type(varA) == str or type(varB) == str:
print("string involved")
elif varA > varB:
print("bigger")
elif varA == varB:
print("equal")
else:
print("smaller")
#Checkin types, elif statements, elses... What else do you need?
#This little snippet is a pretty cool one.
#You can find the sum of X and all the numbers before X.
#As seen on MIT6.001X Week 1.2 question 3 in while loops!
n = 0
X = 10
while X > 0:
n += X
X -= 1
print (n)
#Now how do the same in a for loop??
n = 0
X = 10
for i in range(X, 0, -1):
n += i
print (n)
#Wew so hard!
| n = 0
while n <= 5:
print('While is now ' + str(n))
n = n + 1
for n in range(5):
print(n)
my_sum = 1
for i in range(1, 12, 1):
print('i is now ' + str(i))
if i == 11:
print('Oh snap we are now over 11!')
break
var_a = 200
var_b = 100
if type(varA) == str or type(varB) == str:
print('string involved')
elif varA > varB:
print('bigger')
elif varA == varB:
print('equal')
else:
print('smaller')
n = 0
x = 10
while X > 0:
n += X
x -= 1
print(n)
n = 0
x = 10
for i in range(X, 0, -1):
n += i
print(n) |
class DailySchedule:
def __init__(self, day_number: int, day_off: bool = False):
self.day_number = day_number
self.day_off = day_off
self.lessons: list[tuple[str, str, str]] = [] | class Dailyschedule:
def __init__(self, day_number: int, day_off: bool=False):
self.day_number = day_number
self.day_off = day_off
self.lessons: list[tuple[str, str, str]] = [] |
class SpaceSequenceEditor:
display_channel = None
display_mode = None
draw_overexposed = None
grease_pencil = None
overlay_type = None
preview_channels = None
proxy_render_size = None
show_backdrop = None
show_frame_indicator = None
show_frames = None
show_grease_pencil = None
show_metadata = None
show_safe_areas = None
show_safe_center = None
show_seconds = None
show_separate_color = None
show_strip_offset = None
use_marker_sync = None
view_type = None
waveform_draw_type = None
def draw_handler_add(self):
pass
def draw_handler_remove(self):
pass
| class Spacesequenceeditor:
display_channel = None
display_mode = None
draw_overexposed = None
grease_pencil = None
overlay_type = None
preview_channels = None
proxy_render_size = None
show_backdrop = None
show_frame_indicator = None
show_frames = None
show_grease_pencil = None
show_metadata = None
show_safe_areas = None
show_safe_center = None
show_seconds = None
show_separate_color = None
show_strip_offset = None
use_marker_sync = None
view_type = None
waveform_draw_type = None
def draw_handler_add(self):
pass
def draw_handler_remove(self):
pass |
# Write for loops that iterate over the elements of a list without the use of the range
# function for the following tasks.
# c. Counting how many elements in a list are negative.
list = [ -5, 10, 15, -20, -2, 0, -8, 94 ]
numNegativeElements = 0
for item in list:
if item < 0:
numNegativeElements += 1
print("Number of negative elements:", numNegativeElements) | list = [-5, 10, 15, -20, -2, 0, -8, 94]
num_negative_elements = 0
for item in list:
if item < 0:
num_negative_elements += 1
print('Number of negative elements:', numNegativeElements) |
# Letter Phone
# https://www.interviewbit.com/problems/letter-phone/
#
# Given a digit string, return all possible letter combinations that the number could represent.
#
# A mapping of digit to letters (just like on the telephone buttons) is given below.
#
# The digit 0 maps to 0 itself.
# The digit 1 maps to 1 itself.
#
# Input: Digit string "23"
# Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
#
# Make sure the returned strings are lexicographically sorted.
#
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
class Solution:
MAP = {
'0': '0',
'1': '1',
'2': 'abc',
'3': 'def',
'4': 'ghi',
'5': 'jkl',
'6': 'mno',
'7': 'pqrs',
'8': 'tuv',
'9': 'wxyz',
}
def _letterCombinations(self, i, A, sub):
if(i == len(A) - 1):
return [sub + char for char in Solution.MAP[A[i]]]
res = list()
for char in Solution.MAP[A[i]]:
res.extend(self._letterCombinations(i + 1, A, sub + char))
return res
# @param A : string
# @return a list of strings
def letterCombinations(self, A):
return self._letterCombinations(0, A, '')
| class Solution:
map = {'0': '0', '1': '1', '2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'}
def _letter_combinations(self, i, A, sub):
if i == len(A) - 1:
return [sub + char for char in Solution.MAP[A[i]]]
res = list()
for char in Solution.MAP[A[i]]:
res.extend(self._letterCombinations(i + 1, A, sub + char))
return res
def letter_combinations(self, A):
return self._letterCombinations(0, A, '') |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def test_install_extension(lib):
lib.cmd('extension install hello')
lib.cmd('hello')
def test_install_extension_with_github_syntax(lib):
lib.cmd('extension install clk-project/hello')
lib.cmd('hello')
def test_update_extension(lib):
lib.cmd('extension install hello')
lib.cmd('extension update hello')
lib.cmd('hello --update-extension')
def test_copy_extension(lib):
lib.cmd('extension create someext')
lib.cmd('parameter --global-someext set echo test')
assert lib.cmd('echo') == 'test'
lib.cmd('extension disable someext')
assert lib.cmd('echo') == ''
lib.cmd('extension copy someext someext2')
assert lib.cmd('echo') == 'test'
lib.cmd('extension disable someext2')
assert lib.cmd('echo') == ''
def test_move_extension(lib):
lib.cmd('extension create someext')
lib.cmd('parameter --global-someext set echo test')
assert lib.cmd('echo') == 'test'
lib.cmd('extension disable someext')
assert lib.cmd('echo') == ''
lib.cmd('extension rename someext someext2')
assert lib.cmd('echo') == 'test'
lib.cmd('extension disable someext2')
assert lib.cmd('echo') == ''
lib.cmd('extension enable someext')
assert lib.cmd('echo') == ''
| def test_install_extension(lib):
lib.cmd('extension install hello')
lib.cmd('hello')
def test_install_extension_with_github_syntax(lib):
lib.cmd('extension install clk-project/hello')
lib.cmd('hello')
def test_update_extension(lib):
lib.cmd('extension install hello')
lib.cmd('extension update hello')
lib.cmd('hello --update-extension')
def test_copy_extension(lib):
lib.cmd('extension create someext')
lib.cmd('parameter --global-someext set echo test')
assert lib.cmd('echo') == 'test'
lib.cmd('extension disable someext')
assert lib.cmd('echo') == ''
lib.cmd('extension copy someext someext2')
assert lib.cmd('echo') == 'test'
lib.cmd('extension disable someext2')
assert lib.cmd('echo') == ''
def test_move_extension(lib):
lib.cmd('extension create someext')
lib.cmd('parameter --global-someext set echo test')
assert lib.cmd('echo') == 'test'
lib.cmd('extension disable someext')
assert lib.cmd('echo') == ''
lib.cmd('extension rename someext someext2')
assert lib.cmd('echo') == 'test'
lib.cmd('extension disable someext2')
assert lib.cmd('echo') == ''
lib.cmd('extension enable someext')
assert lib.cmd('echo') == '' |
'''
ref: https://www.datacamp.com/community/tutorials/decorators-python
'''
def uppercase_decorator(function):
def wrapper():
func = function()
make_uppercase = func.upper()
return make_uppercase
return wrapper
def say_hi():
return 'hi there'
decorate = uppercase_decorator(say_hi)
decorate()
print(decorate())
print('----------------------------------------------------------------------------')
print('----------------------------------------------------------------------------')
'''
Here is the decorator annotated as @uppercase_decorator
'''
@uppercase_decorator
def say_hello():
return 'hello there'
print(say_hello())
print('----------------------------------------------------------------------------')
print('----------------------------------------------------------------------------')
'''
Applying Multiple Decorators to a Single Function
'''
def split_string(function):
def wrapper():
func = function()
splitted_string = func.split()
return splitted_string
return wrapper
'''
Application of decorators is from the bottom up.
Had we interchanged the order, we'd have seen an error since lists don't have an upper attribute.
The sentence has first been converted to uppercase and then split into a list.
'''
@split_string # second applied
@uppercase_decorator # first applied
def say_hello():
return 'hello there'
print(say_hello())
print('----------------------------------------------------------------------------')
print('----------------------------------------------------------------------------')
'''
Function defination with parameters
'''
def decorator_with_arguments(function):
def wrapper_accepting_arguments(arg1, arg2):
print("Parameters passed to the function are: {0}, {1}".format(arg1,arg2))
function(arg1, arg2)
return wrapper_accepting_arguments
@decorator_with_arguments
def cities(city_one, city_two):
print("Cities I love are {0} and {1}".format(city_one, city_two))
cities("Duluth", "Leesburg")
print('----------------------------------------------------------------------------')
print('----------------------------------------------------------------------------')
def a_decorator_passing_arguments(function_to_decorate):
def a_wrapper_accepting_arguments(*args,**kwargs):
print('The positional arguments are', args)
print('The keyword arguments are', kwargs)
function_to_decorate(*args, *kwargs)
return a_wrapper_accepting_arguments
@a_decorator_passing_arguments
def function_with_positional_keyword_arguments(param1, param2, service="glue", region='us-east-1'):
print("This has both keyword and arguments")
print(f'param1: {param1} param2: {param2} service: {service} region: {region}')
function_with_positional_keyword_arguments('first-parameter', 'second-parameter')
print('----------------------------------------------------------------------------')
print('----------------------------------------------------------------------------')
function_with_positional_keyword_arguments('first-parameter', 'second-parameter', 's3', 'us-east-2')
| """
ref: https://www.datacamp.com/community/tutorials/decorators-python
"""
def uppercase_decorator(function):
def wrapper():
func = function()
make_uppercase = func.upper()
return make_uppercase
return wrapper
def say_hi():
return 'hi there'
decorate = uppercase_decorator(say_hi)
decorate()
print(decorate())
print('----------------------------------------------------------------------------')
print('----------------------------------------------------------------------------')
'\nHere is the decorator annotated as @uppercase_decorator\n'
@uppercase_decorator
def say_hello():
return 'hello there'
print(say_hello())
print('----------------------------------------------------------------------------')
print('----------------------------------------------------------------------------')
'\nApplying Multiple Decorators to a Single Function\n'
def split_string(function):
def wrapper():
func = function()
splitted_string = func.split()
return splitted_string
return wrapper
"\nApplication of decorators is from the bottom up. \nHad we interchanged the order, we'd have seen an error since lists don't have an upper attribute.\nThe sentence has first been converted to uppercase and then split into a list.\n"
@split_string
@uppercase_decorator
def say_hello():
return 'hello there'
print(say_hello())
print('----------------------------------------------------------------------------')
print('----------------------------------------------------------------------------')
'\n Function defination with parameters\n'
def decorator_with_arguments(function):
def wrapper_accepting_arguments(arg1, arg2):
print('Parameters passed to the function are: {0}, {1}'.format(arg1, arg2))
function(arg1, arg2)
return wrapper_accepting_arguments
@decorator_with_arguments
def cities(city_one, city_two):
print('Cities I love are {0} and {1}'.format(city_one, city_two))
cities('Duluth', 'Leesburg')
print('----------------------------------------------------------------------------')
print('----------------------------------------------------------------------------')
def a_decorator_passing_arguments(function_to_decorate):
def a_wrapper_accepting_arguments(*args, **kwargs):
print('The positional arguments are', args)
print('The keyword arguments are', kwargs)
function_to_decorate(*args, *kwargs)
return a_wrapper_accepting_arguments
@a_decorator_passing_arguments
def function_with_positional_keyword_arguments(param1, param2, service='glue', region='us-east-1'):
print('This has both keyword and arguments')
print(f'param1: {param1} param2: {param2} service: {service} region: {region}')
function_with_positional_keyword_arguments('first-parameter', 'second-parameter')
print('----------------------------------------------------------------------------')
print('----------------------------------------------------------------------------')
function_with_positional_keyword_arguments('first-parameter', 'second-parameter', 's3', 'us-east-2') |
MAX_CHAR_GROUP_NAME = 30
MAX_CHAR_CONTEXT_NAME = 30
MAX_CHAR_DEVICE_NAME = 30
MAX_DEVICES = 10
MAX_GROUPS = 10
MAX_CONTEXTS = 10
MAX_ACTIONS = 10
MAX_TRIGGERS = 10
# in seconds
INTERVAL_PUB_GROUP_DATA = 120
INTERVAL_ONLINE = 60
STATE_NO_CONNECTION = 1
STATE_CONNECTED_INTERNET = 2
STATE_CONNECTED_NO_INTERNET = 3 | max_char_group_name = 30
max_char_context_name = 30
max_char_device_name = 30
max_devices = 10
max_groups = 10
max_contexts = 10
max_actions = 10
max_triggers = 10
interval_pub_group_data = 120
interval_online = 60
state_no_connection = 1
state_connected_internet = 2
state_connected_no_internet = 3 |
def login(client, username, password):
payload = dict(username=username, password=password)
return client.post('/login', data=payload, follow_redirects=True)
def logout(client):
return client.get('/logout', follow_redirects=True)
| def login(client, username, password):
payload = dict(username=username, password=password)
return client.post('/login', data=payload, follow_redirects=True)
def logout(client):
return client.get('/logout', follow_redirects=True) |
largest_number=None
smallest_number=None
while True:
order=input('Enter a number: ')
if order=='done':
break
try:
number=int(order)
except Exception as e:
print("Invalid Input")
continue
if largest_number is None:
largest_number=number
if smallest_number is None:
smallest_number=number
if largest_number<number:
largest_number=number
if smallest_number>number:
smallest_number=number
print(largest_number)
print(smallest_number) | largest_number = None
smallest_number = None
while True:
order = input('Enter a number: ')
if order == 'done':
break
try:
number = int(order)
except Exception as e:
print('Invalid Input')
continue
if largest_number is None:
largest_number = number
if smallest_number is None:
smallest_number = number
if largest_number < number:
largest_number = number
if smallest_number > number:
smallest_number = number
print(largest_number)
print(smallest_number) |
# XXXXXXXXXXX
class Node:
def __init__(self, value, prev_item=None, next_item=None):
self.value = value
self.prev_item = prev_item
self.next_item = next_item
class Queue():
def __init__(self, max_size):
self.max_size = max_size
self.size = 0
self.head = None
self.last = None
def push_back(self, x):
node = Node(value=x)
if self.max_size != self.size:
if self.size == 0:
self.head = node
self.last = node
else:
node.prev_item = self.last
self.last.next_item = node
self.last = node
self.size += 1
else:
print('error')
def push_front(self, x):
node = Node(value=x)
if self.max_size != self.size:
if self.size == 0:
self.head = node
self.last = node
else:
node.next_item = self.head
self.head.prev_item = node
self.head = node
self.size += 1
else:
print('error')
def pop_back(self):
if self.size == 0:
print('error')
else:
x = self.last
self.last = self.last.prev_item
self.size -= 1
print(x.value)
def pop_front(self):
if self.size == 0:
print('error')
else:
x = self.head
self.head = self.head.next_item
self.size -= 1
print(x.value)
def get_size(self):
print(self.size)
def run():
num_com = int(input())
max_size = int(input())
q = Queue(max_size)
for _ in range(num_com):
command = input().split()
if command[0] == 'push_back':
q.push_back(command[1])
if command[0] == 'push_front':
q.push_front(command[1])
if command[0] == 'pop_back':
q.pop_back()
if command[0] == 'pop_front':
q.pop_front()
if __name__ == '__main__':
run() | class Node:
def __init__(self, value, prev_item=None, next_item=None):
self.value = value
self.prev_item = prev_item
self.next_item = next_item
class Queue:
def __init__(self, max_size):
self.max_size = max_size
self.size = 0
self.head = None
self.last = None
def push_back(self, x):
node = node(value=x)
if self.max_size != self.size:
if self.size == 0:
self.head = node
self.last = node
else:
node.prev_item = self.last
self.last.next_item = node
self.last = node
self.size += 1
else:
print('error')
def push_front(self, x):
node = node(value=x)
if self.max_size != self.size:
if self.size == 0:
self.head = node
self.last = node
else:
node.next_item = self.head
self.head.prev_item = node
self.head = node
self.size += 1
else:
print('error')
def pop_back(self):
if self.size == 0:
print('error')
else:
x = self.last
self.last = self.last.prev_item
self.size -= 1
print(x.value)
def pop_front(self):
if self.size == 0:
print('error')
else:
x = self.head
self.head = self.head.next_item
self.size -= 1
print(x.value)
def get_size(self):
print(self.size)
def run():
num_com = int(input())
max_size = int(input())
q = queue(max_size)
for _ in range(num_com):
command = input().split()
if command[0] == 'push_back':
q.push_back(command[1])
if command[0] == 'push_front':
q.push_front(command[1])
if command[0] == 'pop_back':
q.pop_back()
if command[0] == 'pop_front':
q.pop_front()
if __name__ == '__main__':
run() |
#!/usr/bin/python3.6
# created by cicek on 12.10.2018 15:09
digits = "7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450"
d_list = list(digits)
i, res = 0, 1
product_array = []
while ((i+12) < len(d_list)):
for x in range(0, 13):
res *= int(d_list[i+x])
product_array.append(res)
res = 1
i += 1
product_array.sort()
print(product_array[-1])
| digits = '7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450'
d_list = list(digits)
(i, res) = (0, 1)
product_array = []
while i + 12 < len(d_list):
for x in range(0, 13):
res *= int(d_list[i + x])
product_array.append(res)
res = 1
i += 1
product_array.sort()
print(product_array[-1]) |
user_schema = {
"type": "object",
"properties": {
"name": {"type": "string"}
},
"required": ["name"],
"additionalProperties": False
}
get_users_query_params_schema = {
"type": ["object", "null"],
"properties": {
"page": {"type": "string"}
},
"additionalProperties": False
}
| user_schema = {'type': 'object', 'properties': {'name': {'type': 'string'}}, 'required': ['name'], 'additionalProperties': False}
get_users_query_params_schema = {'type': ['object', 'null'], 'properties': {'page': {'type': 'string'}}, 'additionalProperties': False} |
#!/usr/bin/env python
class HostType:
GPCHECK_HOSTTYPE_UNDEFINED = 0
GPCHECK_HOSTTYPE_APPLIANCE = 1
GPCHECK_HOSTTYPE_GENERIC_LINUX = 2
def hosttype_str(type):
if type == HostType.GPCHECK_HOSTTYPE_APPLIANCE:
return "GPDB Appliance"
elif type == HostType.GPCHECK_HOSTTYPE_GENERIC_LINUX:
return "Generic Linux Cluster"
else:
return "Undetected Platform"
class sysctl:
def __init__(self):
self.variables = dict() # dictionary of values
self.errormsg = None
class omreport:
def __init__(self):
self.biossetup = dict() # key value pairs
self.biossetup_errormsg = None
self.bootorder = list() # list of Devices in order of boot
self.bootorder_errormsg = None
self.remoteaccess = dict() # key value pairs
self.remoteaccess_errormsg = None
self.vdisks = list() # list of dicts, 1 for each virtual disk
self.vdisks_errormsg = None
self.controller = dict() # key value pairs
self.controller_errormsg = None
self.omversion = None
self.omversion_errormsg = None
self.bios = dict() # key value pairs
self.bios_errormsg = None
self.alerts = list() # list of alerts... each alert is a dictionary of key value pairs
self.alerts_errormsg = None
class chkconfig:
def __init__(self):
self.services = dict() # hash of services, each entry is hash of run levels and boolean value
self.xinetd = dict() # hash of services, value is boolean
self.errormsg = None
class grubconf:
def __init__(self):
self.serial_declaration = False
self.terminal_declaration = False
self.ttyS1_declaration = False
self.errormsg = None
def __str__(self):
return "serial_declaration(%s) terminal_declaration(%s) ttyS1_declaration(%s)" % (self.serial_declaration, self.terminal_declaration, self.ttyS1_declaration)
class inittab:
def __init__(self):
self.s1 = False
self.defaultRunLevel = None
self.errormsg = None
def __str__(self):
return "s1_declaration(%s) default_run_level(%s)" % (self.s1, self.defaultRunLevel)
class uname:
def __init__(self):
self.output = None
self.errormsg = None
def __str__(self):
return self.output
class connectemc:
def __init__(self):
self.output = None
self.errormsg = None
def __str__(self):
return self.output
class securetty:
def __init__(self):
self.errormsg = None
self.data = set()
class bcu:
def __init__(self):
self.firmware = None
self.biosversion = None
self.errormsg = None
def __str__(self):
return "firmware_version=%s|biosversion=%s" % (self.firmware, self.biosversion)
class ioschedulers:
def __init__(self):
self.devices = dict() # key is device name value is scheduler name
self.errormsg = ''
class blockdev:
def __init__(self):
self.ra = dict() # key is device name value is getra value
self.errormsg = ''
class rclocal:
def __init__(self):
self.isexecutable = False # check that /etc/rc.d/rc.local is executable permissions
def __str__(self):
return "executable(%s)" % self.isexecutable
class limitsconf_entry:
def __init__(self, domain, type, item, value):
self.domain = domain
self.type = type
self.item = item
self.value = value
def __str__(self):
return "%s %s %s %s" % (self.domain, self.type, self.item, self.value)
class limitsconf:
def __init__(self):
self.lines = list()
self.errormsg = None
def __str__(self):
output = ""
for line in self.lines:
output = "%s\n%s" % (output, line)
return output
class GpMount:
def __init__(self):
self.partition = None
self.dir= None
self.type = None
self.options = set() # mount options
def __str__(self):
optionstring = ''
first = True
for k in self.options:
if not first:
optionstring = "%s," % optionstring
thisoption = k
optionstring = "%s%s" % (optionstring, thisoption)
first = False
return "%s on %s type %s (%s)" % (self.partition, self.dir, self.type, optionstring)
class ntp:
def __init__(self):
self.running = False
self.hosts = set()
self.currentime = None
self.errormsg = None
def __str__(self):
return "(running %s) (time %f) (peers: %s)" % (self.running, self.currenttime, self.hosts)
class mounts:
def __init__(self):
self.entries = dict() # dictionary key=partition value=mount object
self.errormsg = None
def __str__(self):
output = ''
for k in self.entries.keys():
output = "%s\n%s" % (output, self.entries[k].__str__())
return output
class GenericLinuxOutputData:
def __init__(self):
self.mounts = None
self.uname = None
self.blockdev = None
self.ioschedulers = None
self.sysctl = None
self.limitsconf = None
self.ntp = None
def __str__(self):
grc = "============= SYSCTL=========================\n"
gre = "============= SYSCTL ERRORMSG================\n"
output = "%s%s\n%s%s" % (grc, self.sysctl.variables.__str__(), gre, self.sysctl.errormsg)
grc = "============= LIMITS=========================\n"
gre = "============= LIMITS ERRORMSG================\n"
output = "%s\n%s%s\n%s%s" % (output, grc, self.limitsconf.__str__(), gre, self.limitsconf.errormsg)
mnt = "============= MOUNT==========================\n"
mte = "============= MOUNT ERRORMSG=================\n"
output = "%s\n%s%s\n%s%s" % (output, mnt, self.mounts.__str__(), mte, self.mounts.errormsg)
grc = "============= UNAME==========================\n"
gre = "============= UNAME ERRORMSG=================\n"
output = "%s\n%s%s\n%s%s" % (output, grc, self.uname.__str__(), gre, self.uname.errormsg)
grc = "============= IO SCHEDULERS==================\n"
gre = "============= IO SCHEDULERS ERRORMSG========\n"
output = "%s\n%s%s\n%s%s" % (output, grc, self.ioschedulers.devices.__str__(), gre, self.ioschedulers.errormsg)
grc = "============= BLOCKDEV RA ====================\n"
gre = "============= BLOCKDEV RA ERRORMSG============\n"
output = "%s\n%s%s\n%s%s" % (output, grc, self.blockdev.ra.__str__(), gre, self.blockdev.errormsg)
grc = "============= NTPD ===========================\n"
gre = "============= NTPD ERRORMSG===================\n"
output = "%s\n%s%s\n%s%s" % (output, grc, self.ntp.__str__(), gre, self.ntp.errormsg)
return output
class ApplianceOutputData:
def __init__(self):
self.chkconfig = None
self.omreport = None
self.grubconf = None
self.mounts = None
self.inittab = None
self.uname = None
self.securetty = None
self.bcu = None
self.blockdev = None
self.rclocal = None
self.ioschedulers = None
self.sysctl = None
self.limitsconf = None
self.connectemc = None
self.ntp = None
def __str__(self):
ser = "=============SERVICES=======================\n"
xin = "=============XINETD =======================\n"
err = "=============CHKCONFIG ERRORMSG=============\n"
output = "%s%s\n%s%s\n%s%s" % (ser, self.chkconfig.services.__str__(), xin, self.chkconfig.xinetd.__str__(), err, self.chkconfig.errormsg)
omr = "=============OMREPORT VERSION ==============\n"
ome = "=============OMREPORT VERSION ERRORMSG======\n"
output = "%s\n%s%s\n%s%s" % (output, omr, self.omreport.omversion, ome, self.omreport.omversion_errormsg)
omr = "=============OMREPORT BIOS==================\n"
ome = "=============OMREPORT BIOS ERRORMSG=========\n"
output = "%s\n%s%s\n%s%s" % (output, omr, self.omreport.bios.__str__(), ome,self.omreport.bios_errormsg)
omr = "=============OMREPORT BIOSSETUP=============\n"
ome = "=============OMREPORT BIOSSETUP ERRORMSG====\n"
output = "%s\n%s%s\n%s%s" % (output, omr, self.omreport.biossetup.__str__(), ome,self.omreport.biossetup_errormsg)
omr = "=============OMREPORT CONTROLLER============\n"
ome = "=============OMREPORT CONTROLLER ERRORMSG===\n"
output = "%s\n%s%s\n%s%s" % (output, omr, self.omreport.controller.__str__(), ome,self.omreport.controller_errormsg)
boo = "=============OMREPORT BOOTORDER=============\n"
boe = "=============OMREPORT BOOTORDER ERRORMSG====\n"
output = "%s\n%s%s\n%s%s" % (output, boo, self.omreport.bootorder.__str__(), boe, self.omreport.bootorder_errormsg)
omr = "=============OMREPORT REMOTEACCESS==========\n"
ome = "=============OMREPORT REMOTEACCESS ERRORMSG=\n"
output = "%s\n%s%s\n%s%s" % (output, omr, self.omreport.remoteaccess.__str__(), ome,self.omreport.remoteaccess_errormsg)
omr = "=============OMREPORT ALERTS==========\n"
ome = "=============OMREPORT ALERTS ERRORMSG=\n"
output = "%s\n%s%s\n%s%s" % (output, omr, self.omreport.alerts.__str__(), ome,self.omreport.alerts_errormsg)
omr = "=============OMREPORT VIRTUAL DISKS=========\n"
ome = "=============OMREPORT VIRTUAL DISKS ERRORMSG\n"
output = "%s\n%s%s\n%s%s" % (output, omr, self.omreport.vdisks.__str__(), ome,self.omreport.vdisks_errormsg)
grc = "============= GRUB.CONF======================\n"
gre = "============= GRUB.CONF ERRORMSG=============\n"
output = "%s\n%s%s\n%s%s" % (output, grc, self.grubconf.__str__(), gre, self.grubconf.errormsg)
grc = "============= SYSCTL=========================\n"
gre = "============= SYSCTL ERRORMSG================\n"
output = "%s\n%s%s\n%s%s" % (output, grc, self.sysctl.variables.__str__(), gre, self.sysctl.errormsg)
grc = "============= LIMITS=========================\n"
gre = "============= LIMITS ERRORMSG================\n"
output = "%s\n%s%s\n%s%s" % (output, grc, self.limitsconf.__str__(), gre, self.limitsconf.errormsg)
mnt = "============= MOUNT==========================\n"
mte = "============= MOUNT ERRORMSG=================\n"
output = "%s\n%s%s\n%s%s" % (output, mnt, self.mounts.__str__(), mte, self.mounts.errormsg)
grc = "============= INITTAB========================\n"
gre = "============= INITTAB ERRORMSG===============\n"
output = "%s\n%s%s\n%s%s" % (output, grc, self.inittab.__str__(), gre, self.inittab.errormsg)
grc = "============= UNAME==========================\n"
gre = "============= UNAME ERRORMSG=================\n"
output = "%s\n%s%s\n%s%s" % (output, grc, self.uname.__str__(), gre, self.uname.errormsg)
grc = "============= CONNECTEMC=====================\n"
gre = "============= CONNECtEMC ERRORMSG============\n"
output = "%s\n%s%s\n%s%s" % (output, grc, self.connectemc.__str__(), gre, self.connectemc.errormsg)
grc = "============= SECURETTY======================\n"
gre = "============= SECURETTY ERRORMSG=============\n"
output = "%s\n%s%s\n%s%s" % (output, grc, self.securetty.data.__str__(), gre, self.securetty.errormsg)
grc = "============= IO SCHEDULERS==================\n"
gre = "============= IO SCHEDULERS ERRORMSG========\n"
output = "%s\n%s%s\n%s%s" % (output, grc, self.ioschedulers.devices.__str__(), gre, self.ioschedulers.errormsg)
grc = "============= BLOCKDEV RA ====================\n"
gre = "============= BLOCKDEV RA ERRORMSG============\n"
output = "%s\n%s%s\n%s%s" % (output, grc, self.blockdev.ra.__str__(), gre, self.blockdev.errormsg)
grc = "============= BCU CNA ========================\n"
gre = "============= BCU CNA ERRORMSG================\n"
output = "%s\n%s%s\n%s%s" % (output, grc, self.bcu.__str__(), gre, self.bcu.errormsg)
grc = "============= /etc/rc.d/rc.local =============\n"
output = "%s\n%s%s" % (output, grc, self.rclocal.__str__())
grc = "============= NTPD ===========================\n"
gre = "============= NTPD ERRORMSG===================\n"
output = "%s\n%s%s\n%s%s" % (output, grc, self.ntp.__str__(), gre, self.ntp.errormsg)
return output
| class Hosttype:
gpcheck_hosttype_undefined = 0
gpcheck_hosttype_appliance = 1
gpcheck_hosttype_generic_linux = 2
def hosttype_str(type):
if type == HostType.GPCHECK_HOSTTYPE_APPLIANCE:
return 'GPDB Appliance'
elif type == HostType.GPCHECK_HOSTTYPE_GENERIC_LINUX:
return 'Generic Linux Cluster'
else:
return 'Undetected Platform'
class Sysctl:
def __init__(self):
self.variables = dict()
self.errormsg = None
class Omreport:
def __init__(self):
self.biossetup = dict()
self.biossetup_errormsg = None
self.bootorder = list()
self.bootorder_errormsg = None
self.remoteaccess = dict()
self.remoteaccess_errormsg = None
self.vdisks = list()
self.vdisks_errormsg = None
self.controller = dict()
self.controller_errormsg = None
self.omversion = None
self.omversion_errormsg = None
self.bios = dict()
self.bios_errormsg = None
self.alerts = list()
self.alerts_errormsg = None
class Chkconfig:
def __init__(self):
self.services = dict()
self.xinetd = dict()
self.errormsg = None
class Grubconf:
def __init__(self):
self.serial_declaration = False
self.terminal_declaration = False
self.ttyS1_declaration = False
self.errormsg = None
def __str__(self):
return 'serial_declaration(%s) terminal_declaration(%s) ttyS1_declaration(%s)' % (self.serial_declaration, self.terminal_declaration, self.ttyS1_declaration)
class Inittab:
def __init__(self):
self.s1 = False
self.defaultRunLevel = None
self.errormsg = None
def __str__(self):
return 's1_declaration(%s) default_run_level(%s)' % (self.s1, self.defaultRunLevel)
class Uname:
def __init__(self):
self.output = None
self.errormsg = None
def __str__(self):
return self.output
class Connectemc:
def __init__(self):
self.output = None
self.errormsg = None
def __str__(self):
return self.output
class Securetty:
def __init__(self):
self.errormsg = None
self.data = set()
class Bcu:
def __init__(self):
self.firmware = None
self.biosversion = None
self.errormsg = None
def __str__(self):
return 'firmware_version=%s|biosversion=%s' % (self.firmware, self.biosversion)
class Ioschedulers:
def __init__(self):
self.devices = dict()
self.errormsg = ''
class Blockdev:
def __init__(self):
self.ra = dict()
self.errormsg = ''
class Rclocal:
def __init__(self):
self.isexecutable = False
def __str__(self):
return 'executable(%s)' % self.isexecutable
class Limitsconf_Entry:
def __init__(self, domain, type, item, value):
self.domain = domain
self.type = type
self.item = item
self.value = value
def __str__(self):
return '%s %s %s %s' % (self.domain, self.type, self.item, self.value)
class Limitsconf:
def __init__(self):
self.lines = list()
self.errormsg = None
def __str__(self):
output = ''
for line in self.lines:
output = '%s\n%s' % (output, line)
return output
class Gpmount:
def __init__(self):
self.partition = None
self.dir = None
self.type = None
self.options = set()
def __str__(self):
optionstring = ''
first = True
for k in self.options:
if not first:
optionstring = '%s,' % optionstring
thisoption = k
optionstring = '%s%s' % (optionstring, thisoption)
first = False
return '%s on %s type %s (%s)' % (self.partition, self.dir, self.type, optionstring)
class Ntp:
def __init__(self):
self.running = False
self.hosts = set()
self.currentime = None
self.errormsg = None
def __str__(self):
return '(running %s) (time %f) (peers: %s)' % (self.running, self.currenttime, self.hosts)
class Mounts:
def __init__(self):
self.entries = dict()
self.errormsg = None
def __str__(self):
output = ''
for k in self.entries.keys():
output = '%s\n%s' % (output, self.entries[k].__str__())
return output
class Genericlinuxoutputdata:
def __init__(self):
self.mounts = None
self.uname = None
self.blockdev = None
self.ioschedulers = None
self.sysctl = None
self.limitsconf = None
self.ntp = None
def __str__(self):
grc = '============= SYSCTL=========================\n'
gre = '============= SYSCTL ERRORMSG================\n'
output = '%s%s\n%s%s' % (grc, self.sysctl.variables.__str__(), gre, self.sysctl.errormsg)
grc = '============= LIMITS=========================\n'
gre = '============= LIMITS ERRORMSG================\n'
output = '%s\n%s%s\n%s%s' % (output, grc, self.limitsconf.__str__(), gre, self.limitsconf.errormsg)
mnt = '============= MOUNT==========================\n'
mte = '============= MOUNT ERRORMSG=================\n'
output = '%s\n%s%s\n%s%s' % (output, mnt, self.mounts.__str__(), mte, self.mounts.errormsg)
grc = '============= UNAME==========================\n'
gre = '============= UNAME ERRORMSG=================\n'
output = '%s\n%s%s\n%s%s' % (output, grc, self.uname.__str__(), gre, self.uname.errormsg)
grc = '============= IO SCHEDULERS==================\n'
gre = '============= IO SCHEDULERS ERRORMSG========\n'
output = '%s\n%s%s\n%s%s' % (output, grc, self.ioschedulers.devices.__str__(), gre, self.ioschedulers.errormsg)
grc = '============= BLOCKDEV RA ====================\n'
gre = '============= BLOCKDEV RA ERRORMSG============\n'
output = '%s\n%s%s\n%s%s' % (output, grc, self.blockdev.ra.__str__(), gre, self.blockdev.errormsg)
grc = '============= NTPD ===========================\n'
gre = '============= NTPD ERRORMSG===================\n'
output = '%s\n%s%s\n%s%s' % (output, grc, self.ntp.__str__(), gre, self.ntp.errormsg)
return output
class Applianceoutputdata:
def __init__(self):
self.chkconfig = None
self.omreport = None
self.grubconf = None
self.mounts = None
self.inittab = None
self.uname = None
self.securetty = None
self.bcu = None
self.blockdev = None
self.rclocal = None
self.ioschedulers = None
self.sysctl = None
self.limitsconf = None
self.connectemc = None
self.ntp = None
def __str__(self):
ser = '=============SERVICES=======================\n'
xin = '=============XINETD =======================\n'
err = '=============CHKCONFIG ERRORMSG=============\n'
output = '%s%s\n%s%s\n%s%s' % (ser, self.chkconfig.services.__str__(), xin, self.chkconfig.xinetd.__str__(), err, self.chkconfig.errormsg)
omr = '=============OMREPORT VERSION ==============\n'
ome = '=============OMREPORT VERSION ERRORMSG======\n'
output = '%s\n%s%s\n%s%s' % (output, omr, self.omreport.omversion, ome, self.omreport.omversion_errormsg)
omr = '=============OMREPORT BIOS==================\n'
ome = '=============OMREPORT BIOS ERRORMSG=========\n'
output = '%s\n%s%s\n%s%s' % (output, omr, self.omreport.bios.__str__(), ome, self.omreport.bios_errormsg)
omr = '=============OMREPORT BIOSSETUP=============\n'
ome = '=============OMREPORT BIOSSETUP ERRORMSG====\n'
output = '%s\n%s%s\n%s%s' % (output, omr, self.omreport.biossetup.__str__(), ome, self.omreport.biossetup_errormsg)
omr = '=============OMREPORT CONTROLLER============\n'
ome = '=============OMREPORT CONTROLLER ERRORMSG===\n'
output = '%s\n%s%s\n%s%s' % (output, omr, self.omreport.controller.__str__(), ome, self.omreport.controller_errormsg)
boo = '=============OMREPORT BOOTORDER=============\n'
boe = '=============OMREPORT BOOTORDER ERRORMSG====\n'
output = '%s\n%s%s\n%s%s' % (output, boo, self.omreport.bootorder.__str__(), boe, self.omreport.bootorder_errormsg)
omr = '=============OMREPORT REMOTEACCESS==========\n'
ome = '=============OMREPORT REMOTEACCESS ERRORMSG=\n'
output = '%s\n%s%s\n%s%s' % (output, omr, self.omreport.remoteaccess.__str__(), ome, self.omreport.remoteaccess_errormsg)
omr = '=============OMREPORT ALERTS==========\n'
ome = '=============OMREPORT ALERTS ERRORMSG=\n'
output = '%s\n%s%s\n%s%s' % (output, omr, self.omreport.alerts.__str__(), ome, self.omreport.alerts_errormsg)
omr = '=============OMREPORT VIRTUAL DISKS=========\n'
ome = '=============OMREPORT VIRTUAL DISKS ERRORMSG\n'
output = '%s\n%s%s\n%s%s' % (output, omr, self.omreport.vdisks.__str__(), ome, self.omreport.vdisks_errormsg)
grc = '============= GRUB.CONF======================\n'
gre = '============= GRUB.CONF ERRORMSG=============\n'
output = '%s\n%s%s\n%s%s' % (output, grc, self.grubconf.__str__(), gre, self.grubconf.errormsg)
grc = '============= SYSCTL=========================\n'
gre = '============= SYSCTL ERRORMSG================\n'
output = '%s\n%s%s\n%s%s' % (output, grc, self.sysctl.variables.__str__(), gre, self.sysctl.errormsg)
grc = '============= LIMITS=========================\n'
gre = '============= LIMITS ERRORMSG================\n'
output = '%s\n%s%s\n%s%s' % (output, grc, self.limitsconf.__str__(), gre, self.limitsconf.errormsg)
mnt = '============= MOUNT==========================\n'
mte = '============= MOUNT ERRORMSG=================\n'
output = '%s\n%s%s\n%s%s' % (output, mnt, self.mounts.__str__(), mte, self.mounts.errormsg)
grc = '============= INITTAB========================\n'
gre = '============= INITTAB ERRORMSG===============\n'
output = '%s\n%s%s\n%s%s' % (output, grc, self.inittab.__str__(), gre, self.inittab.errormsg)
grc = '============= UNAME==========================\n'
gre = '============= UNAME ERRORMSG=================\n'
output = '%s\n%s%s\n%s%s' % (output, grc, self.uname.__str__(), gre, self.uname.errormsg)
grc = '============= CONNECTEMC=====================\n'
gre = '============= CONNECtEMC ERRORMSG============\n'
output = '%s\n%s%s\n%s%s' % (output, grc, self.connectemc.__str__(), gre, self.connectemc.errormsg)
grc = '============= SECURETTY======================\n'
gre = '============= SECURETTY ERRORMSG=============\n'
output = '%s\n%s%s\n%s%s' % (output, grc, self.securetty.data.__str__(), gre, self.securetty.errormsg)
grc = '============= IO SCHEDULERS==================\n'
gre = '============= IO SCHEDULERS ERRORMSG========\n'
output = '%s\n%s%s\n%s%s' % (output, grc, self.ioschedulers.devices.__str__(), gre, self.ioschedulers.errormsg)
grc = '============= BLOCKDEV RA ====================\n'
gre = '============= BLOCKDEV RA ERRORMSG============\n'
output = '%s\n%s%s\n%s%s' % (output, grc, self.blockdev.ra.__str__(), gre, self.blockdev.errormsg)
grc = '============= BCU CNA ========================\n'
gre = '============= BCU CNA ERRORMSG================\n'
output = '%s\n%s%s\n%s%s' % (output, grc, self.bcu.__str__(), gre, self.bcu.errormsg)
grc = '============= /etc/rc.d/rc.local =============\n'
output = '%s\n%s%s' % (output, grc, self.rclocal.__str__())
grc = '============= NTPD ===========================\n'
gre = '============= NTPD ERRORMSG===================\n'
output = '%s\n%s%s\n%s%s' % (output, grc, self.ntp.__str__(), gre, self.ntp.errormsg)
return output |
true = True
false = False
abi = [
{
"inputs": [],
"stateMutability": "nonpayable",
"type": "constructor"
},
{
"stateMutability": "payable",
"type": "fallback"
},
{
"inputs": [],
"name": "client_cancellation",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [],
"name": "client_delete_random_index",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{
"internalType": "uint256",
"name": "i",
"type": "uint256"
}
],
"name": "client_download_MSRI",
"outputs": [
{
"internalType": "bytes",
"name": "",
"type": "bytes"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [
{
"internalType": "uint256",
"name": "i",
"type": "uint256"
}
],
"name": "client_download_encrypted_keys",
"outputs": [
{
"internalType": "bytes",
"name": "",
"type": "bytes"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "client_generate_random_index",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [],
"name": "client_get_RIAlength",
"outputs": [
{
"internalType": "uint8",
"name": "",
"type": "uint8"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "client_get_current_RIA_length",
"outputs": [
{
"internalType": "uint256",
"name": "",
"type": "uint256"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "client_get_update_period",
"outputs": [
{
"internalType": "uint256",
"name": "",
"type": "uint256"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [
{
"internalType": "bytes",
"name": "str",
"type": "bytes"
}
],
"name": "client_register",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [],
"name": "client_registration_check",
"outputs": [
{
"internalType": "uint256",
"name": "",
"type": "uint256"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [
{
"internalType": "address payable",
"name": "addr",
"type": "address"
}
],
"name": "contract_transfer_to_relay",
"outputs": [],
"stateMutability": "payable",
"type": "function"
},
{
"inputs": [
{
"internalType": "address",
"name": "Addr",
"type": "address"
}
],
"name": "getClientFlag",
"outputs": [
{
"internalType": "bool",
"name": "",
"type": "bool"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [
{
"internalType": "address",
"name": "addr",
"type": "address"
}
],
"name": "getRIA",
"outputs": [
{
"internalType": "uint16[]",
"name": "",
"type": "uint16[]"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [
{
"internalType": "uint16",
"name": "i",
"type": "uint16"
}
],
"name": "getRelayFlag",
"outputs": [
{
"internalType": "bool",
"name": "",
"type": "bool"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "getclientNum",
"outputs": [
{
"internalType": "uint24",
"name": "",
"type": "uint24"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [
{
"internalType": "uint16",
"name": "i",
"type": "uint16"
}
],
"name": "getinfo",
"outputs": [
{
"internalType": "bytes",
"name": "",
"type": "bytes"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "getrelayIndex",
"outputs": [
{
"internalType": "uint16",
"name": "",
"type": "uint16"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [
{
"internalType": "address",
"name": "Addr",
"type": "address"
},
{
"internalType": "bool",
"name": "flag",
"type": "bool"
}
],
"name": "modifyClientFlag",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{
"internalType": "uint16",
"name": "i",
"type": "uint16"
},
{
"internalType": "bool",
"name": "flag",
"type": "bool"
}
],
"name": "modifyRelayFlag",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [],
"name": "relay_cancellation",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{
"internalType": "uint256",
"name": "i",
"type": "uint256"
}
],
"name": "relay_download_clients_public_keys",
"outputs": [
{
"internalType": "bytes",
"name": "",
"type": "bytes"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "relay_get_clientlist_length",
"outputs": [
{
"internalType": "uint256",
"name": "",
"type": "uint256"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "relay_get_upload_period",
"outputs": [
{
"internalType": "uint256",
"name": "",
"type": "uint256"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "relay_register",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [],
"name": "relay_registration_check",
"outputs": [
{
"internalType": "uint256",
"name": "",
"type": "uint256"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [
{
"internalType": "bytes",
"name": "info",
"type": "bytes"
},
{
"internalType": "uint256",
"name": "num",
"type": "uint256"
},
{
"internalType": "bytes[]",
"name": "keys",
"type": "bytes[]"
}
],
"name": "relay_upload_SRI_and_keys",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{
"internalType": "uint256",
"name": "i",
"type": "uint256"
},
{
"internalType": "uint256",
"name": "num",
"type": "uint256"
},
{
"internalType": "bytes[]",
"name": "keys",
"type": "bytes[]"
}
],
"name": "relay_upload_keys",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{
"internalType": "uint8",
"name": "num",
"type": "uint8"
}
],
"name": "setRIAlength",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{
"internalType": "uint256",
"name": "period",
"type": "uint256"
}
],
"name": "setRIAperiod",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{
"internalType": "uint256",
"name": "period",
"type": "uint256"
}
],
"name": "setSRIperiod",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"stateMutability": "payable",
"type": "receive"
}
] | true = True
false = False
abi = [{'inputs': [], 'stateMutability': 'nonpayable', 'type': 'constructor'}, {'stateMutability': 'payable', 'type': 'fallback'}, {'inputs': [], 'name': 'client_cancellation', 'outputs': [], 'stateMutability': 'nonpayable', 'type': 'function'}, {'inputs': [], 'name': 'client_delete_random_index', 'outputs': [], 'stateMutability': 'nonpayable', 'type': 'function'}, {'inputs': [{'internalType': 'uint256', 'name': 'i', 'type': 'uint256'}], 'name': 'client_download_MSRI', 'outputs': [{'internalType': 'bytes', 'name': '', 'type': 'bytes'}], 'stateMutability': 'view', 'type': 'function'}, {'inputs': [{'internalType': 'uint256', 'name': 'i', 'type': 'uint256'}], 'name': 'client_download_encrypted_keys', 'outputs': [{'internalType': 'bytes', 'name': '', 'type': 'bytes'}], 'stateMutability': 'view', 'type': 'function'}, {'inputs': [], 'name': 'client_generate_random_index', 'outputs': [], 'stateMutability': 'nonpayable', 'type': 'function'}, {'inputs': [], 'name': 'client_get_RIAlength', 'outputs': [{'internalType': 'uint8', 'name': '', 'type': 'uint8'}], 'stateMutability': 'view', 'type': 'function'}, {'inputs': [], 'name': 'client_get_current_RIA_length', 'outputs': [{'internalType': 'uint256', 'name': '', 'type': 'uint256'}], 'stateMutability': 'view', 'type': 'function'}, {'inputs': [], 'name': 'client_get_update_period', 'outputs': [{'internalType': 'uint256', 'name': '', 'type': 'uint256'}], 'stateMutability': 'view', 'type': 'function'}, {'inputs': [{'internalType': 'bytes', 'name': 'str', 'type': 'bytes'}], 'name': 'client_register', 'outputs': [], 'stateMutability': 'nonpayable', 'type': 'function'}, {'inputs': [], 'name': 'client_registration_check', 'outputs': [{'internalType': 'uint256', 'name': '', 'type': 'uint256'}], 'stateMutability': 'view', 'type': 'function'}, {'inputs': [{'internalType': 'address payable', 'name': 'addr', 'type': 'address'}], 'name': 'contract_transfer_to_relay', 'outputs': [], 'stateMutability': 'payable', 'type': 'function'}, {'inputs': [{'internalType': 'address', 'name': 'Addr', 'type': 'address'}], 'name': 'getClientFlag', 'outputs': [{'internalType': 'bool', 'name': '', 'type': 'bool'}], 'stateMutability': 'view', 'type': 'function'}, {'inputs': [{'internalType': 'address', 'name': 'addr', 'type': 'address'}], 'name': 'getRIA', 'outputs': [{'internalType': 'uint16[]', 'name': '', 'type': 'uint16[]'}], 'stateMutability': 'view', 'type': 'function'}, {'inputs': [{'internalType': 'uint16', 'name': 'i', 'type': 'uint16'}], 'name': 'getRelayFlag', 'outputs': [{'internalType': 'bool', 'name': '', 'type': 'bool'}], 'stateMutability': 'view', 'type': 'function'}, {'inputs': [], 'name': 'getclientNum', 'outputs': [{'internalType': 'uint24', 'name': '', 'type': 'uint24'}], 'stateMutability': 'view', 'type': 'function'}, {'inputs': [{'internalType': 'uint16', 'name': 'i', 'type': 'uint16'}], 'name': 'getinfo', 'outputs': [{'internalType': 'bytes', 'name': '', 'type': 'bytes'}], 'stateMutability': 'view', 'type': 'function'}, {'inputs': [], 'name': 'getrelayIndex', 'outputs': [{'internalType': 'uint16', 'name': '', 'type': 'uint16'}], 'stateMutability': 'view', 'type': 'function'}, {'inputs': [{'internalType': 'address', 'name': 'Addr', 'type': 'address'}, {'internalType': 'bool', 'name': 'flag', 'type': 'bool'}], 'name': 'modifyClientFlag', 'outputs': [], 'stateMutability': 'nonpayable', 'type': 'function'}, {'inputs': [{'internalType': 'uint16', 'name': 'i', 'type': 'uint16'}, {'internalType': 'bool', 'name': 'flag', 'type': 'bool'}], 'name': 'modifyRelayFlag', 'outputs': [], 'stateMutability': 'nonpayable', 'type': 'function'}, {'inputs': [], 'name': 'relay_cancellation', 'outputs': [], 'stateMutability': 'nonpayable', 'type': 'function'}, {'inputs': [{'internalType': 'uint256', 'name': 'i', 'type': 'uint256'}], 'name': 'relay_download_clients_public_keys', 'outputs': [{'internalType': 'bytes', 'name': '', 'type': 'bytes'}], 'stateMutability': 'view', 'type': 'function'}, {'inputs': [], 'name': 'relay_get_clientlist_length', 'outputs': [{'internalType': 'uint256', 'name': '', 'type': 'uint256'}], 'stateMutability': 'view', 'type': 'function'}, {'inputs': [], 'name': 'relay_get_upload_period', 'outputs': [{'internalType': 'uint256', 'name': '', 'type': 'uint256'}], 'stateMutability': 'view', 'type': 'function'}, {'inputs': [], 'name': 'relay_register', 'outputs': [], 'stateMutability': 'nonpayable', 'type': 'function'}, {'inputs': [], 'name': 'relay_registration_check', 'outputs': [{'internalType': 'uint256', 'name': '', 'type': 'uint256'}], 'stateMutability': 'view', 'type': 'function'}, {'inputs': [{'internalType': 'bytes', 'name': 'info', 'type': 'bytes'}, {'internalType': 'uint256', 'name': 'num', 'type': 'uint256'}, {'internalType': 'bytes[]', 'name': 'keys', 'type': 'bytes[]'}], 'name': 'relay_upload_SRI_and_keys', 'outputs': [], 'stateMutability': 'nonpayable', 'type': 'function'}, {'inputs': [{'internalType': 'uint256', 'name': 'i', 'type': 'uint256'}, {'internalType': 'uint256', 'name': 'num', 'type': 'uint256'}, {'internalType': 'bytes[]', 'name': 'keys', 'type': 'bytes[]'}], 'name': 'relay_upload_keys', 'outputs': [], 'stateMutability': 'nonpayable', 'type': 'function'}, {'inputs': [{'internalType': 'uint8', 'name': 'num', 'type': 'uint8'}], 'name': 'setRIAlength', 'outputs': [], 'stateMutability': 'nonpayable', 'type': 'function'}, {'inputs': [{'internalType': 'uint256', 'name': 'period', 'type': 'uint256'}], 'name': 'setRIAperiod', 'outputs': [], 'stateMutability': 'nonpayable', 'type': 'function'}, {'inputs': [{'internalType': 'uint256', 'name': 'period', 'type': 'uint256'}], 'name': 'setSRIperiod', 'outputs': [], 'stateMutability': 'nonpayable', 'type': 'function'}, {'stateMutability': 'payable', 'type': 'receive'}] |
# Copyright 2020 The FedLearner Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the 'License');
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an 'AS IS' BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# coding: utf-8
# TODO THIS FILE SHOULD BE MERGED WITH fedlearner.common.common
# TODO MIND THE SUBTLE DIFFERENCES DUE TO ES COMPATIBILITY WHEN MERGING
# YYYY-MM-DD'T'hh:mm:ss.SSSSSSZ
_es_datetime_format = 'strict_date_optional_time'
RAW_DATA_MAPPINGS = {
'dynamic': True,
'dynamic_templates': [
{
'strings': {
'match_mapping_type': 'string',
'mapping': {
'type': 'keyword'
}
}
}
],
'properties': {
'partition': {
'type': 'short'
},
'application_id': {
'ignore_above': 128,
'type': 'keyword'
},
'event_time': {
'format': _es_datetime_format,
'type': 'date'
},
'process_time': {
'format': _es_datetime_format,
'type': 'date'
}
}
}
DATA_JOIN_MAPPINGS = {
'dynamic': True,
# for dynamically adding string fields, use keyword to reduce space
'dynamic_templates': [
{
'strings': {
'match_mapping_type': 'string',
'mapping': {
'type': 'keyword'
}
}
}
],
'properties': {
'partition': {
'type': 'short'
},
'joined': {
'type': 'byte'
},
'label': {
'ignore_above': 32,
'type': 'keyword'
},
'type': {
'ignore_above': 32,
'type': 'keyword'
},
'has_click_id': {
'type': 'boolean'
},
'has_example_id': {
'type': 'boolean'
},
'application_id': {
'ignore_above': 128,
'type': 'keyword'
},
'process_time': {
'format': _es_datetime_format,
'type': 'date'
},
'event_time': {
'format': _es_datetime_format,
'type': 'date'
}
}
}
METRICS_MAPPINGS = {
'dynamic': True,
'dynamic_templates': [
{
'strings': {
'match_mapping_type': 'string',
'mapping': {
'type': 'keyword'
}
}
}
],
'properties': {
'name': {
'type': 'keyword'
},
'value': {
'type': 'float'
},
'date_time': {
'format': _es_datetime_format,
'type': 'date'
},
'tags': {
'properties': {
'partition': {
'type': 'short'
},
'application_id': {
'ignore_above': 128,
'type': 'keyword'
},
'data_source_name': {
'ignore_above': 128,
'type': 'keyword'
},
'joiner_name': {
'ignore_above': 32,
'type': 'keyword'
},
'role': {
'ignore_above': 32,
'type': 'keyword'
},
'event_time': {
'type': 'date',
'format': _es_datetime_format
}
}
}
}
}
ALIAS_NAME = {'metrics': 'metrics_v2',
'raw_data': 'raw_data',
'data_join': 'data_join'}
INDEX_MAP = {'metrics': METRICS_MAPPINGS,
'raw_data': RAW_DATA_MAPPINGS,
'data_join': DATA_JOIN_MAPPINGS}
def get_es_template(index_type, shards):
assert index_type in ALIAS_NAME
alias_name = ALIAS_NAME[index_type]
template = {'index_patterns': ['{}-*'.format(alias_name)],
'settings': {
'index': {
'lifecycle': {
'name': 'fedlearner_{}_ilm'.format(index_type),
'rollover_alias': alias_name
},
'codec': 'best_compression',
'routing': {
'allocation': {
'total_shards_per_node': '1'
}
},
'refresh_interval': '60s',
'number_of_shards': str(shards),
'number_of_replicas': '1',
}
},
'mappings': INDEX_MAP[index_type]}
return template
| _es_datetime_format = 'strict_date_optional_time'
raw_data_mappings = {'dynamic': True, 'dynamic_templates': [{'strings': {'match_mapping_type': 'string', 'mapping': {'type': 'keyword'}}}], 'properties': {'partition': {'type': 'short'}, 'application_id': {'ignore_above': 128, 'type': 'keyword'}, 'event_time': {'format': _es_datetime_format, 'type': 'date'}, 'process_time': {'format': _es_datetime_format, 'type': 'date'}}}
data_join_mappings = {'dynamic': True, 'dynamic_templates': [{'strings': {'match_mapping_type': 'string', 'mapping': {'type': 'keyword'}}}], 'properties': {'partition': {'type': 'short'}, 'joined': {'type': 'byte'}, 'label': {'ignore_above': 32, 'type': 'keyword'}, 'type': {'ignore_above': 32, 'type': 'keyword'}, 'has_click_id': {'type': 'boolean'}, 'has_example_id': {'type': 'boolean'}, 'application_id': {'ignore_above': 128, 'type': 'keyword'}, 'process_time': {'format': _es_datetime_format, 'type': 'date'}, 'event_time': {'format': _es_datetime_format, 'type': 'date'}}}
metrics_mappings = {'dynamic': True, 'dynamic_templates': [{'strings': {'match_mapping_type': 'string', 'mapping': {'type': 'keyword'}}}], 'properties': {'name': {'type': 'keyword'}, 'value': {'type': 'float'}, 'date_time': {'format': _es_datetime_format, 'type': 'date'}, 'tags': {'properties': {'partition': {'type': 'short'}, 'application_id': {'ignore_above': 128, 'type': 'keyword'}, 'data_source_name': {'ignore_above': 128, 'type': 'keyword'}, 'joiner_name': {'ignore_above': 32, 'type': 'keyword'}, 'role': {'ignore_above': 32, 'type': 'keyword'}, 'event_time': {'type': 'date', 'format': _es_datetime_format}}}}}
alias_name = {'metrics': 'metrics_v2', 'raw_data': 'raw_data', 'data_join': 'data_join'}
index_map = {'metrics': METRICS_MAPPINGS, 'raw_data': RAW_DATA_MAPPINGS, 'data_join': DATA_JOIN_MAPPINGS}
def get_es_template(index_type, shards):
assert index_type in ALIAS_NAME
alias_name = ALIAS_NAME[index_type]
template = {'index_patterns': ['{}-*'.format(alias_name)], 'settings': {'index': {'lifecycle': {'name': 'fedlearner_{}_ilm'.format(index_type), 'rollover_alias': alias_name}, 'codec': 'best_compression', 'routing': {'allocation': {'total_shards_per_node': '1'}}, 'refresh_interval': '60s', 'number_of_shards': str(shards), 'number_of_replicas': '1'}}, 'mappings': INDEX_MAP[index_type]}
return template |
my_list = list(range(1, 11))
print(my_list)
def maxInList(aList): # non-recursion method
max_number = aList[0]
for i in range(1, len(aList)):
if max_number < aList[i]:
max_number = aList[i]
return max_number
def minInList(aList): # non-recursion method
min_number = aList[0]
for i in range(1, len(aList)):
if min_number > aList[i]:
min_number = aList[i]
return min_number
print(maxInList(my_list))
print(minInList(my_list))
| my_list = list(range(1, 11))
print(my_list)
def max_in_list(aList):
max_number = aList[0]
for i in range(1, len(aList)):
if max_number < aList[i]:
max_number = aList[i]
return max_number
def min_in_list(aList):
min_number = aList[0]
for i in range(1, len(aList)):
if min_number > aList[i]:
min_number = aList[i]
return min_number
print(max_in_list(my_list))
print(min_in_list(my_list)) |
#!/usr/bin/env python
#
# Copyright (c) 2018 10X Genomics, Inc. All rights reserved.
#
MATRIX_MEM_GB_MULTIPLIER = 2 # TODO reduce this once we're confident about the actual memory bounds
NUM_MATRIX_ENTRIES_PER_MEM_GB = 50e6
# Empirical obs: with new CountMatrix setup, take ~ 50 bytes/bc
NUM_MATRIX_BARCODES_PER_MEM_GB = 2000000
MIN_MEM_GB = 3
MIN_MEM_GB_NOWHITELIST = 64
GZIP_SUFFIX = '.gz'
LZ4_SUFFIX = '.lz4'
H5_COMPRESSION_LEVEL = 1
H5_FILETYPE_KEY = 'filetype'
H5_FEATURE_REF_ATTR = 'features'
H5_BCS_ATTR = 'barcodes'
H5_MATRIX_DATA_ATTR = 'data'
H5_MATRIX_INDICES_ATTR = 'indices'
H5_MATRIX_INDPTR_ATTR = 'indptr'
H5_MATRIX_SHAPE_ATTR = 'shape'
H5_MATRIX_ATTRS = {H5_MATRIX_DATA_ATTR: 'int32', H5_MATRIX_INDICES_ATTR: 'int64', H5_MATRIX_INDPTR_ATTR: 'int64', H5_MATRIX_SHAPE_ATTR: 'int32'}
H5_CHEMISTRY_DESC_KEY = 'chemistry_description'
H5_LIBRARY_ID_MAPPING_KEY = 'library_ids'
H5_ORIG_GEM_GROUP_MAPPING_KEY = 'original_gem_groups'
H5_METADATA_ATTRS = [H5_LIBRARY_ID_MAPPING_KEY, H5_ORIG_GEM_GROUP_MAPPING_KEY, H5_CHEMISTRY_DESC_KEY]
| matrix_mem_gb_multiplier = 2
num_matrix_entries_per_mem_gb = 50000000.0
num_matrix_barcodes_per_mem_gb = 2000000
min_mem_gb = 3
min_mem_gb_nowhitelist = 64
gzip_suffix = '.gz'
lz4_suffix = '.lz4'
h5_compression_level = 1
h5_filetype_key = 'filetype'
h5_feature_ref_attr = 'features'
h5_bcs_attr = 'barcodes'
h5_matrix_data_attr = 'data'
h5_matrix_indices_attr = 'indices'
h5_matrix_indptr_attr = 'indptr'
h5_matrix_shape_attr = 'shape'
h5_matrix_attrs = {H5_MATRIX_DATA_ATTR: 'int32', H5_MATRIX_INDICES_ATTR: 'int64', H5_MATRIX_INDPTR_ATTR: 'int64', H5_MATRIX_SHAPE_ATTR: 'int32'}
h5_chemistry_desc_key = 'chemistry_description'
h5_library_id_mapping_key = 'library_ids'
h5_orig_gem_group_mapping_key = 'original_gem_groups'
h5_metadata_attrs = [H5_LIBRARY_ID_MAPPING_KEY, H5_ORIG_GEM_GROUP_MAPPING_KEY, H5_CHEMISTRY_DESC_KEY] |
# 8. Write a program that swaps the values of three variables x,y, and z, so that x gets the value
# of y, y gets the value of z, and z gets the value of x.
x, y, z = 5, 10, 15
x, y, z = y, z, x # The power of Python ;)
# print(x, y, z) : 10 15 5
| (x, y, z) = (5, 10, 15)
(x, y, z) = (y, z, x) |
vts = list()
vts.append(0)
vtx = list()
total = 0
def dfs(cur, visited:list):
global vtx, total
if cache[cur] != -1:
total += cache[cur]
return
if not vtx[cur]:
if cur == tg + 3:
total += 1
return
visited = visited.copy()
visited.append(cur)
for i in vtx[cur]:
if not i in visited:
dfs(i, visited)
while True:
try:
vts.append(int(input()))
except EOFError:
break
tg = max(vts)
vts.append(tg + 3)
vts.sort()
vtx = [0]*(tg + 4)
cache = [-1]*(tg + 4)
cnt = len(vts) - 1
for i in range(cnt):
vtx[vts[i]] = list()
vtx[vts[i]].append(vts[i + 1])
if i + 2 <= cnt and vts[i + 2] - vts[i] <= 3: vtx[vts[i]].append(vts[i+2])
if i + 3 <= cnt and vts[i + 3] - vts[i] <= 3: vtx[vts[i]].append(vts[i+3])
for i in range(cnt + 1):
if vtx[cnt - i] == 0: continue
total = 0
dfs(cnt - i, list())
cache[cnt - i] = total
print(total) | vts = list()
vts.append(0)
vtx = list()
total = 0
def dfs(cur, visited: list):
global vtx, total
if cache[cur] != -1:
total += cache[cur]
return
if not vtx[cur]:
if cur == tg + 3:
total += 1
return
visited = visited.copy()
visited.append(cur)
for i in vtx[cur]:
if not i in visited:
dfs(i, visited)
while True:
try:
vts.append(int(input()))
except EOFError:
break
tg = max(vts)
vts.append(tg + 3)
vts.sort()
vtx = [0] * (tg + 4)
cache = [-1] * (tg + 4)
cnt = len(vts) - 1
for i in range(cnt):
vtx[vts[i]] = list()
vtx[vts[i]].append(vts[i + 1])
if i + 2 <= cnt and vts[i + 2] - vts[i] <= 3:
vtx[vts[i]].append(vts[i + 2])
if i + 3 <= cnt and vts[i + 3] - vts[i] <= 3:
vtx[vts[i]].append(vts[i + 3])
for i in range(cnt + 1):
if vtx[cnt - i] == 0:
continue
total = 0
dfs(cnt - i, list())
cache[cnt - i] = total
print(total) |
#!/usr/bin/env prey
async def main():
await x("ls -a")
cd("..")
a = await x("ls")
await asyncio.sleep(2)
| async def main():
await x('ls -a')
cd('..')
a = await x('ls')
await asyncio.sleep(2) |
class Solution:
def halvesAreAlike(self, s: str) -> bool:
num_vowels=0
num_vowels1=0
split = -( ( -len(s) )//2 )
p1, p2 = s[:split], s[split:]
for char in p1:
if char in "aeiouAEIOU":
num_vowels = num_vowels+1
for char in p2:
if char in "aeiouAEIOU":
num_vowels1 = num_vowels1+1
return num_vowels== num_vowels1
| class Solution:
def halves_are_alike(self, s: str) -> bool:
num_vowels = 0
num_vowels1 = 0
split = -(-len(s) // 2)
(p1, p2) = (s[:split], s[split:])
for char in p1:
if char in 'aeiouAEIOU':
num_vowels = num_vowels + 1
for char in p2:
if char in 'aeiouAEIOU':
num_vowels1 = num_vowels1 + 1
return num_vowels == num_vowels1 |
class BaseValidationError(ValueError):
pass
class LogInFileNotParsedError(BaseValidationError):
pass
| class Basevalidationerror(ValueError):
pass
class Loginfilenotparsederror(BaseValidationError):
pass |
# -*- coding: utf-8 -*-
class TransitionType(object):
def __init__(self, utc_offset, is_dst, abbrev):
self.utc_offset = utc_offset
self.is_dst = is_dst
self.abbrev = abbrev
def __repr__(self):
return '<TransitionType [{}, {}, {}]>'.format(
self.utc_offset,
self.is_dst,
self.abbrev
)
| class Transitiontype(object):
def __init__(self, utc_offset, is_dst, abbrev):
self.utc_offset = utc_offset
self.is_dst = is_dst
self.abbrev = abbrev
def __repr__(self):
return '<TransitionType [{}, {}, {}]>'.format(self.utc_offset, self.is_dst, self.abbrev) |
#!/usr/bin/env python
# coding: utf-8
# In given array find the duplicate odd number .
#
# Note: There is only one duplicate odd number
#
# <b> Ex [1,4,6,3,1] should return 1 </b>
# In[3]:
def dup_odd_num(num):
count=0
for i in range(len(num)):
if num[i] % 2 != 0:
count+=1
if count > 1: return num[i]
return False
print(dup_odd_num([1,3,2,3]))
# In[ ]:
def dup_odd_num(num):
count=0
dic={}
for i in range(len(num)):
if num[i] % 2 != 0:
dic[0]=count
dic[1]=num[i]
count+=1
return dic[1]
# In[28]:
print(dup_odd_num([3,4,6,8,]))
| def dup_odd_num(num):
count = 0
for i in range(len(num)):
if num[i] % 2 != 0:
count += 1
if count > 1:
return num[i]
return False
print(dup_odd_num([1, 3, 2, 3]))
def dup_odd_num(num):
count = 0
dic = {}
for i in range(len(num)):
if num[i] % 2 != 0:
dic[0] = count
dic[1] = num[i]
count += 1
return dic[1]
print(dup_odd_num([3, 4, 6, 8])) |
a = int(input())
b = int(input())
count = 0
x = 0
a1 = str(a)
b1 = str(b)
if len(a1) == len(b1):
for i in a1:
for j in b1[x::]:
if i != j:
count += 1
x += 1
break
print(count)
| a = int(input())
b = int(input())
count = 0
x = 0
a1 = str(a)
b1 = str(b)
if len(a1) == len(b1):
for i in a1:
for j in b1[x:]:
if i != j:
count += 1
x += 1
break
print(count) |
valores =[]
valores_quadrado =[]
for i in range(10):
valores.append(int(input("Digite um numero inteiro: ")))
for i in valores:
valores_quadrado.append(i**2)
print("Valores da lista ao quadrado: ",valores_quadrado)
print("Soma dos quadrados: ",sum(valores_quadrado)) | valores = []
valores_quadrado = []
for i in range(10):
valores.append(int(input('Digite um numero inteiro: ')))
for i in valores:
valores_quadrado.append(i ** 2)
print('Valores da lista ao quadrado: ', valores_quadrado)
print('Soma dos quadrados: ', sum(valores_quadrado)) |
def str_seems_like_json(txt):
for c in txt:
if c not in "\r\n\t ":
return c == '{'
return False
def bytes_seems_like_json(binary):
for b in binary:
if b not in [13, 10, 9, 32]:
return b == 123
return False
| def str_seems_like_json(txt):
for c in txt:
if c not in '\r\n\t ':
return c == '{'
return False
def bytes_seems_like_json(binary):
for b in binary:
if b not in [13, 10, 9, 32]:
return b == 123
return False |
DEFAULT_SESSION_DURATION = 43200 # 12 hours
SANDBOX_SESSION_DURATION = 60 * 60 # 1 hour
BASTION_PROFILE_ENV_NAME = 'FIGGY_AWS_PROFILE'
AWS_REGIONS = ['us-east-1', 'us-east-2', 'us-west-1', 'us-west-2', 'af-south-1', 'ap-east-1', 'ap-east-2',
'ap-northeast-3', 'ap-northeast-2', 'ap-northeast-1', 'ap-southeast-1', 'ap-southeast-2',
'ca-central-1', 'cn-north-1', 'cn-northwest-1', 'eu-central-1', 'eu-west-1', 'eu-west-2',
'eu-west-3', 'eu-north-1', 'me-south-1', 'sa-east-1', 'us-gov-east-1', 'us-gov-west-1']
AWS_CFG_ACCESS_KEY_ID = 'aws_access_key_id'
AWS_CFG_SECRET_KEY = 'aws_secret_access_key'
AWS_CFG_TOKEN = 'aws_session_token'
AWS_CFG_REGION = 'region'
AWS_CFG_OUTPUT = 'output'
RESTRICTED_ENV_VARS = ['AWS_ACCESS_KEY_ID', 'AWS_DEFAULT_REGION', 'AWS_PROFILE', 'AWS_SECRET_ACCESS_KEY', 'AWS_SESSION_TOKEN'] | default_session_duration = 43200
sandbox_session_duration = 60 * 60
bastion_profile_env_name = 'FIGGY_AWS_PROFILE'
aws_regions = ['us-east-1', 'us-east-2', 'us-west-1', 'us-west-2', 'af-south-1', 'ap-east-1', 'ap-east-2', 'ap-northeast-3', 'ap-northeast-2', 'ap-northeast-1', 'ap-southeast-1', 'ap-southeast-2', 'ca-central-1', 'cn-north-1', 'cn-northwest-1', 'eu-central-1', 'eu-west-1', 'eu-west-2', 'eu-west-3', 'eu-north-1', 'me-south-1', 'sa-east-1', 'us-gov-east-1', 'us-gov-west-1']
aws_cfg_access_key_id = 'aws_access_key_id'
aws_cfg_secret_key = 'aws_secret_access_key'
aws_cfg_token = 'aws_session_token'
aws_cfg_region = 'region'
aws_cfg_output = 'output'
restricted_env_vars = ['AWS_ACCESS_KEY_ID', 'AWS_DEFAULT_REGION', 'AWS_PROFILE', 'AWS_SECRET_ACCESS_KEY', 'AWS_SESSION_TOKEN'] |
#
# SOFTWARE HISTORY
#
# Date Ticket# Engineer Description
# ------------ ---------- ----------- --------------------------
# Sep 16, 2016 pmoyer Generated
class GetStationsRequest(object):
def __init__(self):
self.pluginName = None
def getPluginName(self):
return self.pluginName
def setPluginName(self, pluginName):
self.pluginName = pluginName
| class Getstationsrequest(object):
def __init__(self):
self.pluginName = None
def get_plugin_name(self):
return self.pluginName
def set_plugin_name(self, pluginName):
self.pluginName = pluginName |
def compute():
ans = sum(1 for i in range(10000) if is_lychrel(i))
return str(ans)
def is_lychrel(n):
for i in range(50):
n += int(str(n)[ : : -1])
if str(n) == str(n)[ : : -1]:
return False
return True
if __name__ == "__main__":
print(compute())
| def compute():
ans = sum((1 for i in range(10000) if is_lychrel(i)))
return str(ans)
def is_lychrel(n):
for i in range(50):
n += int(str(n)[::-1])
if str(n) == str(n)[::-1]:
return False
return True
if __name__ == '__main__':
print(compute()) |
# lecture 3.6, slide 2
# bisection search for square root
x = 12345
epsilon = 0.01
numGuesses = 0
low = 0.0
high = x
ans = (high + low)/2.0
while abs(ans**2 - x) >= epsilon:
print('low = ' + str(low) + ' high = ' + str(high) + ' ans = ' + str(ans))
numGuesses += 1
if ans**2 < x:
low = ans
else:
high = ans
ans = (high + low)/2.0
print('numGuesses = ' + str(numGuesses))
print(str(ans) + ' is close to square root of ' + str(x))
| x = 12345
epsilon = 0.01
num_guesses = 0
low = 0.0
high = x
ans = (high + low) / 2.0
while abs(ans ** 2 - x) >= epsilon:
print('low = ' + str(low) + ' high = ' + str(high) + ' ans = ' + str(ans))
num_guesses += 1
if ans ** 2 < x:
low = ans
else:
high = ans
ans = (high + low) / 2.0
print('numGuesses = ' + str(numGuesses))
print(str(ans) + ' is close to square root of ' + str(x)) |
#!/usr/bin/env python3
# imports go here
#
# Free Coding session for 2015-03-02
# Written by Matt Warren
#
class SimpleClass:
def main(self):
return "HI"
def main2(self):
return "HELLO AGAIN"
if __name__ == '__main__':
sc = SimpleClass()
assert(sc.main.__name__ == 'main')
fn = getattr(sc, 'main')
assert(fn() == 'HI')
fn = getattr(sc, 'main', sc.main2)
assert(fn() == 'HI')
fn = getattr(sc, 'main3', sc.main2)
assert(fn() == 'HELLO AGAIN')
setattr(sc, 'main3', fn)
fn = getattr(sc, 'main3', sc.main2)
assert(fn() == 'HELLO AGAIN')
assert(sc.main3() == 'HELLO AGAIN')
| class Simpleclass:
def main(self):
return 'HI'
def main2(self):
return 'HELLO AGAIN'
if __name__ == '__main__':
sc = simple_class()
assert sc.main.__name__ == 'main'
fn = getattr(sc, 'main')
assert fn() == 'HI'
fn = getattr(sc, 'main', sc.main2)
assert fn() == 'HI'
fn = getattr(sc, 'main3', sc.main2)
assert fn() == 'HELLO AGAIN'
setattr(sc, 'main3', fn)
fn = getattr(sc, 'main3', sc.main2)
assert fn() == 'HELLO AGAIN'
assert sc.main3() == 'HELLO AGAIN' |
r =int(input("enter the row:"))
for i in range(1, r+1):
for j in range(1, i+1):
print("*", end = " ")
print("\n")
x = r
for j in range(1, r):
for i in range(1, x):
print("*", end = " ")
x = x - 1
print("\n")
| r = int(input('enter the row:'))
for i in range(1, r + 1):
for j in range(1, i + 1):
print('*', end=' ')
print('\n')
x = r
for j in range(1, r):
for i in range(1, x):
print('*', end=' ')
x = x - 1
print('\n') |
SERVIDOR_DESTINO = "BIGSQL"
YAML_SCOOP_IMPORT = "sqoop-import"
YAML_SCOOP_EXPORT = "sqoop-export"
YAML_BIGSQL_EXEC = "bigsql-import"
YAML_HDFS_IMPORT = "hdfs-import"
YAML_HDFS_EXPORT = "hdfs-export"
YAML_PYTHON_SCRIPT = "python-script"
YAML_ORIGEM = "origem"
YAML_DESTINO = "destino"
YAML_TABLE = "tabela"
YAML_QUERY = "consulta"
YAML_SCRIPT_FINAL = "script_final"
YAML_SPLITBY = "chave"
YAML_TIPO_TABELA = "tipo_tabela"
YAML_QUANDO_EXISTIR = "se_existir"
YAML_ACAO_SUBSTITUIR = "substituir"
YAML_ACAO_IGNORAR = "ignorar"
YAML_ACAO_INCREMENTAR = "incrementar"
YAML_ACAO_ERRO = "erro"
YAML_ACAO_CARREGAR = "carregar"
YAML_REMOVER_TABELA_GERADA = "remover_tabela_gerada"
YAML_SERVIDORES_TRANSACIONAIS = "servidores"
YAML_SCHEMA = "schema"
YAML_LISTA_ARQUIVOS = "arquivos"
YAML_LISTA_TABELAS = "tabelas"
YAML_ARQUIVO_SCRIPT = "nome_arquivo_script"
YAML_ARQUIVO_SAIDA = "nome_arquivo_saida"
YAML_SCRIPT_PRE = "script_pre_processamento"
YAML_SCRIPT_POS = "script_pos_processamento"
YAML_ARQUIVO_ENTRADA = "nome_arquivo_entrada"
YAML_ESTRUTURA = "estrutura"
YAML_ARQUIVO_ESTRUTURA = "nome_arquivo_estrutura"
YAML_CONVERSAO_AUTOMATICA = "converter_tipos_na_stage"
YAML_FORMATO_TABELA = "nome_tabela"
YAML_FORMATO_SEQUENCIA = "sequencia"
YAML_CONFIG = "configuracao"
YAML_DIR_LOGS = "diretorio_logs"
YAML_DIR_SCRIPTS = "diretorio_scripts"
YAML_DIR_SAIDA = "diretorio_saida"
YAML_DIR_ENTRADA = "diretorio_entrada"
YAML_DIR_ESTRUTURA = "diretorio_estrutura"
YAML_DIR_BACKUP = "diretorio_backup"
YAML_CONTINUA_ERRO = "continuar_em_erro"
YAML_TABELA_CONTROLE = "tabela_controle"
YAML_TABELA_CONTROLE_SQOOP = "sqoop.tabela_controle"
YAML_TABELA_CONTROLE_BIGSQL = "bigsql.tabela_controle"
YAML_WEB_HDFS_HOST = "webhdfs_host"
YAML_HDFS_TEMP_DIR = "hdfs_temp_dir"
YAML_EXECUTA_EM_ERRO = "executar_em_erro"
YAML_MAIL_TO = "reportar"
YAML_SEP_COLUNA = "delimitador_coluna"
YAML_SEP_LINHA = "delimitador_linha"
YAML_CABECALHO = "cabecalho_primeira_linha"
YAML_TIPO_ARQUIVO = "tipo_arquivo"
#YAML_QUOTATION = "delimitador_texto"
| servidor_destino = 'BIGSQL'
yaml_scoop_import = 'sqoop-import'
yaml_scoop_export = 'sqoop-export'
yaml_bigsql_exec = 'bigsql-import'
yaml_hdfs_import = 'hdfs-import'
yaml_hdfs_export = 'hdfs-export'
yaml_python_script = 'python-script'
yaml_origem = 'origem'
yaml_destino = 'destino'
yaml_table = 'tabela'
yaml_query = 'consulta'
yaml_script_final = 'script_final'
yaml_splitby = 'chave'
yaml_tipo_tabela = 'tipo_tabela'
yaml_quando_existir = 'se_existir'
yaml_acao_substituir = 'substituir'
yaml_acao_ignorar = 'ignorar'
yaml_acao_incrementar = 'incrementar'
yaml_acao_erro = 'erro'
yaml_acao_carregar = 'carregar'
yaml_remover_tabela_gerada = 'remover_tabela_gerada'
yaml_servidores_transacionais = 'servidores'
yaml_schema = 'schema'
yaml_lista_arquivos = 'arquivos'
yaml_lista_tabelas = 'tabelas'
yaml_arquivo_script = 'nome_arquivo_script'
yaml_arquivo_saida = 'nome_arquivo_saida'
yaml_script_pre = 'script_pre_processamento'
yaml_script_pos = 'script_pos_processamento'
yaml_arquivo_entrada = 'nome_arquivo_entrada'
yaml_estrutura = 'estrutura'
yaml_arquivo_estrutura = 'nome_arquivo_estrutura'
yaml_conversao_automatica = 'converter_tipos_na_stage'
yaml_formato_tabela = 'nome_tabela'
yaml_formato_sequencia = 'sequencia'
yaml_config = 'configuracao'
yaml_dir_logs = 'diretorio_logs'
yaml_dir_scripts = 'diretorio_scripts'
yaml_dir_saida = 'diretorio_saida'
yaml_dir_entrada = 'diretorio_entrada'
yaml_dir_estrutura = 'diretorio_estrutura'
yaml_dir_backup = 'diretorio_backup'
yaml_continua_erro = 'continuar_em_erro'
yaml_tabela_controle = 'tabela_controle'
yaml_tabela_controle_sqoop = 'sqoop.tabela_controle'
yaml_tabela_controle_bigsql = 'bigsql.tabela_controle'
yaml_web_hdfs_host = 'webhdfs_host'
yaml_hdfs_temp_dir = 'hdfs_temp_dir'
yaml_executa_em_erro = 'executar_em_erro'
yaml_mail_to = 'reportar'
yaml_sep_coluna = 'delimitador_coluna'
yaml_sep_linha = 'delimitador_linha'
yaml_cabecalho = 'cabecalho_primeira_linha'
yaml_tipo_arquivo = 'tipo_arquivo' |
{
# Ports for the left-side motors
"leftMotorPorts": [0, 1],
# Ports for the right-side motors
"rightMotorPorts": [2, 3],
# NOTE: Inversions of the slaves (i.e. any motor *after* the first on
# each side of the drive) are *with respect to their master*. This is
# different from the other poject types!
# Inversions for the left-side motors
"leftMotorsInverted": [False, False],
# Inversions for the right side motors
"rightMotorsInverted": [False, False],
# If your robot has only one encoder, remove all of the right encoder fields
# Encoder pulses-per-revolution (*NOT* cycles per revolution!)
# This value should be the pulses per revolution *of the wheels*, and so
# should take into account gearing between the encoder and the wheels
"encoderPPR": 512,
# Whether the left encoder is inverted
"leftEncoderInverted": False,
# Whether the right encoder is inverted:
"rightEncoderInverted": False,
# The total gear reduction between the motor and the wheels, expressed as
# a fraction [motor turns]/[wheel turns]
"gearing": 1,
# Wheel diameter (in units of your choice - will dictate units of analysis)
"wheelDiameter": 0.333,
# Your gyro type (one of "NavX", "Pigeon", "ADXRS450", "AnalogGyro", or "None")
"gyroType": "None",
# Whatever you put into the constructor of your gyro
# Could be:
# "SPI.Port.kMXP" (MXP SPI port for NavX or ADXRS450),
# "I2C.Port.kOnboard" (Onboard I2C port for NavX)
# "0" (Pigeon CAN ID or AnalogGyro channel),
# "new TalonSRX(3)" (Pigeon on a Talon SRX),
# "" (NavX using default SPI, ADXRS450 using onboard CS0, or no gyro)
"gyroPort": "",
}
| {'leftMotorPorts': [0, 1], 'rightMotorPorts': [2, 3], 'leftMotorsInverted': [False, False], 'rightMotorsInverted': [False, False], 'encoderPPR': 512, 'leftEncoderInverted': False, 'rightEncoderInverted': False, 'gearing': 1, 'wheelDiameter': 0.333, 'gyroType': 'None', 'gyroPort': ''} |
# AUTOGENERATED BY NBDEV! DO NOT EDIT!
__all__ = ["index", "modules", "custom_doc_links", "git_url"]
index = {"generate": "00_numpy.ipynb",
"square_root_by_exhaustive": "01_python03.ipynb",
"square_root_by_binary_search": "01_python03.ipynb",
"square_root_by_newton": "01_python03.ipynb",
"search": "01_python03.ipynb",
"select_sort": "01_python03.ipynb"}
modules = ["numpycore.py",
"py03.py"]
doc_url = "https://greyhawk.github.io/pandas_exercises/"
git_url = "https://github.com/greyhawk/pandas_exercises/tree/master/"
def custom_doc_links(name): return None
| __all__ = ['index', 'modules', 'custom_doc_links', 'git_url']
index = {'generate': '00_numpy.ipynb', 'square_root_by_exhaustive': '01_python03.ipynb', 'square_root_by_binary_search': '01_python03.ipynb', 'square_root_by_newton': '01_python03.ipynb', 'search': '01_python03.ipynb', 'select_sort': '01_python03.ipynb'}
modules = ['numpycore.py', 'py03.py']
doc_url = 'https://greyhawk.github.io/pandas_exercises/'
git_url = 'https://github.com/greyhawk/pandas_exercises/tree/master/'
def custom_doc_links(name):
return None |
answer1 = widget_inputs["radio1"]
answer2 = widget_inputs["radio2"]
answer3 = widget_inputs["radio3"]
answer4 = widget_inputs["radio4"]
is_correct = False
comments = []
def commentizer(new):
if new not in comments:
comments.append(new)
if answer1 == True:
is_correct = True
else:
is_correct = is_correct and False
commentizer("Check the first one. Remember, an SVG animation will animate the rotation of an image, as opposed to a gif which is a series of raster images displayed one after another.")
if answer4 == True:
is_correct = is_correct and True
else:
is_correct = is_correct and False
commentizer("Check the second one. Will the image be reused? If so, an external file probably makes more sense.")
if is_correct:
commentizer("Great job!")
commentizer(" I love the internet :)")
grade_result["comment"] = "\n\n".join(comments)
grade_result["correct"] = is_correct | answer1 = widget_inputs['radio1']
answer2 = widget_inputs['radio2']
answer3 = widget_inputs['radio3']
answer4 = widget_inputs['radio4']
is_correct = False
comments = []
def commentizer(new):
if new not in comments:
comments.append(new)
if answer1 == True:
is_correct = True
else:
is_correct = is_correct and False
commentizer('Check the first one. Remember, an SVG animation will animate the rotation of an image, as opposed to a gif which is a series of raster images displayed one after another.')
if answer4 == True:
is_correct = is_correct and True
else:
is_correct = is_correct and False
commentizer('Check the second one. Will the image be reused? If so, an external file probably makes more sense.')
if is_correct:
commentizer('Great job!')
commentizer(' I love the internet :)')
grade_result['comment'] = '\n\n'.join(comments)
grade_result['correct'] = is_correct |
digit = input('Enter number:')
name = input("Name:")
if not digit.i:
print("Input must be a digit")
exit(1)
print(int(digit) + 1)
| digit = input('Enter number:')
name = input('Name:')
if not digit.i:
print('Input must be a digit')
exit(1)
print(int(digit) + 1) |
num1 = 11
num2 = 222
num3 = 3333333
num3 = 333
num4 = 44444
| num1 = 11
num2 = 222
num3 = 3333333
num3 = 333
num4 = 44444 |
# mock data
OP_STATIC_ATTRS = {
"objectClass": ["top", "oxAuthClient"],
"oxAuthScope": [
"inum=F0C4,ou=scopes,o=gluu",
"inum=C4F5,ou=scopes,o=gluu",
],
"inum": "w124asdgggAGs",
}
ADD_OP_TEST_ARGS = {
"oxAuthLogoutSessionRequired": False,
"oxAuthTrustedClient": False,
"oxAuthResponseType": "token",
"oxAuthTokenEndpointAuthMethod": "client_secret_basic",
"oxAuthRequireAuthTime": False,
"oxAccessTokenAsJwt": False,
"oxPersistClientAuthorizations": True,
"oxAuthGrantType": "client_credentials",
"oxAttributes":
'{"tlsClientAuthSubjectDn":null,"runIntrospectionScriptBeforeAccessTokenAsJwtCreationAndIncludeClaims":false,"keepClientAuthorizationAfterExpiration":false}',
"oxAuthAppType": "web",
"oxDisabled": False,
"oxIncludeClaimsInIdToken": False,
"oxRptAsJwt": False,
"displayName": "test-client2",
"oxAuthClientSecret": "somecoolsecret",
"oxAuthSubjectType": "pairwise",
}
MOCKED_SEARCH_S_VALID_RESPONSE = [(
"inum=59376804-e84b-411a-9492-653d14e52c24,ou=clients,o=gluu",
{
"objectClass": [b"top", b"oxAuthClient"],
"oxAuthLogoutSessionRequired": [b"false"],
"oxAuthScope": [
b"inum=F0C4,ou=scopes,o=gluu",
b"inum=C4F5,ou=scopes,o=gluu",
],
"oxAuthTrustedClient": [b"false"],
"oxAuthResponseType": [b"token"],
"oxAuthTokenEndpointAuthMethod": [b"client_secret_basic"],
"oxAuthRequireAuthTime": [b"false"],
"oxAccessTokenAsJwt": [b"false"],
"oxPersistClientAuthorizations": [b"true"],
"oxAuthGrantType": [b"client_credentials"],
"inum": [b"59376804-e84b-411a-9492-653d14e52c24"],
"oxAttributes": [
b'{"tlsClientAuthSubjectDn":null,"runIntrospectionScriptBeforeAccessTokenAsJwtCreationAndIncludeClaims":false,"keepClientAuthorizationAfterExpiration":false}'
],
"oxAuthAppType": [b"web"],
"oxLastLogonTime": [b"20200714072830.011Z"],
"oxAuthClientSecretExpiresAt": [b"21200623000000.000Z"],
"oxDisabled": [b"false"],
"oxIncludeClaimsInIdToken": [b"false"],
"oxRptAsJwt": [b"false"],
"displayName": [b"test-client"],
"oxAuthClientSecret": [b"gWxnjnUdCm8Rpc0WPmm9lQ=="],
"oxAuthSubjectType": [b"pairwise"],
"oxLastAccessTime": [b"20200714072830.011Z"],
},
)]
OP_ADD_OP_EXPECTED_RETURN = expected_created_op = (
"inum=w124asdgggAGs,ou=clients,o=gluu",
{
"objectClass": [b"top", b"oxAuthClient"],
"oxAuthLogoutSessionRequired": [b"false"],
"oxAuthTrustedClient": [b"false"],
"oxAuthScope":
[b"inum=F0C4,ou=scopes,o=gluu", b"inum=C4F5,ou=scopes,o=gluu"],
"oxAuthResponseType": [b"token"],
"oxAuthTokenEndpointAuthMethod": [b"client_secret_basic"],
"oxAuthRequireAuthTime": [b"false"],
"oxAccessTokenAsJwt": [b"false"],
"oxPersistClientAuthorizations": [b"true"],
"oxAuthGrantType": [b"client_credentials"],
"inum": [b"w124asdgggAGs"],
"oxAttributes": [
b'{"tlsClientAuthSubjectDn":null,"runIntrospectionScriptBeforeAccessTokenAsJwtCreationAndIncludeClaims":false,"keepClientAuthorizationAfterExpiration":false}'
],
"oxAuthAppType": [b"web"],
"oxIncludeClaimsInIdToken": [b"false"],
"oxRptAsJwt": [b"false"],
"oxDisabled": [b"false"],
"displayName": [b"test-client2"],
"oxAuthClientSecret": [b"somecoolsecret"],
"oxAuthSubjectType": [b"pairwise"],
},
)
| op_static_attrs = {'objectClass': ['top', 'oxAuthClient'], 'oxAuthScope': ['inum=F0C4,ou=scopes,o=gluu', 'inum=C4F5,ou=scopes,o=gluu'], 'inum': 'w124asdgggAGs'}
add_op_test_args = {'oxAuthLogoutSessionRequired': False, 'oxAuthTrustedClient': False, 'oxAuthResponseType': 'token', 'oxAuthTokenEndpointAuthMethod': 'client_secret_basic', 'oxAuthRequireAuthTime': False, 'oxAccessTokenAsJwt': False, 'oxPersistClientAuthorizations': True, 'oxAuthGrantType': 'client_credentials', 'oxAttributes': '{"tlsClientAuthSubjectDn":null,"runIntrospectionScriptBeforeAccessTokenAsJwtCreationAndIncludeClaims":false,"keepClientAuthorizationAfterExpiration":false}', 'oxAuthAppType': 'web', 'oxDisabled': False, 'oxIncludeClaimsInIdToken': False, 'oxRptAsJwt': False, 'displayName': 'test-client2', 'oxAuthClientSecret': 'somecoolsecret', 'oxAuthSubjectType': 'pairwise'}
mocked_search_s_valid_response = [('inum=59376804-e84b-411a-9492-653d14e52c24,ou=clients,o=gluu', {'objectClass': [b'top', b'oxAuthClient'], 'oxAuthLogoutSessionRequired': [b'false'], 'oxAuthScope': [b'inum=F0C4,ou=scopes,o=gluu', b'inum=C4F5,ou=scopes,o=gluu'], 'oxAuthTrustedClient': [b'false'], 'oxAuthResponseType': [b'token'], 'oxAuthTokenEndpointAuthMethod': [b'client_secret_basic'], 'oxAuthRequireAuthTime': [b'false'], 'oxAccessTokenAsJwt': [b'false'], 'oxPersistClientAuthorizations': [b'true'], 'oxAuthGrantType': [b'client_credentials'], 'inum': [b'59376804-e84b-411a-9492-653d14e52c24'], 'oxAttributes': [b'{"tlsClientAuthSubjectDn":null,"runIntrospectionScriptBeforeAccessTokenAsJwtCreationAndIncludeClaims":false,"keepClientAuthorizationAfterExpiration":false}'], 'oxAuthAppType': [b'web'], 'oxLastLogonTime': [b'20200714072830.011Z'], 'oxAuthClientSecretExpiresAt': [b'21200623000000.000Z'], 'oxDisabled': [b'false'], 'oxIncludeClaimsInIdToken': [b'false'], 'oxRptAsJwt': [b'false'], 'displayName': [b'test-client'], 'oxAuthClientSecret': [b'gWxnjnUdCm8Rpc0WPmm9lQ=='], 'oxAuthSubjectType': [b'pairwise'], 'oxLastAccessTime': [b'20200714072830.011Z']})]
op_add_op_expected_return = expected_created_op = ('inum=w124asdgggAGs,ou=clients,o=gluu', {'objectClass': [b'top', b'oxAuthClient'], 'oxAuthLogoutSessionRequired': [b'false'], 'oxAuthTrustedClient': [b'false'], 'oxAuthScope': [b'inum=F0C4,ou=scopes,o=gluu', b'inum=C4F5,ou=scopes,o=gluu'], 'oxAuthResponseType': [b'token'], 'oxAuthTokenEndpointAuthMethod': [b'client_secret_basic'], 'oxAuthRequireAuthTime': [b'false'], 'oxAccessTokenAsJwt': [b'false'], 'oxPersistClientAuthorizations': [b'true'], 'oxAuthGrantType': [b'client_credentials'], 'inum': [b'w124asdgggAGs'], 'oxAttributes': [b'{"tlsClientAuthSubjectDn":null,"runIntrospectionScriptBeforeAccessTokenAsJwtCreationAndIncludeClaims":false,"keepClientAuthorizationAfterExpiration":false}'], 'oxAuthAppType': [b'web'], 'oxIncludeClaimsInIdToken': [b'false'], 'oxRptAsJwt': [b'false'], 'oxDisabled': [b'false'], 'displayName': [b'test-client2'], 'oxAuthClientSecret': [b'somecoolsecret'], 'oxAuthSubjectType': [b'pairwise']}) |
#!/usr/bin/env python3
# Day 15: Non-overlapping Intervals
#
# Given a collection of intervals, find the minimum number of intervals you
# need to remove to make the rest of the intervals non-overlapping.
#
# Note:
# - You may assume the interval's end point is always bigger than its start
# point.
# - Intervals like [1,2] and [2,3] have borders "touching" but they don't
# overlap each other.
class Solution:
def eraseOverlapIntervals(self, intervals: [[int]]) -> int:
# Edge case
if len(intervals) == 0:
return 0
# Convenience functions for code clarity
start = lambda interval: interval[0]
end = lambda interval: interval[1]
# Sort intervals by their end
intervals = sorted(intervals, key = end)
# Greedy!
intervals_to_remove = 0
previous_start = start(intervals[0])
previous_end = end(intervals[0])
for interval in intervals[1:]:
if start(interval) < previous_end:
intervals_to_remove += 1
else:
previous_start = start(interval)
previous_end = end(interval)
return intervals_to_remove
# Tests
assert Solution().eraseOverlapIntervals([[1,2],[2,3],[3,4],[1,3]]) == 1
assert Solution().eraseOverlapIntervals([[1,2],[1,2],[1,2]]) == 2
assert Solution().eraseOverlapIntervals([[1,2],[2,3]]) == 0
| class Solution:
def erase_overlap_intervals(self, intervals: [[int]]) -> int:
if len(intervals) == 0:
return 0
start = lambda interval: interval[0]
end = lambda interval: interval[1]
intervals = sorted(intervals, key=end)
intervals_to_remove = 0
previous_start = start(intervals[0])
previous_end = end(intervals[0])
for interval in intervals[1:]:
if start(interval) < previous_end:
intervals_to_remove += 1
else:
previous_start = start(interval)
previous_end = end(interval)
return intervals_to_remove
assert solution().eraseOverlapIntervals([[1, 2], [2, 3], [3, 4], [1, 3]]) == 1
assert solution().eraseOverlapIntervals([[1, 2], [1, 2], [1, 2]]) == 2
assert solution().eraseOverlapIntervals([[1, 2], [2, 3]]) == 0 |
aux = 0
num = int(input("Ingrese un numero entero positivo: "))
if num>0:
for x in range(0,num+1):
aux = aux + x
print (aux) | aux = 0
num = int(input('Ingrese un numero entero positivo: '))
if num > 0:
for x in range(0, num + 1):
aux = aux + x
print(aux) |
start = [8,13,1,0,18,9]
last_said = None
history = {}
def say(num, turn_no):
print(f'turn {i}\tsay {num}')
for i in range(30000000):
if i < len(start):
num = start[i]
else:
# print(f'turn {i} last said {last_said} {history}')
if last_said in history:
# print('in')
num = i - history[last_said] - 1
else:
num = 0
# print(history)
if last_said is not None:
history[last_said] = i - 1
# say(num, i)
if i % 1000000 == 0: print(i, num)
last_said = num
print(i, num) | start = [8, 13, 1, 0, 18, 9]
last_said = None
history = {}
def say(num, turn_no):
print(f'turn {i}\tsay {num}')
for i in range(30000000):
if i < len(start):
num = start[i]
elif last_said in history:
num = i - history[last_said] - 1
else:
num = 0
if last_said is not None:
history[last_said] = i - 1
if i % 1000000 == 0:
print(i, num)
last_said = num
print(i, num) |
num1 = '100'
num2 = '200'
# 100200
print(num1 + num2)
# Casting - 300
num1 = int(num1)
num2 = int(num2)
print(num1 + num2) | num1 = '100'
num2 = '200'
print(num1 + num2)
num1 = int(num1)
num2 = int(num2)
print(num1 + num2) |
# ------- FUNCTION BASICS --------
def allotEmail(firstName, surname):
return firstName+'.'+surname+'@pythonabc.org'
name = input("Enter your name: ")
fName, sName = name.split()
compEmail = allotEmail(fName, sName)
print(compEmail)
def get_sum(*args):
sum = 0
for i in args:
sum += i
return sum
print("sum =", get_sum(3,4,5,7)) | def allot_email(firstName, surname):
return firstName + '.' + surname + '@pythonabc.org'
name = input('Enter your name: ')
(f_name, s_name) = name.split()
comp_email = allot_email(fName, sName)
print(compEmail)
def get_sum(*args):
sum = 0
for i in args:
sum += i
return sum
print('sum =', get_sum(3, 4, 5, 7)) |
'''
An approximation of network latency in the Bitcoin network based on the
following paper: https://ieeexplore.ieee.org/document/6688704/.
From the green line in Fig 1, we can approximate the function as:
Network latency (sec) = 19/300 sec/KB * KB + 1 sec
If we assume a transaction is 500 bytes or 1/2 KB, we get the function
Network latency (sec) = 19/600 sec/tx * tx + 1 sec
We use this as a parameter into our exponential delay
'''
SEC_PER_TRANSACTION = 19.0/600
'''
Required depth for longest chain to consider a block to be finalized
'''
FINALIZATION_DEPTH = 6
'''
Transaction rate in transactions/sec used when generating a transaction
dataset
'''
TX_RATE = 1
'''
Transaction size used for computing network latency when broadcasting transactions
'''
TX_SIZE = 1
| """
An approximation of network latency in the Bitcoin network based on the
following paper: https://ieeexplore.ieee.org/document/6688704/.
From the green line in Fig 1, we can approximate the function as:
Network latency (sec) = 19/300 sec/KB * KB + 1 sec
If we assume a transaction is 500 bytes or 1/2 KB, we get the function
Network latency (sec) = 19/600 sec/tx * tx + 1 sec
We use this as a parameter into our exponential delay
"""
sec_per_transaction = 19.0 / 600
'\nRequired depth for longest chain to consider a block to be finalized\n'
finalization_depth = 6
'\nTransaction rate in transactions/sec used when generating a transaction\ndataset\n'
tx_rate = 1
'\nTransaction size used for computing network latency when broadcasting transactions \n'
tx_size = 1 |
class Spam(object):
'''
The Spam object contains lots of spam
Args:
arg (str): The arg is used for ...
*args: The variable arguments are used for ...
**kwargs: The keyword arguments are used for ...
Attributes:
arg (str): This is where we store arg,
'''
def __init__(self, arg, *args, **kwargs):
self.arg = arg
def eggs(self, amount, cooked):
'''We can't have spam without eggs, so here's the eggs
Args:
amount (int): The amount of eggs to return
cooked (bool): Should the eggs be cooked?
Raises:
RuntimeError: Out of eggs
Returns:
Eggs: A bunch of eggs
'''
pass
| class Spam(object):
"""
The Spam object contains lots of spam
Args:
arg (str): The arg is used for ...
*args: The variable arguments are used for ...
**kwargs: The keyword arguments are used for ...
Attributes:
arg (str): This is where we store arg,
"""
def __init__(self, arg, *args, **kwargs):
self.arg = arg
def eggs(self, amount, cooked):
"""We can't have spam without eggs, so here's the eggs
Args:
amount (int): The amount of eggs to return
cooked (bool): Should the eggs be cooked?
Raises:
RuntimeError: Out of eggs
Returns:
Eggs: A bunch of eggs
"""
pass |
'''
Given an integer array nums, return the length of the longest strictly increasing subsequence.
A subsequence is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements. For example, [3,6,2,7] is a subsequence of the array [0,3,1,6,2,2,7].
Example 1:
Input: nums = [10,9,2,5,3,7,101,18]
Output: 4
Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4.
Example 2:
Input: nums = [0,1,0,3,2,3]
Output: 4
Example 3:
Input: nums = [7,7,7,7,7,7,7]
Output: 1
Constraints:
1 <= nums.length <= 2500
-104 <= nums[i] <= 104
Follow up:
Could you come up with the O(n2) solution?
Could you improve it to O(n log(n)) time complexity?
'''
# Bin Search Approach -> Time: O(NlogN), Space: O(n)
class Solution(object):
def binarySearch(self, temp_arr, low, high, target):
while low <= high:
mid = low + (high - low) // 2
if temp_arr[mid] == target:
return mid
if temp_arr[mid] > target:
high = mid - 1
else:
low = mid + 1
return low # low is always ending at the right position
def lengthOfLIS(self, nums):
if not nums or len(nums) == 0:
return 0
temp_arr = []
len_point = 1 # len_point put on temp_arr
temp_arr.append(nums[0])
for i in range(1, len(nums)):
if nums[i] > temp_arr[-1]:
temp_arr.append(nums[i])
len_point += 1
else:
bs_idx = self.binarySearch(temp_arr, 0, len(temp_arr)- 1, nums[i])
temp_arr[bs_idx] = nums[i]
return len_point
# DP Approach -> Time: O(n^2), Space: O(n)
class Solution(object):
def lengthOfLIS(self, nums):
res = 0
dp_table = [1] * len(nums)
for elem in range (1, len(nums)):
for elem1 in range (0, elem):
if (nums[elem] > nums[elem1] and dp_table[elem] < dp_table[elem1] + 1):
dp_table[elem] = dp_table[elem1] + 1
for elem in range (0, len(nums)):
res = max(res, dp_table[elem])
return res
| """
Given an integer array nums, return the length of the longest strictly increasing subsequence.
A subsequence is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements. For example, [3,6,2,7] is a subsequence of the array [0,3,1,6,2,2,7].
Example 1:
Input: nums = [10,9,2,5,3,7,101,18]
Output: 4
Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4.
Example 2:
Input: nums = [0,1,0,3,2,3]
Output: 4
Example 3:
Input: nums = [7,7,7,7,7,7,7]
Output: 1
Constraints:
1 <= nums.length <= 2500
-104 <= nums[i] <= 104
Follow up:
Could you come up with the O(n2) solution?
Could you improve it to O(n log(n)) time complexity?
"""
class Solution(object):
def binary_search(self, temp_arr, low, high, target):
while low <= high:
mid = low + (high - low) // 2
if temp_arr[mid] == target:
return mid
if temp_arr[mid] > target:
high = mid - 1
else:
low = mid + 1
return low
def length_of_lis(self, nums):
if not nums or len(nums) == 0:
return 0
temp_arr = []
len_point = 1
temp_arr.append(nums[0])
for i in range(1, len(nums)):
if nums[i] > temp_arr[-1]:
temp_arr.append(nums[i])
len_point += 1
else:
bs_idx = self.binarySearch(temp_arr, 0, len(temp_arr) - 1, nums[i])
temp_arr[bs_idx] = nums[i]
return len_point
class Solution(object):
def length_of_lis(self, nums):
res = 0
dp_table = [1] * len(nums)
for elem in range(1, len(nums)):
for elem1 in range(0, elem):
if nums[elem] > nums[elem1] and dp_table[elem] < dp_table[elem1] + 1:
dp_table[elem] = dp_table[elem1] + 1
for elem in range(0, len(nums)):
res = max(res, dp_table[elem])
return res |
class Solution(object):
@staticmethod
def min_steps(candy, n, m):
min_step = float("inf")
def dfs(curr, i, j, num_candy, steps):
nonlocal min_step
if num_candy == m:
min_step = min(steps, min_step)
if steps > min_step:
return
if (i, j) in candy:
num_candy += 1
if 0 <= i+1 < n and 0 <= j < n and (i+1, j) not in curr:
curr.append((i+1, j))
dfs(curr, i+1, j, num_candy, steps+1)
curr.pop()
if 0 <= i < n and 0 <= j-1 < n and (i, j-1) not in curr:
curr.append((i, j-1))
dfs(curr, i, j-1, num_candy, steps+1)
curr.pop()
if 0 <= j+1 < n and 0 <= i < n and (i, j+1) not in curr:
curr.append((i, j+1))
dfs(curr, i, j+1, num_candy, steps+1)
curr.pop()
dfs([], 0, 0, 0, 0)
# need to -1 because last one should be exactly has candy, and in current
# implementation, step+1 then find candy == m
print(min_step-1)
return min_step-1
candy = [(0, 3), (1, 1), (2, 2), (3, 3)]
m = len(candy)
n = 4
s = Solution()
s.min_steps(candy, n, m)
| class Solution(object):
@staticmethod
def min_steps(candy, n, m):
min_step = float('inf')
def dfs(curr, i, j, num_candy, steps):
nonlocal min_step
if num_candy == m:
min_step = min(steps, min_step)
if steps > min_step:
return
if (i, j) in candy:
num_candy += 1
if 0 <= i + 1 < n and 0 <= j < n and ((i + 1, j) not in curr):
curr.append((i + 1, j))
dfs(curr, i + 1, j, num_candy, steps + 1)
curr.pop()
if 0 <= i < n and 0 <= j - 1 < n and ((i, j - 1) not in curr):
curr.append((i, j - 1))
dfs(curr, i, j - 1, num_candy, steps + 1)
curr.pop()
if 0 <= j + 1 < n and 0 <= i < n and ((i, j + 1) not in curr):
curr.append((i, j + 1))
dfs(curr, i, j + 1, num_candy, steps + 1)
curr.pop()
dfs([], 0, 0, 0, 0)
print(min_step - 1)
return min_step - 1
candy = [(0, 3), (1, 1), (2, 2), (3, 3)]
m = len(candy)
n = 4
s = solution()
s.min_steps(candy, n, m) |
class Employee:
# Constructor untuk Employee
def __init__(self, first_name, last_name, monthly_salary):
self._first_name = first_name
self._last_name = last_name
self._monthly_salary = monthly_salary
if monthly_salary < 0:
self._monthly_salary = 0
# Getter dan setter first_name
@property
def first_name(self):
return self._first_name
@first_name.setter
def first_name(self, new_first_name):
self._first_name = new_first_name
# Getter dan setter last_name
@property
def last_name(self):
return self._last_name
@last_name.setter
def last_name(self, new_last_name):
self._last_name = new_last_name
# Getter dan setter monthly_salary
@property
def monthly_salary(self):
return self._monthly_salary
@monthly_salary.setter
def monthly_salary(self, new_monthly_salary):
self._monthly_salary = new_monthly_salary
| class Employee:
def __init__(self, first_name, last_name, monthly_salary):
self._first_name = first_name
self._last_name = last_name
self._monthly_salary = monthly_salary
if monthly_salary < 0:
self._monthly_salary = 0
@property
def first_name(self):
return self._first_name
@first_name.setter
def first_name(self, new_first_name):
self._first_name = new_first_name
@property
def last_name(self):
return self._last_name
@last_name.setter
def last_name(self, new_last_name):
self._last_name = new_last_name
@property
def monthly_salary(self):
return self._monthly_salary
@monthly_salary.setter
def monthly_salary(self, new_monthly_salary):
self._monthly_salary = new_monthly_salary |
class Solution:
def minFallingPathSum(self, arr: List[List[int]]) -> int:
min1 = min2 = -1
for j in range(len(arr[0])):
if min1 == -1 or arr[0][j] < arr[0][min1]:
min2 = min1
min1 = j
elif min2 == -1 or arr[0][j] < arr[0][min2]:
min2 = j
for i in range(1, len(arr)):
currMin1 = currMin2 = -1
for j in range(len(arr[i])):
if j == min1:
arr[i][j] += arr[i - 1][min2]
else:
arr[i][j] += arr[i - 1][min1]
if currMin1 == -1 or arr[i][j] < arr[i][currMin1]:
currMin2 = currMin1
currMin1 = j
elif currMin2 == -1 or arr[i][j] < arr[i][currMin2]:
currMin2 = j
min1, min2 = currMin1, currMin2
return arr[-1][min1]
| class Solution:
def min_falling_path_sum(self, arr: List[List[int]]) -> int:
min1 = min2 = -1
for j in range(len(arr[0])):
if min1 == -1 or arr[0][j] < arr[0][min1]:
min2 = min1
min1 = j
elif min2 == -1 or arr[0][j] < arr[0][min2]:
min2 = j
for i in range(1, len(arr)):
curr_min1 = curr_min2 = -1
for j in range(len(arr[i])):
if j == min1:
arr[i][j] += arr[i - 1][min2]
else:
arr[i][j] += arr[i - 1][min1]
if currMin1 == -1 or arr[i][j] < arr[i][currMin1]:
curr_min2 = currMin1
curr_min1 = j
elif currMin2 == -1 or arr[i][j] < arr[i][currMin2]:
curr_min2 = j
(min1, min2) = (currMin1, currMin2)
return arr[-1][min1] |
GENERAL_HELP = '''
Usage:
vt <command> [options]
Commands:
lists Get all lists
list Return items of a specific list
item Return a specific item
show Alias for item
done Mark an item done
complete Alias for done
undone Mark an item undone
uncomplete Alias for undone
modify Modify item by providing a comment
edit Alias for modify
comment Alias for modify
comments Alias for modify
add Create a new item
move Associate an item with a new list
mv Alias for move
categories Return a list of valid categories for a given list
categorize Provide a category for a given item
label Alias for categorize
help Get help on a command
'''
LISTS_HELP = '''
Usage:
vt lists
Description:
Return all lists
'''
LIST_HELP = '''
Usage:
vt list [GUID] [options]
Description:
Return all items of a specified list. GUID may be either the unique identifier of
a list or the name of the list if it is unique. If no GUID is provided, use the
default list defined in the VT_DEFAULT_LIST environment variable.
Options:
-e, --extended Show extended information about items.
-u, --unfinished Only display items that have not been completed yet.
-c, --categories Include item categories in output.
-q, --quiet Quiet mode. Remove any extraneous output.
-W, --no-wrap Do not apply any text wrapping to output.
'''
DONE_HELP = '''
Usage:
vt done [GUID] ...
vt complete [GUID] ...
Description:
Mark an item done. When run without a GUID, display all recently completed items.
'''
UNDONE_HELP = '''
Usage:
vt undone [GUID] ...
vt uncomplete [GUID] ...
Description:
Mark an item undone. When run without a GUID, display all recently completed items.
'''
COMMENT_HELP = '''
Usage:
vt modify GUID [options] [comment]
vt comment GUID [options] [comment]
vt comments GUID [options] [comment]
vt edit GUID [options] [comment]
Description:
Add a comment to the specified item. No comment should be provided when using the -d flag.
Options:
-a, --append Append comment rather than overwriting.
-d, --delete Remove comment from item.
'''
ADD_HELP = '''
Usage:
vt add [GUID] item
Description:
Create a new item. GUID is the unique identifier for the list the item will be placed on.
When GUID is not provided, use the default list defined in VT_DEFAULT_LIST environment variable.
'''
MOVE_HELP = '''
Usage:
vt move ITEM LIST
vt mv ITEM LIST
Description:
Move item to a new list where ITEM is the guid of the item and LIST is the guid of the new list.
'''
CATEGORIES_HELP = '''
Usage:
vt categories [GUID]
Description:
Display the available categories for a list. GUID is the unique identifier for a list.
When GUID is not provided, use the default list defined in VT_DEFAULT_LIST environment variable.
'''
CATEGORIZE_HELP = '''
Usage:
vt categorize GUID CATEGORY
vt label GUID CATEGORY
Description:
Assign CATEGORY to the item specified by GUID.
'''
| general_help = '\nUsage:\n vt <command> [options]\n\nCommands:\n lists Get all lists\n list Return items of a specific list\n item Return a specific item\n show Alias for item\n done Mark an item done\n complete Alias for done\n undone Mark an item undone\n uncomplete Alias for undone\n modify Modify item by providing a comment\n edit Alias for modify\n comment Alias for modify\n comments Alias for modify\n add Create a new item\n move Associate an item with a new list\n mv Alias for move\n categories Return a list of valid categories for a given list\n categorize Provide a category for a given item\n label Alias for categorize\n help Get help on a command\n'
lists_help = '\nUsage:\n vt lists\n\nDescription:\n Return all lists\n'
list_help = '\nUsage:\n vt list [GUID] [options]\n\nDescription:\n Return all items of a specified list. GUID may be either the unique identifier of\n a list or the name of the list if it is unique. If no GUID is provided, use the\n default list defined in the VT_DEFAULT_LIST environment variable.\n\nOptions:\n -e, --extended Show extended information about items.\n -u, --unfinished Only display items that have not been completed yet.\n -c, --categories Include item categories in output.\n -q, --quiet Quiet mode. Remove any extraneous output.\n -W, --no-wrap Do not apply any text wrapping to output.\n'
done_help = '\nUsage:\n vt done [GUID] ...\n vt complete [GUID] ...\n\nDescription:\n Mark an item done. When run without a GUID, display all recently completed items.\n'
undone_help = '\nUsage:\n vt undone [GUID] ...\n vt uncomplete [GUID] ...\n\nDescription:\n Mark an item undone. When run without a GUID, display all recently completed items.\n'
comment_help = '\nUsage:\n vt modify GUID [options] [comment]\n vt comment GUID [options] [comment]\n vt comments GUID [options] [comment]\n vt edit GUID [options] [comment]\n\nDescription:\n Add a comment to the specified item. No comment should be provided when using the -d flag.\n\nOptions:\n -a, --append Append comment rather than overwriting.\n -d, --delete Remove comment from item.\n'
add_help = '\nUsage:\n vt add [GUID] item\n\nDescription:\n Create a new item. GUID is the unique identifier for the list the item will be placed on.\n When GUID is not provided, use the default list defined in VT_DEFAULT_LIST environment variable.\n'
move_help = '\nUsage:\n vt move ITEM LIST\n vt mv ITEM LIST\n\nDescription:\n Move item to a new list where ITEM is the guid of the item and LIST is the guid of the new list.\n'
categories_help = '\nUsage:\n vt categories [GUID]\n\nDescription:\n Display the available categories for a list. GUID is the unique identifier for a list.\n When GUID is not provided, use the default list defined in VT_DEFAULT_LIST environment variable.\n'
categorize_help = '\nUsage:\n vt categorize GUID CATEGORY\n vt label GUID CATEGORY\n\nDescription:\n Assign CATEGORY to the item specified by GUID.\n' |
# slicing lab
def swap(seq):
return seq[-1:]+seq[1:-1]+seq[:1]
assert swap('something') == 'gomethins'
assert swap(tuple(range(10))) == (9,1,2,3,4,5,6,7,8,0)
def rem(seq):
return seq[::2]
assert rem('a word') == 'awr'
def rem4(seq):
return seq[4:-4:2]
print(rem4( (1,2,3,4,5,6,7,8,9,10,11), ) )
def reverse(seq):
return seq[::-1]
print(reverse('a string'))
def thirds(seq):
i = len(seq)//3
#return seq[i*2:i*3+1] + seq[:i] + seq[i:i*2]
return seq[i:-i] + seq[-i:] + seq[:i]
print (thirds(tuple(range(12))))
| def swap(seq):
return seq[-1:] + seq[1:-1] + seq[:1]
assert swap('something') == 'gomethins'
assert swap(tuple(range(10))) == (9, 1, 2, 3, 4, 5, 6, 7, 8, 0)
def rem(seq):
return seq[::2]
assert rem('a word') == 'awr'
def rem4(seq):
return seq[4:-4:2]
print(rem4((1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)))
def reverse(seq):
return seq[::-1]
print(reverse('a string'))
def thirds(seq):
i = len(seq) // 3
return seq[i:-i] + seq[-i:] + seq[:i]
print(thirds(tuple(range(12)))) |
def minkowski(a, b, p) :
summ = 0
n = len(a)
for i in range(n) :
summ += (b[i]-a[i])**p
summ = summ ** (1/p)
return summ
a = [0, 3, 4, 5]
b = [7, 6, 3, -1]
p=3
print(minkowski(a, b, p))
| def minkowski(a, b, p):
summ = 0
n = len(a)
for i in range(n):
summ += (b[i] - a[i]) ** p
summ = summ ** (1 / p)
return summ
a = [0, 3, 4, 5]
b = [7, 6, 3, -1]
p = 3
print(minkowski(a, b, p)) |
inp = input()
points = inp.split(" ")
for i in range(len(points)):
points[i] = int(points[i])
points.sort()
result = points[len(points) - 1] - points[0]
print(result) | inp = input()
points = inp.split(' ')
for i in range(len(points)):
points[i] = int(points[i])
points.sort()
result = points[len(points) - 1] - points[0]
print(result) |
# Created by MechAviv
# ID :: [4000013]
# Maple Road : Inside the Small Forest
sm.showFieldEffect("maplemap/enter/40000", 0) | sm.showFieldEffect('maplemap/enter/40000', 0) |
# Define time, time constant
t = np.arange(0, 10, .1)
tau = 0.5
# Compute alpha function
f = t * np.exp(-t/tau)
# Define u(t), v(t)
u_t = t
v_t = np.exp(-t/tau)
# Define du/dt, dv/dt
du_dt = 1
dv_dt = -1/tau * np.exp(-t/tau)
# Define full derivative
df_dt = u_t * dv_dt + v_t * du_dt
# Uncomment below to visualize
with plt.xkcd():
plot_alpha_func(t, f, df_dt) | t = np.arange(0, 10, 0.1)
tau = 0.5
f = t * np.exp(-t / tau)
u_t = t
v_t = np.exp(-t / tau)
du_dt = 1
dv_dt = -1 / tau * np.exp(-t / tau)
df_dt = u_t * dv_dt + v_t * du_dt
with plt.xkcd():
plot_alpha_func(t, f, df_dt) |
al = 0
ga = 0
di = 0
x = 0
while x != 4:
x = int(input())
if x == 1:
al = al + 1
if x == 2:
ga = ga + 1
if x == 3:
di = di + 1
print('MUITO OBRIGADO')
print('Alcool: {}'.format(al))
print('Gasolina: {}'.format(ga))
print('Diesel: {}'.format(di))
| al = 0
ga = 0
di = 0
x = 0
while x != 4:
x = int(input())
if x == 1:
al = al + 1
if x == 2:
ga = ga + 1
if x == 3:
di = di + 1
print('MUITO OBRIGADO')
print('Alcool: {}'.format(al))
print('Gasolina: {}'.format(ga))
print('Diesel: {}'.format(di)) |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def countNodes(self, root: TreeNode) -> int:
maxDepth = self.findLeftMaxDepth(root)
if maxDepth <= 1:
return maxDepth
else:
curRoot = root
curDepth = 1
totalNum = 0
while True:
if curRoot.left == None:
totalNum += 1
break
elif curRoot.right == None:
totalNum += 2
break
elif self.findLeftMaxDepth(curRoot.right) + curDepth == maxDepth:
totalNum += 2 ** (maxDepth-curDepth)
curRoot = curRoot.right
curDepth += 1
elif self.findRightMaxDepth(curRoot.left) + curDepth == maxDepth:
totalNum += 2 ** (maxDepth-curDepth-1)
totalNum += (2 ** (maxDepth-curDepth) - 1)
break
else:
totalNum += 2 ** (maxDepth-curDepth-1)
curRoot = curRoot.left
curDepth += 1
return totalNum
def findLeftMaxDepth(self, root):
if root == None:
return 0
elif root.left == None:
return 1
else:
return 1 + self.findLeftMaxDepth(root.left)
def findRightMaxDepth(self, root):
if root == None:
return 0
elif root.right == None:
return 1
else:
return 1 + self.findRightMaxDepth(root.right) | class Solution:
def count_nodes(self, root: TreeNode) -> int:
max_depth = self.findLeftMaxDepth(root)
if maxDepth <= 1:
return maxDepth
else:
cur_root = root
cur_depth = 1
total_num = 0
while True:
if curRoot.left == None:
total_num += 1
break
elif curRoot.right == None:
total_num += 2
break
elif self.findLeftMaxDepth(curRoot.right) + curDepth == maxDepth:
total_num += 2 ** (maxDepth - curDepth)
cur_root = curRoot.right
cur_depth += 1
elif self.findRightMaxDepth(curRoot.left) + curDepth == maxDepth:
total_num += 2 ** (maxDepth - curDepth - 1)
total_num += 2 ** (maxDepth - curDepth) - 1
break
else:
total_num += 2 ** (maxDepth - curDepth - 1)
cur_root = curRoot.left
cur_depth += 1
return totalNum
def find_left_max_depth(self, root):
if root == None:
return 0
elif root.left == None:
return 1
else:
return 1 + self.findLeftMaxDepth(root.left)
def find_right_max_depth(self, root):
if root == None:
return 0
elif root.right == None:
return 1
else:
return 1 + self.findRightMaxDepth(root.right) |
'''
A library to speed up physics data analysis.
Contains functions for error analysis and calculations
for various physics mechanics values.
''' | """
A library to speed up physics data analysis.
Contains functions for error analysis and calculations
for various physics mechanics values.
""" |
# Creating variables dynamically.
# To be able to pass arguments to variable file, we must define
# and use "get_variables" in a similar manner as follows:
def get_variables(server_uri, start_port):
# Note that the order in which the libraries are listed here must match
# that in 'server.py'.
port = int(start_port)
target_uri = "%s:%d" % (server_uri, port)
port += 1
common_uri = "%s:%d" % (server_uri, port)
port += 1
security_uri = "%s:%d" % (server_uri, port)
# The following variables will be available in the caller's
# file.
return { "target_uri" : target_uri,
"common_uri" : common_uri,
"security_uri" : security_uri }
| def get_variables(server_uri, start_port):
port = int(start_port)
target_uri = '%s:%d' % (server_uri, port)
port += 1
common_uri = '%s:%d' % (server_uri, port)
port += 1
security_uri = '%s:%d' % (server_uri, port)
return {'target_uri': target_uri, 'common_uri': common_uri, 'security_uri': security_uri} |
class StageOutputs:
execute_outputs = {
# Outputs from public Cisco docs:
# https://www.cisco.com/c/en/us/td/docs/routers/asr1000/release/notes/asr1k_rn_rel_notes/asr1k_rn_sys_req.html
'copy running-config startup-config': '''\
PE1#copy running-config startup-config
Destination filename [startup-config]?
%Error opening bootflash:running-config (Permission denied)
''',
'show boot': '''\
starfleet-1#show boot
BOOT variable = bootflash:/cat9k_iosxe.BLD_V173_THROTTLE_LATEST_20200421_032634.SSA.bin;
Configuration Register is 0x102
MANUAL_BOOT variable = no
BAUD variable = 9600
ENABLE_BREAK variable does not exist
BOOTMODE variable does not exist
IPXE_TIMEOUT variable does not exist
CONFIG_FILE variable =
''',
}
parsed_outputs = {
'show boot': {
'active':
{'boot_variable': 'bootflash:/cat9k_iosxe.BLD_V173_THROTTLE_LATEST_20200421_032634.SSA.bin;',
'configuration_register': '0x102'}}
}
config_outputs = {
'no boot system bootflash:/cat9k_iosxe.BLD_V173_THROTTLE_LATEST_20200421_032634.SSA.bin': '',
'boot system bootflash:/cat9k_iosxe.BLD_V173_THROTTLE_LATEST_20200421_032634.SSA.bin': '',
'config-register 0x2102': '',
}
def get_execute_output(arg, **kwargs):
'''Return the execute output of the given show command'''
return StageOutputs.execute_outputs[arg]
def get_parsed_output(arg, **kwargs):
'''Return the parsed output of the given show command '''
return StageOutputs.parsed_outputs[arg]
def get_config_output(arg, **kwargs):
'''Return the out of the given config string'''
return StageOutputs.config_outputs[arg]
| class Stageoutputs:
execute_outputs = {'copy running-config startup-config': ' PE1#copy running-config startup-config\n Destination filename [startup-config]?\n %Error opening bootflash:running-config (Permission denied)\n ', 'show boot': ' starfleet-1#show boot\n BOOT variable = bootflash:/cat9k_iosxe.BLD_V173_THROTTLE_LATEST_20200421_032634.SSA.bin;\n Configuration Register is 0x102\n MANUAL_BOOT variable = no\n BAUD variable = 9600\n ENABLE_BREAK variable does not exist\n BOOTMODE variable does not exist\n IPXE_TIMEOUT variable does not exist\n CONFIG_FILE variable =\n '}
parsed_outputs = {'show boot': {'active': {'boot_variable': 'bootflash:/cat9k_iosxe.BLD_V173_THROTTLE_LATEST_20200421_032634.SSA.bin;', 'configuration_register': '0x102'}}}
config_outputs = {'no boot system bootflash:/cat9k_iosxe.BLD_V173_THROTTLE_LATEST_20200421_032634.SSA.bin': '', 'boot system bootflash:/cat9k_iosxe.BLD_V173_THROTTLE_LATEST_20200421_032634.SSA.bin': '', 'config-register 0x2102': ''}
def get_execute_output(arg, **kwargs):
"""Return the execute output of the given show command"""
return StageOutputs.execute_outputs[arg]
def get_parsed_output(arg, **kwargs):
"""Return the parsed output of the given show command """
return StageOutputs.parsed_outputs[arg]
def get_config_output(arg, **kwargs):
"""Return the out of the given config string"""
return StageOutputs.config_outputs[arg] |
class UnknownCommand(Exception):
pass
class ModuleNotFound(Exception):
pass
class VariableError(Exception):
pass
class ModuleError:
error = ""
def __init__(self, error):
self.error = error | class Unknowncommand(Exception):
pass
class Modulenotfound(Exception):
pass
class Variableerror(Exception):
pass
class Moduleerror:
error = ''
def __init__(self, error):
self.error = error |
class Node:
def __init__(self,tag,valid_bit = 1,next = None,previous = None):
self.tag = tag
self.valid_bit = valid_bit
self.next = next
self.previous = previous
def set_next_pointer(self,next):
self.next = next
def set_previous_pointer(self,previous):
self.previous = previous
def get_tag(self):
return self.tag
def get_index(self):
return self.index
def get_next_pointer(self):
return self.next
def get_previous_pointer(self):
return self.previous
| class Node:
def __init__(self, tag, valid_bit=1, next=None, previous=None):
self.tag = tag
self.valid_bit = valid_bit
self.next = next
self.previous = previous
def set_next_pointer(self, next):
self.next = next
def set_previous_pointer(self, previous):
self.previous = previous
def get_tag(self):
return self.tag
def get_index(self):
return self.index
def get_next_pointer(self):
return self.next
def get_previous_pointer(self):
return self.previous |
# Do not hard code credentials
client = boto3.client(
's3',
# Hard coded strings as credentials, not recommended.
aws_access_key_id='AKIAIO5FODNN7EXAMPLE',
aws_secret_access_key='ABCDEF+c2L7yXeGvUyrPgYsDnWRRC1AYEXAMPLE'
)
# adding another line
| client = boto3.client('s3', aws_access_key_id='AKIAIO5FODNN7EXAMPLE', aws_secret_access_key='ABCDEF+c2L7yXeGvUyrPgYsDnWRRC1AYEXAMPLE') |
#!/usr/bin/env python3
#
## @file
# checkout_humble.py
#
# Copyright (c) 2020, Intel Corporation. All rights reserved.<BR>
# SPDX-License-Identifier: BSD-2-Clause-Patent
#
NO_COMBO = 'A combination named: {} does not exist in the workspace manifest'
| no_combo = 'A combination named: {} does not exist in the workspace manifest' |
cuda_code = '''
extern "C" __global__ void my_kernel(float* input_domain, int input_domain_n, int* layer_sizes, int layer_number, float* full_weights,
float* full_biases, float* results_cuda, int max_layer_size, int* activations) {
// Calculate all the bounds, node by node, for each layer. 'new_layer_values' is the current working layer, old layer is the prevoius (first step old layer is the input layer)
int thread_id = blockDim.x * blockIdx.x + threadIdx.x;
if (thread_id >= input_domain_n) return;
int area_start = thread_id * layer_sizes[0] * 2;
float* old_layer_values = new float[max_layer_size * 2]();
float* new_layer_values = new float[max_layer_size * 2]();
// Step 1: copy inputs in 'old_layer_values' ('new_layer_values' is the first hidden layer)
for (int i = 0; i < (2 * layer_sizes[0]); i++) old_layer_values[i] = input_domain[area_start + i];
// Step 2: starting the propagation cycle
int bias_index = 0;
int weights_index = 0;
for (int layer_idx = 0; layer_idx < layer_number - 1; layer_idx ++){
int old_layer_size = layer_sizes[layer_idx];
int new_layer_size = layer_sizes[layer_idx + 1];
for (int new_node_idx = 0; new_node_idx < new_layer_size*2; new_node_idx += 2){
for (int old_node_idx = 0; old_node_idx < old_layer_size*2; old_node_idx += 2){
if(full_weights[weights_index] > 0) {
new_layer_values[new_node_idx] += (old_layer_values[old_node_idx] * full_weights[weights_index]); //lower bound
new_layer_values[new_node_idx + 1] += (old_layer_values[old_node_idx + 1] * full_weights[weights_index]); //upper bound
} else {
new_layer_values[new_node_idx] += (old_layer_values[old_node_idx + 1] * full_weights[weights_index]); //lower bound
new_layer_values[new_node_idx + 1] += (old_layer_values[old_node_idx] * full_weights[weights_index]); //upper bound
}
weights_index += 1;
}
// Adding bias for each layer (including the output)
new_layer_values[new_node_idx] += full_biases[bias_index];
new_layer_values[new_node_idx+1] += full_biases[bias_index];
bias_index += 1;
// Application of the activation function
// ReLU
if (activations[layer_idx] == 1){
if (new_layer_values[new_node_idx] < 0) new_layer_values[new_node_idx] = 0;
if (new_layer_values[new_node_idx+1] < 0) new_layer_values[new_node_idx+1] = 0;
// TanH
} else if (activations[layer_idx] == 2){
new_layer_values[new_node_idx] = ( 1 - pow(2.71828f, -2*new_layer_values[new_node_idx]) ) / ( 1 + pow(2.71828f, -2*new_layer_values[new_node_idx]) );
new_layer_values[new_node_idx+1] = ( 1 - pow(2.71828f, -2*new_layer_values[new_node_idx+1]) ) / ( 1 + pow(2.71828f, -2*new_layer_values[new_node_idx+1]) );
// Sigmoid
} else if (activations[layer_idx] == 3){
new_layer_values[new_node_idx] = 1 / ( 1 + pow(2.71828f, -new_layer_values[new_node_idx]) );
new_layer_values[new_node_idx+1] = 1 / ( 1 + pow(2.71828f, -new_layer_values[new_node_idx+1]) );
}
}
for (int i = 0; i < max_layer_size * 2; i++) old_layer_values[i] = new_layer_values[i];
for (int i = 0; i < max_layer_size * 2; i++) new_layer_values[i] = 0;
}
// Step 3: copy the local output layer in the global 'results_cuda' array
int results_start = thread_id * layer_sizes[layer_number - 1] * 2;
for (int i=0; i < layer_sizes[layer_number - 1] * 2; i++) results_cuda[results_start + i] = old_layer_values[i];
// Free memory
delete[] old_layer_values;
delete[] new_layer_values;
}
''' | cuda_code = '\n\nextern "C" __global__ void my_kernel(float* input_domain, int input_domain_n, int* layer_sizes, int layer_number, float* full_weights, \n\t\t\tfloat* full_biases, float* results_cuda, int max_layer_size, int* activations) {\n\n\t// Calculate all the bounds, node by node, for each layer. \'new_layer_values\' is the current working layer, old layer is the prevoius (first step old layer is the input layer)\n\tint thread_id = blockDim.x * blockIdx.x + threadIdx.x;\n\tif (thread_id >= input_domain_n) return;\n\tint area_start = thread_id * layer_sizes[0] * 2;\n\t\n\tfloat* old_layer_values = new float[max_layer_size * 2]();\n\tfloat* new_layer_values = new float[max_layer_size * 2]();\n\n\t// Step 1: copy inputs in \'old_layer_values\' (\'new_layer_values\' is the first hidden layer)\n\tfor (int i = 0; i < (2 * layer_sizes[0]); i++) old_layer_values[i] = input_domain[area_start + i];\n\t\n\t// Step 2: starting the propagation cycle\n\tint bias_index = 0;\n\tint weights_index = 0;\n\tfor (int layer_idx = 0; layer_idx < layer_number - 1; layer_idx ++){\n\t\tint old_layer_size = layer_sizes[layer_idx];\n\t\tint new_layer_size = layer_sizes[layer_idx + 1];\n\t\t\n\t\tfor (int new_node_idx = 0; new_node_idx < new_layer_size*2; new_node_idx += 2){\n\t\t\tfor (int old_node_idx = 0; old_node_idx < old_layer_size*2; old_node_idx += 2){\n\t\t\t\tif(full_weights[weights_index] > 0) {\n\t\t\t\t\tnew_layer_values[new_node_idx] += (old_layer_values[old_node_idx] * full_weights[weights_index]); //lower bound\n\t\t\t\t\tnew_layer_values[new_node_idx + 1] += (old_layer_values[old_node_idx + 1] * full_weights[weights_index]); //upper bound\n\t\t\t\t} else {\n\t\t\t\t\tnew_layer_values[new_node_idx] += (old_layer_values[old_node_idx + 1] * full_weights[weights_index]); //lower bound\n\t\t\t\t\tnew_layer_values[new_node_idx + 1] += (old_layer_values[old_node_idx] * full_weights[weights_index]); //upper bound\n\t\t\t\t}\n\t\t\t\tweights_index += 1;\n\t\t\t}\n\n\t\t\t// Adding bias for each layer (including the output)\n\t\t\tnew_layer_values[new_node_idx] += full_biases[bias_index];\n\t\t\tnew_layer_values[new_node_idx+1] += full_biases[bias_index]; \n\t\t\tbias_index += 1;\n\n\t\t\t// Application of the activation function\n\t\t\t// ReLU\n\t\t\tif (activations[layer_idx] == 1){\n\t\t\t\tif (new_layer_values[new_node_idx] < 0) new_layer_values[new_node_idx] = 0;\n\t\t\t\tif (new_layer_values[new_node_idx+1] < 0) new_layer_values[new_node_idx+1] = 0;\n\t\t\t// TanH\n\t\t\t} else if (activations[layer_idx] == 2){\n\t\t\t\tnew_layer_values[new_node_idx] = ( 1 - pow(2.71828f, -2*new_layer_values[new_node_idx]) ) / ( 1 + pow(2.71828f, -2*new_layer_values[new_node_idx]) );\n\t\t\t\tnew_layer_values[new_node_idx+1] = ( 1 - pow(2.71828f, -2*new_layer_values[new_node_idx+1]) ) / ( 1 + pow(2.71828f, -2*new_layer_values[new_node_idx+1]) );\n\t\t\t// Sigmoid\n\t\t\t} else if (activations[layer_idx] == 3){\n\t\t\t\tnew_layer_values[new_node_idx] = 1 / ( 1 + pow(2.71828f, -new_layer_values[new_node_idx]) );\n\t\t\t\tnew_layer_values[new_node_idx+1] = 1 / ( 1 + pow(2.71828f, -new_layer_values[new_node_idx+1]) );\n\t\t\t}\n\t\t}\n\t\tfor (int i = 0; i < max_layer_size * 2; i++) old_layer_values[i] = new_layer_values[i];\n\t\tfor (int i = 0; i < max_layer_size * 2; i++) new_layer_values[i] = 0;\n\t}\n\n\t// Step 3: copy the local output layer in the global \'results_cuda\' array\n\tint results_start = thread_id * layer_sizes[layer_number - 1] * 2;\n\tfor (int i=0; i < layer_sizes[layer_number - 1] * 2; i++) results_cuda[results_start + i] = old_layer_values[i];\n\t// Free memory\n\tdelete[] old_layer_values;\n\tdelete[] new_layer_values; \n}\n\n' |
class Point:
def __init__(self, x, y):
self.x = float(x)
self.y = float(y)
def __str__(self):
return "(" + str(round(self.x, 1)) + ', ' + str(round(self.y, 1)) + ")"
class Triangle:
def __init__(self, points):
self.points = points
def get_centroid(self):
sum_x = 0
for point in self.points:
sum_x += point.x
sum_y = 0
for point in self.points:
sum_y += point.y
return Point(sum_x/3, sum_y/3)
def main():
info = input().split()
point1 = Point(x=info[0], y=info[1])
point2 = Point(x=info[2], y=info[3])
point3 = Point(x=info[4], y=info[5])
triangle1 = Triangle([point1, point2, point3])
centroid1 = triangle1.get_centroid()
print(centroid1)
if(__name__ == '__main__'):
main()
| class Point:
def __init__(self, x, y):
self.x = float(x)
self.y = float(y)
def __str__(self):
return '(' + str(round(self.x, 1)) + ', ' + str(round(self.y, 1)) + ')'
class Triangle:
def __init__(self, points):
self.points = points
def get_centroid(self):
sum_x = 0
for point in self.points:
sum_x += point.x
sum_y = 0
for point in self.points:
sum_y += point.y
return point(sum_x / 3, sum_y / 3)
def main():
info = input().split()
point1 = point(x=info[0], y=info[1])
point2 = point(x=info[2], y=info[3])
point3 = point(x=info[4], y=info[5])
triangle1 = triangle([point1, point2, point3])
centroid1 = triangle1.get_centroid()
print(centroid1)
if __name__ == '__main__':
main() |
class TrackableObject:
def __init__(self, objectID, centroid_frame_timestamp, detection_class_id, centroid, boxoid, bbox_rw_coords):
# store the object ID, then initialize a list of centroids
# using the current centroid
self.objectID = objectID
# initialize instance variable, 'oids' as a list
self.oids = []
# initialize instance variable, 'centroids' as a list
self.centroids = []
# initialize instance variable, 'boxoids' as a list
self.boxoids = []
# initialize instance variable, 'bbox_rw_coords' as a list
self.bbox_rw_coords = []
# initialize instance variable 'detection_class_id' as 0
self.detection_class_id = detection_class_id
# initialize a boolean used to indicate if the object has
# already been counted or not
self.counted = False
# initialize a boolean used to indicate if the object has left the node's field of view and the tracks complete
self.complete = False
# pass first boxoid to 'append_boxoids' method for processing
self.append_boxoid(boxoid)
# pass first centroid to 'append_centroids' method for processing
self.append_centroid(centroid)
self.append_oids(centroid_frame_timestamp, detection_class_id, centroid, boxoid, bbox_rw_coords)
def append_centroid(self, centroid):
pass
#self.centroids.append(list(centroid))
def append_boxoid(self, boxoid):
#self.boxoids.append(list(boxoid))
# if self.detection_class_id > 0 and boxoid[5] <= 0: # if object's class has been identified already but this isn't a new identification
# pass # ... then don't change the current detection class. Even if the new detection_class_id is a -1, which means that the detection has changed but we'll stick with the first detected object class
# else: # if the object's class hasn't been identified yet or this is a new identification from a detected frame or a -1
# self.detection_class_id = boxoid[5]
pass
def append_oids(self, centroid_frame_timestamp, detection_class_id, centroid, boxoid, bbox_rw_coords):
if self.detection_class_id > 0 and detection_class_id <= 0: # if object's class has been identified already but this isn't a new identification
pass # ... then don't change the current detection class. Even if the new detection_class_id is a -1, which means that the detection has changed but we'll stick with the first detected object class
else: # if the object's class hasn't been identified yet or this is a new identification from a detected frame or a -1
self.detection_class_id = detection_class_id
oid = {
"frame_timestamp": centroid_frame_timestamp,
"centroid": list(centroid),
"boxoid": list(boxoid),
"bbox_rw_coords": bbox_rw_coords
}
self.oids.append(oid)
| class Trackableobject:
def __init__(self, objectID, centroid_frame_timestamp, detection_class_id, centroid, boxoid, bbox_rw_coords):
self.objectID = objectID
self.oids = []
self.centroids = []
self.boxoids = []
self.bbox_rw_coords = []
self.detection_class_id = detection_class_id
self.counted = False
self.complete = False
self.append_boxoid(boxoid)
self.append_centroid(centroid)
self.append_oids(centroid_frame_timestamp, detection_class_id, centroid, boxoid, bbox_rw_coords)
def append_centroid(self, centroid):
pass
def append_boxoid(self, boxoid):
pass
def append_oids(self, centroid_frame_timestamp, detection_class_id, centroid, boxoid, bbox_rw_coords):
if self.detection_class_id > 0 and detection_class_id <= 0:
pass
else:
self.detection_class_id = detection_class_id
oid = {'frame_timestamp': centroid_frame_timestamp, 'centroid': list(centroid), 'boxoid': list(boxoid), 'bbox_rw_coords': bbox_rw_coords}
self.oids.append(oid) |
#---------------------------------------
# Selection Sort
#---------------------------------------
def selection_sort(A):
for i in range (0, len(A) - 1):
minIndex = i
for j in range (i+1, len(A)):
if A[j] < A[minIndex]:
minIndex = j
if minIndex != i:
A[i], A[minIndex] = A[minIndex], A[i]
A = [5,9,1,2,4,8,6,3,7]
print(A)
selection_sort(A)
print(A) | def selection_sort(A):
for i in range(0, len(A) - 1):
min_index = i
for j in range(i + 1, len(A)):
if A[j] < A[minIndex]:
min_index = j
if minIndex != i:
(A[i], A[minIndex]) = (A[minIndex], A[i])
a = [5, 9, 1, 2, 4, 8, 6, 3, 7]
print(A)
selection_sort(A)
print(A) |
games = ["chess", "soccer", "tennis"]
foods = ["chicken", "milk", "fruits"]
favorites = games + foods
print(favorites)
| games = ['chess', 'soccer', 'tennis']
foods = ['chicken', 'milk', 'fruits']
favorites = games + foods
print(favorites) |
# Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
# For example,
# Given the following matrix:
# [
# [ 1, 2, 3 ],
# [ 4, 5, 6 ],
# [ 7, 8, 9 ]
# ]
# You should return [1,2,3,6,9,8,7,4,5].
class Solution:
# @param {integer[][]} matrix
# @return {integer[]}
def spiralOrder(self, matrix):
if not matrix or not matrix[0]:
return []
total = len(matrix) * len(matrix[0])
spiral = []
l, r, u, d = -1, len(matrix[0]), 0, len(matrix)
s, i, j = 0, 0, 0
for c in range(total):
spiral.append(matrix[i][j])
s, i, j, l, r, u, d = self._next(s, i, j, l, r, u, d)
return spiral
def _next(self, s, i, j, l, r, u, d):
if s == 0: # step right
j += 1
if j == r:
i, j = i+1, r-1
r -= 1
s = 1
elif s == 1: # step down
i += 1
if i == d:
i, j = d-1, j-1
d -= 1
s = 2
elif s == 2: # step left
j -= 1
if j == l:
i, j = i-1, l+1
l += 1
s = 3
else: # step up
i -= 1
if i == u:
i, j = u+1, j+1
u += 1
s = 0
return s, i, j, l, r, u, d | class Solution:
def spiral_order(self, matrix):
if not matrix or not matrix[0]:
return []
total = len(matrix) * len(matrix[0])
spiral = []
(l, r, u, d) = (-1, len(matrix[0]), 0, len(matrix))
(s, i, j) = (0, 0, 0)
for c in range(total):
spiral.append(matrix[i][j])
(s, i, j, l, r, u, d) = self._next(s, i, j, l, r, u, d)
return spiral
def _next(self, s, i, j, l, r, u, d):
if s == 0:
j += 1
if j == r:
(i, j) = (i + 1, r - 1)
r -= 1
s = 1
elif s == 1:
i += 1
if i == d:
(i, j) = (d - 1, j - 1)
d -= 1
s = 2
elif s == 2:
j -= 1
if j == l:
(i, j) = (i - 1, l + 1)
l += 1
s = 3
else:
i -= 1
if i == u:
(i, j) = (u + 1, j + 1)
u += 1
s = 0
return (s, i, j, l, r, u, d) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.