content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class InvalidTemplateError(Exception):
"""
Raised when a CloudFormation template fails the Validate Template call
"""
pass
| class Invalidtemplateerror(Exception):
"""
Raised when a CloudFormation template fails the Validate Template call
"""
pass |
class BinarySearch:
def __init__(self, arr, target):
self.arr = arr
self.target = target
def binary_search(self):
lo, hi = 0, len(self.arr)
while lo<hi:
mid = lo + (hi-lo)//2
# dont use (lo+hi)//2. Integer overflow.
# https://en.wikipedia.org/wiki/Binary_search_algorithm#Implementation_issues
if self.arr[mid] == self.target:
return mid
if self.arr[mid] > self.target:
hi = mid-1
else:
lo = mid+1
return -1
# input in python3 returns a string
n = int(input('Enter the size of array'))
# example of using map
# a = ['1', '2'] conver it into int
# a = list(map(int, a)) in python2 this will work a=map(int,a)
# in python3 map returns a map object which is a generator where as in py2 map returns a list
# n is used so that even if we enter n+1 numbers list will only contain n number
arr = list(map(int, input("Enter the number").strip().split()))[:n]
target = int(input("Enter the number to be searched"))
print(BinarySearch(arr, target).binary_search())
| class Binarysearch:
def __init__(self, arr, target):
self.arr = arr
self.target = target
def binary_search(self):
(lo, hi) = (0, len(self.arr))
while lo < hi:
mid = lo + (hi - lo) // 2
if self.arr[mid] == self.target:
return mid
if self.arr[mid] > self.target:
hi = mid - 1
else:
lo = mid + 1
return -1
n = int(input('Enter the size of array'))
arr = list(map(int, input('Enter the number').strip().split()))[:n]
target = int(input('Enter the number to be searched'))
print(binary_search(arr, target).binary_search()) |
class Solution(object):
# def validPalindrome(self, s):
# """
# :type s: str
# :rtype: bool
# """
# def is_pali_range(i, j):
# return all(s[k] == s[j - k + i] for k in range(i, j))
# for i in xrange(len(s) / 2):
# if s[i] != s[~i]:
# j = len(s) - 1 - i
# return is_pali_range(i + 1, j) or is_pali_range(i, j - 1)
# return True
# Actually we can make this solution more general
def validPalindrome(self, s):
return self.validPalindromeHelper(s, 0, len(s) - 1, 1)
def validPalindromeHelper(self, s, left, right, budget):
# Note that budget can be more than 1
while left < len(s) and right >= 0 and left <= right and s[left] == s[right]:
left += 1
right -= 1
if left >= len(s) or right < 0 or left >= right:
return True
if budget == 0:
return False
budget -= 1
return self.validPalindromeHelper(s, left + 1, right, budget) or self.validPalindromeHelper(s, left, right - 1, budget)
| class Solution(object):
def valid_palindrome(self, s):
return self.validPalindromeHelper(s, 0, len(s) - 1, 1)
def valid_palindrome_helper(self, s, left, right, budget):
while left < len(s) and right >= 0 and (left <= right) and (s[left] == s[right]):
left += 1
right -= 1
if left >= len(s) or right < 0 or left >= right:
return True
if budget == 0:
return False
budget -= 1
return self.validPalindromeHelper(s, left + 1, right, budget) or self.validPalindromeHelper(s, left, right - 1, budget) |
class connectionFinder:
def __init__(self, length):
self.id = [0] * length
self.size = [0] * length
for i in range(length):
self.id[i] = i
self.size[i] = i
# Id2 will become a root of Id1 :
def union(self, id1, id2):
rootA = self.find(id1)
rootB = self.find(id2)
self.id[rootA] = rootB
print(self.id)
# Optimization to remove skewed tree and construct weighted binary tree:
def weightedUnion(self, id1, id2):
root1 = self.find(id1)
root2 = self.find(id2)
size1 = self.size[root1]
size2 = self.size[root2]
if size1 < size2:
# Make small one child
self.id[root1] = root2
self.size[root2] += self.size[root1]
else:
self.id[root2] = root1
self.size[root1] += self.size[root2]
def find(self, x):
if self.id[x] == x:
return x
x = self.id[self.id[x]]
# To cut the overhead next when we call this find method for the same root
self.id[x] = x
return self.find(x)
def isConnected(self, id1, id2):
return self.find(id1) == self.find(id2)
uf = connectionFinder(10)
uf.union(1, 2)
print(" check ", uf.isConnected(1, 2))
| class Connectionfinder:
def __init__(self, length):
self.id = [0] * length
self.size = [0] * length
for i in range(length):
self.id[i] = i
self.size[i] = i
def union(self, id1, id2):
root_a = self.find(id1)
root_b = self.find(id2)
self.id[rootA] = rootB
print(self.id)
def weighted_union(self, id1, id2):
root1 = self.find(id1)
root2 = self.find(id2)
size1 = self.size[root1]
size2 = self.size[root2]
if size1 < size2:
self.id[root1] = root2
self.size[root2] += self.size[root1]
else:
self.id[root2] = root1
self.size[root1] += self.size[root2]
def find(self, x):
if self.id[x] == x:
return x
x = self.id[self.id[x]]
self.id[x] = x
return self.find(x)
def is_connected(self, id1, id2):
return self.find(id1) == self.find(id2)
uf = connection_finder(10)
uf.union(1, 2)
print(' check ', uf.isConnected(1, 2)) |
expected_output = {
"vrf": {
"vrf1": {
"lib_entry": {
"10.11.0.0/24": {
"rev": "7",
"remote_binding": {
"label": {
"imp-null": {
"lsr_id": {"10.132.0.1": {"label_space_id": {0: {}}}}
}
}
},
},
"10.12.0.0/24": {
"label_binding": {"label": {"17": {}}},
"rev": "8",
"remote_binding": {
"label": {
"imp-null": {
"lsr_id": {"10.132.0.1": {"label_space_id": {0: {}}}}
}
}
},
},
"10.0.0.0/24": {
"rev": "6",
"remote_binding": {
"label": {
"imp-null": {
"lsr_id": {"10.132.0.1": {"label_space_id": {0: {}}}}
}
}
},
},
}
},
"default": {
"lib_entry": {
"10.11.0.0/24": {
"label_binding": {"label": {"imp-null": {}}},
"rev": "15",
"remote_binding": {
"label": {
"imp-null": {
"lsr_id": {"10.131.0.1": {"label_space_id": {0: {}}}}
}
}
},
},
"10.0.0.0/24": {
"label_binding": {"label": {"imp-null": {}}},
"rev": "4",
"remote_binding": {
"label": {
"imp-null": {
"lsr_id": {"10.131.0.1": {"label_space_id": {0: {}}}}
}
}
},
},
}
},
}
}
| expected_output = {'vrf': {'vrf1': {'lib_entry': {'10.11.0.0/24': {'rev': '7', 'remote_binding': {'label': {'imp-null': {'lsr_id': {'10.132.0.1': {'label_space_id': {0: {}}}}}}}}, '10.12.0.0/24': {'label_binding': {'label': {'17': {}}}, 'rev': '8', 'remote_binding': {'label': {'imp-null': {'lsr_id': {'10.132.0.1': {'label_space_id': {0: {}}}}}}}}, '10.0.0.0/24': {'rev': '6', 'remote_binding': {'label': {'imp-null': {'lsr_id': {'10.132.0.1': {'label_space_id': {0: {}}}}}}}}}}, 'default': {'lib_entry': {'10.11.0.0/24': {'label_binding': {'label': {'imp-null': {}}}, 'rev': '15', 'remote_binding': {'label': {'imp-null': {'lsr_id': {'10.131.0.1': {'label_space_id': {0: {}}}}}}}}, '10.0.0.0/24': {'label_binding': {'label': {'imp-null': {}}}, 'rev': '4', 'remote_binding': {'label': {'imp-null': {'lsr_id': {'10.131.0.1': {'label_space_id': {0: {}}}}}}}}}}}} |
nmr = int(input("Digite um numero: "))
if nmr %2 == 0:
print("Numero par")
else:
print("Numero impar") | nmr = int(input('Digite um numero: '))
if nmr % 2 == 0:
print('Numero par')
else:
print('Numero impar') |
class DefaultConfig(object):
# Flask Settings
# ------------------------------
# There is a whole bunch of more settings available here:
# http://flask.pocoo.org/docs/0.11/config/#builtin-configuration-values
DEBUG = False
TESTING = False
| class Defaultconfig(object):
debug = False
testing = False |
n = int(input())
ss = input().split()
s = int(ss[0])
a = []
for i in range(n):
ss = input().split()
a.append((int(ss[0]), int(ss[1])))
a.sort(key=lambda x: x[0] * x[1])
ans = 0
for i in range(n):
if (s // (a[i])[1] > ans):
ans = s // (a[i])[1]
s *= (a[i])[0]
print(ans) | n = int(input())
ss = input().split()
s = int(ss[0])
a = []
for i in range(n):
ss = input().split()
a.append((int(ss[0]), int(ss[1])))
a.sort(key=lambda x: x[0] * x[1])
ans = 0
for i in range(n):
if s // a[i][1] > ans:
ans = s // a[i][1]
s *= a[i][0]
print(ans) |
def city_formatter(city, country):
formatted = f"{city.title()}, {country.title()}"
return formatted
print(city_formatter('hello', 'world')) | def city_formatter(city, country):
formatted = f'{city.title()}, {country.title()}'
return formatted
print(city_formatter('hello', 'world')) |
'''
Given an integer array sorted in non-decreasing order,
there is exactly one integer in the array that occurs
more than 25% of the time.
Return that integer.
Example:
Input: arr = [1,2,2,6,6,6,6,7,10]
Output: 6
Constraints:
- 1 <= arr.length <= 10^4
- 0 <= arr[i] <= 10^5
'''
#Difficulty: Easy
#18 / 18 test cases passed.
#Runtime: 120 ms
#Memory Usage: 15.9 MB
#Runtime: 120 ms, faster than 14.93% of Python3 online submissions for Element Appearing More Than 25% In Sorted Array.
#Memory Usage: 15.9 MB, less than 12.26% of Python3 online submissions for Element Appearing More Than 25% In Sorted Array.
class Solution:
def findSpecialInteger(self, arr: List[int]) -> int:
length = len(arr)
nums = set(arr)
if length == 1:
return arr[0]
for num in nums:
n = self.binarySearch(arr, num, length)
if n:
return n
def binarySearch(self, arr: int, num: int, length: int) -> int:
l = 0
r = length - 1
q = length // 4
while l < r:
m = (l+r) // 2
if arr[m] == num and arr[min(length-1, m+q)] == num:
return num
elif num > arr[m]:
l = m + 1
else:
r = m - 1
| """
Given an integer array sorted in non-decreasing order,
there is exactly one integer in the array that occurs
more than 25% of the time.
Return that integer.
Example:
Input: arr = [1,2,2,6,6,6,6,7,10]
Output: 6
Constraints:
- 1 <= arr.length <= 10^4
- 0 <= arr[i] <= 10^5
"""
class Solution:
def find_special_integer(self, arr: List[int]) -> int:
length = len(arr)
nums = set(arr)
if length == 1:
return arr[0]
for num in nums:
n = self.binarySearch(arr, num, length)
if n:
return n
def binary_search(self, arr: int, num: int, length: int) -> int:
l = 0
r = length - 1
q = length // 4
while l < r:
m = (l + r) // 2
if arr[m] == num and arr[min(length - 1, m + q)] == num:
return num
elif num > arr[m]:
l = m + 1
else:
r = m - 1 |
class json_to_csv():
def __init__(self):
self.stri=''
self.st=''
self.a=[]
self.b=[]
self.p=''
def read_js(self,path):
self.p=path
l=open(path,'r').readlines()
for i in l:
i=i.replace('\t','')
i=i.replace('\n','')
self.stri+=i
self.st=self.stri
def write_cs(self,path=None,head=None):
self.st=self.stri
self.st=self.st.replace('{','')
self.st=self.st.replace('}','')
while len(self.st)!=0:
try:
i=self.st.index(':')
k=self.st[:i]
k=k.replace(' ','')
if k not in self.a:
self.a.append(k)
self.st=self.st[i+1:]
try :
i=self.st.index(',')
self.b.append(self.st[:i])
self.st=self.st[i+1:]
except :
self.b.append(self.st[:])
self.st=''
except:
self.st=''
for i in range(len(self.b)):
self.b[i]=self.b[i].replace(' ','')
if path==None:
m=self.p.index('.')
self.p=(self.p[:m]+'.csv')
f=open(self.p,'w')
else :
f=open(path,'w')
if head==None:
for i in self.a:
if self.a.index(i)!=len(self.a)-1:
f.write(i)
f.write(',')
else:
f.write(i)
f.write('\n')
for i in range(len(self.b)):
if i%len(self.a)!=len(self.a)-1:
f.write(self.b[i])
f.write(',')
else:
f.write(self.b[i])
f.write('\n')
else :
for i in head:
if head.index(i)!=len(head)-1:
f.write(i)
f.write(',')
else:
f.write(i)
f.write('\n')
for i in self.b:
if self.b.index(i)%len(self.a)!=len(self.a)-1:
f.write(i)
f.write(',')
else:
f.write(i)
f.write('\n')
| class Json_To_Csv:
def __init__(self):
self.stri = ''
self.st = ''
self.a = []
self.b = []
self.p = ''
def read_js(self, path):
self.p = path
l = open(path, 'r').readlines()
for i in l:
i = i.replace('\t', '')
i = i.replace('\n', '')
self.stri += i
self.st = self.stri
def write_cs(self, path=None, head=None):
self.st = self.stri
self.st = self.st.replace('{', '')
self.st = self.st.replace('}', '')
while len(self.st) != 0:
try:
i = self.st.index(':')
k = self.st[:i]
k = k.replace(' ', '')
if k not in self.a:
self.a.append(k)
self.st = self.st[i + 1:]
try:
i = self.st.index(',')
self.b.append(self.st[:i])
self.st = self.st[i + 1:]
except:
self.b.append(self.st[:])
self.st = ''
except:
self.st = ''
for i in range(len(self.b)):
self.b[i] = self.b[i].replace(' ', '')
if path == None:
m = self.p.index('.')
self.p = self.p[:m] + '.csv'
f = open(self.p, 'w')
else:
f = open(path, 'w')
if head == None:
for i in self.a:
if self.a.index(i) != len(self.a) - 1:
f.write(i)
f.write(',')
else:
f.write(i)
f.write('\n')
for i in range(len(self.b)):
if i % len(self.a) != len(self.a) - 1:
f.write(self.b[i])
f.write(',')
else:
f.write(self.b[i])
f.write('\n')
else:
for i in head:
if head.index(i) != len(head) - 1:
f.write(i)
f.write(',')
else:
f.write(i)
f.write('\n')
for i in self.b:
if self.b.index(i) % len(self.a) != len(self.a) - 1:
f.write(i)
f.write(',')
else:
f.write(i)
f.write('\n') |
def es5(tree):
# inserisci qui il tuo codice
d={}
for x in tree.f:
d1=es5(x)
for x in d1:
if x in d:
d[x]=d[x] | d1[x]
else:
d[x]=d1[x]
y=len(tree.f)
if y in d:
d[y]=d[y]| {tree.id}
else: d[y]= {tree.id}
return d | def es5(tree):
d = {}
for x in tree.f:
d1 = es5(x)
for x in d1:
if x in d:
d[x] = d[x] | d1[x]
else:
d[x] = d1[x]
y = len(tree.f)
if y in d:
d[y] = d[y] | {tree.id}
else:
d[y] = {tree.id}
return d |
#!/home/jepoy/anaconda3/bin/python
def main():
x = dict(Buffy = 'meow', Zilla = 'grrr', Angel = 'purr')
kitten(**x)
def kitten(**kwargs):
if len(kwargs):
for k in kwargs:
print('Kitten {} says {}'.format(k, kwargs[k]))
else:
print('Meow.')
if __name__ == '__main__':
main() | def main():
x = dict(Buffy='meow', Zilla='grrr', Angel='purr')
kitten(**x)
def kitten(**kwargs):
if len(kwargs):
for k in kwargs:
print('Kitten {} says {}'.format(k, kwargs[k]))
else:
print('Meow.')
if __name__ == '__main__':
main() |
def resolve():
'''
code here
'''
x, y = [int(item) for item in input().split()]
res = 0
if x < 0 and abs(y) - abs(x) >= 0:
res += 1
elif x > 0 and abs(y) - abs(x) <= 0:
res += 1
res += abs(abs(x) - abs(y))
if y > 0 and abs(y) - abs(x) < 0:
res += 1
elif y < 0 and abs(y) - abs(x) > 0:
res += 1
print(res)
if __name__ == "__main__":
resolve()
| def resolve():
"""
code here
"""
(x, y) = [int(item) for item in input().split()]
res = 0
if x < 0 and abs(y) - abs(x) >= 0:
res += 1
elif x > 0 and abs(y) - abs(x) <= 0:
res += 1
res += abs(abs(x) - abs(y))
if y > 0 and abs(y) - abs(x) < 0:
res += 1
elif y < 0 and abs(y) - abs(x) > 0:
res += 1
print(res)
if __name__ == '__main__':
resolve() |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
@File : 1410.py
@Contact : huanghoward@foxmail.com
@Modify Time : 2022/4/12 16:18
------------
"""
class Solution:
def entityParser(self, text: str) -> str:
l = 0
r = 0
reading = False
result = ""
convert = {
""": "\"",
"'": "\'",
"&": "&",
">": ">",
"<": "<",
"⁄": "/"
}
for i, char in enumerate(text):
if reading:
if char == ";":
r = i
if text[l:r + 1] not in convert.keys():
result += text[l:r + 1]
else:
result += convert[text[l:r + 1]]
r = 0
l = 0
reading = False
elif char == "&":
r = i
result += text[l:r]
l = i
continue
else:
if char == "&":
l = i
reading = True
continue
result += char
return result
if __name__ == '__main__':
s = Solution()
print(s.entityParser("&&&"))
| """
@File : 1410.py
@Contact : huanghoward@foxmail.com
@Modify Time : 2022/4/12 16:18
------------
"""
class Solution:
def entity_parser(self, text: str) -> str:
l = 0
r = 0
reading = False
result = ''
convert = {'"': '"', ''': "'", '&': '&', '>': '>', '<': '<', '⁄': '/'}
for (i, char) in enumerate(text):
if reading:
if char == ';':
r = i
if text[l:r + 1] not in convert.keys():
result += text[l:r + 1]
else:
result += convert[text[l:r + 1]]
r = 0
l = 0
reading = False
elif char == '&':
r = i
result += text[l:r]
l = i
continue
else:
if char == '&':
l = i
reading = True
continue
result += char
return result
if __name__ == '__main__':
s = solution()
print(s.entityParser('&&&')) |
def asm2(param_1, param_2): # push ebp
# mov ebp,esp
# sub esp,0x10
eax = param_2 # mov eax,DWORD PTR [ebp+0xc]
local_1 = eax # mov DWORD PTR [ebp-0x4],eax
eax = param_1 # mov eax,DWORD PTR [ebp+0x8]
local_2 = eax # mov eax,DWORD PTR [ebp+0x8]
while param_1 <= 0x9886:# cmp DWORD PTR [ebp+0x8],0x9886
# jle part_a
local_1 += 0x1 # add DWORD PTR [ebp-0x4],0x1
param_1 += 0x41 # add DWORD PTR [ebp+0x8],0x41
eax = local_1 # mov eax,DWORD PTR [ebp-0x4]
return eax # mov esp,ebp
# pop ebp
# ret
print(hex(asm2(0xe, 0x21)))
| def asm2(param_1, param_2):
eax = param_2
local_1 = eax
eax = param_1
local_2 = eax
while param_1 <= 39046:
local_1 += 1
param_1 += 65
eax = local_1
return eax
print(hex(asm2(14, 33))) |
class _SpeechOperation():
def add_done_callback(callback):
pass | class _Speechoperation:
def add_done_callback(callback):
pass |
class BaseHyperParameter:
"""
This is a base class for all hyper-parameters. It should not be instantiated. Use concrete implementations instead.
"""
def __init__(self, name):
self.name = name
| class Basehyperparameter:
"""
This is a base class for all hyper-parameters. It should not be instantiated. Use concrete implementations instead.
"""
def __init__(self, name):
self.name = name |
def main():
a = 1 if True else 2
print(a)
if __name__ == '__main__':
main()
| def main():
a = 1 if True else 2
print(a)
if __name__ == '__main__':
main() |
# Birth should occur before death of an individual
def userStory03(listOfPeople):
flag = True
def changeDateToNum(date): # date format must be like "2018-10-06"
if date == "NA":
return 0 # 0 will not larger than any date, for later comparison
else:
tempDate = date.split('-')
return int(tempDate[0] + tempDate[1] + tempDate[2])
for people in listOfPeople:
if people.Death != "NA":
BirthdayNum = changeDateToNum(people.Birthday)
DeathNum = changeDateToNum(people.Death)
if BirthdayNum > DeathNum:
print("ERROR: INDIVIDUAL: US03: Birthday of " + people.ID + " occur after Death")
flag = False
return flag
| def user_story03(listOfPeople):
flag = True
def change_date_to_num(date):
if date == 'NA':
return 0
else:
temp_date = date.split('-')
return int(tempDate[0] + tempDate[1] + tempDate[2])
for people in listOfPeople:
if people.Death != 'NA':
birthday_num = change_date_to_num(people.Birthday)
death_num = change_date_to_num(people.Death)
if BirthdayNum > DeathNum:
print('ERROR: INDIVIDUAL: US03: Birthday of ' + people.ID + ' occur after Death')
flag = False
return flag |
name = input("Enter your name: ")
age = input("Enter your age: ")
print("Hello " + name + " ! Your are " + age + " Years old now.")
num1 = input("Enter a number: ")
num2 = input("Enter another number: ")
result = num1 + num2
print(result)
# We need int casting number num1 and num2
result = int(num1) + int(num2)
print(result)
# Adding two Float number
num1 = input("Enter a number: ")
num2 = input("Enter another number: ")
result = float(num1) + float(num2)
print(result) | name = input('Enter your name: ')
age = input('Enter your age: ')
print('Hello ' + name + ' ! Your are ' + age + ' Years old now.')
num1 = input('Enter a number: ')
num2 = input('Enter another number: ')
result = num1 + num2
print(result)
result = int(num1) + int(num2)
print(result)
num1 = input('Enter a number: ')
num2 = input('Enter another number: ')
result = float(num1) + float(num2)
print(result) |
# -*- coding: utf-8 -*-
def find_message(message: str) -> str:
result: str = ""
for i in list(message):
if i.isupper():
result += i
return result
# another pattern
return ''.join(i for i in message if i.isupper())
if __name__ == '__main__':
print("Example:")
print(find_message(('How are you? Eh, ok. Low or Lower? '
+ 'Ohhh.')))
# These "asserts" are used for self-checking and not for an auto-testing
assert find_message(('How are you? Eh, ok. Low or Lower? '
+ 'Ohhh.')) == 'HELLO'
assert find_message('hello world!') == ''
assert find_message('HELLO WORLD!!!') == 'HELLOWORLD'
print("Coding complete? Click 'Check' to earn cool rewards!")
| def find_message(message: str) -> str:
result: str = ''
for i in list(message):
if i.isupper():
result += i
return result
return ''.join((i for i in message if i.isupper()))
if __name__ == '__main__':
print('Example:')
print(find_message('How are you? Eh, ok. Low or Lower? ' + 'Ohhh.'))
assert find_message('How are you? Eh, ok. Low or Lower? ' + 'Ohhh.') == 'HELLO'
assert find_message('hello world!') == ''
assert find_message('HELLO WORLD!!!') == 'HELLOWORLD'
print("Coding complete? Click 'Check' to earn cool rewards!") |
#
# Copyright 2019 Delphix
#
# 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.
#
"""This module contains the "sdb.Error" exception."""
class Error(Exception):
"""
This is the superclass of all SDB error exceptions.
"""
text: str = ""
def __init__(self, text: str) -> None:
self.text = 'sdb: {}'.format(text)
super().__init__(self.text)
class CommandNotFoundError(Error):
# pylint: disable=missing-docstring
command: str = ""
def __init__(self, command: str) -> None:
self.command = command
super().__init__("cannot recognize command: {command}")
class CommandError(Error):
# pylint: disable=missing-docstring
command: str = ""
message: str = ""
def __init__(self, command: str, message: str) -> None:
self.command = command
self.message = message
super().__init__(f"{command}: {message}")
class CommandInvalidInputError(CommandError):
# pylint: disable=missing-docstring
argument: str = ""
def __init__(self, command: str, argument: str) -> None:
self.argument = argument
super().__init__(command, f"invalid input: {argument}")
class SymbolNotFoundError(CommandError):
# pylint: disable=missing-docstring
symbol: str = ""
def __init__(self, command: str, symbol: str) -> None:
self.symbol = symbol
super().__init__(command, f"symbol not found: {symbol}")
class CommandArgumentsError(CommandError):
# pylint: disable=missing-docstring
def __init__(self, command: str) -> None:
super().__init__(command,
'invalid input. Use -h to get argument description')
class CommandEvalSyntaxError(CommandError):
# pylint: disable=missing-docstring
def __init__(self, command: str, err: SyntaxError) -> None:
msg = f"{err.msg}:\n\t{err.text}"
if err.offset is not None and err.text is not None:
nspaces: int = err.offset - 1
spaces_str = list(' ' * len(err.text))
spaces_str[nspaces] = '^'
indicator = ''.join(spaces_str)
msg += f"\n\t{indicator}"
super().__init__(command, msg)
| """This module contains the "sdb.Error" exception."""
class Error(Exception):
"""
This is the superclass of all SDB error exceptions.
"""
text: str = ''
def __init__(self, text: str) -> None:
self.text = 'sdb: {}'.format(text)
super().__init__(self.text)
class Commandnotfounderror(Error):
command: str = ''
def __init__(self, command: str) -> None:
self.command = command
super().__init__('cannot recognize command: {command}')
class Commanderror(Error):
command: str = ''
message: str = ''
def __init__(self, command: str, message: str) -> None:
self.command = command
self.message = message
super().__init__(f'{command}: {message}')
class Commandinvalidinputerror(CommandError):
argument: str = ''
def __init__(self, command: str, argument: str) -> None:
self.argument = argument
super().__init__(command, f'invalid input: {argument}')
class Symbolnotfounderror(CommandError):
symbol: str = ''
def __init__(self, command: str, symbol: str) -> None:
self.symbol = symbol
super().__init__(command, f'symbol not found: {symbol}')
class Commandargumentserror(CommandError):
def __init__(self, command: str) -> None:
super().__init__(command, 'invalid input. Use -h to get argument description')
class Commandevalsyntaxerror(CommandError):
def __init__(self, command: str, err: SyntaxError) -> None:
msg = f'{err.msg}:\n\t{err.text}'
if err.offset is not None and err.text is not None:
nspaces: int = err.offset - 1
spaces_str = list(' ' * len(err.text))
spaces_str[nspaces] = '^'
indicator = ''.join(spaces_str)
msg += f'\n\t{indicator}'
super().__init__(command, msg) |
# Copyright 2020 The Bazel 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.
"""`dtrace_compile` Starlark tests."""
load(
":rules/output_text_match_test.bzl",
"output_text_match_test",
)
def dtrace_compile_test_suite(name):
"""Test suite for `dtrace_compile`.
Args:
name: the base name to be used in things created by this macro
"""
output_text_match_test(
name = "{}_generates_expected_header_contents".format(name),
target_under_test = "//test/starlark_tests/targets_under_test/dtrace:dtrace",
files_match = {
"folder1/probes.h": ["PROVIDERA_MYFUNC"],
"folder2/probes.h": ["PROVIDERB_MYFUNC"],
},
tags = [name],
)
native.test_suite(
name = name,
tags = [name],
)
| """`dtrace_compile` Starlark tests."""
load(':rules/output_text_match_test.bzl', 'output_text_match_test')
def dtrace_compile_test_suite(name):
"""Test suite for `dtrace_compile`.
Args:
name: the base name to be used in things created by this macro
"""
output_text_match_test(name='{}_generates_expected_header_contents'.format(name), target_under_test='//test/starlark_tests/targets_under_test/dtrace:dtrace', files_match={'folder1/probes.h': ['PROVIDERA_MYFUNC'], 'folder2/probes.h': ['PROVIDERB_MYFUNC']}, tags=[name])
native.test_suite(name=name, tags=[name]) |
class Vector(object):
SHORTHAND = 'V'
def __init__(self, **kwargs):
super(Vector, self).__init__()
self.vector = kwargs
def dot(self, other):
product = 0
for member, value in self.vector.items():
product += value * other.member(member)
return product
def apply(self, other):
for member, effect in other.vector.items():
value = self.member(member)
self.vector[member] = value + effect
def member(self, name, default=0):
return self.vector.get(name, default)
def __str__(self):
return '%s(%s)' % (self.SHORTHAND, ','.join(['%s=%.3f' % (key, value) for key, value in self.vector.items()])) | class Vector(object):
shorthand = 'V'
def __init__(self, **kwargs):
super(Vector, self).__init__()
self.vector = kwargs
def dot(self, other):
product = 0
for (member, value) in self.vector.items():
product += value * other.member(member)
return product
def apply(self, other):
for (member, effect) in other.vector.items():
value = self.member(member)
self.vector[member] = value + effect
def member(self, name, default=0):
return self.vector.get(name, default)
def __str__(self):
return '%s(%s)' % (self.SHORTHAND, ','.join(['%s=%.3f' % (key, value) for (key, value) in self.vector.items()])) |
#!/usr/bin/env python3
def first(iterable, default=None, key=None):
if key is None:
for el in iterable:
if el is not None:
return el
else:
for el in iterable:
if key(el) is not None:
return el
return default
| def first(iterable, default=None, key=None):
if key is None:
for el in iterable:
if el is not None:
return el
else:
for el in iterable:
if key(el) is not None:
return el
return default |
class Foo:
def qux2(self):
z = 12
x = z * 3
self.baz = x
for q in range(10):
x += q
lst = ["foo", "bar", "baz"]
lst = lst[1:2]
assert len(lst) == 2, 201
def qux(self):
self.baz = self.bar
self.blah = "hello"
self._priv = 1
self._prot = self.baz
def _prot2(self):
pass
class Bar(Foo):
def something(self):
super()._prot2()
def something2(self):
self._prot = 12
class SpriteKind(Enum):
Player = 0
Projectile = 1
Enemy = 2
Food = 3
ii = img("""
. . . .
. a . .
. b b .
""")
hbuf = hex("a007")
hbuf2 = b'\xB0\x07'
asteroids = [sprites.space.space_small_asteroid1, sprites.space.space_small_asteroid0, sprites.space.space_asteroid0, sprites.space.space_asteroid1, sprites.space.space_asteroid4, sprites.space.space_asteroid3]
ship = sprites.create(sprites.space.space_red_ship, SpriteKind.Player)
ship.set_flag(SpriteFlag.STAY_IN_SCREEN, True)
ship.bottom = 120
controller.move_sprite(ship, 100, 100)
info.set_life(3)
def player_damage(sprite, other_sprite):
scene.camera_shake(4, 500)
other_sprite.destroy(effects.disintegrate)
sprite.start_effect(effects.fire, 200)
info.change_life_by(-1)
sprites.on_overlap(SpriteKind.Player, SpriteKind.Enemy, player_damage)
if False:
player_damage(ship, ship)
def enemy_damage(sprite:Sprite, other_sprite:Sprite):
sprite.destroy()
other_sprite.destroy(effects.disintegrate)
info.change_score_by(1)
sprites.on_overlap(SpriteKind.Projectile, SpriteKind.Enemy, enemy_damage)
def shoot():
projectile = sprites.create_projectile_from_sprite(sprites.food.small_apple, ship, 0, -140)
projectile.start_effect(effects.cool_radial, 100)
controller.A.on_event(ControllerButtonEvent.PRESSED, shoot)
def spawn_enemy():
projectile = sprites.create_projectile_from_side(asteroids[math.random_range(0, asteroids.length - 1)], 0, 75)
projectile.set_kind(SpriteKind.Enemy)
projectile.x = math.random_range(10, 150)
game.on_update_interval(500, spawn_enemy)
| class Foo:
def qux2(self):
z = 12
x = z * 3
self.baz = x
for q in range(10):
x += q
lst = ['foo', 'bar', 'baz']
lst = lst[1:2]
assert len(lst) == 2, 201
def qux(self):
self.baz = self.bar
self.blah = 'hello'
self._priv = 1
self._prot = self.baz
def _prot2(self):
pass
class Bar(Foo):
def something(self):
super()._prot2()
def something2(self):
self._prot = 12
class Spritekind(Enum):
player = 0
projectile = 1
enemy = 2
food = 3
ii = img('\n. . . .\n. a . .\n. b b .\n')
hbuf = hex('a007')
hbuf2 = b'\xb0\x07'
asteroids = [sprites.space.space_small_asteroid1, sprites.space.space_small_asteroid0, sprites.space.space_asteroid0, sprites.space.space_asteroid1, sprites.space.space_asteroid4, sprites.space.space_asteroid3]
ship = sprites.create(sprites.space.space_red_ship, SpriteKind.Player)
ship.set_flag(SpriteFlag.STAY_IN_SCREEN, True)
ship.bottom = 120
controller.move_sprite(ship, 100, 100)
info.set_life(3)
def player_damage(sprite, other_sprite):
scene.camera_shake(4, 500)
other_sprite.destroy(effects.disintegrate)
sprite.start_effect(effects.fire, 200)
info.change_life_by(-1)
sprites.on_overlap(SpriteKind.Player, SpriteKind.Enemy, player_damage)
if False:
player_damage(ship, ship)
def enemy_damage(sprite: Sprite, other_sprite: Sprite):
sprite.destroy()
other_sprite.destroy(effects.disintegrate)
info.change_score_by(1)
sprites.on_overlap(SpriteKind.Projectile, SpriteKind.Enemy, enemy_damage)
def shoot():
projectile = sprites.create_projectile_from_sprite(sprites.food.small_apple, ship, 0, -140)
projectile.start_effect(effects.cool_radial, 100)
controller.A.on_event(ControllerButtonEvent.PRESSED, shoot)
def spawn_enemy():
projectile = sprites.create_projectile_from_side(asteroids[math.random_range(0, asteroids.length - 1)], 0, 75)
projectile.set_kind(SpriteKind.Enemy)
projectile.x = math.random_range(10, 150)
game.on_update_interval(500, spawn_enemy) |
pattern_zero=[0.0, 0.138888888889, 0.222222222222, 0.25, 0.333333333333, 0.472222222222, 0.555555555556, 0.583333333333, 0.666666666667, 0.805555555556, 0.888888888889, 0.916666666667]
pattern_odd=[0.0, 0.138888888889, 0.222222222222, 0.25, 0.333333333333, 0.472222222222, 0.555555555556, 0.583333333333, 0.666666666667, 0.805555555556, 0.888888888889, 0.916666666667]
pattern_even=[0.0, 0.138888888889, 0.222222222222, 0.25, 0.333333333333, 0.472222222222, 0.555555555556, 0.583333333333, 0.666666666667, 0.805555555556, 0.888888888889, 0.916666666667]
averages_even={0.0: [0.0], 0.25: [0.5], 0.916666666667: [0.5], 0.138888888889: [0.8333333333333, 0.1666666666667], 0.583333333333: [0.5], 0.555555555556: [0.3333333333333, 0.6666666666667], 0.222222222222: [0.3333333333333, 0.6666666666667], 0.333333333333: [0.0], 0.805555555556: [0.8333333333333, 0.1666666666667], 0.888888888889: [0.3333333333333, 0.6666666666667], 0.472222222222: [0.8333333333333, 0.1666666666667], 0.666666666667: [0.0]}
averages_odd={0.0: [0.0], 0.25: [0.5], 0.916666666667: [0.5], 0.138888888889: [0.8333333333333, 0.1666666666667], 0.583333333333: [0.5], 0.555555555556: [0.3333333333333, 0.6666666666667], 0.222222222222: [0.3333333333333, 0.6666666666667], 0.333333333333: [0.0], 0.805555555556: [0.8333333333333, 0.1666666666667], 0.888888888889: [0.3333333333333, 0.6666666666667], 0.472222222222: [0.8333333333333, 0.1666666666667], 0.666666666667: [0.0]} | pattern_zero = [0.0, 0.138888888889, 0.222222222222, 0.25, 0.333333333333, 0.472222222222, 0.555555555556, 0.583333333333, 0.666666666667, 0.805555555556, 0.888888888889, 0.916666666667]
pattern_odd = [0.0, 0.138888888889, 0.222222222222, 0.25, 0.333333333333, 0.472222222222, 0.555555555556, 0.583333333333, 0.666666666667, 0.805555555556, 0.888888888889, 0.916666666667]
pattern_even = [0.0, 0.138888888889, 0.222222222222, 0.25, 0.333333333333, 0.472222222222, 0.555555555556, 0.583333333333, 0.666666666667, 0.805555555556, 0.888888888889, 0.916666666667]
averages_even = {0.0: [0.0], 0.25: [0.5], 0.916666666667: [0.5], 0.138888888889: [0.8333333333333, 0.1666666666667], 0.583333333333: [0.5], 0.555555555556: [0.3333333333333, 0.6666666666667], 0.222222222222: [0.3333333333333, 0.6666666666667], 0.333333333333: [0.0], 0.805555555556: [0.8333333333333, 0.1666666666667], 0.888888888889: [0.3333333333333, 0.6666666666667], 0.472222222222: [0.8333333333333, 0.1666666666667], 0.666666666667: [0.0]}
averages_odd = {0.0: [0.0], 0.25: [0.5], 0.916666666667: [0.5], 0.138888888889: [0.8333333333333, 0.1666666666667], 0.583333333333: [0.5], 0.555555555556: [0.3333333333333, 0.6666666666667], 0.222222222222: [0.3333333333333, 0.6666666666667], 0.333333333333: [0.0], 0.805555555556: [0.8333333333333, 0.1666666666667], 0.888888888889: [0.3333333333333, 0.6666666666667], 0.472222222222: [0.8333333333333, 0.1666666666667], 0.666666666667: [0.0]} |
class Solution(object):
def isReflected(self, points):
"""
:type points: List[List[int]]
:rtype: bool
"""
if not points:
return True
positions=set()
sumk=0
for p in points:
positions.add((p[0],p[1]))
# avoid duplicate points
for p in positions:
sumk+=p[0]
pivot=float(sumk)/float(len(positions))
for p in positions:
if (int(2*pivot-p[0]),p[1]) not in positions:
return False
return True
| class Solution(object):
def is_reflected(self, points):
"""
:type points: List[List[int]]
:rtype: bool
"""
if not points:
return True
positions = set()
sumk = 0
for p in points:
positions.add((p[0], p[1]))
for p in positions:
sumk += p[0]
pivot = float(sumk) / float(len(positions))
for p in positions:
if (int(2 * pivot - p[0]), p[1]) not in positions:
return False
return True |
Pathogen = {
'name': 'pathogen',
'fields': [
{'name': 'reported_name'},
{'name': 'drug_resistance'},
{'name': 'authority'},
{'name': 'tax_order'},
{'name': 'class'},
{'name': 'family'},
{'name': 'genus'},
{'name': 'species'},
{'name': 'sub_species'}
]
}
| pathogen = {'name': 'pathogen', 'fields': [{'name': 'reported_name'}, {'name': 'drug_resistance'}, {'name': 'authority'}, {'name': 'tax_order'}, {'name': 'class'}, {'name': 'family'}, {'name': 'genus'}, {'name': 'species'}, {'name': 'sub_species'}]} |
def merge(di1, di2, fu=None):
di3 = {}
for ke in sorted(di1.keys() | di2.keys()):
if ke in di1 and ke in di2:
if fu is None:
va1 = di1[ke]
va2 = di2[ke]
if isinstance(va1, dict) and isinstance(va2, dict):
di3[ke] = merge(va1, va2)
else:
di3[ke] = va2
else:
di3[ke] = fu(di1[ke], di2[ke])
elif ke in di1:
di3[ke] = di1[ke]
elif ke in di2:
di3[ke] = di2[ke]
return di3
| def merge(di1, di2, fu=None):
di3 = {}
for ke in sorted(di1.keys() | di2.keys()):
if ke in di1 and ke in di2:
if fu is None:
va1 = di1[ke]
va2 = di2[ke]
if isinstance(va1, dict) and isinstance(va2, dict):
di3[ke] = merge(va1, va2)
else:
di3[ke] = va2
else:
di3[ke] = fu(di1[ke], di2[ke])
elif ke in di1:
di3[ke] = di1[ke]
elif ke in di2:
di3[ke] = di2[ke]
return di3 |
def read_list(t): return [t(x) for x in input().split()]
def read_line(t): return t(input())
def read_lines(t, N): return [t(input()) for _ in range(N)]
N, Q = read_list(int)
array = read_list(int)
C = [[0, 0, 0]]
for a in array:
c = C[-1][:]
c[a % 3] += 1
C.append(c)
for _ in range(Q):
l, r = read_list(int)
c1, c2 = C[l-1], C[r]
if c2[0] - c1[0] == 1:
print(0)
else:
print(2 if (c2[2]-c1[2]) % 2 == 1 else 1)
| def read_list(t):
return [t(x) for x in input().split()]
def read_line(t):
return t(input())
def read_lines(t, N):
return [t(input()) for _ in range(N)]
(n, q) = read_list(int)
array = read_list(int)
c = [[0, 0, 0]]
for a in array:
c = C[-1][:]
c[a % 3] += 1
C.append(c)
for _ in range(Q):
(l, r) = read_list(int)
(c1, c2) = (C[l - 1], C[r])
if c2[0] - c1[0] == 1:
print(0)
else:
print(2 if (c2[2] - c1[2]) % 2 == 1 else 1) |
arr=[[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]
n=4#col
m=4#row
#print matrix in spiral form
loop=0
while(loop<n/2):
for i in range(loop,n-loop-1):
print(arr[loop][i],end=" ")
for i in range(loop,m-loop-1):
print(arr[i][m-loop-1],end=" ")
for i in range(n-1-loop,loop-1+1,-1):
print(arr[m-loop-1][i],end=" ")
for i in range(m-loop-1,loop,-1):
print(arr[i][loop],end=" ")
loop+=1
| arr = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
n = 4
m = 4
loop = 0
while loop < n / 2:
for i in range(loop, n - loop - 1):
print(arr[loop][i], end=' ')
for i in range(loop, m - loop - 1):
print(arr[i][m - loop - 1], end=' ')
for i in range(n - 1 - loop, loop - 1 + 1, -1):
print(arr[m - loop - 1][i], end=' ')
for i in range(m - loop - 1, loop, -1):
print(arr[i][loop], end=' ')
loop += 1 |
class Color:
red = None
green = None
blue = None
white = None
bit_color = None
def __init__(self, red, green, blue, white=0):
self.red = red
self.green = green
self.blue = blue
self.white = white
def get_rgb(self):
return 'rgb(%d,%d,%d)' % (self.red, self.green, self.blue)
def get_hex(self):
return '#%02x%02x%02x' % (self.red, self.green, self.blue)
def get_hsv(self):
red = self.red / 255.0
green = self.green / 255.0
blue = self.blue / 255.0
median_max = max(red, green, blue)
median_min = min(red, green, blue)
difference = median_max - median_min
if median_max == median_min:
hue = 0
elif median_max == red:
hue = (60 * ((green - blue) / difference) + 360) % 360
elif median_max == green:
hue = (60 * ((blue - red) / difference) + 120) % 360
elif median_max == blue:
hue = (60 * ((red - green) / difference) + 240) % 360
else:
hue = 0
if median_max == 0:
saturation = 0
else:
saturation = difference / median_max
value = median_max
return 'hsv(%d,%d,%d)' % (hue, saturation, value)
def get_bit(self):
return (self.white << 24) | (self.red << 16) | (self.green << 8) | self.blue
def __str__(self):
return '%d,%d,%d' % (self.red, self.green, self.blue)
| class Color:
red = None
green = None
blue = None
white = None
bit_color = None
def __init__(self, red, green, blue, white=0):
self.red = red
self.green = green
self.blue = blue
self.white = white
def get_rgb(self):
return 'rgb(%d,%d,%d)' % (self.red, self.green, self.blue)
def get_hex(self):
return '#%02x%02x%02x' % (self.red, self.green, self.blue)
def get_hsv(self):
red = self.red / 255.0
green = self.green / 255.0
blue = self.blue / 255.0
median_max = max(red, green, blue)
median_min = min(red, green, blue)
difference = median_max - median_min
if median_max == median_min:
hue = 0
elif median_max == red:
hue = (60 * ((green - blue) / difference) + 360) % 360
elif median_max == green:
hue = (60 * ((blue - red) / difference) + 120) % 360
elif median_max == blue:
hue = (60 * ((red - green) / difference) + 240) % 360
else:
hue = 0
if median_max == 0:
saturation = 0
else:
saturation = difference / median_max
value = median_max
return 'hsv(%d,%d,%d)' % (hue, saturation, value)
def get_bit(self):
return self.white << 24 | self.red << 16 | self.green << 8 | self.blue
def __str__(self):
return '%d,%d,%d' % (self.red, self.green, self.blue) |
N = int(input())
ano = N // 365
resto = N % 365
mes = resto // 30
dia = resto % 30
print(str(ano) + " ano(s)")
print(str(mes) + " mes(es)")
print(str(dia) + " dia(s)")
| n = int(input())
ano = N // 365
resto = N % 365
mes = resto // 30
dia = resto % 30
print(str(ano) + ' ano(s)')
print(str(mes) + ' mes(es)')
print(str(dia) + ' dia(s)') |
r, c = (map(int, input().split(' ')))
for row in range(r):
for col in range(c):
print(f'{chr(97 + row)}{chr(97 + row + col)}{chr(97 + row)}', end=' ')
print() | (r, c) = map(int, input().split(' '))
for row in range(r):
for col in range(c):
print(f'{chr(97 + row)}{chr(97 + row + col)}{chr(97 + row)}', end=' ')
print() |
'''Colocando cores no terminal do python'''
# \033[0;033;44m codigo para colocar as cores
# tipo de texto em cod (estilo do texto)
# 0 - sem estilo nenhum
# 1 - negrito
# 4 - sublinhado
# 7 - inverter as confgs
# cores em cod (cores do texto)
# 30 - branco
# 31 - vermelho
# 32 - verde
# 33 - amarelo
# 34 - azul
# 35 - lilas
# 36 - ciano
# 37 - cinza
# back em cod (cores de fundo)
# 40 - branco
# 41 - vermelho
# 42 - verde
# 43 - amarelo
# 44 - azul
# 45 - lilas
# 46 - ciano
# 47 - cinza
| """Colocando cores no terminal do python""" |
"""
An array is monotonic if it is either monotone increasing or monotone decreasing.
An array A is monotone increasing if for all i <= j, A[i] <= A[j]. An array A is monotone decreasing if for all i <= j, A[i] >= A[j].
Return true if and only if the given array A is monotonic.
Example 1:
Input: [1,2,2,3]
Output: true
Example 2:
Input: [6,5,4,4]
Output: true
Example 3:
Input: [1,3,2]
Output: false
Example 4:
Input: [1,2,4,5]
Output: true
Example 5:
Input: [1,1,1]
Output: true
Note:
1 <= A.length <= 50000
-100000 <= A[i] <= 100000
Solution:
1. Two variables. One for increasing, one for decreasing.
"""
class Solution:
def isMonotonic(self, A: List[int]) -> bool:
increase = True
decrease = True
for i in range(len(A)-1):
if A[i] > A[i+1]:
increase = False
if A[i] < A[i+1]:
decrease = False
return increase or decrease
| """
An array is monotonic if it is either monotone increasing or monotone decreasing.
An array A is monotone increasing if for all i <= j, A[i] <= A[j]. An array A is monotone decreasing if for all i <= j, A[i] >= A[j].
Return true if and only if the given array A is monotonic.
Example 1:
Input: [1,2,2,3]
Output: true
Example 2:
Input: [6,5,4,4]
Output: true
Example 3:
Input: [1,3,2]
Output: false
Example 4:
Input: [1,2,4,5]
Output: true
Example 5:
Input: [1,1,1]
Output: true
Note:
1 <= A.length <= 50000
-100000 <= A[i] <= 100000
Solution:
1. Two variables. One for increasing, one for decreasing.
"""
class Solution:
def is_monotonic(self, A: List[int]) -> bool:
increase = True
decrease = True
for i in range(len(A) - 1):
if A[i] > A[i + 1]:
increase = False
if A[i] < A[i + 1]:
decrease = False
return increase or decrease |
valid_passport = 0
invalid_passport = 0
def get_key(p_line):
keys = []
for i in p_line.split():
keys.append(i.split(':')[0])
return keys
def check_validation(keys):
for_valid = ' '.join(sorted(['byr', 'iyr', 'eyr', 'hgt', 'hcl', 'ecl', 'pid']))
# CID is optional
if 'cid' in keys:
keys.remove('cid')
keys = ' '.join(sorted(keys))
if for_valid == keys:
return True
else:
return False
with open('passport.txt') as file:
passport_line = ''
current_line = True
while current_line:
current_line = file.readline()
if current_line != '\n':
passport_line += ' ' + current_line[:-1]
else:
passport_line = get_key(passport_line)
if check_validation(passport_line):
valid_passport += 1
else:
invalid_passport += 1
passport_line = ''
passport_line = get_key(passport_line)
if check_validation(passport_line):
valid_passport += 1
else:
invalid_passport += 1
passport_line = ''
print(f'Valid Passport : {valid_passport}')
print(f'Invalid Passport : {invalid_passport}')
| valid_passport = 0
invalid_passport = 0
def get_key(p_line):
keys = []
for i in p_line.split():
keys.append(i.split(':')[0])
return keys
def check_validation(keys):
for_valid = ' '.join(sorted(['byr', 'iyr', 'eyr', 'hgt', 'hcl', 'ecl', 'pid']))
if 'cid' in keys:
keys.remove('cid')
keys = ' '.join(sorted(keys))
if for_valid == keys:
return True
else:
return False
with open('passport.txt') as file:
passport_line = ''
current_line = True
while current_line:
current_line = file.readline()
if current_line != '\n':
passport_line += ' ' + current_line[:-1]
else:
passport_line = get_key(passport_line)
if check_validation(passport_line):
valid_passport += 1
else:
invalid_passport += 1
passport_line = ''
passport_line = get_key(passport_line)
if check_validation(passport_line):
valid_passport += 1
else:
invalid_passport += 1
passport_line = ''
print(f'Valid Passport : {valid_passport}')
print(f'Invalid Passport : {invalid_passport}') |
# Copyright 2017 The Forseti Security 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.
"""Fake folders data."""
FAKE_FOLDERS_DB_ROWS = [
{'folder_id': '111111111111',
'name': 'folders/111111111111',
'display_name': 'Folder1',
'lifecycle_state': 'ACTIVE',
'create_time': '2015-09-09 00:01:01',
'parent_id': '9999',
'parent_type': 'organization'},
{'folder_id': '222222222222',
'name': 'folders/222222222222',
'display_name': 'Folder2',
'lifecycle_state': 'ACTIVE',
'create_time': '2015-10-10 00:02:02',
'parent_id': None,
'parent_type': None},
]
FAKE_FOLDERS_RESPONSE = {
'folders': [
{
'name': 'folders/1111111111',
'display_name': 'Folder1',
'lifecycleState': 'ACTIVE',
'parent': 'organizations/9999',
},
{
'name': 'folders/2222222222',
'display_name': 'Folder2',
'lifecycleState': 'ACTIVE',
},
{
'name': 'folders/3333333333',
'display_name': 'Folder3',
'lifecycleState': 'ACTIVE',
}
]
}
EXPECTED_FAKE_FOLDERS_FROM_API = FAKE_FOLDERS_RESPONSE['folders']
FAKE_FOLDERS_OK_IAM_DB_ROWS = [
{'folder_id': '1111111111',
'display_name': 'Folder1',
'lifecycle_state': 'ACTIVE',
'parent_id': '9999',
'parent_type': 'organizations',
'iam_policy': '{"bindings": [{"role": "roles/viewer", "members": ["user:a@b.c"]}]}'},
{'folder_id': '2222222222',
'display_name': 'Folder2',
'lifecycle_state': 'ACTIVE',
'parent_id': None,
'parent_type': None,
'iam_policy': '{"bindings": [{"role": "roles/viewer", "members": ["user:d@e.f"]}]}'},
]
FAKE_FOLDERS_BAD_IAM_DB_ROWS = [
{'folder_id': '1111111111',
'display_name': 'Folder1',
'lifecycle_state': 'ACTIVE',
'parent_id': '9999',
'parent_type': 'organizations',
'iam_policy': '{"bindings": [{"role": "roles/viewer", "members": ["user:a@b.c"]}]}'},
{'folder_id': '2222222222',
'display_name': 'Folder2',
'lifecycle_state': 'ACTIVE',
'parent_id': None,
'parent_type': None,
'iam_policy': ''},
]
FAKE_FOLDERS_API_RESPONSE1 = {
'folders': [
{
'displayName': 'folder-1',
'name': 'folders/111',
'parent': 'folders/1111111',
'lifecycleState': 'ACTIVE',
'parent': 'organizations/9999'
},
{
'displayName': 'folder-2',
'name': 'folders/222',
'parent': 'folders/2222222',
'lifecycleState': 'DELETE_REQUESTED'
},
{
'displayName': 'folder-3',
'name': 'folders/333',
'parent': 'folders/3333333',
'lifecycleState': 'ACTIVE'
},
]
}
EXPECTED_FAKE_FOLDERS1 = FAKE_FOLDERS_API_RESPONSE1['folders']
FAKE_FOLDERS_LIST_API_RESPONSE1 = {
'folders': [
f for f in FAKE_FOLDERS_API_RESPONSE1['folders']
if f['parent'] == 'organizations/9999'
]
}
EXPECTED_FAKE_FOLDERS_LIST1 = FAKE_FOLDERS_LIST_API_RESPONSE1['folders']
FAKE_ACTIVE_FOLDERS_API_RESPONSE1 = {
'folders': [
f for f in FAKE_FOLDERS_API_RESPONSE1['folders']
if f['lifecycleState'] == 'ACTIVE'
]
}
EXPECTED_FAKE_ACTIVE_FOLDERS1 = FAKE_ACTIVE_FOLDERS_API_RESPONSE1['folders']
| """Fake folders data."""
fake_folders_db_rows = [{'folder_id': '111111111111', 'name': 'folders/111111111111', 'display_name': 'Folder1', 'lifecycle_state': 'ACTIVE', 'create_time': '2015-09-09 00:01:01', 'parent_id': '9999', 'parent_type': 'organization'}, {'folder_id': '222222222222', 'name': 'folders/222222222222', 'display_name': 'Folder2', 'lifecycle_state': 'ACTIVE', 'create_time': '2015-10-10 00:02:02', 'parent_id': None, 'parent_type': None}]
fake_folders_response = {'folders': [{'name': 'folders/1111111111', 'display_name': 'Folder1', 'lifecycleState': 'ACTIVE', 'parent': 'organizations/9999'}, {'name': 'folders/2222222222', 'display_name': 'Folder2', 'lifecycleState': 'ACTIVE'}, {'name': 'folders/3333333333', 'display_name': 'Folder3', 'lifecycleState': 'ACTIVE'}]}
expected_fake_folders_from_api = FAKE_FOLDERS_RESPONSE['folders']
fake_folders_ok_iam_db_rows = [{'folder_id': '1111111111', 'display_name': 'Folder1', 'lifecycle_state': 'ACTIVE', 'parent_id': '9999', 'parent_type': 'organizations', 'iam_policy': '{"bindings": [{"role": "roles/viewer", "members": ["user:a@b.c"]}]}'}, {'folder_id': '2222222222', 'display_name': 'Folder2', 'lifecycle_state': 'ACTIVE', 'parent_id': None, 'parent_type': None, 'iam_policy': '{"bindings": [{"role": "roles/viewer", "members": ["user:d@e.f"]}]}'}]
fake_folders_bad_iam_db_rows = [{'folder_id': '1111111111', 'display_name': 'Folder1', 'lifecycle_state': 'ACTIVE', 'parent_id': '9999', 'parent_type': 'organizations', 'iam_policy': '{"bindings": [{"role": "roles/viewer", "members": ["user:a@b.c"]}]}'}, {'folder_id': '2222222222', 'display_name': 'Folder2', 'lifecycle_state': 'ACTIVE', 'parent_id': None, 'parent_type': None, 'iam_policy': ''}]
fake_folders_api_response1 = {'folders': [{'displayName': 'folder-1', 'name': 'folders/111', 'parent': 'folders/1111111', 'lifecycleState': 'ACTIVE', 'parent': 'organizations/9999'}, {'displayName': 'folder-2', 'name': 'folders/222', 'parent': 'folders/2222222', 'lifecycleState': 'DELETE_REQUESTED'}, {'displayName': 'folder-3', 'name': 'folders/333', 'parent': 'folders/3333333', 'lifecycleState': 'ACTIVE'}]}
expected_fake_folders1 = FAKE_FOLDERS_API_RESPONSE1['folders']
fake_folders_list_api_response1 = {'folders': [f for f in FAKE_FOLDERS_API_RESPONSE1['folders'] if f['parent'] == 'organizations/9999']}
expected_fake_folders_list1 = FAKE_FOLDERS_LIST_API_RESPONSE1['folders']
fake_active_folders_api_response1 = {'folders': [f for f in FAKE_FOLDERS_API_RESPONSE1['folders'] if f['lifecycleState'] == 'ACTIVE']}
expected_fake_active_folders1 = FAKE_ACTIVE_FOLDERS_API_RESPONSE1['folders'] |
class Security:
def __init__(self, name, ticker, country, ir_website, currency):
self.name = name.strip()
self.ticker = ticker.strip()
self.country = country.strip()
self.currency = currency.strip()
self.ir_website = ir_website.strip()
@staticmethod
def summary(name, ticker):
return f"{name} ({ticker})"
@staticmethod
def example_input():
return "Air-Products APD.US US http://investors.airproducts.com/upcoming-events USD"
| class Security:
def __init__(self, name, ticker, country, ir_website, currency):
self.name = name.strip()
self.ticker = ticker.strip()
self.country = country.strip()
self.currency = currency.strip()
self.ir_website = ir_website.strip()
@staticmethod
def summary(name, ticker):
return f'{name} ({ticker})'
@staticmethod
def example_input():
return 'Air-Products APD.US US http://investors.airproducts.com/upcoming-events USD' |
def plot_frames(motion, ax, times=1, fps=0.01):
joints = [j for j in motion.joint_names() if not j.startswith('ignore_')]
x, ys = [], []
for t, frame in motion.frames(fps):
x.append(t)
ys.append(frame.positions)
if t > motion.length() * times:
break
for joint in joints:
ax.plot(x, [y[joint] for y in ys], label=joint)
| def plot_frames(motion, ax, times=1, fps=0.01):
joints = [j for j in motion.joint_names() if not j.startswith('ignore_')]
(x, ys) = ([], [])
for (t, frame) in motion.frames(fps):
x.append(t)
ys.append(frame.positions)
if t > motion.length() * times:
break
for joint in joints:
ax.plot(x, [y[joint] for y in ys], label=joint) |
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless 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.
"""Wait messages for the compute instance groups managed commands."""
_CURRENT_ACTION_TYPES = ['abandoning', 'creating', 'creatingWithoutRetries',
'deleting', 'recreating', 'refreshing', 'restarting',
'verifying']
_PENDING_ACTION_TYPES = ['creating', 'deleting', 'restarting', 'recreating']
def IsGroupStable(igm_ref):
"""Checks if IGM is has no current actions on instances.
Args:
igm_ref: reference to the Instance Group Manager.
Returns:
True if IGM has no current actions, false otherwise.
"""
return not any(getattr(igm_ref.currentActions, action, 0)
for action in _CURRENT_ACTION_TYPES)
def IsGroupStableAlpha(igm_ref):
"""Checks if IGM is has no current or pending actions on instances.
Args:
igm_ref: reference to the Instance Group Manager.
Returns:
True if IGM has no current actions, false otherwise.
"""
no_current_actions = not any(getattr(igm_ref.currentActions, action, 0)
for action in _CURRENT_ACTION_TYPES)
no_pending_actions = not any(getattr(igm_ref.pendingActions, action, 0)
for action in _PENDING_ACTION_TYPES)
return no_current_actions and no_pending_actions
def CreateWaitText(igm_ref):
"""Creates text presented at each wait operation.
Args:
igm_ref: reference to the Instance Group Manager.
Returns:
A message with current operations count for IGM.
"""
text = 'Waiting for group to become stable'
current_actions_text = _CreateActionsText(
', current operations: ',
igm_ref.currentActions,
_CURRENT_ACTION_TYPES)
return text + current_actions_text
def CreateWaitTextAlpha(igm_ref):
"""Creates text presented at each wait operation.
Args:
igm_ref: reference to the Instance Group Manager.
Returns:
A message with current and pending operations count for IGM.
"""
text = 'Waiting for group to become stable'
current_actions_text = _CreateActionsText(
', current operations: ',
igm_ref.currentActions,
_CURRENT_ACTION_TYPES)
pending_actions_text = _CreateActionsText(
', pending operations: ',
igm_ref.pendingActions,
_PENDING_ACTION_TYPES)
return text + current_actions_text + pending_actions_text
def _CreateActionsText(text, igm_field, action_types):
"""Creates text presented at each wait operation for given IGM field.
Args:
text: the text associated with the field.
igm_field: reference to a field in the Instance Group Manager.
action_types: array with field values to be counted.
Returns:
A message with given field and action types count for IGM.
"""
actions = []
for action in action_types:
action_count = getattr(igm_field, action, 0)
if action_count > 0:
actions.append('{0}: {1}'.format(action, action_count))
return text + ', '.join(actions) if actions else ''
| """Wait messages for the compute instance groups managed commands."""
_current_action_types = ['abandoning', 'creating', 'creatingWithoutRetries', 'deleting', 'recreating', 'refreshing', 'restarting', 'verifying']
_pending_action_types = ['creating', 'deleting', 'restarting', 'recreating']
def is_group_stable(igm_ref):
"""Checks if IGM is has no current actions on instances.
Args:
igm_ref: reference to the Instance Group Manager.
Returns:
True if IGM has no current actions, false otherwise.
"""
return not any((getattr(igm_ref.currentActions, action, 0) for action in _CURRENT_ACTION_TYPES))
def is_group_stable_alpha(igm_ref):
"""Checks if IGM is has no current or pending actions on instances.
Args:
igm_ref: reference to the Instance Group Manager.
Returns:
True if IGM has no current actions, false otherwise.
"""
no_current_actions = not any((getattr(igm_ref.currentActions, action, 0) for action in _CURRENT_ACTION_TYPES))
no_pending_actions = not any((getattr(igm_ref.pendingActions, action, 0) for action in _PENDING_ACTION_TYPES))
return no_current_actions and no_pending_actions
def create_wait_text(igm_ref):
"""Creates text presented at each wait operation.
Args:
igm_ref: reference to the Instance Group Manager.
Returns:
A message with current operations count for IGM.
"""
text = 'Waiting for group to become stable'
current_actions_text = __create_actions_text(', current operations: ', igm_ref.currentActions, _CURRENT_ACTION_TYPES)
return text + current_actions_text
def create_wait_text_alpha(igm_ref):
"""Creates text presented at each wait operation.
Args:
igm_ref: reference to the Instance Group Manager.
Returns:
A message with current and pending operations count for IGM.
"""
text = 'Waiting for group to become stable'
current_actions_text = __create_actions_text(', current operations: ', igm_ref.currentActions, _CURRENT_ACTION_TYPES)
pending_actions_text = __create_actions_text(', pending operations: ', igm_ref.pendingActions, _PENDING_ACTION_TYPES)
return text + current_actions_text + pending_actions_text
def __create_actions_text(text, igm_field, action_types):
"""Creates text presented at each wait operation for given IGM field.
Args:
text: the text associated with the field.
igm_field: reference to a field in the Instance Group Manager.
action_types: array with field values to be counted.
Returns:
A message with given field and action types count for IGM.
"""
actions = []
for action in action_types:
action_count = getattr(igm_field, action, 0)
if action_count > 0:
actions.append('{0}: {1}'.format(action, action_count))
return text + ', '.join(actions) if actions else '' |
default_vimrc = "\
set fileencoding=utf-8 fileformat=unix\n\
call plug#begin('~/.vim/plugged')\n\
Plug 'prabirshrestha/async.vim'\n\
Plug 'prabirshrestha/vim-lsp'\n\
Plug 'prabirshrestha/asyncomplete.vim'\n\
Plug 'prabirshrestha/asyncomplete-lsp.vim'\n\
Plug 'mattn/vim-lsp-settings'\n\
Plug 'prabirshrestha/asyncomplete-file.vim'\n\
Plug 'prabirshrestha/asyncomplete-buffer.vim'\n\
Plug 'vim-airline/vim-airline'\n\
Plug 'vim-airline/vim-airline-themes'\n\
Plug 'elzr/vim-json'\n\
Plug 'cohama/lexima.vim'\n\
Plug '{}'\n\
Plug 'cespare/vim-toml'\n\
Plug 'tpope/vim-markdown'\n\
Plug 'kannokanno/previm'\n\
Plug 'tyru/open-browser.vim'\n\
Plug 'ryanoasis/vim-devicons'\n\
Plug 'scrooloose/nerdtree'\n\
Plug 'mattn/emmet-vim'\n\
Plug 'vim/killersheep'\n\
\n\
call plug#end()\n\
\n\
syntax enable\n\
colorscheme {}\n\
set background=dark\n\
\n\
set hlsearch\n\
set cursorline\n\
set cursorcolumn\n\
set number\n\
set foldmethod=marker\n\
set backspace=indent,eol,start\n\
set clipboard^=unnamedplus\n\
set nostartofline\n\
noremap <silent><C-x> :bdelete<CR>\n\
noremap <silent><C-h> :bprevious<CR>\n\
noremap <silent><C-l> :bnext<CR>\n\
set ruler\n\
set noerrorbells\n\
set laststatus={}\n\
set shiftwidth={}\n\
set tabstop={}\n\
set softtabstop={}\n\
set expandtab\n\
set smarttab\n\
set cindent\n\
"
indent_setting_base = "\
augroup {}Indent\n\
autocmd!\n\
autocmd FileType {} set tabstop={} softtabstop={} shitwidth={}\n\
augroup END\n\
"
| default_vimrc = "set fileencoding=utf-8 fileformat=unix\ncall plug#begin('~/.vim/plugged')\nPlug 'prabirshrestha/async.vim'\nPlug 'prabirshrestha/vim-lsp'\nPlug 'prabirshrestha/asyncomplete.vim'\nPlug 'prabirshrestha/asyncomplete-lsp.vim'\nPlug 'mattn/vim-lsp-settings'\nPlug 'prabirshrestha/asyncomplete-file.vim'\nPlug 'prabirshrestha/asyncomplete-buffer.vim'\nPlug 'vim-airline/vim-airline'\nPlug 'vim-airline/vim-airline-themes'\nPlug 'elzr/vim-json'\nPlug 'cohama/lexima.vim'\nPlug '{}'\nPlug 'cespare/vim-toml'\nPlug 'tpope/vim-markdown'\nPlug 'kannokanno/previm'\nPlug 'tyru/open-browser.vim'\nPlug 'ryanoasis/vim-devicons'\nPlug 'scrooloose/nerdtree'\nPlug 'mattn/emmet-vim'\nPlug 'vim/killersheep'\n\ncall plug#end()\n\nsyntax enable\ncolorscheme {}\nset background=dark\n\nset hlsearch\nset cursorline\nset cursorcolumn\nset number\nset foldmethod=marker\nset backspace=indent,eol,start\nset clipboard^=unnamedplus\nset nostartofline\nnoremap <silent><C-x> :bdelete<CR>\nnoremap <silent><C-h> :bprevious<CR>\nnoremap <silent><C-l> :bnext<CR>\nset ruler\nset noerrorbells\nset laststatus={}\nset shiftwidth={}\nset tabstop={}\nset softtabstop={}\nset expandtab\nset smarttab\nset cindent\n"
indent_setting_base = 'augroup {}Indent\n autocmd!\n autocmd FileType {} set tabstop={} softtabstop={} shitwidth={}\naugroup END\n' |
extensions = ["myst_parser"]
exclude_patterns = ["_build"]
copyright = "2020, Executable Book Project"
myst_enable_extensions = ["deflist"]
| extensions = ['myst_parser']
exclude_patterns = ['_build']
copyright = '2020, Executable Book Project'
myst_enable_extensions = ['deflist'] |
# encoding: utf-8
"""
Configuration file. Please prefix application specific config values with
the application name.
"""
# Slack settings
SLACKBACK_CHANNEL = '#feedback'
SLACKBACK_EMOJI = ':goberserk:'
SLACKBACK_USERNAME = 'TownCrier'
# These values are necessary only if the app needs to be a client of the API
FEEDBACK_SLACK_END_POINT = 'https://hooks.slack.com/services/TOKEN/TOKEN'
GOOGLE_RECAPTCHA_ENDPOINT = 'https://www.google.com/recaptcha/api/siteverify'
GOOGLE_RECAPTCHA_PRIVATE_KEY = 'MY_RECAPTCHA_KEY'
# Log settings
SLACKBACK_LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'default': {
'format': '%(levelname)s\t%(process)d '
'[%(asctime)s]:\t%(message)s',
'datefmt': '%m/%d/%Y %H:%M:%S',
}
},
'handlers': {
'file': {
'formatter': 'default',
'level': 'DEBUG',
'class': 'logging.handlers.TimedRotatingFileHandler',
'filename': '/tmp/slackback.log',
},
'console': {
'formatter': 'default',
'level': 'DEBUG',
'class': 'logging.StreamHandler'
}
},
'loggers': {
'': {
'handlers': ['file', 'console'],
'level': 'DEBUG',
'propagate': True,
},
},
}
| """
Configuration file. Please prefix application specific config values with
the application name.
"""
slackback_channel = '#feedback'
slackback_emoji = ':goberserk:'
slackback_username = 'TownCrier'
feedback_slack_end_point = 'https://hooks.slack.com/services/TOKEN/TOKEN'
google_recaptcha_endpoint = 'https://www.google.com/recaptcha/api/siteverify'
google_recaptcha_private_key = 'MY_RECAPTCHA_KEY'
slackback_logging = {'version': 1, 'disable_existing_loggers': False, 'formatters': {'default': {'format': '%(levelname)s\t%(process)d [%(asctime)s]:\t%(message)s', 'datefmt': '%m/%d/%Y %H:%M:%S'}}, 'handlers': {'file': {'formatter': 'default', 'level': 'DEBUG', 'class': 'logging.handlers.TimedRotatingFileHandler', 'filename': '/tmp/slackback.log'}, 'console': {'formatter': 'default', 'level': 'DEBUG', 'class': 'logging.StreamHandler'}}, 'loggers': {'': {'handlers': ['file', 'console'], 'level': 'DEBUG', 'propagate': True}}} |
# Given a list and a num. Write a function to return boolean if that element is not in the list.
def check_num_in_list(alist, num):
for i in alist:
if num in alist and num%2 != 0:
return True
else:
return False
sample = check_num_in_list([2,7,3,1,6,9], 6)
print(sample)
| def check_num_in_list(alist, num):
for i in alist:
if num in alist and num % 2 != 0:
return True
else:
return False
sample = check_num_in_list([2, 7, 3, 1, 6, 9], 6)
print(sample) |
z = 10
y = 0
x = y < z and z > y or y > z and z < y
print(x)
# X = True
| z = 10
y = 0
x = y < z and z > y or (y > z and z < y)
print(x) |
"""
Global constants.
"""
# Instrument message fields
INSTRUMENTS = 'instruments'
INSTRUMENT_ID = 'instrumentID'
EXCHANGE_ID = 'exchangeID'
INSTRUMENT_SYMBOL = 'symbol'
INSTRUMENT_TRADING_HOURS = 'instrument_trading_hours'
UNIT_SIZE = 'unit_size' # future's contract unit size
TICK_SIZE = 'tick_size'
MARGIN_TYPE = 'margin_type'
MARGIN_RATE = 'margin_rate'
OPEN_COMM_TYPE = 'open_comm_type'
OPEN_COMM_RATE = 'open_comm_rate'
CLOSE_COMM_TYPE = 'close_comm_type'
CLOSE_COMM_RATE = 'close_comm_rate'
CLOSE_TODAY_COMM_TYPE = 'close_today_comm_type'
CLOSE_TODAY_COMM_RATE = 'close_today_comm_rate'
# Tick message fields
ASK = 'ask'
BID = 'bid'
ASK_VOLUME = 'askVolume'
BID_VOLUME = 'bidVolume'
HIGH_LIMIT = 'highLimit'
LOW_LIMIT = 'lowLimit'
# Order and trade message fields
PRICE = 'price'
VOLUME = 'volume'
DIRECTION_LONG = 'long'
DIRECTION_SHORT = 'short'
DIRECTION = 'direction'
BUY = '0'
SELL = '1'
ORDER_ID = 'orderID'
TRADE_ID = 'tradeID'
QTY = 'qty'
TRADED_QTY = 'traded_qty'
TAG = 'tag'
ORDER_ACTION = 'order_action'
ORDER_STATUS = 'order_status'
ORDER_CREATE_DATE = 'order_create_date'
ORDER_EXPIRATION_DATE = 'order_expiration_date'
ORDER_ACCEPT_FLAG = 'order_accept_flag'
BUY_ORDERS = 'buy_orders'
SELL_ORDERS = 'sell_orders'
ORDER_IDS = 'order_ids'
# Order cancel type
CANCEL_TYPE = 'cancel_type'
CANCEL_ALL = 0
CANCEL_OPEN_ORDERS = 1
CANCEL_CLOSE_ORDERS = 2
CANCEL_STOPLOSS_ORDERS = 3
CANCEL_ORDERS = 4
# Order status
ORDER_ACCEPTED = 'order_status_accepted'
ORDER_OPEN = 'order_status_open'
ORDER_CLOSED = 'order_status_closed'
ORDER_CLOSED_ALIAS = 'order_status_executed'
ORDER_REJECTED = 'order_status_rejected'
ORDER_CANCELLED = 'order_status_cancelled'
ORDER_CANCEL_SUBMITTED = 'order_status_cancel_submitted'
ORDER_PARTIAL_CLOSED = 'order_status_partial_closed'
ORDER_NO_CANCEL = 'order_status_no_cancel'
ORDER_REPEAT_CANCEL = 'order_status_repeat_cancel'
# Broker data fields
PORTFOLIO_ID = 'portfolioID'
ACCOUNT_ID = 'accountID'
# Strategy debug log message strings
STRATEGY_CONFIG = "The strategy has been configured."
STRATEGY_OPEN = "The strategy opens a position. Params: [%s]"
STRATEGY_CLOSE = "The strategy closes a position. Params: [%s]"
STRATEGY_START = "The strategy is starting..."
STRATEGY_STOP = "The strategy is stopping..."
STRATEGY_SUSPEND = "The strategy is suspending..."
STRATEGY_RESUME = "The strategy is resuming..."
STRATEGY_STOPPED = "The strategy has stopped."
STRATEGY_SETTING_PARAMS = "The strategy parameters: [%s]"
ON_TICK = "onTick triggered with the event: [%s]"
ON_UPDATE_ORDER_STATUS = "Updating order status. Params [%s]"
ON_PROFIT_CHANGE = "EVENT_PROFITCHANGED triggered. Params: [%s]"
ON_BUY = "EVENT_BUY triggered. Params: [%s]"
ON_SELL = "EVENT_SELL triggered. Params: [%s]"
# Misc
COMPARED_FLOAT = 0.0000001
INVALID_VALUE = -1.0
TAG_DEFAULT_VALUE = ''
APP_ID = 'app_id'
| """
Global constants.
"""
instruments = 'instruments'
instrument_id = 'instrumentID'
exchange_id = 'exchangeID'
instrument_symbol = 'symbol'
instrument_trading_hours = 'instrument_trading_hours'
unit_size = 'unit_size'
tick_size = 'tick_size'
margin_type = 'margin_type'
margin_rate = 'margin_rate'
open_comm_type = 'open_comm_type'
open_comm_rate = 'open_comm_rate'
close_comm_type = 'close_comm_type'
close_comm_rate = 'close_comm_rate'
close_today_comm_type = 'close_today_comm_type'
close_today_comm_rate = 'close_today_comm_rate'
ask = 'ask'
bid = 'bid'
ask_volume = 'askVolume'
bid_volume = 'bidVolume'
high_limit = 'highLimit'
low_limit = 'lowLimit'
price = 'price'
volume = 'volume'
direction_long = 'long'
direction_short = 'short'
direction = 'direction'
buy = '0'
sell = '1'
order_id = 'orderID'
trade_id = 'tradeID'
qty = 'qty'
traded_qty = 'traded_qty'
tag = 'tag'
order_action = 'order_action'
order_status = 'order_status'
order_create_date = 'order_create_date'
order_expiration_date = 'order_expiration_date'
order_accept_flag = 'order_accept_flag'
buy_orders = 'buy_orders'
sell_orders = 'sell_orders'
order_ids = 'order_ids'
cancel_type = 'cancel_type'
cancel_all = 0
cancel_open_orders = 1
cancel_close_orders = 2
cancel_stoploss_orders = 3
cancel_orders = 4
order_accepted = 'order_status_accepted'
order_open = 'order_status_open'
order_closed = 'order_status_closed'
order_closed_alias = 'order_status_executed'
order_rejected = 'order_status_rejected'
order_cancelled = 'order_status_cancelled'
order_cancel_submitted = 'order_status_cancel_submitted'
order_partial_closed = 'order_status_partial_closed'
order_no_cancel = 'order_status_no_cancel'
order_repeat_cancel = 'order_status_repeat_cancel'
portfolio_id = 'portfolioID'
account_id = 'accountID'
strategy_config = 'The strategy has been configured.'
strategy_open = 'The strategy opens a position. Params: [%s]'
strategy_close = 'The strategy closes a position. Params: [%s]'
strategy_start = 'The strategy is starting...'
strategy_stop = 'The strategy is stopping...'
strategy_suspend = 'The strategy is suspending...'
strategy_resume = 'The strategy is resuming...'
strategy_stopped = 'The strategy has stopped.'
strategy_setting_params = 'The strategy parameters: [%s]'
on_tick = 'onTick triggered with the event: [%s]'
on_update_order_status = 'Updating order status. Params [%s]'
on_profit_change = 'EVENT_PROFITCHANGED triggered. Params: [%s]'
on_buy = 'EVENT_BUY triggered. Params: [%s]'
on_sell = 'EVENT_SELL triggered. Params: [%s]'
compared_float = 1e-07
invalid_value = -1.0
tag_default_value = ''
app_id = 'app_id' |
# Merge Sort: D&C Algo, Breaks data into individual pieces and merges them, uses recursion to operate on datasets. Key is to understand how to merge 2 sorted arrays.
items = [6, 20, 8, 9, 19, 56, 23, 87, 41, 49, 53]
def mergesort(dataset):
if len(dataset) > 1:
mid = len(dataset) // 2
leftarr = dataset[:mid]
rightarr = dataset[mid:]
# TODO: Recursively break down the arrays
mergesort(leftarr)
mergesort(rightarr)
# TODO: Perform merging
i = 0 # index into the left array
j = 0 # index into the right array
k = 0 # index into the merger array
while i < len(leftarr) and j < len(rightarr):
if(leftarr[i] <= rightarr[j]):
dataset[k] = leftarr[i]
i += 1
else:
dataset[k] = rightarr[j]
j += 1
k += 1
while i < len(leftarr):
dataset[k] = leftarr[i]
i += 1
k += 1
while j < len(rightarr):
dataset[k] = rightarr[j]
j += 1
k += 1
print(items)
mergesort(items)
print(items)
| items = [6, 20, 8, 9, 19, 56, 23, 87, 41, 49, 53]
def mergesort(dataset):
if len(dataset) > 1:
mid = len(dataset) // 2
leftarr = dataset[:mid]
rightarr = dataset[mid:]
mergesort(leftarr)
mergesort(rightarr)
i = 0
j = 0
k = 0
while i < len(leftarr) and j < len(rightarr):
if leftarr[i] <= rightarr[j]:
dataset[k] = leftarr[i]
i += 1
else:
dataset[k] = rightarr[j]
j += 1
k += 1
while i < len(leftarr):
dataset[k] = leftarr[i]
i += 1
k += 1
while j < len(rightarr):
dataset[k] = rightarr[j]
j += 1
k += 1
print(items)
mergesort(items)
print(items) |
def nameCreator(playerName):
firstLetter = playerName.split(" ")[1][0]
try:
lastName = playerName.split(" ")[1][0:5]
except:
lastNameSize = len(playerName.split(" ")[1])
lastName = playerName.split(" ")[1][len(lastNameSize)]
firstName = playerName[0:2]
return lastName + firstName + '0', firstLetter
| def name_creator(playerName):
first_letter = playerName.split(' ')[1][0]
try:
last_name = playerName.split(' ')[1][0:5]
except:
last_name_size = len(playerName.split(' ')[1])
last_name = playerName.split(' ')[1][len(lastNameSize)]
first_name = playerName[0:2]
return (lastName + firstName + '0', firstLetter) |
# Copyright: 2005-2008 Brian Harring <ferringb@gmail.com>
# License: GPL2/BSD
"""
exceptions thrown by repository classes.
Need to extend the usage a bit further still.
"""
__all__ = ("TreeCorruption", "InitializationError")
class TreeCorruption(Exception):
def __init__(self, err):
Exception.__init__(self, "unexpected tree corruption: %s" % (err,))
self.err = err
class InitializationError(TreeCorruption):
def __str__(self):
return "initialization failed: %s" % str(self.err)
| """
exceptions thrown by repository classes.
Need to extend the usage a bit further still.
"""
__all__ = ('TreeCorruption', 'InitializationError')
class Treecorruption(Exception):
def __init__(self, err):
Exception.__init__(self, 'unexpected tree corruption: %s' % (err,))
self.err = err
class Initializationerror(TreeCorruption):
def __str__(self):
return 'initialization failed: %s' % str(self.err) |
class Solution(object):
def multiply(self, A, B):
"""
:type A: List[List[int]]
:type B: List[List[int]]
:rtype: List[List[int]]
"""
ret = [[0 for j in range(len(B[0]))] for i in range(len(A))]
for i, row in enumerate(A):
for k, a in enumerate(row):
if a:
for j, b in enumerate(B[k]):
if b:
ret[i][j] += a * b
return ret | class Solution(object):
def multiply(self, A, B):
"""
:type A: List[List[int]]
:type B: List[List[int]]
:rtype: List[List[int]]
"""
ret = [[0 for j in range(len(B[0]))] for i in range(len(A))]
for (i, row) in enumerate(A):
for (k, a) in enumerate(row):
if a:
for (j, b) in enumerate(B[k]):
if b:
ret[i][j] += a * b
return ret |
# Author : Aniruddha Krishna Jha
# Date : 22/10/2021
'''**********************************************************************************
Given an array nums of positive integers, return the longest possible length of an array prefix of nums,
such that it is possible to remove exactly one element from this prefix so that every number that has appeared in it will have the same number of occurrences.
If after removing one element there are no remaining elements,
it's still considered that every appeared number has the same number of ocurrences (0).
Input: nums = [2,2,1,1,5,3,3,5]
Output: 7
Explanation: For the subarray [2,2,1,1,5,3,3] of length 7, if we remove nums[4]=5, we will get [2,2,1,1,3,3], so that each number will appear exactly twice.
**********************************************************************************'''
class Solution:
def maxEqualFreq(self, nums: List[int]) -> int:
cnt,freq,maxF,res = collections.defaultdict(int), collections.defaultdict(int),0,0
for i,num in enumerate(nums):
cnt[num] += 1
freq[cnt[num]-1] -= 1
freq[cnt[num]] += 1
maxF = max(maxF,cnt[num])
if maxF*freq[maxF] == i or (maxF-1)*(freq[maxF-1]+1) == i or maxF == 1:
res = i + 1
return res
| """**********************************************************************************
Given an array nums of positive integers, return the longest possible length of an array prefix of nums,
such that it is possible to remove exactly one element from this prefix so that every number that has appeared in it will have the same number of occurrences.
If after removing one element there are no remaining elements,
it's still considered that every appeared number has the same number of ocurrences (0).
Input: nums = [2,2,1,1,5,3,3,5]
Output: 7
Explanation: For the subarray [2,2,1,1,5,3,3] of length 7, if we remove nums[4]=5, we will get [2,2,1,1,3,3], so that each number will appear exactly twice.
**********************************************************************************"""
class Solution:
def max_equal_freq(self, nums: List[int]) -> int:
(cnt, freq, max_f, res) = (collections.defaultdict(int), collections.defaultdict(int), 0, 0)
for (i, num) in enumerate(nums):
cnt[num] += 1
freq[cnt[num] - 1] -= 1
freq[cnt[num]] += 1
max_f = max(maxF, cnt[num])
if maxF * freq[maxF] == i or (maxF - 1) * (freq[maxF - 1] + 1) == i or maxF == 1:
res = i + 1
return res |
#!/usr/bin/env python3
"""
Write a function called sed that takes as arguments a pattern string, a replacement
string, and two filenames; it should read the first file and write the contents into the second file
(creating it if necessary). If the pattern string appears anywhere in the file, it should be replaced
with the replacement string.
If an error occurs while opening, reading, writing or closing files, your program should catch the
exception, print an error message, and exit.
"""
def sed(patern, replacement, s_file, d_file):
try:
source_f = open(s_file, mode='r')
dest_f = open(d_file, mode='a')
content = source_f.read()
dest_f.write(content.replace(patern, replacement))
except:
print("Something went wrong")
if __name__ == "__main__":
sed("gosho", "ilian", "file_s", "file_d")
| """
Write a function called sed that takes as arguments a pattern string, a replacement
string, and two filenames; it should read the first file and write the contents into the second file
(creating it if necessary). If the pattern string appears anywhere in the file, it should be replaced
with the replacement string.
If an error occurs while opening, reading, writing or closing files, your program should catch the
exception, print an error message, and exit.
"""
def sed(patern, replacement, s_file, d_file):
try:
source_f = open(s_file, mode='r')
dest_f = open(d_file, mode='a')
content = source_f.read()
dest_f.write(content.replace(patern, replacement))
except:
print('Something went wrong')
if __name__ == '__main__':
sed('gosho', 'ilian', 'file_s', 'file_d') |
class BTNode:
'''Binary Tree Node class - do not modify'''
def __init__(self, value, left, right):
'''Stores a reference to the value, left child node, and right child node. If no left or right child, attributes should be None.'''
self.value = value
self.left = left
self.right = right
class BST:
def __init__(self):
# reference to root node - do not modify
self.root = None
def insert(self, value):
'''Takes a numeric value as argument.
Inserts value into tree, maintaining correct ordering.
Returns nothing.'''
if self.root is None:
self.root = BTNode(value, None, None)
return
self.insert2(self.root, value)
def insert2(self, node, value):
if value < node.value:
if node.left is None:
node.left = BTNode(value, None, None)
return
self.insert2(node.left, value)
elif value > node.value:
if node.right is None:
node.right = BTNode(value, None, None)
return
self.insert2(node.right, value)
else:
return
def search(self, value):
'''Takes a numeric value as argument.
Returns True if its in the tree, false otherwise.'''
return self.search2(self.root, value)
def search2(self, node, value):
if node is None:
return False
if value == node.value:
return True
elif value < node.value:
return self.search2(node.left, value)
else:
return self.search2(node.right, value)
def height(self):
'''Returns the height of the tree.
A tree with 0 or 1 nodes has a height of 0.'''
return self.height2(self.root) - 1
def height2(self, node):
if node is None:
return 0
return max(self.height2(node.left), self.height2(node.right)) + 1
def preorder(self):
'''Returns a list of the values in the tree,
in pre-order order.'''
return self.preorder2(self.root, [])
def preorder2(self, node, lst):
if node is not None:
lst.append(node.value)
self.preorder2(node.left, lst)
self.preorder2(node.right, lst)
return lst
#bst = BST()
#for value in [4, 2, 5, 3, 1, 6, 7]:
# bst.insert(value)
## BST now looks like this:
## 4
## / \
## 2 5
## / \ \
## 1 3 6
## \
## 7
#print(bst.search(5)) # True
#print(bst.search(8)) # False
#print(bst.preorder()) # [4, 2, 1, 3, 5, 6, 7]
#print(bst.height()) # 3
| class Btnode:
"""Binary Tree Node class - do not modify"""
def __init__(self, value, left, right):
"""Stores a reference to the value, left child node, and right child node. If no left or right child, attributes should be None."""
self.value = value
self.left = left
self.right = right
class Bst:
def __init__(self):
self.root = None
def insert(self, value):
"""Takes a numeric value as argument.
Inserts value into tree, maintaining correct ordering.
Returns nothing."""
if self.root is None:
self.root = bt_node(value, None, None)
return
self.insert2(self.root, value)
def insert2(self, node, value):
if value < node.value:
if node.left is None:
node.left = bt_node(value, None, None)
return
self.insert2(node.left, value)
elif value > node.value:
if node.right is None:
node.right = bt_node(value, None, None)
return
self.insert2(node.right, value)
else:
return
def search(self, value):
"""Takes a numeric value as argument.
Returns True if its in the tree, false otherwise."""
return self.search2(self.root, value)
def search2(self, node, value):
if node is None:
return False
if value == node.value:
return True
elif value < node.value:
return self.search2(node.left, value)
else:
return self.search2(node.right, value)
def height(self):
"""Returns the height of the tree.
A tree with 0 or 1 nodes has a height of 0."""
return self.height2(self.root) - 1
def height2(self, node):
if node is None:
return 0
return max(self.height2(node.left), self.height2(node.right)) + 1
def preorder(self):
"""Returns a list of the values in the tree,
in pre-order order."""
return self.preorder2(self.root, [])
def preorder2(self, node, lst):
if node is not None:
lst.append(node.value)
self.preorder2(node.left, lst)
self.preorder2(node.right, lst)
return lst |
checksum = 0
with open("Day 2 - input", "r") as file:
for line in file:
row = [int(i) for i in line.split()]
result = max(row) - min(row)
checksum += result
print(f"The checksum is {checksum}")
| checksum = 0
with open('Day 2 - input', 'r') as file:
for line in file:
row = [int(i) for i in line.split()]
result = max(row) - min(row)
checksum += result
print(f'The checksum is {checksum}') |
def bytes_to(bytes_value, to_unit, bytes_size=1024):
units = {'k': 1, 'm': 2, 'g': 3, 't': 4, 'p': 5, 'e': 6}
return round(float(bytes_value) / (bytes_size ** units[to_unit]), 2)
def convert_to_human(value):
if value < 1024:
return str(value) + 'b'
if value < 1048576:
return str(bytes_to(value, 'k')) + 'k'
if value < 1073741824:
return str(bytes_to(value, 'm')) + 'm'
return str(bytes_to(value, 'g')) + 'g'
def convert_to_human_with_limits(value, limit):
if value < limit:
return convert_to_human(value)
return "[bold magenta]" + convert_to_human(value) + "[/]"
| def bytes_to(bytes_value, to_unit, bytes_size=1024):
units = {'k': 1, 'm': 2, 'g': 3, 't': 4, 'p': 5, 'e': 6}
return round(float(bytes_value) / bytes_size ** units[to_unit], 2)
def convert_to_human(value):
if value < 1024:
return str(value) + 'b'
if value < 1048576:
return str(bytes_to(value, 'k')) + 'k'
if value < 1073741824:
return str(bytes_to(value, 'm')) + 'm'
return str(bytes_to(value, 'g')) + 'g'
def convert_to_human_with_limits(value, limit):
if value < limit:
return convert_to_human(value)
return '[bold magenta]' + convert_to_human(value) + '[/]' |
TLDS = [
"ABB",
"ABBOTT",
"ABOGADO",
"AC",
"ACADEMY",
"ACCENTURE",
"ACCOUNTANT",
"ACCOUNTANTS",
"ACTIVE",
"ACTOR",
"AD",
"ADS",
"ADULT",
"AE",
"AEG",
"AERO",
"AF",
"AFL",
"AG",
"AGENCY",
"AI",
"AIG",
"AIRFORCE",
"AL",
"ALLFINANZ",
"ALSACE",
"AM",
"AMSTERDAM",
"AN",
"ANDROID",
"AO",
"APARTMENTS",
"AQ",
"AQUARELLE",
"AR",
"ARCHI",
"ARMY",
"ARPA",
"AS",
"ASIA",
"ASSOCIATES",
"AT",
"ATTORNEY",
"AU",
"AUCTION",
"AUDIO",
"AUTO",
"AUTOS",
"AW",
"AX",
"AXA",
"AZ",
"AZURE",
"BA",
"BAND",
"BANK",
"BAR",
"BARCLAYCARD",
"BARCLAYS",
"BARGAINS",
"BAUHAUS",
"BAYERN",
"BB",
"BBC",
"BBVA",
"BD",
"BE",
"BEER",
"BERLIN",
"BEST",
"BF",
"BG",
"BH",
"BHARTI",
"BI",
"BIBLE",
"BID",
"BIKE",
"BING",
"BINGO",
"BIO",
"BIZ",
"BJ",
"BLACK",
"BLACKFRIDAY",
"BLOOMBERG",
"BLUE",
"BM",
"BMW",
"BN",
"BNL",
"BNPPARIBAS",
"BO",
"BOATS",
"BOND",
"BOO",
"BOUTIQUE",
"BR",
"BRADESCO",
"BRIDGESTONE",
"BROKER",
"BROTHER",
"BRUSSELS",
"BS",
"BT",
"BUDAPEST",
"BUILD",
"BUILDERS",
"BUSINESS",
"BUZZ",
"BV",
"BW",
"BY",
"BZ",
"BZH",
"CA",
"CAB",
"CAFE",
"CAL",
"CAMERA",
"CAMP",
"CANCERRESEARCH",
"CANON",
"CAPETOWN",
"CAPITAL",
"CARAVAN",
"CARDS",
"CARE",
"CAREER",
"CAREERS",
"CARS",
"CARTIER",
"CASA",
"CASH",
"CASINO",
"CAT",
"CATERING",
"CBA",
"CBN",
"CC",
"CD",
"CENTER",
"CEO",
"CERN",
"CF",
"CFA",
"CFD",
"CG",
"CH",
"CHANNEL",
"CHAT",
"CHEAP",
"CHLOE",
"CHRISTMAS",
"CHROME",
"CHURCH",
"CI",
"CISCO",
"CITIC",
"CITY",
"CK",
"CL",
"CLAIMS",
"CLEANING",
"CLICK",
"CLINIC",
"CLOTHING",
"CLOUD",
"CLUB",
"CM",
"CN",
"CO",
"COACH",
"CODES",
"COFFEE",
"COLLEGE",
"COLOGNE",
"COM",
"COMMBANK",
"COMMUNITY",
"COMPANY",
"COMPUTER",
"CONDOS",
"CONSTRUCTION",
"CONSULTING",
"CONTRACTORS",
"COOKING",
"COOL",
"COOP",
"CORSICA",
"COUNTRY",
"COUPONS",
"COURSES",
"CR",
"CREDIT",
"CREDITCARD",
"CRICKET",
"CROWN",
"CRS",
"CRUISES",
"CU",
"CUISINELLA",
"CV",
"CW",
"CX",
"CY",
"CYMRU",
"CYOU",
"CZ",
"DABUR",
"DAD",
"DANCE",
"DATE",
"DATING",
"DATSUN",
"DAY",
"DCLK",
"DE",
"DEALS",
"DEGREE",
"DELIVERY",
"DEMOCRAT",
"DENTAL",
"DENTIST",
"DESI",
"DESIGN",
"DEV",
"DIAMONDS",
"DIET",
"DIGITAL",
"DIRECT",
"DIRECTORY",
"DISCOUNT",
"DJ",
"DK",
"DM",
"DNP",
"DO",
"DOCS",
"DOG",
"DOHA",
"DOMAINS",
"DOOSAN",
"DOWNLOAD",
"DRIVE",
"DURBAN",
"DVAG",
"DZ",
"EARTH",
"EAT",
"EC",
"EDU",
"EDUCATION",
"EE",
"EG",
"EMAIL",
"EMERCK",
"ENERGY",
"ENGINEER",
"ENGINEERING",
"ENTERPRISES",
"EPSON",
"EQUIPMENT",
"ER",
"ERNI",
"ES",
"ESQ",
"ESTATE",
"ET",
"EU",
"EUROVISION",
"EUS",
"EVENTS",
"EVERBANK",
"EXCHANGE",
"EXPERT",
"EXPOSED",
"EXPRESS",
"FAIL",
"FAITH",
"FAN",
"FANS",
"FARM",
"FASHION",
"FEEDBACK",
"FI",
"FILM",
"FINANCE",
"FINANCIAL",
"FIRMDALE",
"FISH",
"FISHING",
"FIT",
"FITNESS",
"FJ",
"FK",
"FLIGHTS",
"FLORIST",
"FLOWERS",
"FLSMIDTH",
"FLY",
"FM",
"FO",
"FOO",
"FOOTBALL",
"FOREX",
"FORSALE",
"FORUM",
"FOUNDATION",
"FR",
"FRL",
"FROGANS",
"FUND",
"FURNITURE",
"FUTBOL",
"FYI",
"GA",
"GAL",
"GALLERY",
"GARDEN",
"GB",
"GBIZ",
"GD",
"GDN",
"GE",
"GENT",
"GENTING",
"GF",
"GG",
"GGEE",
"GH",
"GI",
"GIFT",
"GIFTS",
"GIVES",
"GL",
"GLASS",
"GLE",
"GLOBAL",
"GLOBO",
"GM",
"GMAIL",
"GMO",
"GMX",
"GN",
"GOLD",
"GOLDPOINT",
"GOLF",
"GOO",
"GOOG",
"GOOGLE",
"GOP",
"GOV",
"GP",
"GQ",
"GR",
"GRAPHICS",
"GRATIS",
"GREEN",
"GRIPE",
"GS",
"GT",
"GU",
"GUGE",
"GUIDE",
"GUITARS",
"GURU",
"GW",
"GY",
"HAMBURG",
"HANGOUT",
"HAUS",
"HEALTHCARE",
"HELP",
"HERE",
"HERMES",
"HIPHOP",
"HITACHI",
"HIV",
"HK",
"HM",
"HN",
"HOCKEY",
"HOLDINGS",
"HOLIDAY",
"HOMEDEPOT",
"HOMES",
"HONDA",
"HORSE",
"HOST",
"HOSTING",
"HOTELES",
"HOTMAIL",
"HOUSE",
"HOW",
"HR",
"HT",
"HU",
"IBM",
"ICBC",
"ICU",
"ID",
"IE",
"IFM",
"IL",
"IM",
"IMMO",
"IMMOBILIEN",
"IN",
"INDUSTRIES",
"INFINITI",
"INFO",
"ING",
"INK",
"INSTITUTE",
"INSURE",
"INT",
"INTERNATIONAL",
"INVESTMENTS",
"IO",
"IQ",
"IR",
"IRISH",
"IS",
"IT",
"IWC",
"JAVA",
"JCB",
"JE",
"JETZT",
"JEWELRY",
"JLC",
"JLL",
"JM",
"JO",
"JOBS",
"JOBURG",
"JP",
"JUEGOS",
"KAUFEN",
"KDDI",
"KE",
"KG",
"KH",
"KI",
"KIM",
"KITCHEN",
"KIWI",
"KM",
"KN",
"KOELN",
"KOMATSU",
"KP",
"KR",
"KRD",
"KRED",
"KW",
"KY",
"KYOTO",
"KZ",
"LA",
"LACAIXA",
"LAND",
"LASALLE",
"LAT",
"LATROBE",
"LAW",
"LAWYER",
"LB",
"LC",
"LDS",
"LEASE",
"LECLERC",
"LEGAL",
"LGBT",
"LI",
"LIAISON",
"LIDL",
"LIFE",
"LIGHTING",
"LIMITED",
"LIMO",
"LINK",
"LK",
"LOAN",
"LOANS",
"LOL",
"LONDON",
"LOTTE",
"LOTTO",
"LOVE",
"LR",
"LS",
"LT",
"LTDA",
"LU",
"LUPIN",
"LUXE",
"LUXURY",
"LV",
"LY",
"MA",
"MADRID",
"MAIF",
"MAISON",
"MANAGEMENT",
"MANGO",
"MARKET",
"MARKETING",
"MARKETS",
"MARRIOTT",
"MBA",
"MC",
"MD",
"ME",
"MEDIA",
"MEET",
"MELBOURNE",
"MEME",
"MEMORIAL",
"MEN",
"MENU",
"MG",
"MH",
"MIAMI",
"MICROSOFT",
"MIL",
"MINI",
"MK",
"ML",
"MM",
"MMA",
"MN",
"MO",
"MOBI",
"MODA",
"MOE",
"MONASH",
"MONEY",
"MONTBLANC",
"MORMON",
"MORTGAGE",
"MOSCOW",
"MOTORCYCLES",
"MOV",
"MOVIE",
"MOVISTAR",
"MP",
"MQ",
"MR",
"MS",
"MT",
"MTN",
"MTPC",
"MU",
"MUSEUM",
"MV",
"MW",
"MX",
"MY",
"MZ",
"NA",
"NADEX",
"NAGOYA",
"NAME",
"NAVY",
"NC",
"NE",
"NEC",
"NET",
"NETBANK",
"NETWORK",
"NEUSTAR",
"NEW",
"NEWS",
"NEXUS",
"NF",
"NG",
"NGO",
"NHK",
"NI",
"NICO",
"NINJA",
"NISSAN",
"NL",
"NO",
"NP",
"NR",
"NRA",
"NRW",
"NTT",
"NU",
"NYC",
"NZ",
"OFFICE",
"OKINAWA",
"OM",
"OMEGA",
"ONE",
"ONG",
"ONL",
"ONLINE",
"OOO",
"ORACLE",
"ORG",
"ORGANIC",
"OSAKA",
"OTSUKA",
"OVH",
"PA",
"PAGE",
"PANERAI",
"PARIS",
"PARTNERS",
"PARTS",
"PARTY",
"PE",
"PF",
"PG",
"PH",
"PHARMACY",
"PHILIPS",
"PHOTO",
"PHOTOGRAPHY",
"PHOTOS",
"PHYSIO",
"PIAGET",
"PICS",
"PICTET",
"PICTURES",
"PINK",
"PIZZA",
"PK",
"PL",
"PLACE",
"PLAY",
"PLUMBING",
"PLUS",
"PM",
"PN",
"POHL",
"POKER",
"PORN",
"POST",
"PR",
"PRAXI",
"PRESS",
"PRO",
"PROD",
"PRODUCTIONS",
"PROF",
"PROPERTIES",
"PROPERTY",
"PS",
"PT",
"PUB",
"PW",
"PY",
"QA",
"QPON",
"QUEBEC",
"RACING",
"RE",
"REALTOR",
"REALTY",
"RECIPES",
"RED",
"REDSTONE",
"REHAB",
"REISE",
"REISEN",
"REIT",
"REN",
"RENT",
"RENTALS",
"REPAIR",
"REPORT",
"REPUBLICAN",
"REST",
"RESTAURANT",
"REVIEW",
"REVIEWS",
"RICH",
"RICOH",
"RIO",
"RIP",
"RO",
"ROCKS",
"RODEO",
"RS",
"RSVP",
"RU",
"RUHR",
"RUN",
"RW",
"RYUKYU",
"SA",
"SAARLAND",
"SALE",
"SAMSUNG",
"SANDVIK",
"SANDVIKCOROMANT",
"SAP",
"SARL",
"SAXO",
"SB",
"SC",
"SCA",
"SCB",
"SCHMIDT",
"SCHOLARSHIPS",
"SCHOOL",
"SCHULE",
"SCHWARZ",
"SCIENCE",
"SCOR",
"SCOT",
"SD",
"SE",
"SEAT",
"SENER",
"SERVICES",
"SEW",
"SEX",
"SEXY",
"SG",
"SH",
"SHIKSHA",
"SHOES",
"SHOW",
"SHRIRAM",
"SI",
"SINGLES",
"SITE",
"SJ",
"SK",
"SKI",
"SKY",
"SKYPE",
"SL",
"SM",
"SN",
"SNCF",
"SO",
"SOCCER",
"SOCIAL",
"SOFTWARE",
"SOHU",
"SOLAR",
"SOLUTIONS",
"SONY",
"SOY",
"SPACE",
"SPIEGEL",
"SPREADBETTING",
"SR",
"ST",
"STARHUB",
"STATOIL",
"STUDY",
"STYLE",
"SU",
"SUCKS",
"SUPPLIES",
"SUPPLY",
"SUPPORT",
"SURF",
"SURGERY",
"SUZUKI",
"SV",
"SWATCH",
"SWISS",
"SX",
"SY",
"SYDNEY",
"SYSTEMS",
"SZ",
"TAIPEI",
"TATAR",
"TATTOO",
"TAX",
"TAXI",
"TC",
"TD",
"TEAM",
"TECH",
"TECHNOLOGY",
"TEL",
"TELEFONICA",
"TEMASEK",
"TENNIS",
"TF",
"TG",
"TH",
"THD",
"THEATER",
"TICKETS",
"TIENDA",
"TIPS",
"TIRES",
"TIROL",
"TJ",
"TK",
"TL",
"TM",
"TN",
"TO",
"TODAY",
"TOKYO",
"TOOLS",
"TOP",
"TORAY",
"TOSHIBA",
"TOURS",
"TOWN",
"TOYS",
"TR",
"TRADE",
"TRADING",
"TRAINING",
"TRAVEL",
"TRUST",
"TT",
"TUI",
"TV",
"TW",
"TZ",
"UA",
"UG",
"UK",
"UNIVERSITY",
"UNO",
"UOL",
"US",
"UY",
"UZ",
"VA",
"VACATIONS",
"VC",
"VE",
"VEGAS",
"VENTURES",
"VERSICHERUNG",
"VET",
"VG",
"VI",
"VIAJES",
"VIDEO",
"VILLAS",
"VISION",
"VISTA",
"VISTAPRINT",
"VLAANDEREN",
"VN",
"VODKA",
"VOTE",
"VOTING",
"VOTO",
"VOYAGE",
"VU",
"WALES",
"WALTER",
"WANG",
"WATCH",
"WEBCAM",
"WEBSITE",
"WED",
"WEDDING",
"WEIR",
"WF",
"WHOSWHO",
"WIEN",
"WIKI",
"WILLIAMHILL",
"WIN",
"WINDOWS",
"WME",
"WORK",
"WORKS",
"WORLD",
"WS",
"WTC",
"WTF",
"XBOX",
"XEROX",
"XIN",
"XN--1QQW23A",
"XN--30RR7Y",
"XN--3BST00M",
"XN--3DS443G",
"XN--3E0B707E",
"XN--45BRJ9C",
"XN--45Q11C",
"XN--4GBRIM",
"XN--55QW42G",
"XN--55QX5D",
"XN--6FRZ82G",
"XN--6QQ986B3XL",
"XN--80ADXHKS",
"XN--80AO21A",
"XN--80ASEHDB",
"XN--80ASWG",
"XN--90A3AC",
"XN--90AIS",
"XN--9ET52U",
"XN--B4W605FERD",
"XN--C1AVG",
"XN--CG4BKI",
"XN--CLCHC0EA0B2G2A9GCD",
"XN--CZR694B",
"XN--CZRS0T",
"XN--CZRU2D",
"XN--D1ACJ3B",
"XN--D1ALF",
"XN--ESTV75G",
"XN--FIQ228C5HS",
"XN--FIQ64B",
"XN--FIQS8S",
"XN--FIQZ9S",
"XN--FJQ720A",
"XN--FLW351E",
"XN--FPCRJ9C3D",
"XN--FZC2C9E2C",
"XN--GECRJ9C",
"XN--H2BRJ9C",
"XN--HXT814E",
"XN--I1B6B1A6A2E",
"XN--IMR513N",
"XN--IO0A7I",
"XN--J1AMH",
"XN--J6W193G",
"XN--KCRX77D1X4A",
"XN--KPRW13D",
"XN--KPRY57D",
"XN--KPUT3I",
"XN--L1ACC",
"XN--LGBBAT1AD8J",
"XN--MGB9AWBF",
"XN--MGBA3A4F16A",
"XN--MGBAAM7A8H",
"XN--MGBAB2BD",
"XN--MGBAYH7GPA",
"XN--MGBBH1A71E",
"XN--MGBC0A9AZCG",
"XN--MGBERP4A5D4AR",
"XN--MGBPL2FH",
"XN--MGBX4CD0AB",
"XN--MXTQ1M",
"XN--NGBC5AZD",
"XN--NODE",
"XN--NQV7F",
"XN--NQV7FS00EMA",
"XN--NYQY26A",
"XN--O3CW4H",
"XN--OGBPF8FL",
"XN--P1ACF",
"XN--P1AI",
"XN--PGBS0DH",
"XN--Q9JYB4C",
"XN--QCKA1PMC",
"XN--RHQV96G",
"XN--S9BRJ9C",
"XN--SES554G",
"XN--UNUP4Y",
"XN--VERMGENSBERATER-CTB",
"XN--VERMGENSBERATUNG-PWB",
"XN--VHQUV",
"XN--VUQ861B",
"XN--WGBH1C",
"XN--WGBL6A",
"XN--XHQ521B",
"XN--XKC2AL3HYE2A",
"XN--XKC2DL3A5EE0H",
"XN--Y9A3AQ",
"XN--YFRO4I67O",
"XN--YGBI2AMMX",
"XN--ZFR164B",
"XXX",
"XYZ",
"YACHTS",
"YANDEX",
"YE",
"YODOBASHI",
"YOGA",
"YOKOHAMA",
"YOUTUBE",
"YT",
"ZA",
"ZIP",
"ZM",
"ZONE",
"ZUERICH",
"ZW",
]
| tlds = ['ABB', 'ABBOTT', 'ABOGADO', 'AC', 'ACADEMY', 'ACCENTURE', 'ACCOUNTANT', 'ACCOUNTANTS', 'ACTIVE', 'ACTOR', 'AD', 'ADS', 'ADULT', 'AE', 'AEG', 'AERO', 'AF', 'AFL', 'AG', 'AGENCY', 'AI', 'AIG', 'AIRFORCE', 'AL', 'ALLFINANZ', 'ALSACE', 'AM', 'AMSTERDAM', 'AN', 'ANDROID', 'AO', 'APARTMENTS', 'AQ', 'AQUARELLE', 'AR', 'ARCHI', 'ARMY', 'ARPA', 'AS', 'ASIA', 'ASSOCIATES', 'AT', 'ATTORNEY', 'AU', 'AUCTION', 'AUDIO', 'AUTO', 'AUTOS', 'AW', 'AX', 'AXA', 'AZ', 'AZURE', 'BA', 'BAND', 'BANK', 'BAR', 'BARCLAYCARD', 'BARCLAYS', 'BARGAINS', 'BAUHAUS', 'BAYERN', 'BB', 'BBC', 'BBVA', 'BD', 'BE', 'BEER', 'BERLIN', 'BEST', 'BF', 'BG', 'BH', 'BHARTI', 'BI', 'BIBLE', 'BID', 'BIKE', 'BING', 'BINGO', 'BIO', 'BIZ', 'BJ', 'BLACK', 'BLACKFRIDAY', 'BLOOMBERG', 'BLUE', 'BM', 'BMW', 'BN', 'BNL', 'BNPPARIBAS', 'BO', 'BOATS', 'BOND', 'BOO', 'BOUTIQUE', 'BR', 'BRADESCO', 'BRIDGESTONE', 'BROKER', 'BROTHER', 'BRUSSELS', 'BS', 'BT', 'BUDAPEST', 'BUILD', 'BUILDERS', 'BUSINESS', 'BUZZ', 'BV', 'BW', 'BY', 'BZ', 'BZH', 'CA', 'CAB', 'CAFE', 'CAL', 'CAMERA', 'CAMP', 'CANCERRESEARCH', 'CANON', 'CAPETOWN', 'CAPITAL', 'CARAVAN', 'CARDS', 'CARE', 'CAREER', 'CAREERS', 'CARS', 'CARTIER', 'CASA', 'CASH', 'CASINO', 'CAT', 'CATERING', 'CBA', 'CBN', 'CC', 'CD', 'CENTER', 'CEO', 'CERN', 'CF', 'CFA', 'CFD', 'CG', 'CH', 'CHANNEL', 'CHAT', 'CHEAP', 'CHLOE', 'CHRISTMAS', 'CHROME', 'CHURCH', 'CI', 'CISCO', 'CITIC', 'CITY', 'CK', 'CL', 'CLAIMS', 'CLEANING', 'CLICK', 'CLINIC', 'CLOTHING', 'CLOUD', 'CLUB', 'CM', 'CN', 'CO', 'COACH', 'CODES', 'COFFEE', 'COLLEGE', 'COLOGNE', 'COM', 'COMMBANK', 'COMMUNITY', 'COMPANY', 'COMPUTER', 'CONDOS', 'CONSTRUCTION', 'CONSULTING', 'CONTRACTORS', 'COOKING', 'COOL', 'COOP', 'CORSICA', 'COUNTRY', 'COUPONS', 'COURSES', 'CR', 'CREDIT', 'CREDITCARD', 'CRICKET', 'CROWN', 'CRS', 'CRUISES', 'CU', 'CUISINELLA', 'CV', 'CW', 'CX', 'CY', 'CYMRU', 'CYOU', 'CZ', 'DABUR', 'DAD', 'DANCE', 'DATE', 'DATING', 'DATSUN', 'DAY', 'DCLK', 'DE', 'DEALS', 'DEGREE', 'DELIVERY', 'DEMOCRAT', 'DENTAL', 'DENTIST', 'DESI', 'DESIGN', 'DEV', 'DIAMONDS', 'DIET', 'DIGITAL', 'DIRECT', 'DIRECTORY', 'DISCOUNT', 'DJ', 'DK', 'DM', 'DNP', 'DO', 'DOCS', 'DOG', 'DOHA', 'DOMAINS', 'DOOSAN', 'DOWNLOAD', 'DRIVE', 'DURBAN', 'DVAG', 'DZ', 'EARTH', 'EAT', 'EC', 'EDU', 'EDUCATION', 'EE', 'EG', 'EMAIL', 'EMERCK', 'ENERGY', 'ENGINEER', 'ENGINEERING', 'ENTERPRISES', 'EPSON', 'EQUIPMENT', 'ER', 'ERNI', 'ES', 'ESQ', 'ESTATE', 'ET', 'EU', 'EUROVISION', 'EUS', 'EVENTS', 'EVERBANK', 'EXCHANGE', 'EXPERT', 'EXPOSED', 'EXPRESS', 'FAIL', 'FAITH', 'FAN', 'FANS', 'FARM', 'FASHION', 'FEEDBACK', 'FI', 'FILM', 'FINANCE', 'FINANCIAL', 'FIRMDALE', 'FISH', 'FISHING', 'FIT', 'FITNESS', 'FJ', 'FK', 'FLIGHTS', 'FLORIST', 'FLOWERS', 'FLSMIDTH', 'FLY', 'FM', 'FO', 'FOO', 'FOOTBALL', 'FOREX', 'FORSALE', 'FORUM', 'FOUNDATION', 'FR', 'FRL', 'FROGANS', 'FUND', 'FURNITURE', 'FUTBOL', 'FYI', 'GA', 'GAL', 'GALLERY', 'GARDEN', 'GB', 'GBIZ', 'GD', 'GDN', 'GE', 'GENT', 'GENTING', 'GF', 'GG', 'GGEE', 'GH', 'GI', 'GIFT', 'GIFTS', 'GIVES', 'GL', 'GLASS', 'GLE', 'GLOBAL', 'GLOBO', 'GM', 'GMAIL', 'GMO', 'GMX', 'GN', 'GOLD', 'GOLDPOINT', 'GOLF', 'GOO', 'GOOG', 'GOOGLE', 'GOP', 'GOV', 'GP', 'GQ', 'GR', 'GRAPHICS', 'GRATIS', 'GREEN', 'GRIPE', 'GS', 'GT', 'GU', 'GUGE', 'GUIDE', 'GUITARS', 'GURU', 'GW', 'GY', 'HAMBURG', 'HANGOUT', 'HAUS', 'HEALTHCARE', 'HELP', 'HERE', 'HERMES', 'HIPHOP', 'HITACHI', 'HIV', 'HK', 'HM', 'HN', 'HOCKEY', 'HOLDINGS', 'HOLIDAY', 'HOMEDEPOT', 'HOMES', 'HONDA', 'HORSE', 'HOST', 'HOSTING', 'HOTELES', 'HOTMAIL', 'HOUSE', 'HOW', 'HR', 'HT', 'HU', 'IBM', 'ICBC', 'ICU', 'ID', 'IE', 'IFM', 'IL', 'IM', 'IMMO', 'IMMOBILIEN', 'IN', 'INDUSTRIES', 'INFINITI', 'INFO', 'ING', 'INK', 'INSTITUTE', 'INSURE', 'INT', 'INTERNATIONAL', 'INVESTMENTS', 'IO', 'IQ', 'IR', 'IRISH', 'IS', 'IT', 'IWC', 'JAVA', 'JCB', 'JE', 'JETZT', 'JEWELRY', 'JLC', 'JLL', 'JM', 'JO', 'JOBS', 'JOBURG', 'JP', 'JUEGOS', 'KAUFEN', 'KDDI', 'KE', 'KG', 'KH', 'KI', 'KIM', 'KITCHEN', 'KIWI', 'KM', 'KN', 'KOELN', 'KOMATSU', 'KP', 'KR', 'KRD', 'KRED', 'KW', 'KY', 'KYOTO', 'KZ', 'LA', 'LACAIXA', 'LAND', 'LASALLE', 'LAT', 'LATROBE', 'LAW', 'LAWYER', 'LB', 'LC', 'LDS', 'LEASE', 'LECLERC', 'LEGAL', 'LGBT', 'LI', 'LIAISON', 'LIDL', 'LIFE', 'LIGHTING', 'LIMITED', 'LIMO', 'LINK', 'LK', 'LOAN', 'LOANS', 'LOL', 'LONDON', 'LOTTE', 'LOTTO', 'LOVE', 'LR', 'LS', 'LT', 'LTDA', 'LU', 'LUPIN', 'LUXE', 'LUXURY', 'LV', 'LY', 'MA', 'MADRID', 'MAIF', 'MAISON', 'MANAGEMENT', 'MANGO', 'MARKET', 'MARKETING', 'MARKETS', 'MARRIOTT', 'MBA', 'MC', 'MD', 'ME', 'MEDIA', 'MEET', 'MELBOURNE', 'MEME', 'MEMORIAL', 'MEN', 'MENU', 'MG', 'MH', 'MIAMI', 'MICROSOFT', 'MIL', 'MINI', 'MK', 'ML', 'MM', 'MMA', 'MN', 'MO', 'MOBI', 'MODA', 'MOE', 'MONASH', 'MONEY', 'MONTBLANC', 'MORMON', 'MORTGAGE', 'MOSCOW', 'MOTORCYCLES', 'MOV', 'MOVIE', 'MOVISTAR', 'MP', 'MQ', 'MR', 'MS', 'MT', 'MTN', 'MTPC', 'MU', 'MUSEUM', 'MV', 'MW', 'MX', 'MY', 'MZ', 'NA', 'NADEX', 'NAGOYA', 'NAME', 'NAVY', 'NC', 'NE', 'NEC', 'NET', 'NETBANK', 'NETWORK', 'NEUSTAR', 'NEW', 'NEWS', 'NEXUS', 'NF', 'NG', 'NGO', 'NHK', 'NI', 'NICO', 'NINJA', 'NISSAN', 'NL', 'NO', 'NP', 'NR', 'NRA', 'NRW', 'NTT', 'NU', 'NYC', 'NZ', 'OFFICE', 'OKINAWA', 'OM', 'OMEGA', 'ONE', 'ONG', 'ONL', 'ONLINE', 'OOO', 'ORACLE', 'ORG', 'ORGANIC', 'OSAKA', 'OTSUKA', 'OVH', 'PA', 'PAGE', 'PANERAI', 'PARIS', 'PARTNERS', 'PARTS', 'PARTY', 'PE', 'PF', 'PG', 'PH', 'PHARMACY', 'PHILIPS', 'PHOTO', 'PHOTOGRAPHY', 'PHOTOS', 'PHYSIO', 'PIAGET', 'PICS', 'PICTET', 'PICTURES', 'PINK', 'PIZZA', 'PK', 'PL', 'PLACE', 'PLAY', 'PLUMBING', 'PLUS', 'PM', 'PN', 'POHL', 'POKER', 'PORN', 'POST', 'PR', 'PRAXI', 'PRESS', 'PRO', 'PROD', 'PRODUCTIONS', 'PROF', 'PROPERTIES', 'PROPERTY', 'PS', 'PT', 'PUB', 'PW', 'PY', 'QA', 'QPON', 'QUEBEC', 'RACING', 'RE', 'REALTOR', 'REALTY', 'RECIPES', 'RED', 'REDSTONE', 'REHAB', 'REISE', 'REISEN', 'REIT', 'REN', 'RENT', 'RENTALS', 'REPAIR', 'REPORT', 'REPUBLICAN', 'REST', 'RESTAURANT', 'REVIEW', 'REVIEWS', 'RICH', 'RICOH', 'RIO', 'RIP', 'RO', 'ROCKS', 'RODEO', 'RS', 'RSVP', 'RU', 'RUHR', 'RUN', 'RW', 'RYUKYU', 'SA', 'SAARLAND', 'SALE', 'SAMSUNG', 'SANDVIK', 'SANDVIKCOROMANT', 'SAP', 'SARL', 'SAXO', 'SB', 'SC', 'SCA', 'SCB', 'SCHMIDT', 'SCHOLARSHIPS', 'SCHOOL', 'SCHULE', 'SCHWARZ', 'SCIENCE', 'SCOR', 'SCOT', 'SD', 'SE', 'SEAT', 'SENER', 'SERVICES', 'SEW', 'SEX', 'SEXY', 'SG', 'SH', 'SHIKSHA', 'SHOES', 'SHOW', 'SHRIRAM', 'SI', 'SINGLES', 'SITE', 'SJ', 'SK', 'SKI', 'SKY', 'SKYPE', 'SL', 'SM', 'SN', 'SNCF', 'SO', 'SOCCER', 'SOCIAL', 'SOFTWARE', 'SOHU', 'SOLAR', 'SOLUTIONS', 'SONY', 'SOY', 'SPACE', 'SPIEGEL', 'SPREADBETTING', 'SR', 'ST', 'STARHUB', 'STATOIL', 'STUDY', 'STYLE', 'SU', 'SUCKS', 'SUPPLIES', 'SUPPLY', 'SUPPORT', 'SURF', 'SURGERY', 'SUZUKI', 'SV', 'SWATCH', 'SWISS', 'SX', 'SY', 'SYDNEY', 'SYSTEMS', 'SZ', 'TAIPEI', 'TATAR', 'TATTOO', 'TAX', 'TAXI', 'TC', 'TD', 'TEAM', 'TECH', 'TECHNOLOGY', 'TEL', 'TELEFONICA', 'TEMASEK', 'TENNIS', 'TF', 'TG', 'TH', 'THD', 'THEATER', 'TICKETS', 'TIENDA', 'TIPS', 'TIRES', 'TIROL', 'TJ', 'TK', 'TL', 'TM', 'TN', 'TO', 'TODAY', 'TOKYO', 'TOOLS', 'TOP', 'TORAY', 'TOSHIBA', 'TOURS', 'TOWN', 'TOYS', 'TR', 'TRADE', 'TRADING', 'TRAINING', 'TRAVEL', 'TRUST', 'TT', 'TUI', 'TV', 'TW', 'TZ', 'UA', 'UG', 'UK', 'UNIVERSITY', 'UNO', 'UOL', 'US', 'UY', 'UZ', 'VA', 'VACATIONS', 'VC', 'VE', 'VEGAS', 'VENTURES', 'VERSICHERUNG', 'VET', 'VG', 'VI', 'VIAJES', 'VIDEO', 'VILLAS', 'VISION', 'VISTA', 'VISTAPRINT', 'VLAANDEREN', 'VN', 'VODKA', 'VOTE', 'VOTING', 'VOTO', 'VOYAGE', 'VU', 'WALES', 'WALTER', 'WANG', 'WATCH', 'WEBCAM', 'WEBSITE', 'WED', 'WEDDING', 'WEIR', 'WF', 'WHOSWHO', 'WIEN', 'WIKI', 'WILLIAMHILL', 'WIN', 'WINDOWS', 'WME', 'WORK', 'WORKS', 'WORLD', 'WS', 'WTC', 'WTF', 'XBOX', 'XEROX', 'XIN', 'XN--1QQW23A', 'XN--30RR7Y', 'XN--3BST00M', 'XN--3DS443G', 'XN--3E0B707E', 'XN--45BRJ9C', 'XN--45Q11C', 'XN--4GBRIM', 'XN--55QW42G', 'XN--55QX5D', 'XN--6FRZ82G', 'XN--6QQ986B3XL', 'XN--80ADXHKS', 'XN--80AO21A', 'XN--80ASEHDB', 'XN--80ASWG', 'XN--90A3AC', 'XN--90AIS', 'XN--9ET52U', 'XN--B4W605FERD', 'XN--C1AVG', 'XN--CG4BKI', 'XN--CLCHC0EA0B2G2A9GCD', 'XN--CZR694B', 'XN--CZRS0T', 'XN--CZRU2D', 'XN--D1ACJ3B', 'XN--D1ALF', 'XN--ESTV75G', 'XN--FIQ228C5HS', 'XN--FIQ64B', 'XN--FIQS8S', 'XN--FIQZ9S', 'XN--FJQ720A', 'XN--FLW351E', 'XN--FPCRJ9C3D', 'XN--FZC2C9E2C', 'XN--GECRJ9C', 'XN--H2BRJ9C', 'XN--HXT814E', 'XN--I1B6B1A6A2E', 'XN--IMR513N', 'XN--IO0A7I', 'XN--J1AMH', 'XN--J6W193G', 'XN--KCRX77D1X4A', 'XN--KPRW13D', 'XN--KPRY57D', 'XN--KPUT3I', 'XN--L1ACC', 'XN--LGBBAT1AD8J', 'XN--MGB9AWBF', 'XN--MGBA3A4F16A', 'XN--MGBAAM7A8H', 'XN--MGBAB2BD', 'XN--MGBAYH7GPA', 'XN--MGBBH1A71E', 'XN--MGBC0A9AZCG', 'XN--MGBERP4A5D4AR', 'XN--MGBPL2FH', 'XN--MGBX4CD0AB', 'XN--MXTQ1M', 'XN--NGBC5AZD', 'XN--NODE', 'XN--NQV7F', 'XN--NQV7FS00EMA', 'XN--NYQY26A', 'XN--O3CW4H', 'XN--OGBPF8FL', 'XN--P1ACF', 'XN--P1AI', 'XN--PGBS0DH', 'XN--Q9JYB4C', 'XN--QCKA1PMC', 'XN--RHQV96G', 'XN--S9BRJ9C', 'XN--SES554G', 'XN--UNUP4Y', 'XN--VERMGENSBERATER-CTB', 'XN--VERMGENSBERATUNG-PWB', 'XN--VHQUV', 'XN--VUQ861B', 'XN--WGBH1C', 'XN--WGBL6A', 'XN--XHQ521B', 'XN--XKC2AL3HYE2A', 'XN--XKC2DL3A5EE0H', 'XN--Y9A3AQ', 'XN--YFRO4I67O', 'XN--YGBI2AMMX', 'XN--ZFR164B', 'XXX', 'XYZ', 'YACHTS', 'YANDEX', 'YE', 'YODOBASHI', 'YOGA', 'YOKOHAMA', 'YOUTUBE', 'YT', 'ZA', 'ZIP', 'ZM', 'ZONE', 'ZUERICH', 'ZW'] |
class Bank:
def __init__(self):
self.inf = 0
self._observers = []
def register_observer(self, observer):
self._observers.append(observer)
def notify_observers(self):
print("Inflacja na poziomie: ", format(self.inf, '.2f'))
for observer in self._observers:
observer.notify(self)
| class Bank:
def __init__(self):
self.inf = 0
self._observers = []
def register_observer(self, observer):
self._observers.append(observer)
def notify_observers(self):
print('Inflacja na poziomie: ', format(self.inf, '.2f'))
for observer in self._observers:
observer.notify(self) |
fruta = 'kiwi'
if fruta == 'kiwi':
print("El valor es kiwi")
elif fruta == 'manzana':
print("Es una manzana")
elif fruta == 'manzana2':
pass #si no sabemos que poner y no marque error
else:
print("No son iguales")
mensaje = 'El valor es kiwi' if fruta == 'kiwis' else False
print(mensaje)
| fruta = 'kiwi'
if fruta == 'kiwi':
print('El valor es kiwi')
elif fruta == 'manzana':
print('Es una manzana')
elif fruta == 'manzana2':
pass
else:
print('No son iguales')
mensaje = 'El valor es kiwi' if fruta == 'kiwis' else False
print(mensaje) |
# Status code
API_HANDLER_OK_CODE = 200
API_HANDLER_ERROR_CODE = 400
# REST parameters
SERVICE_HANDLER_POST_ARG_KEY = "key"
SERVICE_HANDLER_POST_BODY_KEY = "body_key"
| api_handler_ok_code = 200
api_handler_error_code = 400
service_handler_post_arg_key = 'key'
service_handler_post_body_key = 'body_key' |
class Solution:
def minSubArrayLen(self, s, nums):
"""
:type s: int
:type nums: List[int]
:rtype: int
------------------------------
15 / 15 test cases passed.
Status: Accepted
Runtime: 72 ms
"""
l, sum, res = 0, 0, len(nums) + 1
for r in range(len(nums)):
sum += nums[r]
while l <= r and sum >= s:
res = min(res, r - l + 1)
sum -= nums[l]
l += 1
return res if res != len(nums) + 1 else 0
if __name__ == '__main__':
print(Solution().minSubArrayLen(15, [1, 2, 3, 4, 5]))
print(Solution().minSubArrayLen(7, [2, 3, 1, 2, 4, 3]))
| class Solution:
def min_sub_array_len(self, s, nums):
"""
:type s: int
:type nums: List[int]
:rtype: int
------------------------------
15 / 15 test cases passed.
Status: Accepted
Runtime: 72 ms
"""
(l, sum, res) = (0, 0, len(nums) + 1)
for r in range(len(nums)):
sum += nums[r]
while l <= r and sum >= s:
res = min(res, r - l + 1)
sum -= nums[l]
l += 1
return res if res != len(nums) + 1 else 0
if __name__ == '__main__':
print(solution().minSubArrayLen(15, [1, 2, 3, 4, 5]))
print(solution().minSubArrayLen(7, [2, 3, 1, 2, 4, 3])) |
def get_paginated_result(query, page, per_page, field, timestamp):
new_query = query
if page != 1 and timestamp != None:
new_query = query.filter(
field < timestamp
)
try:
return new_query.paginate(
per_page=per_page,
page=page
).items, 200
except:
response_object = {
'status': 'error',
'message': 'end of content',
}
return response_object, 470
| def get_paginated_result(query, page, per_page, field, timestamp):
new_query = query
if page != 1 and timestamp != None:
new_query = query.filter(field < timestamp)
try:
return (new_query.paginate(per_page=per_page, page=page).items, 200)
except:
response_object = {'status': 'error', 'message': 'end of content'}
return (response_object, 470) |
# -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2015-2018 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Errors for Invenio-Records module."""
class RecordsError(Exception):
"""Base class for errors in Invenio-Records module."""
class MissingModelError(RecordsError):
"""Error raised when a record has no model."""
| """Errors for Invenio-Records module."""
class Recordserror(Exception):
"""Base class for errors in Invenio-Records module."""
class Missingmodelerror(RecordsError):
"""Error raised when a record has no model.""" |
#!/usr/bin/env python3
# encoding: utf-8
def _subclasses(cls):
try:
return cls.__subclasses__()
except TypeError:
return type.__subclasses__(cls)
class _SubclassNode:
__slots__ = frozenset(('cls', 'children'))
def __init__(self, cls, children=None):
self.cls = cls
self.children = children or []
def __repr__(self):
if not self.children:
return repr(self.cls)
return '<{0.__class__.__qualname__} {0.cls} {0.children}>'.format(self)
def subclasses(cls, root=None):
root = root or _SubclassNode(cls)
root.children.extend(map(_SubclassNode, _subclasses(cls)))
for child in root.children:
subclasses(child.cls, child)
return root
if __name__ == '__main__':
class A: pass
class B(A): pass
class C(A): pass
class D(B, C): pass
class E(A): pass
print(subclasses(A))
| def _subclasses(cls):
try:
return cls.__subclasses__()
except TypeError:
return type.__subclasses__(cls)
class _Subclassnode:
__slots__ = frozenset(('cls', 'children'))
def __init__(self, cls, children=None):
self.cls = cls
self.children = children or []
def __repr__(self):
if not self.children:
return repr(self.cls)
return '<{0.__class__.__qualname__} {0.cls} {0.children}>'.format(self)
def subclasses(cls, root=None):
root = root or __subclass_node(cls)
root.children.extend(map(_SubclassNode, _subclasses(cls)))
for child in root.children:
subclasses(child.cls, child)
return root
if __name__ == '__main__':
class A:
pass
class B(A):
pass
class C(A):
pass
class D(B, C):
pass
class E(A):
pass
print(subclasses(A)) |
def longest_uppercase(input,k):
final_out = 0
for i in input:
test_letters = i
for j in input:
if len(test_letters) == k :
break
if test_letters.find(j) >= 0:
pass
else:
test_letters += j
max = 0
count = 0
for m in input :
if test_letters.find(m) == -1:
if count > max:
max = count
count = 0
else:
count += 1
if len(input) <= k:
return len(input)
if final_out < max:
final_out = max
return final_out
| def longest_uppercase(input, k):
final_out = 0
for i in input:
test_letters = i
for j in input:
if len(test_letters) == k:
break
if test_letters.find(j) >= 0:
pass
else:
test_letters += j
max = 0
count = 0
for m in input:
if test_letters.find(m) == -1:
if count > max:
max = count
count = 0
else:
count += 1
if len(input) <= k:
return len(input)
if final_out < max:
final_out = max
return final_out |
# The following dependencies were calculated from:
#
# generate_workspace --artifact=io.opencensus:opencensus-api:0.12.2 --artifact=io.opencensus:opencensus-contrib-zpages:0.12.2 --artifact=io.opencensus:opencensus-exporter-trace-logging:0.12.2 --artifact=io.opencensus:opencensus-impl:0.12.2 --repositories=http://repo.maven.apache.org/maven2
def opencensus_maven_jars():
# io.opencensus:opencensus-impl-core:jar:0.12.2 got requested version
# io.opencensus:opencensus-contrib-zpages:jar:0.12.2 got requested version
# io.opencensus:opencensus-contrib-grpc-metrics:jar:0.12.2 got requested version
# io.opencensus:opencensus-api:jar:0.12.2
# io.opencensus:opencensus-exporter-trace-logging:jar:0.12.2 got requested version
# io.opencensus:opencensus-impl:jar:0.12.2 got requested version
native.maven_jar(
name = "com_google_code_findbugs_jsr305",
artifact = "com.google.code.findbugs:jsr305:3.0.1",
repository = "http://repo.maven.apache.org/maven2/",
sha1 = "f7be08ec23c21485b9b5a1cf1654c2ec8c58168d",
)
# io.opencensus:opencensus-api:jar:0.12.2
native.maven_jar(
name = "io_grpc_grpc_context",
artifact = "io.grpc:grpc-context:1.9.0",
repository = "http://repo.maven.apache.org/maven2/",
sha1 = "28b0836f48c9705abf73829bbc536dba29a1329a",
)
native.maven_jar(
name = "io_opencensus_opencensus_exporter_trace_logging",
artifact = "io.opencensus:opencensus-exporter-trace-logging:0.12.2",
repository = "http://repo.maven.apache.org/maven2/",
sha1 = "15b8b3d2c9b3ffd2d8e242d252ee056a1c30d203",
)
# io.opencensus:opencensus-impl-core:jar:0.12.2 got requested version
# io.opencensus:opencensus-contrib-zpages:jar:0.12.2 got requested version
# io.opencensus:opencensus-contrib-grpc-metrics:jar:0.12.2 got requested version
# io.opencensus:opencensus-api:jar:0.12.2
# io.opencensus:opencensus-exporter-trace-logging:jar:0.12.2 got requested version
# io.opencensus:opencensus-impl:jar:0.12.2 got requested version
native.maven_jar(
name = "com_google_errorprone_error_prone_annotations",
artifact = "com.google.errorprone:error_prone_annotations:2.2.0",
repository = "http://repo.maven.apache.org/maven2/",
sha1 = "88e3c593e9b3586e1c6177f89267da6fc6986f0c",
)
native.maven_jar(
name = "io_opencensus_opencensus_contrib_zpages",
artifact = "io.opencensus:opencensus-contrib-zpages:0.12.2",
repository = "http://repo.maven.apache.org/maven2/",
sha1 = "44f8d5b81b20f9f0d34091baecffd67c2ce0c952",
)
# io.opencensus:opencensus-impl:jar:0.12.2
native.maven_jar(
name = "com_lmax_disruptor",
artifact = "com.lmax:disruptor:3.3.9",
repository = "http://repo.maven.apache.org/maven2/",
sha1 = "7898f8e8dc2d908d4ae5240fbb17eb1a9c213b9b",
)
# io.opencensus:opencensus-impl-core:jar:0.12.2 got requested version
# io.opencensus:opencensus-contrib-zpages:jar:0.12.2 got requested version
# io.opencensus:opencensus-api:jar:0.12.2
# io.opencensus:opencensus-exporter-trace-logging:jar:0.12.2 got requested version
native.maven_jar(
name = "com_google_guava_guava",
artifact = "com.google.guava:guava:19.0",
repository = "http://repo.maven.apache.org/maven2/",
sha1 = "6ce200f6b23222af3d8abb6b6459e6c44f4bb0e9",
)
# io.opencensus:opencensus-contrib-zpages:jar:0.12.2
native.maven_jar(
name = "io_opencensus_opencensus_contrib_grpc_metrics",
artifact = "io.opencensus:opencensus-contrib-grpc-metrics:0.12.2",
repository = "http://repo.maven.apache.org/maven2/",
sha1 = "20dd982bd8942fc6d612fedd4466cda0461267ec",
)
# io.opencensus:opencensus-impl-core:jar:0.12.2 got requested version
# io.opencensus:opencensus-contrib-zpages:jar:0.12.2 got requested version
# io.opencensus:opencensus-contrib-grpc-metrics:jar:0.12.2 got requested version
# io.opencensus:opencensus-exporter-trace-logging:jar:0.12.2 got requested version
# io.opencensus:opencensus-impl:jar:0.12.2 got requested version
native.maven_jar(
name = "io_opencensus_opencensus_api",
artifact = "io.opencensus:opencensus-api:0.12.2",
repository = "http://repo.maven.apache.org/maven2/",
sha1 = "a2d524b62869350942106ab8f9a1f5adb1212775",
)
# io.opencensus:opencensus-impl:jar:0.12.2
native.maven_jar(
name = "io_opencensus_opencensus_impl_core",
artifact = "io.opencensus:opencensus-impl-core:0.12.2",
repository = "http://repo.maven.apache.org/maven2/",
sha1 = "9e059704131a4455b3bd6d84cfa8e6875551d647",
)
native.maven_jar(
name = "io_opencensus_opencensus_impl",
artifact = "io.opencensus:opencensus-impl:0.12.2",
repository = "http://repo.maven.apache.org/maven2/",
sha1 = "4e5cd57bddbd9b47cd16cc8b0b608b43355b223f",
)
def opencensus_java_libraries():
native.java_library(
name = "com_google_code_findbugs_jsr305",
visibility = ["//visibility:public"],
exports = ["@com_google_code_findbugs_jsr305//jar"],
)
native.java_library(
name = "io_grpc_grpc_context",
visibility = ["//visibility:public"],
exports = ["@io_grpc_grpc_context//jar"],
)
native.java_library(
name = "io_opencensus_opencensus_exporter_trace_logging",
visibility = ["//visibility:public"],
exports = ["@io_opencensus_opencensus_exporter_trace_logging//jar"],
runtime_deps = [
":com_google_code_findbugs_jsr305",
":com_google_errorprone_error_prone_annotations",
":com_google_guava_guava",
":io_opencensus_opencensus_api",
],
)
native.java_library(
name = "com_google_errorprone_error_prone_annotations",
visibility = ["//visibility:public"],
exports = ["@com_google_errorprone_error_prone_annotations//jar"],
)
native.java_library(
name = "io_opencensus_opencensus_contrib_zpages",
visibility = ["//visibility:public"],
exports = ["@io_opencensus_opencensus_contrib_zpages//jar"],
runtime_deps = [
":com_google_code_findbugs_jsr305",
":com_google_errorprone_error_prone_annotations",
":com_google_guava_guava",
":io_opencensus_opencensus_api",
":io_opencensus_opencensus_contrib_grpc_metrics",
],
)
native.java_library(
name = "com_lmax_disruptor",
visibility = ["//visibility:public"],
exports = ["@com_lmax_disruptor//jar"],
)
native.java_library(
name = "com_google_guava_guava",
visibility = ["//visibility:public"],
exports = ["@com_google_guava_guava//jar"],
)
native.java_library(
name = "io_opencensus_opencensus_contrib_grpc_metrics",
visibility = ["//visibility:public"],
exports = ["@io_opencensus_opencensus_contrib_grpc_metrics//jar"],
runtime_deps = [
":com_google_code_findbugs_jsr305",
":com_google_errorprone_error_prone_annotations",
":io_opencensus_opencensus_api",
],
)
native.java_library(
name = "io_opencensus_opencensus_api",
visibility = ["//visibility:public"],
exports = ["@io_opencensus_opencensus_api//jar"],
runtime_deps = [
":com_google_code_findbugs_jsr305",
":com_google_errorprone_error_prone_annotations",
":com_google_guava_guava",
":io_grpc_grpc_context",
],
)
native.java_library(
name = "io_opencensus_opencensus_impl_core",
visibility = ["//visibility:public"],
exports = ["@io_opencensus_opencensus_impl_core//jar"],
runtime_deps = [
":com_google_code_findbugs_jsr305",
":com_google_errorprone_error_prone_annotations",
":com_google_guava_guava",
":io_opencensus_opencensus_api",
],
)
native.java_library(
name = "io_opencensus_opencensus_impl",
visibility = ["//visibility:public"],
exports = ["@io_opencensus_opencensus_impl//jar"],
runtime_deps = [
":com_google_code_findbugs_jsr305",
":com_google_errorprone_error_prone_annotations",
":com_google_guava_guava",
":com_lmax_disruptor",
":io_opencensus_opencensus_api",
":io_opencensus_opencensus_impl_core",
],
)
| def opencensus_maven_jars():
native.maven_jar(name='com_google_code_findbugs_jsr305', artifact='com.google.code.findbugs:jsr305:3.0.1', repository='http://repo.maven.apache.org/maven2/', sha1='f7be08ec23c21485b9b5a1cf1654c2ec8c58168d')
native.maven_jar(name='io_grpc_grpc_context', artifact='io.grpc:grpc-context:1.9.0', repository='http://repo.maven.apache.org/maven2/', sha1='28b0836f48c9705abf73829bbc536dba29a1329a')
native.maven_jar(name='io_opencensus_opencensus_exporter_trace_logging', artifact='io.opencensus:opencensus-exporter-trace-logging:0.12.2', repository='http://repo.maven.apache.org/maven2/', sha1='15b8b3d2c9b3ffd2d8e242d252ee056a1c30d203')
native.maven_jar(name='com_google_errorprone_error_prone_annotations', artifact='com.google.errorprone:error_prone_annotations:2.2.0', repository='http://repo.maven.apache.org/maven2/', sha1='88e3c593e9b3586e1c6177f89267da6fc6986f0c')
native.maven_jar(name='io_opencensus_opencensus_contrib_zpages', artifact='io.opencensus:opencensus-contrib-zpages:0.12.2', repository='http://repo.maven.apache.org/maven2/', sha1='44f8d5b81b20f9f0d34091baecffd67c2ce0c952')
native.maven_jar(name='com_lmax_disruptor', artifact='com.lmax:disruptor:3.3.9', repository='http://repo.maven.apache.org/maven2/', sha1='7898f8e8dc2d908d4ae5240fbb17eb1a9c213b9b')
native.maven_jar(name='com_google_guava_guava', artifact='com.google.guava:guava:19.0', repository='http://repo.maven.apache.org/maven2/', sha1='6ce200f6b23222af3d8abb6b6459e6c44f4bb0e9')
native.maven_jar(name='io_opencensus_opencensus_contrib_grpc_metrics', artifact='io.opencensus:opencensus-contrib-grpc-metrics:0.12.2', repository='http://repo.maven.apache.org/maven2/', sha1='20dd982bd8942fc6d612fedd4466cda0461267ec')
native.maven_jar(name='io_opencensus_opencensus_api', artifact='io.opencensus:opencensus-api:0.12.2', repository='http://repo.maven.apache.org/maven2/', sha1='a2d524b62869350942106ab8f9a1f5adb1212775')
native.maven_jar(name='io_opencensus_opencensus_impl_core', artifact='io.opencensus:opencensus-impl-core:0.12.2', repository='http://repo.maven.apache.org/maven2/', sha1='9e059704131a4455b3bd6d84cfa8e6875551d647')
native.maven_jar(name='io_opencensus_opencensus_impl', artifact='io.opencensus:opencensus-impl:0.12.2', repository='http://repo.maven.apache.org/maven2/', sha1='4e5cd57bddbd9b47cd16cc8b0b608b43355b223f')
def opencensus_java_libraries():
native.java_library(name='com_google_code_findbugs_jsr305', visibility=['//visibility:public'], exports=['@com_google_code_findbugs_jsr305//jar'])
native.java_library(name='io_grpc_grpc_context', visibility=['//visibility:public'], exports=['@io_grpc_grpc_context//jar'])
native.java_library(name='io_opencensus_opencensus_exporter_trace_logging', visibility=['//visibility:public'], exports=['@io_opencensus_opencensus_exporter_trace_logging//jar'], runtime_deps=[':com_google_code_findbugs_jsr305', ':com_google_errorprone_error_prone_annotations', ':com_google_guava_guava', ':io_opencensus_opencensus_api'])
native.java_library(name='com_google_errorprone_error_prone_annotations', visibility=['//visibility:public'], exports=['@com_google_errorprone_error_prone_annotations//jar'])
native.java_library(name='io_opencensus_opencensus_contrib_zpages', visibility=['//visibility:public'], exports=['@io_opencensus_opencensus_contrib_zpages//jar'], runtime_deps=[':com_google_code_findbugs_jsr305', ':com_google_errorprone_error_prone_annotations', ':com_google_guava_guava', ':io_opencensus_opencensus_api', ':io_opencensus_opencensus_contrib_grpc_metrics'])
native.java_library(name='com_lmax_disruptor', visibility=['//visibility:public'], exports=['@com_lmax_disruptor//jar'])
native.java_library(name='com_google_guava_guava', visibility=['//visibility:public'], exports=['@com_google_guava_guava//jar'])
native.java_library(name='io_opencensus_opencensus_contrib_grpc_metrics', visibility=['//visibility:public'], exports=['@io_opencensus_opencensus_contrib_grpc_metrics//jar'], runtime_deps=[':com_google_code_findbugs_jsr305', ':com_google_errorprone_error_prone_annotations', ':io_opencensus_opencensus_api'])
native.java_library(name='io_opencensus_opencensus_api', visibility=['//visibility:public'], exports=['@io_opencensus_opencensus_api//jar'], runtime_deps=[':com_google_code_findbugs_jsr305', ':com_google_errorprone_error_prone_annotations', ':com_google_guava_guava', ':io_grpc_grpc_context'])
native.java_library(name='io_opencensus_opencensus_impl_core', visibility=['//visibility:public'], exports=['@io_opencensus_opencensus_impl_core//jar'], runtime_deps=[':com_google_code_findbugs_jsr305', ':com_google_errorprone_error_prone_annotations', ':com_google_guava_guava', ':io_opencensus_opencensus_api'])
native.java_library(name='io_opencensus_opencensus_impl', visibility=['//visibility:public'], exports=['@io_opencensus_opencensus_impl//jar'], runtime_deps=[':com_google_code_findbugs_jsr305', ':com_google_errorprone_error_prone_annotations', ':com_google_guava_guava', ':com_lmax_disruptor', ':io_opencensus_opencensus_api', ':io_opencensus_opencensus_impl_core']) |
# -- Project information -----------------------------------------------------
project = 'showyourwork'
copyright = '2021, Rodrigo Luger'
author = 'Rodrigo Luger'
release = '1.0.0'
# -- General configuration ---------------------------------------------------
extensions = []
templates_path = ['_templates']
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
master_doc = 'index'
# -- Options for HTML output -------------------------------------------------
html_theme = 'sphinx_book_theme'
html_copy_source = True
html_show_sourcelink = True
html_sourcelink_suffix = ""
html_title = "showyourwork"
html_logo = "_static/logo.png"
html_static_path = ["_static"]
html_css_files = []
html_theme_options = {
"repository_url": "https://github.com/rodluger/showyourwork",
"repository_branch": "main",
"use_edit_page_button": True,
"use_issues_button": True,
"use_repository_button": True,
"use_download_button": True,
"logo_only": True,
"use_fullscreen_button": False,
"path_to_docs": "docs/",
}
| project = 'showyourwork'
copyright = '2021, Rodrigo Luger'
author = 'Rodrigo Luger'
release = '1.0.0'
extensions = []
templates_path = ['_templates']
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
master_doc = 'index'
html_theme = 'sphinx_book_theme'
html_copy_source = True
html_show_sourcelink = True
html_sourcelink_suffix = ''
html_title = 'showyourwork'
html_logo = '_static/logo.png'
html_static_path = ['_static']
html_css_files = []
html_theme_options = {'repository_url': 'https://github.com/rodluger/showyourwork', 'repository_branch': 'main', 'use_edit_page_button': True, 'use_issues_button': True, 'use_repository_button': True, 'use_download_button': True, 'logo_only': True, 'use_fullscreen_button': False, 'path_to_docs': 'docs/'} |
#!/usr/bin/env python3
"""
Bubble Sort Script
"""
def bubble_sort(L):
"""
Sorts a list in increasing order. Because of lists are mutable
this function does not have to return something.
This algorithm uses bubble sort.
@param L: a list (in general unsorted)
"""
for i in range(len(L) - 1):
already_sorted = True
for j in range(len(L) - i - 1):
if L[j] > L[j + 1]:
already_sorted = False
L[j], L[j + 1]= L[j + 1], L[j]
# if no swaps were developed in the previous loop,
# it means that the list is already sorted. Thus,
# loop is exited and function terminates (returns None)
if already_sorted:
break
list1 = [1, -2, 3, 2, 0, 4, -1, 2, 0, 1, -5, 5, -6]
#list1 = [2, 1, -1]
bubble_sort(list1)
print(list1) | """
Bubble Sort Script
"""
def bubble_sort(L):
"""
Sorts a list in increasing order. Because of lists are mutable
this function does not have to return something.
This algorithm uses bubble sort.
@param L: a list (in general unsorted)
"""
for i in range(len(L) - 1):
already_sorted = True
for j in range(len(L) - i - 1):
if L[j] > L[j + 1]:
already_sorted = False
(L[j], L[j + 1]) = (L[j + 1], L[j])
if already_sorted:
break
list1 = [1, -2, 3, 2, 0, 4, -1, 2, 0, 1, -5, 5, -6]
bubble_sort(list1)
print(list1) |
class ScriptMessageSent:
""" Triggered when a message is sent using the ScriptConnector
message:str - the message that was sent
index:int - the index into the script (agent.messages) """
def __init__(self, message, index):
self.message = message
self.index = index
def __str__(self):
return "ScriptMessageSent: " + self.message
| class Scriptmessagesent:
""" Triggered when a message is sent using the ScriptConnector
message:str - the message that was sent
index:int - the index into the script (agent.messages) """
def __init__(self, message, index):
self.message = message
self.index = index
def __str__(self):
return 'ScriptMessageSent: ' + self.message |
'''
#3-1
b=0
c=0
while 1 :
a=input("Enthe an integer, the input ends if it is :")
if((a>0)|(a<0)):
if a>0:
b=a
else:
c=-a
if(a==0):
print("zheng shu {},fushu {},pingjunshu {}".format(b,c,(b+c)))
break
'''
'''
#3-2
j = 0
for i in range(15):
s = 10000+10000*0.05
j = j + s
if i==10:
a = j
print(a)
if i == 11:
b = j
d = b-a
print(d)
print(j-a)
'''
'''
#3-3
s=10000
for i in range(10):
s=s+s*0.05
print(s)
n=s
for i in range(4):
n=n+n*0.05
print(n)
'''
'''
#3-4
a=0
for i in range(100,1000):
if(i%5==0 and i%6==0):
a=a+1
print("%3d" % i, end=" ")
if(a%10==0):
print(" ")
'''
'''
#3-5
import math
n=0.0
while 1:
n = n+1.0
if n*n*n<12000:
print(n)
break
if n*n>=12000:
print(n)
break
'''
'''
#3-5
n=1
while(n<12000):
if(n*n>12000):
print(n)
break
n=n+1
s=1
while(s<12000):
if(s*s*s>12000):
print(s-1)
break
s=s+1
'''
'''
#3-6
p = eval(raw_input(">>"))
y = eval(raw_input(">>"))
n = 0.05
while n<8.125:
n = n+0.125
s = p*pow((1.0+n),1)
print(s)
m = s/12
print(m)
'''
'''
#3-7
n=0
for i in range(1,50001):
n=n+1/i
print(n)
s=50000
m=0
while(s>0):
m=m+1/s
s=s-1
print(m)
'''
'''
#3-8
a=1.0
b=3.0
sum1=0
while (a<=97):
sum1=sum1+a/b
a=a+2
b=b+2
print(sum1)
'''
'''
#3-9
#_*_coding:utf8-
a=input(">>")
b=0
sum=0
for i in range(1,a+1):
sum+=pow((-1),(a+1))/2*a-1
b=sum*4
print(b)
'''
'''
#3-9-2
n=0
for i in range(1,100000):
n=n+pow((-1),i+1)/(2*i-1)
if(i%10000==0):
print(4*n)
'''
'''
#3-10
for i in range(1,10001):
n=0
for j in range(1,i/2+1):
if(i%j==0):
n=n+j
if(n==i):
print(i)
'''
'''
#3-11
a=0
for i in range(1,8):
for j in range(i+1,8):
print("sum {}".format((i)+(j)))
a=a+1
print "sum",a
'''
| """
#3-1
b=0
c=0
while 1 :
a=input("Enthe an integer, the input ends if it is :")
if((a>0)|(a<0)):
if a>0:
b=a
else:
c=-a
if(a==0):
print("zheng shu {},fushu {},pingjunshu {}".format(b,c,(b+c)))
break
"""
'\n#3-2\nj = 0\nfor i in range(15):\n s = 10000+10000*0.05\n j = j + s\n if i==10:\n a = j\n print(a)\n if i == 11:\n b = j\n d = b-a\n print(d)\nprint(j-a)\n'
'\n#3-3\ns=10000\nfor i in range(10):\n s=s+s*0.05\nprint(s)\nn=s\nfor i in range(4):\n n=n+n*0.05\nprint(n)\n'
'\n#3-4\na=0\nfor i in range(100,1000):\n if(i%5==0 and i%6==0):\n a=a+1\n print("%3d" % i, end=" ")\n if(a%10==0):\n print(" ")\n\n'
'\n#3-5\nimport math\nn=0.0\nwhile 1:\n n = n+1.0\n if n*n*n<12000:\n print(n)\n break\n\n if n*n>=12000:\n print(n)\n break\n'
'\n#3-5\nn=1\nwhile(n<12000):\n if(n*n>12000):\n print(n)\n break\n n=n+1\ns=1\nwhile(s<12000):\n if(s*s*s>12000):\n print(s-1)\n break\n s=s+1\n'
'\n#3-6\np = eval(raw_input(">>"))\ny = eval(raw_input(">>"))\nn = 0.05\nwhile n<8.125:\n n = n+0.125\n s = p*pow((1.0+n),1)\n print(s)\n m = s/12\n print(m)\n'
'\n#3-7\nn=0\nfor i in range(1,50001):\n n=n+1/i\nprint(n)\ns=50000\nm=0\nwhile(s>0):\n m=m+1/s\n s=s-1\nprint(m)\n'
'\n#3-8\na=1.0\nb=3.0\nsum1=0\nwhile (a<=97):\n sum1=sum1+a/b\n a=a+2\n b=b+2\nprint(sum1)\n'
'\n#3-9\n#_*_coding:utf8-\na=input(">>")\nb=0\nsum=0\nfor i in range(1,a+1):\n sum+=pow((-1),(a+1))/2*a-1\nb=sum*4\nprint(b)\n'
'\n#3-9-2\nn=0\nfor i in range(1,100000):\n n=n+pow((-1),i+1)/(2*i-1)\n if(i%10000==0):\n print(4*n)\n'
'\n#3-10\n\nfor i in range(1,10001):\n n=0\n for j in range(1,i/2+1):\n if(i%j==0):\n n=n+j\n if(n==i):\n print(i)\n'
'\n#3-11\na=0\nfor i in range(1,8):\n for j in range(i+1,8):\n print("sum {}".format((i)+(j)))\n a=a+1\nprint "sum",a\n' |
def mergeSort(myList):
print("Splitting ",myList)
if (len(myList) > 1):
mid = len(myList)//2
leftList = myList[:mid]
rightList = myList[mid:]
mergeSort(leftList)
mergeSort(rightList)
i = 0
j = 0
k = 0
while ((i < len(leftList)) and (j < len(rightList))):
if (leftList[i] < rightList[j]):
myList[k] = leftList[i]
i = i + 1
else:
myList[k] = rightList[j]
j = j + 1
k = k + 1
while (i < len(leftList)):
myList[k] = leftList[i]
i = i + 1
k = k + 1
while (j < len(rightList)):
myList[k] = rightList[j]
j = j + 1
k = k + 1
print("Merging ",myList)
myList = [3,1,4,10,9,6,2,5,8,7]
mergeSort(myList)
print(myList)
| def merge_sort(myList):
print('Splitting ', myList)
if len(myList) > 1:
mid = len(myList) // 2
left_list = myList[:mid]
right_list = myList[mid:]
merge_sort(leftList)
merge_sort(rightList)
i = 0
j = 0
k = 0
while i < len(leftList) and j < len(rightList):
if leftList[i] < rightList[j]:
myList[k] = leftList[i]
i = i + 1
else:
myList[k] = rightList[j]
j = j + 1
k = k + 1
while i < len(leftList):
myList[k] = leftList[i]
i = i + 1
k = k + 1
while j < len(rightList):
myList[k] = rightList[j]
j = j + 1
k = k + 1
print('Merging ', myList)
my_list = [3, 1, 4, 10, 9, 6, 2, 5, 8, 7]
merge_sort(myList)
print(myList) |
while True:
relax = master.relax()
relax.optimize()
pi = [c.Pi for c in relax.getConstrs()]
knapsack = Model("KP")
knapsack.ModelSense=-1
y = {}
for i in range(m):
y[i] = knapsack.addVar(ub=q[i], vtype="I", name="y[%d]"%i)
knapsack.update()
knapsack.addConstr(quicksum(w[i]*y[i] for i in range(m)) <= B, "width")
knapsack.setObjective(quicksum(pi[i]*y[i] for i in range(m)), GRB.MAXIMIZE)
knapsack.optimize()
if knapsack.ObjVal < 1+EPS:
break
pat = [int(y[i].X+0.5) for i in y]
t.append(pat)
col = Column()
for i in range(m):
if t[K][i] > 0:
col.addTerms(t[K][i], orders[i])
x[K] = master.addVar(obj=1, vtype="I", name="x[%d]"%K, column=col)
master.update()
K += 1
master.optimize()
rolls = []
for k in x:
for j in range(int(x[k].X + .5)):
rolls.append(sorted([w[i] for i in range(m) if t[k][i]>0 for j in range(t[k][i])]))
rolls.sort()
return rolls
t = []
m = len(w)
for i in range(m):
pat = [0]*m
pat[i] = int(B/w[i])
t.append(pat) | while True:
relax = master.relax()
relax.optimize()
pi = [c.Pi for c in relax.getConstrs()]
knapsack = model('KP')
knapsack.ModelSense = -1
y = {}
for i in range(m):
y[i] = knapsack.addVar(ub=q[i], vtype='I', name='y[%d]' % i)
knapsack.update()
knapsack.addConstr(quicksum((w[i] * y[i] for i in range(m))) <= B, 'width')
knapsack.setObjective(quicksum((pi[i] * y[i] for i in range(m))), GRB.MAXIMIZE)
knapsack.optimize()
if knapsack.ObjVal < 1 + EPS:
break
pat = [int(y[i].X + 0.5) for i in y]
t.append(pat)
col = column()
for i in range(m):
if t[K][i] > 0:
col.addTerms(t[K][i], orders[i])
x[K] = master.addVar(obj=1, vtype='I', name='x[%d]' % K, column=col)
master.update()
k += 1
master.optimize()
rolls = []
for k in x:
for j in range(int(x[k].X + 0.5)):
rolls.append(sorted([w[i] for i in range(m) if t[k][i] > 0 for j in range(t[k][i])]))
rolls.sort()
return rolls
t = []
m = len(w)
for i in range(m):
pat = [0] * m
pat[i] = int(B / w[i])
t.append(pat) |
def hasDoubleDigits(p):
previous = ''
for c in p:
if c == previous:
return True
previous = c
return False
def neverDecreases(p):
previous = -1
for c in p:
current = int(c)
if current < previous:
return False
previous = current
return True
def isValidPassword(p):
return hasDoubleDigits(p) and neverDecreases(p)
def findNumberOfPasswords(min, max):
current = min
count = 0
while current <= max:
s = str(current)
if isValidPassword(s):
count += 1
current += 1
return count
MIN_VALUE = 245182
MAX_VALUE = 790572
print(findNumberOfPasswords(MIN_VALUE, MAX_VALUE))
| def has_double_digits(p):
previous = ''
for c in p:
if c == previous:
return True
previous = c
return False
def never_decreases(p):
previous = -1
for c in p:
current = int(c)
if current < previous:
return False
previous = current
return True
def is_valid_password(p):
return has_double_digits(p) and never_decreases(p)
def find_number_of_passwords(min, max):
current = min
count = 0
while current <= max:
s = str(current)
if is_valid_password(s):
count += 1
current += 1
return count
min_value = 245182
max_value = 790572
print(find_number_of_passwords(MIN_VALUE, MAX_VALUE)) |
# a red shadow with some blur and a offset
cmykShadow((3, 3), 10, (1, 0, 0, 0))
# draw a rect
rect(100, 100, 30, 30) | cmyk_shadow((3, 3), 10, (1, 0, 0, 0))
rect(100, 100, 30, 30) |
#
# PySNMP MIB module NSLDAP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/NSLDAP-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:25:08 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
ObjectIdentifier, OctetString, Integer = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "OctetString", "Integer")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsIntersection, ConstraintsUnion, ValueSizeConstraint, ValueRangeConstraint, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ConstraintsUnion", "ValueSizeConstraint", "ValueRangeConstraint", "SingleValueConstraint")
URLString, DistinguishedName, applIndex = mibBuilder.importSymbols("NETWORK-SERVICES-MIB", "URLString", "DistinguishedName", "applIndex")
ObjectGroup, ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ObjectGroup", "ModuleCompliance", "NotificationGroup")
iso, NotificationType, Integer32, Counter32, ObjectIdentity, ModuleIdentity, Counter64, Gauge32, Unsigned32, MibScalar, MibTable, MibTableRow, MibTableColumn, NotificationType, Bits, MibIdentifier, TimeTicks, enterprises, IpAddress = mibBuilder.importSymbols("SNMPv2-SMI", "iso", "NotificationType", "Integer32", "Counter32", "ObjectIdentity", "ModuleIdentity", "Counter64", "Gauge32", "Unsigned32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "NotificationType", "Bits", "MibIdentifier", "TimeTicks", "enterprises", "IpAddress")
DisplayString, TimeStamp, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TimeStamp", "TextualConvention")
netscape = MibIdentifier((1, 3, 6, 1, 4, 1, 1450))
nsldap = ModuleIdentity((1, 3, 6, 1, 4, 1, 1450, 7))
if mibBuilder.loadTexts: nsldap.setLastUpdated('9707310000Z')
if mibBuilder.loadTexts: nsldap.setOrganization('Netscape Communications Corp')
if mibBuilder.loadTexts: nsldap.setContactInfo(' Frank Chen Postal: Netscape Communications Corp 501 East Middlefield Rd Mountain View, CA 94043 Tel: (415) 937 - 3703 Fax: (415) 937 - 4164 E-mail: frank@netscape.com')
if mibBuilder.loadTexts: nsldap.setDescription(' An implementation of the MADMAN mib for monitoring LDAP/CLDAP and X.500 directories described in internet draft: draft-ietf-madman-ds-mib-103.txt used for iPlanet Directory Server 5')
dsOpsTable = MibTable((1, 3, 6, 1, 4, 1, 1450, 7, 1), )
if mibBuilder.loadTexts: dsOpsTable.setStatus('current')
if mibBuilder.loadTexts: dsOpsTable.setDescription(' The table holding information related to the DS operations.')
dsOpsEntry = MibTableRow((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1), ).setIndexNames((0, "NETWORK-SERVICES-MIB", "applIndex"))
if mibBuilder.loadTexts: dsOpsEntry.setStatus('current')
if mibBuilder.loadTexts: dsOpsEntry.setDescription(' Entry containing operations related statistics for a DS.')
dsAnonymousBinds = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 1), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dsAnonymousBinds.setStatus('current')
if mibBuilder.loadTexts: dsAnonymousBinds.setDescription(' Number of anonymous binds to this DS from UAs since application start.')
dsUnAuthBinds = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 2), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dsUnAuthBinds.setStatus('current')
if mibBuilder.loadTexts: dsUnAuthBinds.setDescription(' Number of un-authenticated binds to this DS since application start.')
dsSimpleAuthBinds = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 3), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dsSimpleAuthBinds.setReference(' CCITT Blue Book Fascicle VIII.8 - Rec. X.511, 1988: Section 8.1.2.1.1. and, RFC1777 Section 4.1')
if mibBuilder.loadTexts: dsSimpleAuthBinds.setStatus('current')
if mibBuilder.loadTexts: dsSimpleAuthBinds.setDescription(' Number of binds to this DS that were authenticated using simple authentication procedures since application start.')
dsStrongAuthBinds = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 4), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dsStrongAuthBinds.setReference(' CCITT Blue Book Fascicle VIII.8 - Rec. X.511, 1988: Sections 8.1.2.1.2 & 8.1.2.1.3. and, RFC1777 Section 4.1.')
if mibBuilder.loadTexts: dsStrongAuthBinds.setStatus('current')
if mibBuilder.loadTexts: dsStrongAuthBinds.setDescription(' Number of binds to this DS that were authenticated using the strong authentication procedures since application start. This includes the binds that were authenticated using external authentication procedures.')
dsBindSecurityErrors = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 5), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dsBindSecurityErrors.setReference(' CCITT Blue Book Fascicle VIII.8 - Rec. X.511, 1988: Section 12.7.2 and, RFC1777 Section 4.')
if mibBuilder.loadTexts: dsBindSecurityErrors.setStatus('current')
if mibBuilder.loadTexts: dsBindSecurityErrors.setDescription(' Number of bind operations that have been rejected by this DS due to inappropriateAuthentication or invalidCredentials.')
dsInOps = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 6), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dsInOps.setStatus('current')
if mibBuilder.loadTexts: dsInOps.setDescription(' Number of operations forwarded to this DS from UAs or other DSs since application start up.')
dsReadOps = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 7), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dsReadOps.setReference(' CCITT Blue Book Fascicle VIII.8 - Rec. X.511, 1988: Section 9.1.')
if mibBuilder.loadTexts: dsReadOps.setStatus('current')
if mibBuilder.loadTexts: dsReadOps.setDescription(' Number of read operations serviced by this DS since application startup.')
dsCompareOps = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 8), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dsCompareOps.setReference(' CCITT Blue Book Fascicle VIII.8 - Rec. X.511, 1988: Section 9.2. and, RFC1777 section 4.8')
if mibBuilder.loadTexts: dsCompareOps.setStatus('current')
if mibBuilder.loadTexts: dsCompareOps.setDescription(' Number of compare operations serviced by this DS since application startup.')
dsAddEntryOps = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 9), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dsAddEntryOps.setReference(' CCITT Blue Book Fascicle VIII.8 - Rec. X.511, 1988: Section 11.1. and, RFC1777 Section 4.5.')
if mibBuilder.loadTexts: dsAddEntryOps.setStatus('current')
if mibBuilder.loadTexts: dsAddEntryOps.setDescription(' Number of addEntry operations serviced by this DS since application startup.')
dsRemoveEntryOps = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 10), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dsRemoveEntryOps.setReference(' CCITT Blue Book Fascicle VIII.8 - Rec. X.511, 1988: Section 11.2. and, RFC1777 Section 4.6.')
if mibBuilder.loadTexts: dsRemoveEntryOps.setStatus('current')
if mibBuilder.loadTexts: dsRemoveEntryOps.setDescription(' Number of removeEntry operations serviced by this DS since application startup.')
dsModifyEntryOps = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 11), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dsModifyEntryOps.setReference(' CCITT Blue Book Fascicle VIII.8 - Rec. X.511, 1988: Section 11.3. and, RFC1777 Section 4.4.')
if mibBuilder.loadTexts: dsModifyEntryOps.setStatus('current')
if mibBuilder.loadTexts: dsModifyEntryOps.setDescription(' Number of modifyEntry operations serviced by this DS since application startup.')
dsModifyRDNOps = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 12), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dsModifyRDNOps.setReference(' CCITT Blue Book Fascicle VIII.8 - Rec. X.511, 1988: Section 11.4.and, RFC1777 Section 4.7')
if mibBuilder.loadTexts: dsModifyRDNOps.setStatus('current')
if mibBuilder.loadTexts: dsModifyRDNOps.setDescription(' Number of modifyRDN operations serviced by this DS since application startup.')
dsListOps = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 13), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dsListOps.setReference(' CCITT Blue Book Fascicle VIII.8 - Rec. X.511, 1988: Section 10.1.')
if mibBuilder.loadTexts: dsListOps.setStatus('current')
if mibBuilder.loadTexts: dsListOps.setDescription(' Number of list operations serviced by this DS since application startup.')
dsSearchOps = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 14), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dsSearchOps.setReference(' CCITT Blue Book Fascicle VIII.8 - Rec. X.511, 1988: Section 10.2. and, RFC1777 Section 4.3.')
if mibBuilder.loadTexts: dsSearchOps.setStatus('current')
if mibBuilder.loadTexts: dsSearchOps.setDescription(' Number of search operations- baseObject searches, oneLevel searches and wholeSubtree searches, serviced by this DS since application startup.')
dsOneLevelSearchOps = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 15), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dsOneLevelSearchOps.setReference(' CCITT Blue Book Fascicle VIII.8 - Rec. X.511, 1988: Section 10.2.2.2. and, RFC1777 Section 4.3.')
if mibBuilder.loadTexts: dsOneLevelSearchOps.setStatus('current')
if mibBuilder.loadTexts: dsOneLevelSearchOps.setDescription(' Number of oneLevel search operations serviced by this DS since application startup.')
dsWholeSubtreeSearchOps = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 16), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dsWholeSubtreeSearchOps.setReference(' CCITT Blue Book Fascicle VIII.8 - Rec. X.511, 1988: Section 10.2.2.2. and, RFC1777 Section 4.3.')
if mibBuilder.loadTexts: dsWholeSubtreeSearchOps.setStatus('current')
if mibBuilder.loadTexts: dsWholeSubtreeSearchOps.setDescription(' Number of wholeSubtree search operations serviced by this DS since application startup.')
dsReferrals = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 17), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dsReferrals.setReference(' CCITT Blue Book Fascicle VIII.8 - Rec. X.511, 1988: Section 12.6.')
if mibBuilder.loadTexts: dsReferrals.setStatus('current')
if mibBuilder.loadTexts: dsReferrals.setDescription(' Number of referrals returned by this DS in response to requests for operations since application startup.')
dsChainings = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 18), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dsChainings.setReference(' CCITT Blue Book Fascicle VIII.8 - Rec. X.518, 1988: Section 14.')
if mibBuilder.loadTexts: dsChainings.setStatus('current')
if mibBuilder.loadTexts: dsChainings.setDescription(' Number of operations forwarded by this DS to other DSs since application startup.')
dsSecurityErrors = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 19), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dsSecurityErrors.setReference(' CCITT Blue Book Fascicle VIII.8 - Rec. X.511, 1988: Section 12.7. and, RFC1777 Section 4.')
if mibBuilder.loadTexts: dsSecurityErrors.setStatus('current')
if mibBuilder.loadTexts: dsSecurityErrors.setDescription(' Number of operations forwarded to this DS which did not meet the security requirements. ')
dsErrors = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 20), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dsErrors.setReference(' CCITT Blue Book Fascicle VIII.8 - Rec. X.511, 1988: Sections 12.4, 12.5, 12.8 & 12.9. and, RFC1777 Section 4.')
if mibBuilder.loadTexts: dsErrors.setStatus('current')
if mibBuilder.loadTexts: dsErrors.setDescription(' Number of operations that could not be serviced due to errors other than security errors, and referrals. A partially serviced operation will not be counted as an error. The errors include NameErrors, UpdateErrors, Attribute errors and ServiceErrors.')
dsEntriesTable = MibTable((1, 3, 6, 1, 4, 1, 1450, 7, 2), )
if mibBuilder.loadTexts: dsEntriesTable.setStatus('current')
if mibBuilder.loadTexts: dsEntriesTable.setDescription(' The table holding information related to the entry statistics and cache performance of the DSs.')
dsEntriesEntry = MibTableRow((1, 3, 6, 1, 4, 1, 1450, 7, 2, 1), ).setIndexNames((0, "NETWORK-SERVICES-MIB", "applIndex"))
if mibBuilder.loadTexts: dsEntriesEntry.setStatus('current')
if mibBuilder.loadTexts: dsEntriesEntry.setDescription(' Entry containing statistics pertaining to entries held by a DS.')
dsMasterEntries = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 2, 1, 1), Gauge32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dsMasterEntries.setStatus('current')
if mibBuilder.loadTexts: dsMasterEntries.setDescription(' Number of entries mastered in the DS.')
dsCopyEntries = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 2, 1, 2), Gauge32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dsCopyEntries.setStatus('current')
if mibBuilder.loadTexts: dsCopyEntries.setDescription(' Number of entries for which systematic (slave) copies are maintained in the DS.')
dsCacheEntries = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 2, 1, 3), Gauge32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dsCacheEntries.setStatus('current')
if mibBuilder.loadTexts: dsCacheEntries.setDescription(' Number of entries cached (non-systematic copies) in the DS. This will include the entries that are cached partially. The negative cache is not counted.')
dsCacheHits = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 2, 1, 4), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dsCacheHits.setStatus('current')
if mibBuilder.loadTexts: dsCacheHits.setDescription(' Number of operations that were serviced from the locally held cache since application startup.')
dsSlaveHits = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 2, 1, 5), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dsSlaveHits.setStatus('current')
if mibBuilder.loadTexts: dsSlaveHits.setDescription(' Number of operations that were serviced from the locally held object replications ( shadow entries) since application startup.')
dsIntTable = MibTable((1, 3, 6, 1, 4, 1, 1450, 7, 3), )
if mibBuilder.loadTexts: dsIntTable.setStatus('current')
if mibBuilder.loadTexts: dsIntTable.setDescription(' Each row of this table contains some details related to the history of the interaction of the monitored DSs with their respective peer DSs.')
dsIntEntry = MibTableRow((1, 3, 6, 1, 4, 1, 1450, 7, 3, 1), ).setIndexNames((0, "NETWORK-SERVICES-MIB", "applIndex"), (0, "NSLDAP-MIB", "dsIntIndex"))
if mibBuilder.loadTexts: dsIntEntry.setStatus('current')
if mibBuilder.loadTexts: dsIntEntry.setDescription(' Entry containing interaction details of a DS with a peer DS.')
dsIntIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 3, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647)))
if mibBuilder.loadTexts: dsIntIndex.setStatus('current')
if mibBuilder.loadTexts: dsIntIndex.setDescription(' Together with applIndex it forms the unique key to identify the conceptual row which contains useful info on the (attempted) interaction between the DS (referred to by applIndex) and a peer DS.')
dsName = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 3, 1, 2), DistinguishedName()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dsName.setStatus('current')
if mibBuilder.loadTexts: dsName.setDescription(' Distinguished Name of the peer DS to which this entry pertains.')
dsTimeOfCreation = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 3, 1, 3), TimeStamp()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dsTimeOfCreation.setStatus('current')
if mibBuilder.loadTexts: dsTimeOfCreation.setDescription(' The value of sysUpTime when this row was created. If the entry was created before the network management subsystem was initialized, this object will contain a value of zero.')
dsTimeOfLastAttempt = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 3, 1, 4), TimeStamp()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dsTimeOfLastAttempt.setStatus('current')
if mibBuilder.loadTexts: dsTimeOfLastAttempt.setDescription(' The value of sysUpTime when the last attempt was made to contact this DS. If the last attempt was made before the network management subsystem was initialized, this object will contain a value of zero.')
dsTimeOfLastSuccess = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 3, 1, 5), TimeStamp()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dsTimeOfLastSuccess.setStatus('current')
if mibBuilder.loadTexts: dsTimeOfLastSuccess.setDescription(' The value of sysUpTime when the last attempt made to contact this DS was successful. If there have been no successful attempts this entry will have a value of zero. If the last successful attempt was made before the network management subsystem was initialized, this object will contain a value of zero.')
dsFailuresSinceLastSuccess = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 3, 1, 6), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dsFailuresSinceLastSuccess.setStatus('current')
if mibBuilder.loadTexts: dsFailuresSinceLastSuccess.setDescription(' The number of failures since the last time an attempt to contact this DS was successful. If there has been no successful attempts, this counter will contain the number of failures since this entry was created.')
dsFailures = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 3, 1, 7), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dsFailures.setStatus('current')
if mibBuilder.loadTexts: dsFailures.setDescription(' Cumulative failures since the creation of this entry.')
dsSuccesses = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 3, 1, 8), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dsSuccesses.setStatus('current')
if mibBuilder.loadTexts: dsSuccesses.setDescription(' Cumulative successes since the creation of this entry.')
dsURL = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 3, 1, 9), URLString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dsURL.setStatus('current')
if mibBuilder.loadTexts: dsURL.setDescription(' URL of the DS application.')
dsEntityTable = MibTable((1, 3, 6, 1, 4, 1, 1450, 7, 5), )
if mibBuilder.loadTexts: dsEntityTable.setStatus('current')
if mibBuilder.loadTexts: dsEntityTable.setDescription('This table holds general information related to an installed instance of a directory server')
dsEntityEntry = MibTableRow((1, 3, 6, 1, 4, 1, 1450, 7, 5, 1), ).setIndexNames((0, "NETWORK-SERVICES-MIB", "applIndex"))
if mibBuilder.loadTexts: dsEntityEntry.setStatus('current')
if mibBuilder.loadTexts: dsEntityEntry.setDescription('Entry of general information about an installed instance of a directory server')
dsEntityDescr = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 5, 1, 1), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: dsEntityDescr.setStatus('mandatory')
if mibBuilder.loadTexts: dsEntityDescr.setDescription('A general textual description of this directory server.')
dsEntityVers = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 5, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: dsEntityVers.setStatus('mandatory')
if mibBuilder.loadTexts: dsEntityVers.setDescription('The version of this directory server')
dsEntityOrg = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 5, 1, 3), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: dsEntityOrg.setStatus('mandatory')
if mibBuilder.loadTexts: dsEntityOrg.setDescription('Organization responsible for directory server at this installation')
dsEntityLocation = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 5, 1, 4), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: dsEntityLocation.setStatus('mandatory')
if mibBuilder.loadTexts: dsEntityLocation.setDescription('Physical location of this entity (directory server). For example: hostname, building number, lab number, etc.')
dsEntityContact = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 5, 1, 5), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: dsEntityContact.setStatus('mandatory')
if mibBuilder.loadTexts: dsEntityContact.setDescription('Contact person(s)responsible for the directory server at this installation, together with information on how to conact.')
dsEntityName = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 5, 1, 6), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: dsEntityName.setStatus('mandatory')
if mibBuilder.loadTexts: dsEntityName.setDescription('Name assigned to this entity at the installation site')
nsDirectoryServerDown = NotificationType((1, 3, 6, 1, 4, 1, 1450) + (0,7001)).setObjects(("NSLDAP-MIB", "dsEntityDescr"), ("NSLDAP-MIB", "dsEntityVers"), ("NSLDAP-MIB", "dsEntityLocation"), ("NSLDAP-MIB", "dsEntityContact"))
if mibBuilder.loadTexts: nsDirectoryServerDown.setDescription('This trap is generated whenever the agent detects the directory server to be (potentially) Down.')
nsDirectoryServerStart = NotificationType((1, 3, 6, 1, 4, 1, 1450) + (0,7002)).setObjects(("NSLDAP-MIB", "dsEntityDescr"), ("NSLDAP-MIB", "dsEntityVers"), ("NSLDAP-MIB", "dsEntityLocation"))
if mibBuilder.loadTexts: nsDirectoryServerStart.setDescription('This trap is generated whenever the agent detects the directory server to have (re)started.')
mibBuilder.exportSymbols("NSLDAP-MIB", dsEntityTable=dsEntityTable, dsSuccesses=dsSuccesses, dsOpsTable=dsOpsTable, dsAnonymousBinds=dsAnonymousBinds, dsReadOps=dsReadOps, dsOpsEntry=dsOpsEntry, dsErrors=dsErrors, nsDirectoryServerDown=nsDirectoryServerDown, dsSimpleAuthBinds=dsSimpleAuthBinds, netscape=netscape, nsDirectoryServerStart=nsDirectoryServerStart, dsEntriesTable=dsEntriesTable, dsSearchOps=dsSearchOps, dsModifyEntryOps=dsModifyEntryOps, dsEntityVers=dsEntityVers, dsFailures=dsFailures, dsOneLevelSearchOps=dsOneLevelSearchOps, dsSecurityErrors=dsSecurityErrors, dsMasterEntries=dsMasterEntries, dsChainings=dsChainings, dsEntityName=dsEntityName, dsBindSecurityErrors=dsBindSecurityErrors, dsCacheEntries=dsCacheEntries, dsInOps=dsInOps, dsCompareOps=dsCompareOps, dsRemoveEntryOps=dsRemoveEntryOps, dsWholeSubtreeSearchOps=dsWholeSubtreeSearchOps, dsReferrals=dsReferrals, dsEntityOrg=dsEntityOrg, dsSlaveHits=dsSlaveHits, dsName=dsName, dsListOps=dsListOps, dsModifyRDNOps=dsModifyRDNOps, dsTimeOfLastAttempt=dsTimeOfLastAttempt, nsldap=nsldap, dsEntityLocation=dsEntityLocation, dsURL=dsURL, dsEntityEntry=dsEntityEntry, dsIntTable=dsIntTable, PYSNMP_MODULE_ID=nsldap, dsCacheHits=dsCacheHits, dsIntIndex=dsIntIndex, dsFailuresSinceLastSuccess=dsFailuresSinceLastSuccess, dsStrongAuthBinds=dsStrongAuthBinds, dsTimeOfLastSuccess=dsTimeOfLastSuccess, dsEntityContact=dsEntityContact, dsAddEntryOps=dsAddEntryOps, dsTimeOfCreation=dsTimeOfCreation, dsEntityDescr=dsEntityDescr, dsCopyEntries=dsCopyEntries, dsIntEntry=dsIntEntry, dsUnAuthBinds=dsUnAuthBinds, dsEntriesEntry=dsEntriesEntry)
| (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, constraints_union, value_size_constraint, value_range_constraint, single_value_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsIntersection', 'ConstraintsUnion', 'ValueSizeConstraint', 'ValueRangeConstraint', 'SingleValueConstraint')
(url_string, distinguished_name, appl_index) = mibBuilder.importSymbols('NETWORK-SERVICES-MIB', 'URLString', 'DistinguishedName', 'applIndex')
(object_group, module_compliance, notification_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ObjectGroup', 'ModuleCompliance', 'NotificationGroup')
(iso, notification_type, integer32, counter32, object_identity, module_identity, counter64, gauge32, unsigned32, mib_scalar, mib_table, mib_table_row, mib_table_column, notification_type, bits, mib_identifier, time_ticks, enterprises, ip_address) = mibBuilder.importSymbols('SNMPv2-SMI', 'iso', 'NotificationType', 'Integer32', 'Counter32', 'ObjectIdentity', 'ModuleIdentity', 'Counter64', 'Gauge32', 'Unsigned32', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'NotificationType', 'Bits', 'MibIdentifier', 'TimeTicks', 'enterprises', 'IpAddress')
(display_string, time_stamp, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'TimeStamp', 'TextualConvention')
netscape = mib_identifier((1, 3, 6, 1, 4, 1, 1450))
nsldap = module_identity((1, 3, 6, 1, 4, 1, 1450, 7))
if mibBuilder.loadTexts:
nsldap.setLastUpdated('9707310000Z')
if mibBuilder.loadTexts:
nsldap.setOrganization('Netscape Communications Corp')
if mibBuilder.loadTexts:
nsldap.setContactInfo(' Frank Chen Postal: Netscape Communications Corp 501 East Middlefield Rd Mountain View, CA 94043 Tel: (415) 937 - 3703 Fax: (415) 937 - 4164 E-mail: frank@netscape.com')
if mibBuilder.loadTexts:
nsldap.setDescription(' An implementation of the MADMAN mib for monitoring LDAP/CLDAP and X.500 directories described in internet draft: draft-ietf-madman-ds-mib-103.txt used for iPlanet Directory Server 5')
ds_ops_table = mib_table((1, 3, 6, 1, 4, 1, 1450, 7, 1))
if mibBuilder.loadTexts:
dsOpsTable.setStatus('current')
if mibBuilder.loadTexts:
dsOpsTable.setDescription(' The table holding information related to the DS operations.')
ds_ops_entry = mib_table_row((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1)).setIndexNames((0, 'NETWORK-SERVICES-MIB', 'applIndex'))
if mibBuilder.loadTexts:
dsOpsEntry.setStatus('current')
if mibBuilder.loadTexts:
dsOpsEntry.setDescription(' Entry containing operations related statistics for a DS.')
ds_anonymous_binds = mib_table_column((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 1), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dsAnonymousBinds.setStatus('current')
if mibBuilder.loadTexts:
dsAnonymousBinds.setDescription(' Number of anonymous binds to this DS from UAs since application start.')
ds_un_auth_binds = mib_table_column((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 2), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dsUnAuthBinds.setStatus('current')
if mibBuilder.loadTexts:
dsUnAuthBinds.setDescription(' Number of un-authenticated binds to this DS since application start.')
ds_simple_auth_binds = mib_table_column((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 3), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dsSimpleAuthBinds.setReference(' CCITT Blue Book Fascicle VIII.8 - Rec. X.511, 1988: Section 8.1.2.1.1. and, RFC1777 Section 4.1')
if mibBuilder.loadTexts:
dsSimpleAuthBinds.setStatus('current')
if mibBuilder.loadTexts:
dsSimpleAuthBinds.setDescription(' Number of binds to this DS that were authenticated using simple authentication procedures since application start.')
ds_strong_auth_binds = mib_table_column((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 4), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dsStrongAuthBinds.setReference(' CCITT Blue Book Fascicle VIII.8 - Rec. X.511, 1988: Sections 8.1.2.1.2 & 8.1.2.1.3. and, RFC1777 Section 4.1.')
if mibBuilder.loadTexts:
dsStrongAuthBinds.setStatus('current')
if mibBuilder.loadTexts:
dsStrongAuthBinds.setDescription(' Number of binds to this DS that were authenticated using the strong authentication procedures since application start. This includes the binds that were authenticated using external authentication procedures.')
ds_bind_security_errors = mib_table_column((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 5), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dsBindSecurityErrors.setReference(' CCITT Blue Book Fascicle VIII.8 - Rec. X.511, 1988: Section 12.7.2 and, RFC1777 Section 4.')
if mibBuilder.loadTexts:
dsBindSecurityErrors.setStatus('current')
if mibBuilder.loadTexts:
dsBindSecurityErrors.setDescription(' Number of bind operations that have been rejected by this DS due to inappropriateAuthentication or invalidCredentials.')
ds_in_ops = mib_table_column((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 6), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dsInOps.setStatus('current')
if mibBuilder.loadTexts:
dsInOps.setDescription(' Number of operations forwarded to this DS from UAs or other DSs since application start up.')
ds_read_ops = mib_table_column((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 7), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dsReadOps.setReference(' CCITT Blue Book Fascicle VIII.8 - Rec. X.511, 1988: Section 9.1.')
if mibBuilder.loadTexts:
dsReadOps.setStatus('current')
if mibBuilder.loadTexts:
dsReadOps.setDescription(' Number of read operations serviced by this DS since application startup.')
ds_compare_ops = mib_table_column((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 8), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dsCompareOps.setReference(' CCITT Blue Book Fascicle VIII.8 - Rec. X.511, 1988: Section 9.2. and, RFC1777 section 4.8')
if mibBuilder.loadTexts:
dsCompareOps.setStatus('current')
if mibBuilder.loadTexts:
dsCompareOps.setDescription(' Number of compare operations serviced by this DS since application startup.')
ds_add_entry_ops = mib_table_column((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 9), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dsAddEntryOps.setReference(' CCITT Blue Book Fascicle VIII.8 - Rec. X.511, 1988: Section 11.1. and, RFC1777 Section 4.5.')
if mibBuilder.loadTexts:
dsAddEntryOps.setStatus('current')
if mibBuilder.loadTexts:
dsAddEntryOps.setDescription(' Number of addEntry operations serviced by this DS since application startup.')
ds_remove_entry_ops = mib_table_column((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 10), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dsRemoveEntryOps.setReference(' CCITT Blue Book Fascicle VIII.8 - Rec. X.511, 1988: Section 11.2. and, RFC1777 Section 4.6.')
if mibBuilder.loadTexts:
dsRemoveEntryOps.setStatus('current')
if mibBuilder.loadTexts:
dsRemoveEntryOps.setDescription(' Number of removeEntry operations serviced by this DS since application startup.')
ds_modify_entry_ops = mib_table_column((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 11), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dsModifyEntryOps.setReference(' CCITT Blue Book Fascicle VIII.8 - Rec. X.511, 1988: Section 11.3. and, RFC1777 Section 4.4.')
if mibBuilder.loadTexts:
dsModifyEntryOps.setStatus('current')
if mibBuilder.loadTexts:
dsModifyEntryOps.setDescription(' Number of modifyEntry operations serviced by this DS since application startup.')
ds_modify_rdn_ops = mib_table_column((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 12), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dsModifyRDNOps.setReference(' CCITT Blue Book Fascicle VIII.8 - Rec. X.511, 1988: Section 11.4.and, RFC1777 Section 4.7')
if mibBuilder.loadTexts:
dsModifyRDNOps.setStatus('current')
if mibBuilder.loadTexts:
dsModifyRDNOps.setDescription(' Number of modifyRDN operations serviced by this DS since application startup.')
ds_list_ops = mib_table_column((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 13), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dsListOps.setReference(' CCITT Blue Book Fascicle VIII.8 - Rec. X.511, 1988: Section 10.1.')
if mibBuilder.loadTexts:
dsListOps.setStatus('current')
if mibBuilder.loadTexts:
dsListOps.setDescription(' Number of list operations serviced by this DS since application startup.')
ds_search_ops = mib_table_column((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 14), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dsSearchOps.setReference(' CCITT Blue Book Fascicle VIII.8 - Rec. X.511, 1988: Section 10.2. and, RFC1777 Section 4.3.')
if mibBuilder.loadTexts:
dsSearchOps.setStatus('current')
if mibBuilder.loadTexts:
dsSearchOps.setDescription(' Number of search operations- baseObject searches, oneLevel searches and wholeSubtree searches, serviced by this DS since application startup.')
ds_one_level_search_ops = mib_table_column((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 15), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dsOneLevelSearchOps.setReference(' CCITT Blue Book Fascicle VIII.8 - Rec. X.511, 1988: Section 10.2.2.2. and, RFC1777 Section 4.3.')
if mibBuilder.loadTexts:
dsOneLevelSearchOps.setStatus('current')
if mibBuilder.loadTexts:
dsOneLevelSearchOps.setDescription(' Number of oneLevel search operations serviced by this DS since application startup.')
ds_whole_subtree_search_ops = mib_table_column((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 16), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dsWholeSubtreeSearchOps.setReference(' CCITT Blue Book Fascicle VIII.8 - Rec. X.511, 1988: Section 10.2.2.2. and, RFC1777 Section 4.3.')
if mibBuilder.loadTexts:
dsWholeSubtreeSearchOps.setStatus('current')
if mibBuilder.loadTexts:
dsWholeSubtreeSearchOps.setDescription(' Number of wholeSubtree search operations serviced by this DS since application startup.')
ds_referrals = mib_table_column((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 17), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dsReferrals.setReference(' CCITT Blue Book Fascicle VIII.8 - Rec. X.511, 1988: Section 12.6.')
if mibBuilder.loadTexts:
dsReferrals.setStatus('current')
if mibBuilder.loadTexts:
dsReferrals.setDescription(' Number of referrals returned by this DS in response to requests for operations since application startup.')
ds_chainings = mib_table_column((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 18), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dsChainings.setReference(' CCITT Blue Book Fascicle VIII.8 - Rec. X.518, 1988: Section 14.')
if mibBuilder.loadTexts:
dsChainings.setStatus('current')
if mibBuilder.loadTexts:
dsChainings.setDescription(' Number of operations forwarded by this DS to other DSs since application startup.')
ds_security_errors = mib_table_column((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 19), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dsSecurityErrors.setReference(' CCITT Blue Book Fascicle VIII.8 - Rec. X.511, 1988: Section 12.7. and, RFC1777 Section 4.')
if mibBuilder.loadTexts:
dsSecurityErrors.setStatus('current')
if mibBuilder.loadTexts:
dsSecurityErrors.setDescription(' Number of operations forwarded to this DS which did not meet the security requirements. ')
ds_errors = mib_table_column((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 20), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dsErrors.setReference(' CCITT Blue Book Fascicle VIII.8 - Rec. X.511, 1988: Sections 12.4, 12.5, 12.8 & 12.9. and, RFC1777 Section 4.')
if mibBuilder.loadTexts:
dsErrors.setStatus('current')
if mibBuilder.loadTexts:
dsErrors.setDescription(' Number of operations that could not be serviced due to errors other than security errors, and referrals. A partially serviced operation will not be counted as an error. The errors include NameErrors, UpdateErrors, Attribute errors and ServiceErrors.')
ds_entries_table = mib_table((1, 3, 6, 1, 4, 1, 1450, 7, 2))
if mibBuilder.loadTexts:
dsEntriesTable.setStatus('current')
if mibBuilder.loadTexts:
dsEntriesTable.setDescription(' The table holding information related to the entry statistics and cache performance of the DSs.')
ds_entries_entry = mib_table_row((1, 3, 6, 1, 4, 1, 1450, 7, 2, 1)).setIndexNames((0, 'NETWORK-SERVICES-MIB', 'applIndex'))
if mibBuilder.loadTexts:
dsEntriesEntry.setStatus('current')
if mibBuilder.loadTexts:
dsEntriesEntry.setDescription(' Entry containing statistics pertaining to entries held by a DS.')
ds_master_entries = mib_table_column((1, 3, 6, 1, 4, 1, 1450, 7, 2, 1, 1), gauge32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dsMasterEntries.setStatus('current')
if mibBuilder.loadTexts:
dsMasterEntries.setDescription(' Number of entries mastered in the DS.')
ds_copy_entries = mib_table_column((1, 3, 6, 1, 4, 1, 1450, 7, 2, 1, 2), gauge32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dsCopyEntries.setStatus('current')
if mibBuilder.loadTexts:
dsCopyEntries.setDescription(' Number of entries for which systematic (slave) copies are maintained in the DS.')
ds_cache_entries = mib_table_column((1, 3, 6, 1, 4, 1, 1450, 7, 2, 1, 3), gauge32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dsCacheEntries.setStatus('current')
if mibBuilder.loadTexts:
dsCacheEntries.setDescription(' Number of entries cached (non-systematic copies) in the DS. This will include the entries that are cached partially. The negative cache is not counted.')
ds_cache_hits = mib_table_column((1, 3, 6, 1, 4, 1, 1450, 7, 2, 1, 4), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dsCacheHits.setStatus('current')
if mibBuilder.loadTexts:
dsCacheHits.setDescription(' Number of operations that were serviced from the locally held cache since application startup.')
ds_slave_hits = mib_table_column((1, 3, 6, 1, 4, 1, 1450, 7, 2, 1, 5), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dsSlaveHits.setStatus('current')
if mibBuilder.loadTexts:
dsSlaveHits.setDescription(' Number of operations that were serviced from the locally held object replications ( shadow entries) since application startup.')
ds_int_table = mib_table((1, 3, 6, 1, 4, 1, 1450, 7, 3))
if mibBuilder.loadTexts:
dsIntTable.setStatus('current')
if mibBuilder.loadTexts:
dsIntTable.setDescription(' Each row of this table contains some details related to the history of the interaction of the monitored DSs with their respective peer DSs.')
ds_int_entry = mib_table_row((1, 3, 6, 1, 4, 1, 1450, 7, 3, 1)).setIndexNames((0, 'NETWORK-SERVICES-MIB', 'applIndex'), (0, 'NSLDAP-MIB', 'dsIntIndex'))
if mibBuilder.loadTexts:
dsIntEntry.setStatus('current')
if mibBuilder.loadTexts:
dsIntEntry.setDescription(' Entry containing interaction details of a DS with a peer DS.')
ds_int_index = mib_table_column((1, 3, 6, 1, 4, 1, 1450, 7, 3, 1, 1), integer32().subtype(subtypeSpec=value_range_constraint(1, 2147483647)))
if mibBuilder.loadTexts:
dsIntIndex.setStatus('current')
if mibBuilder.loadTexts:
dsIntIndex.setDescription(' Together with applIndex it forms the unique key to identify the conceptual row which contains useful info on the (attempted) interaction between the DS (referred to by applIndex) and a peer DS.')
ds_name = mib_table_column((1, 3, 6, 1, 4, 1, 1450, 7, 3, 1, 2), distinguished_name()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dsName.setStatus('current')
if mibBuilder.loadTexts:
dsName.setDescription(' Distinguished Name of the peer DS to which this entry pertains.')
ds_time_of_creation = mib_table_column((1, 3, 6, 1, 4, 1, 1450, 7, 3, 1, 3), time_stamp()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dsTimeOfCreation.setStatus('current')
if mibBuilder.loadTexts:
dsTimeOfCreation.setDescription(' The value of sysUpTime when this row was created. If the entry was created before the network management subsystem was initialized, this object will contain a value of zero.')
ds_time_of_last_attempt = mib_table_column((1, 3, 6, 1, 4, 1, 1450, 7, 3, 1, 4), time_stamp()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dsTimeOfLastAttempt.setStatus('current')
if mibBuilder.loadTexts:
dsTimeOfLastAttempt.setDescription(' The value of sysUpTime when the last attempt was made to contact this DS. If the last attempt was made before the network management subsystem was initialized, this object will contain a value of zero.')
ds_time_of_last_success = mib_table_column((1, 3, 6, 1, 4, 1, 1450, 7, 3, 1, 5), time_stamp()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dsTimeOfLastSuccess.setStatus('current')
if mibBuilder.loadTexts:
dsTimeOfLastSuccess.setDescription(' The value of sysUpTime when the last attempt made to contact this DS was successful. If there have been no successful attempts this entry will have a value of zero. If the last successful attempt was made before the network management subsystem was initialized, this object will contain a value of zero.')
ds_failures_since_last_success = mib_table_column((1, 3, 6, 1, 4, 1, 1450, 7, 3, 1, 6), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dsFailuresSinceLastSuccess.setStatus('current')
if mibBuilder.loadTexts:
dsFailuresSinceLastSuccess.setDescription(' The number of failures since the last time an attempt to contact this DS was successful. If there has been no successful attempts, this counter will contain the number of failures since this entry was created.')
ds_failures = mib_table_column((1, 3, 6, 1, 4, 1, 1450, 7, 3, 1, 7), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dsFailures.setStatus('current')
if mibBuilder.loadTexts:
dsFailures.setDescription(' Cumulative failures since the creation of this entry.')
ds_successes = mib_table_column((1, 3, 6, 1, 4, 1, 1450, 7, 3, 1, 8), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dsSuccesses.setStatus('current')
if mibBuilder.loadTexts:
dsSuccesses.setDescription(' Cumulative successes since the creation of this entry.')
ds_url = mib_table_column((1, 3, 6, 1, 4, 1, 1450, 7, 3, 1, 9), url_string()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dsURL.setStatus('current')
if mibBuilder.loadTexts:
dsURL.setDescription(' URL of the DS application.')
ds_entity_table = mib_table((1, 3, 6, 1, 4, 1, 1450, 7, 5))
if mibBuilder.loadTexts:
dsEntityTable.setStatus('current')
if mibBuilder.loadTexts:
dsEntityTable.setDescription('This table holds general information related to an installed instance of a directory server')
ds_entity_entry = mib_table_row((1, 3, 6, 1, 4, 1, 1450, 7, 5, 1)).setIndexNames((0, 'NETWORK-SERVICES-MIB', 'applIndex'))
if mibBuilder.loadTexts:
dsEntityEntry.setStatus('current')
if mibBuilder.loadTexts:
dsEntityEntry.setDescription('Entry of general information about an installed instance of a directory server')
ds_entity_descr = mib_table_column((1, 3, 6, 1, 4, 1, 1450, 7, 5, 1, 1), display_string().subtype(subtypeSpec=value_size_constraint(0, 255))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dsEntityDescr.setStatus('mandatory')
if mibBuilder.loadTexts:
dsEntityDescr.setDescription('A general textual description of this directory server.')
ds_entity_vers = mib_table_column((1, 3, 6, 1, 4, 1, 1450, 7, 5, 1, 2), display_string().subtype(subtypeSpec=value_size_constraint(0, 255))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dsEntityVers.setStatus('mandatory')
if mibBuilder.loadTexts:
dsEntityVers.setDescription('The version of this directory server')
ds_entity_org = mib_table_column((1, 3, 6, 1, 4, 1, 1450, 7, 5, 1, 3), display_string().subtype(subtypeSpec=value_size_constraint(0, 255))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dsEntityOrg.setStatus('mandatory')
if mibBuilder.loadTexts:
dsEntityOrg.setDescription('Organization responsible for directory server at this installation')
ds_entity_location = mib_table_column((1, 3, 6, 1, 4, 1, 1450, 7, 5, 1, 4), display_string().subtype(subtypeSpec=value_size_constraint(0, 255))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dsEntityLocation.setStatus('mandatory')
if mibBuilder.loadTexts:
dsEntityLocation.setDescription('Physical location of this entity (directory server). For example: hostname, building number, lab number, etc.')
ds_entity_contact = mib_table_column((1, 3, 6, 1, 4, 1, 1450, 7, 5, 1, 5), display_string().subtype(subtypeSpec=value_size_constraint(0, 255))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dsEntityContact.setStatus('mandatory')
if mibBuilder.loadTexts:
dsEntityContact.setDescription('Contact person(s)responsible for the directory server at this installation, together with information on how to conact.')
ds_entity_name = mib_table_column((1, 3, 6, 1, 4, 1, 1450, 7, 5, 1, 6), display_string().subtype(subtypeSpec=value_size_constraint(0, 255))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dsEntityName.setStatus('mandatory')
if mibBuilder.loadTexts:
dsEntityName.setDescription('Name assigned to this entity at the installation site')
ns_directory_server_down = notification_type((1, 3, 6, 1, 4, 1, 1450) + (0, 7001)).setObjects(('NSLDAP-MIB', 'dsEntityDescr'), ('NSLDAP-MIB', 'dsEntityVers'), ('NSLDAP-MIB', 'dsEntityLocation'), ('NSLDAP-MIB', 'dsEntityContact'))
if mibBuilder.loadTexts:
nsDirectoryServerDown.setDescription('This trap is generated whenever the agent detects the directory server to be (potentially) Down.')
ns_directory_server_start = notification_type((1, 3, 6, 1, 4, 1, 1450) + (0, 7002)).setObjects(('NSLDAP-MIB', 'dsEntityDescr'), ('NSLDAP-MIB', 'dsEntityVers'), ('NSLDAP-MIB', 'dsEntityLocation'))
if mibBuilder.loadTexts:
nsDirectoryServerStart.setDescription('This trap is generated whenever the agent detects the directory server to have (re)started.')
mibBuilder.exportSymbols('NSLDAP-MIB', dsEntityTable=dsEntityTable, dsSuccesses=dsSuccesses, dsOpsTable=dsOpsTable, dsAnonymousBinds=dsAnonymousBinds, dsReadOps=dsReadOps, dsOpsEntry=dsOpsEntry, dsErrors=dsErrors, nsDirectoryServerDown=nsDirectoryServerDown, dsSimpleAuthBinds=dsSimpleAuthBinds, netscape=netscape, nsDirectoryServerStart=nsDirectoryServerStart, dsEntriesTable=dsEntriesTable, dsSearchOps=dsSearchOps, dsModifyEntryOps=dsModifyEntryOps, dsEntityVers=dsEntityVers, dsFailures=dsFailures, dsOneLevelSearchOps=dsOneLevelSearchOps, dsSecurityErrors=dsSecurityErrors, dsMasterEntries=dsMasterEntries, dsChainings=dsChainings, dsEntityName=dsEntityName, dsBindSecurityErrors=dsBindSecurityErrors, dsCacheEntries=dsCacheEntries, dsInOps=dsInOps, dsCompareOps=dsCompareOps, dsRemoveEntryOps=dsRemoveEntryOps, dsWholeSubtreeSearchOps=dsWholeSubtreeSearchOps, dsReferrals=dsReferrals, dsEntityOrg=dsEntityOrg, dsSlaveHits=dsSlaveHits, dsName=dsName, dsListOps=dsListOps, dsModifyRDNOps=dsModifyRDNOps, dsTimeOfLastAttempt=dsTimeOfLastAttempt, nsldap=nsldap, dsEntityLocation=dsEntityLocation, dsURL=dsURL, dsEntityEntry=dsEntityEntry, dsIntTable=dsIntTable, PYSNMP_MODULE_ID=nsldap, dsCacheHits=dsCacheHits, dsIntIndex=dsIntIndex, dsFailuresSinceLastSuccess=dsFailuresSinceLastSuccess, dsStrongAuthBinds=dsStrongAuthBinds, dsTimeOfLastSuccess=dsTimeOfLastSuccess, dsEntityContact=dsEntityContact, dsAddEntryOps=dsAddEntryOps, dsTimeOfCreation=dsTimeOfCreation, dsEntityDescr=dsEntityDescr, dsCopyEntries=dsCopyEntries, dsIntEntry=dsIntEntry, dsUnAuthBinds=dsUnAuthBinds, dsEntriesEntry=dsEntriesEntry) |
def deleteDigit(n):
n = str(n)
return max([int(n[:index] + n[index + 1:]) for index in range(len(n))])
print(deleteDigit(152)) | def delete_digit(n):
n = str(n)
return max([int(n[:index] + n[index + 1:]) for index in range(len(n))])
print(delete_digit(152)) |
# SPDX-FileCopyrightText: 2021 Neradoc NeraOnGit@ri1.fr
#
# SPDX-License-Identifier: MIT
"""
Extended list of consumer controls.
"""
__version__ = "0.0.0-auto.0"
__repo__ = "https://github.com/Neradoc/Circuitpython_Keyboard_Layouts.git"
class ConsumerControlExtended:
UNASSIGNED = 0x00
CONSUMER_CONTROL = 0x01
NUMERIC_KEY_PAD = 0x02
PROGRAMMABLE_BUTTONS = 0x03
PLUS10 = 0x20
PLUS100 = 0x21
AM_PM = 0x22 # AM/PM
AM = AM_PM
PM = AM_PM
POWER = 0x30
RESET = 0x31
SLEEP = 0x32
SLEEP_AFTER = 0x33
SLEEP_MODE = 0x34
ILLUMINATION = 0x35
FUNCTION_BUTTONS = 0x36
MENU = 0x40
MENU_PICK = 0x41
MENU_UP = 0x42
MENU_DOWN = 0x43
MENU_LEFT = 0x44
MENU_RIGHT = 0x45
MENU_ESCAPE = 0x46
MENU_VALUE_INCREASE = 0x47
MENU_VALUE_DECREASE = 0x48
DATA_ON_SCREEN = 0x60
CLOSED_CAPTION = 0x61
CLOSED_CAPTION_SELECT = 0x62
VCR_TV = 0x63 # VCR/TV
# VCR = VCR_TV
# TV = VCR_TV
BROADCAST_MODE = 0x64
SNAPSHOT = 0x65
STILL = 0x66
SELECTION = 0x80
ASSIGN_SELECTION = 0x81
MODE_STEP = 0x82
RECALL_LAST = 0x83
ENTER_CHANNEL = 0x84
ORDER_MOVIE = 0x85
CHANNEL = 0x86
MEDIA_SELECTION = 0x87
MEDIA_SELECT_COMPUTER = 0x88
MEDIA_SELECT_TV = 0x89
MEDIA_SELECT_WWW = 0x8A
MEDIA_SELECT_DVD = 0x8B
MEDIA_SELECT_TELEPHONE = 0x8C
MEDIA_SELECT_PROGRAM_GUIDE = 0x8D
MEDIA_SELECT_VIDEO_PHONE = 0x8E
MEDIA_SELECT_GAMES = 0x8F
MEDIA_SELECT_MESSAGES = 0x90
MEDIA_SELECT_CD = 0x91
MEDIA_SELECT_VCR = 0x92
MEDIA_SELECT_TUNER = 0x93
QUIT = 0x94
HELP = 0x95
MEDIA_SELECT_TAPE = 0x96
MEDIA_SELECT_CABLE = 0x97
MEDIA_SELECT_SATELLITE = 0x98
MEDIA_SELECT_SECURITY = 0x99
MEDIA_SELECT_HOME = 0x9A
MEDIA_SELECT_CALL = 0x9B
CHANNEL_INCREMENT = 0x9C
CHANNEL_DECREMENT = 0x9D
MEDIA_SELECT_SAP = 0x9E
VCR_PLUS = 0xA0
ONCE = 0xA1
DAILY = 0xA2
WEEKLY = 0xA3
MONTHLY = 0xA4
PLAY = 0xB0
PAUSE = 0xB1
RECORD = 0xB2
FAST_FORWARD = 0xB3
REWIND = 0xB4
SCAN_NEXT_TRACK = 0xB5
SCAN_PREVIOUS_TRACK = 0xB6
STOP = 0xB7
EJECT = 0xB8
RANDOM_PLAY = 0xB9
SELECT_DISC = 0xBA
ENTER_DISC = 0xBB
REPEAT = 0xBC
TRACKING = 0xBD
TRACK_NORMAL = 0xBE
SLOW_TRACKING = 0xBF
FRAME_FORWARD = 0xC0
FRAME_BACK = 0xC1
MARK = 0xC2
CLEAR_MARK = 0xC3
REPEAT_FROM_MARK = 0xC4
RETURN_TO_MARK = 0xC5
SEARCH_MARK_FORWARD = 0xC6
SEARCH_MARK_BACKWARDS = 0xC7
COUNTER_RESET = 0xC8
SHOW_COUNTER = 0xC9
TRACKING_INCREMENT = 0xCA
TRACKING_DECREMENT = 0xCB
VOLUME = 0xE0
BALANCE = 0xE1
MUTE = 0xE2
BASS = 0xE3
TREBLE = 0xE4
BASS_BOOST = 0xE5
SURROUND_MODE = 0xE6
LOUDNESS = 0xE7
MPX = 0xE8
VOLUME_UP = 0xE9
VOLUME_DOWN = 0xEA
SPEED_SELECT = 0xF0
PLAYBACK_SPEED = 0xF1
STANDARD_PLAY = 0xF2
LONG_PLAY = 0xF3
EXTENDED_PLAY = 0xF4
SLOW = 0xF5
FAN_ENABLE = 0x100
FAN_SPEED = 0x101
LIGHT = 0x102
LIGHT_ILLUMINATION_LEVEL = 0x103
CLIMATE_CONTROL_ENABLE = 0x104
ROOM_TEMPERATURE = 0x105
SECURITY_ENABLE = 0x106
FIRE_ALARM = 0x107
POLICE_ALARM = 0x108
BALANCE_RIGHT = 0x150
BALANCE_LEFT = 0x151
BASS_INCREMENT = 0x152
BASS_DECREMENT = 0x153
TREBLE_INCREMENT = 0x154
TREBLE_DECREMENT = 0x155
SPEAKER_SYSTEM = 0x160
CHANNEL_LEFT = 0x161
CHANNEL_RIGHT = 0x162
CHANNEL_CENTER = 0x163
CHANNEL_FRONT = 0x164
CHANNEL_CENTER_FRONT = 0x165
CHANNEL_SIDE = 0x166
CHANNEL_SURROUND = 0x167
CHANNEL_LOW_FREQUENCY_ENHANCEMENT = 0x168
CHANNEL_TOP = 0x169
CHANNEL_UNKNOWN = 0x16A
SUB_CHANNEL = 0x170
SUB_CHANNEL_INCREMENT = 0x171
SUB_CHANNEL_DECREMENT = 0x172
ALTERNATE_AUDIO_INCREMENT = 0x173
ALTERNATE_AUDIO_DECREMENT = 0x174
APPLICATION_LAUNCH_BUTTONS = 0x180
AL_LAUNCH_BUTTON_CONFIGURATION_TOOL = 0x181
AL_PROGRAMMABLE_BUTTON_CONFIGURATION = 0x182
AL_CONSUMER_CONTROL_CONFIGURATION = 0x183
AL_WORD_PROCESSOR = 0x184
AL_TEXT_EDITOR = 0x185
AL_SPREADSHEET = 0x186
AL_GRAPHICS_EDITOR = 0x187
AL_PRESENTATION_APP = 0x188
AL_DATABASE_APP = 0x189
AL_EMAIL_READER = 0x18A
AL_NEWSREADER = 0x18B
AL_VOICEMAIL = 0x18C
AL_CONTACTS = 0x18D # AL_CONTACTS/ADDRESS_BOOK
AL_ADDRESS_BOOK = AL_CONTACTS
AL_CALENDAR = 0x18E # AL_CALENDAR/SCHEDULE
AL_SCHEDULE = AL_CALENDAR
AL_PROJECT_MANAGER = 0x18F # AL_TASK/PROJECT_MANAGER
# AL_TASK_MANAGER = AL_PROJECT_MANAGER
AL_LOG = 0x193 # AL_LOG/JOURNAL/TIMECARD
AL_JOURNAL = AL_LOG
AL_TIMECARD = AL_LOG
AL_CHECKBOOK = 0x191 # AL_CHECKBOOK/FINANCE
AL_FINANCE = AL_CHECKBOOK
AL_CALCULATOR = 0x192
AL_AV_CAPTURE_PLAYBACK = 0x193 # AL_A/V_CAPTURE/PLAYBACK
AL_LOCAL_MACHINE_BROWSER = 0x194
AL_LAN_BROWSER = 0x195 # AL_LAN/WAN_BROWSER
AL_WAN_BROWSER = AL_LAN_BROWSER
AL_INTERNET_BROWSER = 0x196
AL_REMOTE_NETWORKING = 0x197 # AL_REMOTE_NETWORKING/ISP_CONNECT
AL_ISP_CONNECT = AL_REMOTE_NETWORKING
AL_NETWORK_CONFERENCE = 0x198
AL_NETWORK_CHAT = 0x199
AL_TELEPHONY = 0x19A # AL_TELEPHONY/DIALER
AL_DIALER = AL_TELEPHONY
AL_LOGON = 0x19B
AL_LOGOFF = 0x19C
AL_LOGON_LOGOFF = 0x19D # AL_LOGON/LOGOFF
AL_TERMINAL_LOCK = 0x19E # AL_TERMINAL_LOCK/SCREENSAVER
AL_SCREENSAVER = AL_TERMINAL_LOCK
AL_CONTROL_PANEL = 0x19F
AL_COMMAND_LINE_PROCESSOR = 0x1A0 # AL_COMMAND_LINE_PROCESSOR/RUN
AL_RUN = AL_COMMAND_LINE_PROCESSOR
AL_PROCESS_MANAGER = 0x1A1 # AL_PROCESS/TASK_MANAGER
AL_TASK_MANAGER = AL_PROCESS_MANAGER
AL_SELECT_TASK = 0x1A2 # AL_SELECT_TASK/APPLICATION
AL_SELECT_APPLICATION = AL_SELECT_TASK
AL_NEXT_TASK = 0x1A3 # AL_NEXT_TASK/APPLICATION
AL_NEXT_APPLICATION = AL_NEXT_TASK
AL_PREVIOUS_TASK = 0x1A4 # AL_PREVIOUS_TASK/APPLICATION
AL_PREVIOUS_APPLICATION = AL_PREVIOUS_TASK
AL_PREEMPTIVE_HALT_TASK = 0x1A5 # AL_PREEMPTIVE_HALT_TASK/APPLICATION
AL_PREEMPTIVE_HALT_APPLICATION = AL_PREEMPTIVE_HALT_TASK
GENERIC_GUI_APPLICATION_CONTROLS = 0x200
AC_NEW = 0x201
AC_OPEN = 0x202
AC_CLOSE = 0x203
AC_EXIT = 0x204
AC_MAXIMIZE = 0x205
AC_MINIMIZE = 0x206
AC_SAVE = 0x207
AC_PRINT = 0x208
AC_PROPERTIES = 0x209
AC_UNDO = 0x21A
AC_COPY = 0x21B
AC_CUT = 0x21C
AC_PASTE = 0x21D
AC_SELECT_ALL = 0x21E
AC_FIND = 0x21F
AC_FIND_AND_REPLACE = 0x220
AC_SEARCH = 0x221
AC_GO_TO = 0x222
AC_HOME = 0x223
AC_BACK = 0x224
AC_FORWARD = 0x225
AC_STOP = 0x226
AC_REFRESH = 0x227
AC_PREVIOUS_LINK = 0x228
AC_NEXT_LINK = 0x229
AC_BOOKMARKS = 0x22A
AC_HISTORY = 0x22B
AC_SUBSCRIPTIONS = 0x22C
AC_ZOOM_IN = 0x22D
AC_ZOOM_OUT = 0x22E
AC_ZOOM = 0x22F
AC_FULL_SCREEN_VIEW = 0x230
AC_NORMAL_VIEW = 0x231
AC_VIEW_TOGGLE = 0x232
AC_SCROLL_UP = 0x233
AC_SCROLL_DOWN = 0x234
AC_SCROLL = 0x235
AC_PAN_LEFT = 0x236
AC_PAN_RIGHT = 0x237
AC_PAN = 0x238
AC_NEW_WINDOW = 0x239
AC_TILE_HORIZONTALLY = 0x23A
AC_TILE_VERTICALLY = 0x23B
AC_FORMAT = 0x23C
| """
Extended list of consumer controls.
"""
__version__ = '0.0.0-auto.0'
__repo__ = 'https://github.com/Neradoc/Circuitpython_Keyboard_Layouts.git'
class Consumercontrolextended:
unassigned = 0
consumer_control = 1
numeric_key_pad = 2
programmable_buttons = 3
plus10 = 32
plus100 = 33
am_pm = 34
am = AM_PM
pm = AM_PM
power = 48
reset = 49
sleep = 50
sleep_after = 51
sleep_mode = 52
illumination = 53
function_buttons = 54
menu = 64
menu_pick = 65
menu_up = 66
menu_down = 67
menu_left = 68
menu_right = 69
menu_escape = 70
menu_value_increase = 71
menu_value_decrease = 72
data_on_screen = 96
closed_caption = 97
closed_caption_select = 98
vcr_tv = 99
broadcast_mode = 100
snapshot = 101
still = 102
selection = 128
assign_selection = 129
mode_step = 130
recall_last = 131
enter_channel = 132
order_movie = 133
channel = 134
media_selection = 135
media_select_computer = 136
media_select_tv = 137
media_select_www = 138
media_select_dvd = 139
media_select_telephone = 140
media_select_program_guide = 141
media_select_video_phone = 142
media_select_games = 143
media_select_messages = 144
media_select_cd = 145
media_select_vcr = 146
media_select_tuner = 147
quit = 148
help = 149
media_select_tape = 150
media_select_cable = 151
media_select_satellite = 152
media_select_security = 153
media_select_home = 154
media_select_call = 155
channel_increment = 156
channel_decrement = 157
media_select_sap = 158
vcr_plus = 160
once = 161
daily = 162
weekly = 163
monthly = 164
play = 176
pause = 177
record = 178
fast_forward = 179
rewind = 180
scan_next_track = 181
scan_previous_track = 182
stop = 183
eject = 184
random_play = 185
select_disc = 186
enter_disc = 187
repeat = 188
tracking = 189
track_normal = 190
slow_tracking = 191
frame_forward = 192
frame_back = 193
mark = 194
clear_mark = 195
repeat_from_mark = 196
return_to_mark = 197
search_mark_forward = 198
search_mark_backwards = 199
counter_reset = 200
show_counter = 201
tracking_increment = 202
tracking_decrement = 203
volume = 224
balance = 225
mute = 226
bass = 227
treble = 228
bass_boost = 229
surround_mode = 230
loudness = 231
mpx = 232
volume_up = 233
volume_down = 234
speed_select = 240
playback_speed = 241
standard_play = 242
long_play = 243
extended_play = 244
slow = 245
fan_enable = 256
fan_speed = 257
light = 258
light_illumination_level = 259
climate_control_enable = 260
room_temperature = 261
security_enable = 262
fire_alarm = 263
police_alarm = 264
balance_right = 336
balance_left = 337
bass_increment = 338
bass_decrement = 339
treble_increment = 340
treble_decrement = 341
speaker_system = 352
channel_left = 353
channel_right = 354
channel_center = 355
channel_front = 356
channel_center_front = 357
channel_side = 358
channel_surround = 359
channel_low_frequency_enhancement = 360
channel_top = 361
channel_unknown = 362
sub_channel = 368
sub_channel_increment = 369
sub_channel_decrement = 370
alternate_audio_increment = 371
alternate_audio_decrement = 372
application_launch_buttons = 384
al_launch_button_configuration_tool = 385
al_programmable_button_configuration = 386
al_consumer_control_configuration = 387
al_word_processor = 388
al_text_editor = 389
al_spreadsheet = 390
al_graphics_editor = 391
al_presentation_app = 392
al_database_app = 393
al_email_reader = 394
al_newsreader = 395
al_voicemail = 396
al_contacts = 397
al_address_book = AL_CONTACTS
al_calendar = 398
al_schedule = AL_CALENDAR
al_project_manager = 399
al_log = 403
al_journal = AL_LOG
al_timecard = AL_LOG
al_checkbook = 401
al_finance = AL_CHECKBOOK
al_calculator = 402
al_av_capture_playback = 403
al_local_machine_browser = 404
al_lan_browser = 405
al_wan_browser = AL_LAN_BROWSER
al_internet_browser = 406
al_remote_networking = 407
al_isp_connect = AL_REMOTE_NETWORKING
al_network_conference = 408
al_network_chat = 409
al_telephony = 410
al_dialer = AL_TELEPHONY
al_logon = 411
al_logoff = 412
al_logon_logoff = 413
al_terminal_lock = 414
al_screensaver = AL_TERMINAL_LOCK
al_control_panel = 415
al_command_line_processor = 416
al_run = AL_COMMAND_LINE_PROCESSOR
al_process_manager = 417
al_task_manager = AL_PROCESS_MANAGER
al_select_task = 418
al_select_application = AL_SELECT_TASK
al_next_task = 419
al_next_application = AL_NEXT_TASK
al_previous_task = 420
al_previous_application = AL_PREVIOUS_TASK
al_preemptive_halt_task = 421
al_preemptive_halt_application = AL_PREEMPTIVE_HALT_TASK
generic_gui_application_controls = 512
ac_new = 513
ac_open = 514
ac_close = 515
ac_exit = 516
ac_maximize = 517
ac_minimize = 518
ac_save = 519
ac_print = 520
ac_properties = 521
ac_undo = 538
ac_copy = 539
ac_cut = 540
ac_paste = 541
ac_select_all = 542
ac_find = 543
ac_find_and_replace = 544
ac_search = 545
ac_go_to = 546
ac_home = 547
ac_back = 548
ac_forward = 549
ac_stop = 550
ac_refresh = 551
ac_previous_link = 552
ac_next_link = 553
ac_bookmarks = 554
ac_history = 555
ac_subscriptions = 556
ac_zoom_in = 557
ac_zoom_out = 558
ac_zoom = 559
ac_full_screen_view = 560
ac_normal_view = 561
ac_view_toggle = 562
ac_scroll_up = 563
ac_scroll_down = 564
ac_scroll = 565
ac_pan_left = 566
ac_pan_right = 567
ac_pan = 568
ac_new_window = 569
ac_tile_horizontally = 570
ac_tile_vertically = 571
ac_format = 572 |
'''
Maximum sum with modified positions
Status: Accepted
'''
###############################################################################
def main():
"""Read input and print output"""
_ = input()
numbers = list(map(int, input().split()))
unmoved, zero_index = 0, numbers.index(0)
for coeff, i in enumerate(numbers, start=1):
unmoved += coeff * i
maximal, nsum = unmoved, unmoved
for i in numbers[zero_index + 1:]:
nsum -= i
maximal = max(nsum, maximal)
nsum = unmoved
for i in reversed(numbers[:zero_index]):
nsum += i
maximal = max(nsum, maximal)
print(maximal)
###############################################################################
if __name__ == '__main__':
main()
| """
Maximum sum with modified positions
Status: Accepted
"""
def main():
"""Read input and print output"""
_ = input()
numbers = list(map(int, input().split()))
(unmoved, zero_index) = (0, numbers.index(0))
for (coeff, i) in enumerate(numbers, start=1):
unmoved += coeff * i
(maximal, nsum) = (unmoved, unmoved)
for i in numbers[zero_index + 1:]:
nsum -= i
maximal = max(nsum, maximal)
nsum = unmoved
for i in reversed(numbers[:zero_index]):
nsum += i
maximal = max(nsum, maximal)
print(maximal)
if __name__ == '__main__':
main() |
name = 'tinymce'
authors = 'Joost Cassee'
version = 'trunk'
release = version
| name = 'tinymce'
authors = 'Joost Cassee'
version = 'trunk'
release = version |
#
# PySNMP MIB module PPVPN-TC (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/PPVPN-TC
# Produced by pysmi-0.3.4 at Mon Apr 29 20:33:05 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols("ASN1", "OctetString", "ObjectIdentifier", "Integer")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsIntersection, ValueRangeConstraint, ValueSizeConstraint, ConstraintsUnion, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ValueRangeConstraint", "ValueSizeConstraint", "ConstraintsUnion", "SingleValueConstraint")
NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance")
Integer32, IpAddress, Gauge32, Unsigned32, ModuleIdentity, Bits, Counter64, Counter32, MibIdentifier, TimeTicks, MibScalar, MibTable, MibTableRow, MibTableColumn, iso, ObjectIdentity, NotificationType = mibBuilder.importSymbols("SNMPv2-SMI", "Integer32", "IpAddress", "Gauge32", "Unsigned32", "ModuleIdentity", "Bits", "Counter64", "Counter32", "MibIdentifier", "TimeTicks", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "iso", "ObjectIdentity", "NotificationType")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
class VPNId(TextualConvention, OctetString):
reference = "RFC 2685, Fox & Gleeson, 'Virtual Private Networks Identifier', September 1999."
status = 'current'
subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(0, 7)
mibBuilder.exportSymbols("PPVPN-TC", VPNId=VPNId)
| (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, value_range_constraint, value_size_constraint, constraints_union, single_value_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsIntersection', 'ValueRangeConstraint', 'ValueSizeConstraint', 'ConstraintsUnion', 'SingleValueConstraint')
(notification_group, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ModuleCompliance')
(integer32, ip_address, gauge32, unsigned32, module_identity, bits, counter64, counter32, mib_identifier, time_ticks, mib_scalar, mib_table, mib_table_row, mib_table_column, iso, object_identity, notification_type) = mibBuilder.importSymbols('SNMPv2-SMI', 'Integer32', 'IpAddress', 'Gauge32', 'Unsigned32', 'ModuleIdentity', 'Bits', 'Counter64', 'Counter32', 'MibIdentifier', 'TimeTicks', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'iso', 'ObjectIdentity', 'NotificationType')
(display_string, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'TextualConvention')
class Vpnid(TextualConvention, OctetString):
reference = "RFC 2685, Fox & Gleeson, 'Virtual Private Networks Identifier', September 1999."
status = 'current'
subtype_spec = OctetString.subtypeSpec + value_size_constraint(0, 7)
mibBuilder.exportSymbols('PPVPN-TC', VPNId=VPNId) |
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def removeElements(self, head, val):
"""
:type head: ListNode
:type val: int
:rtype: ListNode
"""
cur = head
head = tail = None
while cur:
if cur.val != val:
if head:
tail.next = cur
tail = cur
else:
head = tail = cur
cur = cur.next
if tail: tail.next = None
return head | class Solution(object):
def remove_elements(self, head, val):
"""
:type head: ListNode
:type val: int
:rtype: ListNode
"""
cur = head
head = tail = None
while cur:
if cur.val != val:
if head:
tail.next = cur
tail = cur
else:
head = tail = cur
cur = cur.next
if tail:
tail.next = None
return head |
with open('../input.txt','rt') as f:
lst = set(map(int,f.readlines()))
for x in lst:
if 2020-x in lst:
print(x*(2020-x)) | with open('../input.txt', 'rt') as f:
lst = set(map(int, f.readlines()))
for x in lst:
if 2020 - x in lst:
print(x * (2020 - x)) |
print("Calculator has started")
while True:
a = float(input("Enter first number "))
b = float(input("Enter second number "))
chooseop=1
while (chooseop == 1) | (chooseop == 2) | (chooseop == 3) | (chooseop == 4):
chooseop = int(input("Enter 1 for addition, 2 for subtraction, 3 for multiplication and 4 for division "))
print(chooseop)
if chooseop == 1:
print(a+b)
break
elif chooseop == 2:
print(a-b)
break
elif chooseop == 3:
print(a*b)
break
elif chooseop == 4:
if b == 0:
print("Can't divide by zero")
else:
print(a/b)
break
elif (chooseop != 1) & (chooseop != 2) & (chooseop != 3) & (chooseop != 4):
print("Invalid operation number")
| print('Calculator has started')
while True:
a = float(input('Enter first number '))
b = float(input('Enter second number '))
chooseop = 1
while (chooseop == 1) | (chooseop == 2) | (chooseop == 3) | (chooseop == 4):
chooseop = int(input('Enter 1 for addition, 2 for subtraction, 3 for multiplication and 4 for division '))
print(chooseop)
if chooseop == 1:
print(a + b)
break
elif chooseop == 2:
print(a - b)
break
elif chooseop == 3:
print(a * b)
break
elif chooseop == 4:
if b == 0:
print("Can't divide by zero")
else:
print(a / b)
break
elif (chooseop != 1) & (chooseop != 2) & (chooseop != 3) & (chooseop != 4):
print('Invalid operation number') |
class node:
def __init__(self,value=None):
self.value=value
self.left_child=None
self.right_child=None
self.parent=None # pointer to parent node in tree
self.height=1 # height of node in tree (max dist. to leaf) NEW FOR AVL
class AVLTree:
def __init__(self):
self.root=None
def __repr__(self):
if self.root==None: return ''
content='\n' # to hold final string
cur_nodes=[self.root] # all nodes at current level
cur_height=self.root.height # height of nodes at current level
sep=' '*(2**(cur_height-1)) # variable sized separator between elements
while True:
cur_height+=-1 # decrement current height
if len(cur_nodes)==0: break
cur_row=' '
next_row=''
next_nodes=[]
if all(n is None for n in cur_nodes):
break
for n in cur_nodes:
if n==None:
cur_row+=' '+sep
next_row+=' '+sep
next_nodes.extend([None,None])
continue
if n.value!=None:
buf=' '*int((5-len(str(n.value)))/2)
cur_row+='%s%s%s'%(buf,str(n.value),buf)+sep
else:
cur_row+=' '*5+sep
if n.left_child!=None:
next_nodes.append(n.left_child)
next_row+=' /'+sep
else:
next_row+=' '+sep
next_nodes.append(None)
if n.right_child!=None:
next_nodes.append(n.right_child)
next_row+='\ '+sep
else:
next_row+=' '+sep
next_nodes.append(None)
content+=(cur_height*' '+cur_row+'\n'+cur_height*' '+next_row+'\n')
cur_nodes=next_nodes
sep=' '*int(len(sep)/2) # cut separator size in half
return content
def insert(self,value):
if self.root==None:
self.root=node(value)
else:
self._insert(value,self.root)
def _insert(self,value,cur_node):
if value<cur_node.value:
if cur_node.left_child==None:
cur_node.left_child=node(value)
cur_node.left_child.parent=cur_node # set parent
self._inspect_insertion(cur_node.left_child)
else:
self._insert(value,cur_node.left_child)
elif value>cur_node.value:
if cur_node.right_child==None:
cur_node.right_child=node(value)
cur_node.right_child.parent=cur_node # set parent
self._inspect_insertion(cur_node.right_child)
else:
self._insert(value,cur_node.right_child)
else:
print("Value already in tree!")
def print_tree(self):
if self.root!=None:
self._print_tree(self.root)
def _print_tree(self,cur_node):
if cur_node!=None:
self._print_tree(cur_node.left_child)
print ('%s, h=%d'%(str(cur_node.value),cur_node.height))
self._print_tree(cur_node.right_child)
def height(self):
if self.root!=None:
return self._height(self.root,0)
else:
return 0
def _height(self,cur_node,cur_height):
if cur_node==None: return cur_height
left_height=self._height(cur_node.left_child,cur_height+1)
right_height=self._height(cur_node.right_child,cur_height+1)
return max(left_height,right_height)
def find(self,value):
if self.root!=None:
return self._find(value,self.root)
else:
return None
def _find(self,value,cur_node):
if value==cur_node.value:
return cur_node
elif value<cur_node.value and cur_node.left_child!=None:
return self._find(value,cur_node.left_child)
elif value>cur_node.value and cur_node.right_child!=None:
return self._find(value,cur_node.right_child)
def delete_value(self,value):
return self.delete_node(self.find(value))
def delete_node(self,node):
## -----
# Improvements since prior lesson
# Protect against deleting a node not found in the tree
if node==None or self.find(node.value)==None:
print("Node to be deleted not found in the tree!")
return None
## -----
# returns the node with min value in tree rooted at input node
def min_value_node(n):
current=n
while current.left_child!=None:
current=current.left_child
return current
# returns the number of children for the specified node
def num_children(n):
num_children=0
if n.left_child!=None: num_children+=1
if n.right_child!=None: num_children+=1
return num_children
# get the parent of the node to be deleted
node_parent=node.parent
# get the number of children of the node to be deleted
node_children=num_children(node)
# break operation into different cases based on the
# structure of the tree & node to be deleted
# CASE 1 (node has no children)
if node_children==0:
if node_parent!=None:
# remove reference to the node from the parent
if node_parent.left_child==node:
node_parent.left_child=None
else:
node_parent.right_child=None
else:
self.root=None
# CASE 2 (node has a single child)
if node_children==1:
# get the single child node
if node.left_child!=None:
child=node.left_child
else:
child=node.right_child
if node_parent!=None:
# replace the node to be deleted with its child
if node_parent.left_child==node:
node_parent.left_child=child
else:
node_parent.right_child=child
else:
self.root=child
# correct the parent pointer in node
child.parent=node_parent
# CASE 3 (node has two children)
if node_children==2:
# get the inorder successor of the deleted node
successor=min_value_node(node.right_child)
# copy the inorder successor's value to the node formerly
# holding the value we wished to delete
node.value=successor.value
# delete the inorder successor now that it's value was
# copied into the other node
self.delete_node(successor)
# exit function so we don't call the _inspect_deletion twice
return
if node_parent!=None:
# fix the height of the parent of current node
node_parent.height=1+max(self.get_height(node_parent.left_child),self.get_height(node_parent.right_child))
# begin to traverse back up the tree checking if there are
# any sections which now invalidate the AVL balance rules
self._inspect_deletion(node_parent)
def search(self,value):
if self.root!=None:
return self._search(value,self.root)
else:
return False
def _search(self,value,cur_node):
if value==cur_node.value:
return True
elif value<cur_node.value and cur_node.left_child!=None:
return self._search(value,cur_node.left_child)
elif value>cur_node.value and cur_node.right_child!=None:
return self._search(value,cur_node.right_child)
return False
# Functions added for AVL...
def _inspect_insertion(self,cur_node,path=[]):
if cur_node.parent==None: return
path=[cur_node]+path
left_height =self.get_height(cur_node.parent.left_child)
right_height=self.get_height(cur_node.parent.right_child)
if abs(left_height-right_height)>1:
path=[cur_node.parent]+path
self._rebalance_node(path[0],path[1],path[2])
return
new_height=1+cur_node.height
if new_height>cur_node.parent.height:
cur_node.parent.height=new_height
self._inspect_insertion(cur_node.parent,path)
def _inspect_deletion(self,cur_node):
if cur_node==None: return
left_height =self.get_height(cur_node.left_child)
right_height=self.get_height(cur_node.right_child)
if abs(left_height-right_height)>1:
y=self.taller_child(cur_node)
x=self.taller_child(y)
self._rebalance_node(cur_node,y,x)
self._inspect_deletion(cur_node.parent)
def _rebalance_node(self,z,y,x):
if y==z.left_child and x==y.left_child:
self._right_rotate(z)
elif y==z.left_child and x==y.right_child:
self._left_rotate(y)
self._right_rotate(z)
elif y==z.right_child and x==y.right_child:
self._left_rotate(z)
elif y==z.right_child and x==y.left_child:
self._right_rotate(y)
self._left_rotate(z)
else:
raise Exception('_rebalance_node: z,y,x node configuration not recognized!')
def _right_rotate(self,z):
sub_root=z.parent
y=z.left_child
t3=y.right_child
y.right_child=z
z.parent=y
z.left_child=t3
if t3!=None: t3.parent=z
y.parent=sub_root
if y.parent==None:
self.root=y
else:
if y.parent.left_child==z:
y.parent.left_child=y
else:
y.parent.right_child=y
z.height=1+max(self.get_height(z.left_child),
self.get_height(z.right_child))
y.height=1+max(self.get_height(y.left_child),
self.get_height(y.right_child))
def _left_rotate(self,z):
sub_root=z.parent
y=z.right_child
t2=y.left_child
y.left_child=z
z.parent=y
z.right_child=t2
if t2!=None: t2.parent=z
y.parent=sub_root
if y.parent==None:
self.root=y
else:
if y.parent.left_child==z:
y.parent.left_child=y
else:
y.parent.right_child=y
z.height=1+max(self.get_height(z.left_child),
self.get_height(z.right_child))
y.height=1+max(self.get_height(y.left_child),
self.get_height(y.right_child))
def get_height(self,cur_node):
if cur_node==None: return 0
return cur_node.height
def taller_child(self,cur_node):
left=self.get_height(cur_node.left_child)
right=self.get_height(cur_node.right_child)
return cur_node.left_child if left>=right else cur_node.right_child | class Node:
def __init__(self, value=None):
self.value = value
self.left_child = None
self.right_child = None
self.parent = None
self.height = 1
class Avltree:
def __init__(self):
self.root = None
def __repr__(self):
if self.root == None:
return ''
content = '\n'
cur_nodes = [self.root]
cur_height = self.root.height
sep = ' ' * 2 ** (cur_height - 1)
while True:
cur_height += -1
if len(cur_nodes) == 0:
break
cur_row = ' '
next_row = ''
next_nodes = []
if all((n is None for n in cur_nodes)):
break
for n in cur_nodes:
if n == None:
cur_row += ' ' + sep
next_row += ' ' + sep
next_nodes.extend([None, None])
continue
if n.value != None:
buf = ' ' * int((5 - len(str(n.value))) / 2)
cur_row += '%s%s%s' % (buf, str(n.value), buf) + sep
else:
cur_row += ' ' * 5 + sep
if n.left_child != None:
next_nodes.append(n.left_child)
next_row += ' /' + sep
else:
next_row += ' ' + sep
next_nodes.append(None)
if n.right_child != None:
next_nodes.append(n.right_child)
next_row += '\\ ' + sep
else:
next_row += ' ' + sep
next_nodes.append(None)
content += cur_height * ' ' + cur_row + '\n' + cur_height * ' ' + next_row + '\n'
cur_nodes = next_nodes
sep = ' ' * int(len(sep) / 2)
return content
def insert(self, value):
if self.root == None:
self.root = node(value)
else:
self._insert(value, self.root)
def _insert(self, value, cur_node):
if value < cur_node.value:
if cur_node.left_child == None:
cur_node.left_child = node(value)
cur_node.left_child.parent = cur_node
self._inspect_insertion(cur_node.left_child)
else:
self._insert(value, cur_node.left_child)
elif value > cur_node.value:
if cur_node.right_child == None:
cur_node.right_child = node(value)
cur_node.right_child.parent = cur_node
self._inspect_insertion(cur_node.right_child)
else:
self._insert(value, cur_node.right_child)
else:
print('Value already in tree!')
def print_tree(self):
if self.root != None:
self._print_tree(self.root)
def _print_tree(self, cur_node):
if cur_node != None:
self._print_tree(cur_node.left_child)
print('%s, h=%d' % (str(cur_node.value), cur_node.height))
self._print_tree(cur_node.right_child)
def height(self):
if self.root != None:
return self._height(self.root, 0)
else:
return 0
def _height(self, cur_node, cur_height):
if cur_node == None:
return cur_height
left_height = self._height(cur_node.left_child, cur_height + 1)
right_height = self._height(cur_node.right_child, cur_height + 1)
return max(left_height, right_height)
def find(self, value):
if self.root != None:
return self._find(value, self.root)
else:
return None
def _find(self, value, cur_node):
if value == cur_node.value:
return cur_node
elif value < cur_node.value and cur_node.left_child != None:
return self._find(value, cur_node.left_child)
elif value > cur_node.value and cur_node.right_child != None:
return self._find(value, cur_node.right_child)
def delete_value(self, value):
return self.delete_node(self.find(value))
def delete_node(self, node):
if node == None or self.find(node.value) == None:
print('Node to be deleted not found in the tree!')
return None
def min_value_node(n):
current = n
while current.left_child != None:
current = current.left_child
return current
def num_children(n):
num_children = 0
if n.left_child != None:
num_children += 1
if n.right_child != None:
num_children += 1
return num_children
node_parent = node.parent
node_children = num_children(node)
if node_children == 0:
if node_parent != None:
if node_parent.left_child == node:
node_parent.left_child = None
else:
node_parent.right_child = None
else:
self.root = None
if node_children == 1:
if node.left_child != None:
child = node.left_child
else:
child = node.right_child
if node_parent != None:
if node_parent.left_child == node:
node_parent.left_child = child
else:
node_parent.right_child = child
else:
self.root = child
child.parent = node_parent
if node_children == 2:
successor = min_value_node(node.right_child)
node.value = successor.value
self.delete_node(successor)
return
if node_parent != None:
node_parent.height = 1 + max(self.get_height(node_parent.left_child), self.get_height(node_parent.right_child))
self._inspect_deletion(node_parent)
def search(self, value):
if self.root != None:
return self._search(value, self.root)
else:
return False
def _search(self, value, cur_node):
if value == cur_node.value:
return True
elif value < cur_node.value and cur_node.left_child != None:
return self._search(value, cur_node.left_child)
elif value > cur_node.value and cur_node.right_child != None:
return self._search(value, cur_node.right_child)
return False
def _inspect_insertion(self, cur_node, path=[]):
if cur_node.parent == None:
return
path = [cur_node] + path
left_height = self.get_height(cur_node.parent.left_child)
right_height = self.get_height(cur_node.parent.right_child)
if abs(left_height - right_height) > 1:
path = [cur_node.parent] + path
self._rebalance_node(path[0], path[1], path[2])
return
new_height = 1 + cur_node.height
if new_height > cur_node.parent.height:
cur_node.parent.height = new_height
self._inspect_insertion(cur_node.parent, path)
def _inspect_deletion(self, cur_node):
if cur_node == None:
return
left_height = self.get_height(cur_node.left_child)
right_height = self.get_height(cur_node.right_child)
if abs(left_height - right_height) > 1:
y = self.taller_child(cur_node)
x = self.taller_child(y)
self._rebalance_node(cur_node, y, x)
self._inspect_deletion(cur_node.parent)
def _rebalance_node(self, z, y, x):
if y == z.left_child and x == y.left_child:
self._right_rotate(z)
elif y == z.left_child and x == y.right_child:
self._left_rotate(y)
self._right_rotate(z)
elif y == z.right_child and x == y.right_child:
self._left_rotate(z)
elif y == z.right_child and x == y.left_child:
self._right_rotate(y)
self._left_rotate(z)
else:
raise exception('_rebalance_node: z,y,x node configuration not recognized!')
def _right_rotate(self, z):
sub_root = z.parent
y = z.left_child
t3 = y.right_child
y.right_child = z
z.parent = y
z.left_child = t3
if t3 != None:
t3.parent = z
y.parent = sub_root
if y.parent == None:
self.root = y
elif y.parent.left_child == z:
y.parent.left_child = y
else:
y.parent.right_child = y
z.height = 1 + max(self.get_height(z.left_child), self.get_height(z.right_child))
y.height = 1 + max(self.get_height(y.left_child), self.get_height(y.right_child))
def _left_rotate(self, z):
sub_root = z.parent
y = z.right_child
t2 = y.left_child
y.left_child = z
z.parent = y
z.right_child = t2
if t2 != None:
t2.parent = z
y.parent = sub_root
if y.parent == None:
self.root = y
elif y.parent.left_child == z:
y.parent.left_child = y
else:
y.parent.right_child = y
z.height = 1 + max(self.get_height(z.left_child), self.get_height(z.right_child))
y.height = 1 + max(self.get_height(y.left_child), self.get_height(y.right_child))
def get_height(self, cur_node):
if cur_node == None:
return 0
return cur_node.height
def taller_child(self, cur_node):
left = self.get_height(cur_node.left_child)
right = self.get_height(cur_node.right_child)
return cur_node.left_child if left >= right else cur_node.right_child |
class Solution:
def lexicalOrder(self, n):
"""
:type n: int
:rtype: List[int]
"""
results = [n for n in range(1, n+1)]
results.sort(key= lambda x: str(x))
return results | class Solution:
def lexical_order(self, n):
"""
:type n: int
:rtype: List[int]
"""
results = [n for n in range(1, n + 1)]
results.sort(key=lambda x: str(x))
return results |
class Boid():
def __init__(self, x,y,width,height):
self.position = Vector(x,y)
| class Boid:
def __init__(self, x, y, width, height):
self.position = vector(x, y) |
class PaginationType:
LIMIT = 'limit'
OFFSET = 'offset'
PAGINATION_LIMIT = 100
class Pagination:
"""
"""
LIMIT = 20
OFFSET = 0
@staticmethod
def validate(pagination_type, value):
"""
:param pagination_type:
:param value:
:return:
"""
try:
if str(pagination_type).lower() == PaginationType.LIMIT:
if int(value) > PAGINATION_LIMIT:
value = PAGINATION_LIMIT
elif int(value) < 0:
value = Pagination.OFFSET
else:
if int(value) < 0:
value = Pagination.OFFSET
except Exception as err:
if str(pagination_type).lower() == PaginationType.LIMIT:
value = Pagination.LIMIT
else:
value = Pagination.OFFSET
return int(value)
class Order:
ASC = 'ASC'
DESC = 'DESC'
@staticmethod
def validate(value):
if value != Order.ASC:
value = Order.DESC
return value | class Paginationtype:
limit = 'limit'
offset = 'offset'
pagination_limit = 100
class Pagination:
"""
"""
limit = 20
offset = 0
@staticmethod
def validate(pagination_type, value):
"""
:param pagination_type:
:param value:
:return:
"""
try:
if str(pagination_type).lower() == PaginationType.LIMIT:
if int(value) > PAGINATION_LIMIT:
value = PAGINATION_LIMIT
elif int(value) < 0:
value = Pagination.OFFSET
elif int(value) < 0:
value = Pagination.OFFSET
except Exception as err:
if str(pagination_type).lower() == PaginationType.LIMIT:
value = Pagination.LIMIT
else:
value = Pagination.OFFSET
return int(value)
class Order:
asc = 'ASC'
desc = 'DESC'
@staticmethod
def validate(value):
if value != Order.ASC:
value = Order.DESC
return value |
# Area of a Triangle
print("Write a function that takes the base and height of a triangle and return its area.")
def area():
base = float(int(input("Enter the Base of the Triangle : ")))
height = float(int(input("Enter the height of the Triangle : ")))
total_area = (base * height)/2
print(total_area)
area()
# Program not closed emmidately
input("Please Click to Enter to End the Program ") | print('Write a function that takes the base and height of a triangle and return its area.')
def area():
base = float(int(input('Enter the Base of the Triangle : ')))
height = float(int(input('Enter the height of the Triangle : ')))
total_area = base * height / 2
print(total_area)
area()
input('Please Click to Enter to End the Program ') |
"""
Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.
Example:
Input: [1,2,3,null,5,null,4]
Output: [1, 3, 4]
Explanation:
1 <---
/ \
2 3 <---
\ \
5 4 <---
"""
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def rightSideView(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
"""
Method 1: BFS
Same BFS logic as 515, 451, 102
* Create a result array, res containing the root node value
* Create a queue with the res node and 'X'
* While queue: pop the first node
The first node can either be a node or 'X'
* IF 'X', then this indicates that we have
all the elements in that node of the tree;
then take the RIGHTmost element i.e. arr[-1]
to obtain the right side view
* ELSE append the left and right node elements
to the queue
Your runtime beats 96.51 % of python submissions.
"""
# #Boundary conditions
if not root:
return []
if root and ((not root.left) and (not root.right)):
return [root.val]
res = [root.val]
queue = [root, 'X']
while queue:
node = queue.pop(0)
if node == 'X':
if queue:
res.append([ele.val for ele in queue][-1])
queue.append('X')
else:
# #Left comes before right in level order traversal
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
# print([ele.val if ele != 'X' else ele for ele in queue])
return res
| """
Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.
Example:
Input: [1,2,3,null,5,null,4]
Output: [1, 3, 4]
Explanation:
1 <---
/ 2 3 <---
\\ 5 4 <---
"""
class Solution(object):
def right_side_view(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
"\n Method 1: BFS\n\n Same BFS logic as 515, 451, 102\n\n\n * Create a result array, res containing the root node value\n * Create a queue with the res node and 'X'\n\n * While queue: pop the first node\n The first node can either be a node or 'X'\n * IF 'X', then this indicates that we have \n all the elements in that node of the tree;\n then take the RIGHTmost element i.e. arr[-1]\n to obtain the right side view\n * ELSE append the left and right node elements \n to the queue\n\n Your runtime beats 96.51 % of python submissions.\n "
if not root:
return []
if root and (not root.left and (not root.right)):
return [root.val]
res = [root.val]
queue = [root, 'X']
while queue:
node = queue.pop(0)
if node == 'X':
if queue:
res.append([ele.val for ele in queue][-1])
queue.append('X')
else:
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return res |
def make_pizza(*toppings):
print(toppings)
# for item in toppings:
# print("Add " + item)
| def make_pizza(*toppings):
print(toppings) |
class Solution:
def numSplits(self, s: str) -> int:
answer=0
left=[0]*26
right=[0]*26
for x in s:
right[ord(x)-ord('a')]+=1
leftNum=0
rightNum=sum(x > 0 for x in right)
for x in s:
index=ord(x)-ord('a')
if left[index]==0:
leftNum+=1
left[index]+=1
right[index]-=1
if right[index]==0:
rightNum-=1
if leftNum==rightNum:
answer+=1
return answer
| class Solution:
def num_splits(self, s: str) -> int:
answer = 0
left = [0] * 26
right = [0] * 26
for x in s:
right[ord(x) - ord('a')] += 1
left_num = 0
right_num = sum((x > 0 for x in right))
for x in s:
index = ord(x) - ord('a')
if left[index] == 0:
left_num += 1
left[index] += 1
right[index] -= 1
if right[index] == 0:
right_num -= 1
if leftNum == rightNum:
answer += 1
return answer |
#!/usr/bin/python3
# -*- mode: python; coding: utf-8 -*-
VERSION=1
TEMPLATE_KEY_PREFIX = 'jflow.template'
SEPARATOR_KEY = '.'
KEY_VERSION = 'version'
KEY_FORK = 'fork'
KEY_UPSTREAM = 'upstream'
KEY_PUBLIC = 'public'
KEY_DEBUG = 'debug'
KEY_REMOTE = 'remote'
KEY_MERGE_TO = 'merge-to'
KEY_EXTRA = 'extra'
# Template-only keys
KEY_PUBLIC_PREFIX = 'public-prefix'
KEY_PUBLIC_SUFFIX = 'public-suffix'
KEY_DEBUG_PREFIX = 'debug-prefix'
KEY_DEBUG_SUFFIX = 'debug-suffix'
KEY_REMOTE_PREFIX = 'remote-prefix'
KEY_REMOTE_SUFFIX = 'remote-suffix'
DEFAULT_DEBUG_PREFIX = 'feature/'
DEFAULT_DEBUG_SUFFIX = '.debug'
STGIT_SUFFIX = '.stgit'
def make_key(*items):
return SEPARATOR_KEY.join(items)
def make_prefix(*items):
return make_key(*items) + SEPARATOR_KEY
def make_suffix(*items):
return SEPARATOR_KEY + make_key(*items)
def branch_key_base(b):
return make_key('branch', b, 'jflow')
def branch_key_version(b):
return make_key(branch_key_base(b), KEY_VERSION)
def branch_key_fork(b):
return make_key(branch_key_base(b), KEY_FORK)
def branch_key_upstream(b):
return make_key(branch_key_base(b), KEY_UPSTREAM)
def branch_key_public(b):
return make_key(branch_key_base(b), KEY_PUBLIC)
def branch_key_debug(b):
return make_key(branch_key_base(b), KEY_DEBUG)
def branch_key_debug_prefix(b):
return make_key(branch_key_base(b), KEY_DEBUG_PREFIX)
def branch_key_debug_suffix(b):
return make_key(branch_key_base(b), KEY_DEBUG_SUFFIX)
def branch_key_remote(b):
return make_key(branch_key_base(b), KEY_REMOTE)
def branch_key_extra(b):
return make_key(branch_key_base(b), KEY_EXTRA)
def branch_key_merge_to(b):
return make_key(branch_key_base(b), KEY_MERGE_TO)
def branch_key_stgit_version(b):
return make_key('branch', b, 'stgit', 'stackformatversion')
def branch_key_description(b):
return make_key('branch', b, 'description')
def branch_stgit_name(b):
return b + STGIT_SUFFIX
def remote_key_url(r):
return make_key('remote', r, 'url')
| version = 1
template_key_prefix = 'jflow.template'
separator_key = '.'
key_version = 'version'
key_fork = 'fork'
key_upstream = 'upstream'
key_public = 'public'
key_debug = 'debug'
key_remote = 'remote'
key_merge_to = 'merge-to'
key_extra = 'extra'
key_public_prefix = 'public-prefix'
key_public_suffix = 'public-suffix'
key_debug_prefix = 'debug-prefix'
key_debug_suffix = 'debug-suffix'
key_remote_prefix = 'remote-prefix'
key_remote_suffix = 'remote-suffix'
default_debug_prefix = 'feature/'
default_debug_suffix = '.debug'
stgit_suffix = '.stgit'
def make_key(*items):
return SEPARATOR_KEY.join(items)
def make_prefix(*items):
return make_key(*items) + SEPARATOR_KEY
def make_suffix(*items):
return SEPARATOR_KEY + make_key(*items)
def branch_key_base(b):
return make_key('branch', b, 'jflow')
def branch_key_version(b):
return make_key(branch_key_base(b), KEY_VERSION)
def branch_key_fork(b):
return make_key(branch_key_base(b), KEY_FORK)
def branch_key_upstream(b):
return make_key(branch_key_base(b), KEY_UPSTREAM)
def branch_key_public(b):
return make_key(branch_key_base(b), KEY_PUBLIC)
def branch_key_debug(b):
return make_key(branch_key_base(b), KEY_DEBUG)
def branch_key_debug_prefix(b):
return make_key(branch_key_base(b), KEY_DEBUG_PREFIX)
def branch_key_debug_suffix(b):
return make_key(branch_key_base(b), KEY_DEBUG_SUFFIX)
def branch_key_remote(b):
return make_key(branch_key_base(b), KEY_REMOTE)
def branch_key_extra(b):
return make_key(branch_key_base(b), KEY_EXTRA)
def branch_key_merge_to(b):
return make_key(branch_key_base(b), KEY_MERGE_TO)
def branch_key_stgit_version(b):
return make_key('branch', b, 'stgit', 'stackformatversion')
def branch_key_description(b):
return make_key('branch', b, 'description')
def branch_stgit_name(b):
return b + STGIT_SUFFIX
def remote_key_url(r):
return make_key('remote', r, 'url') |
"""
Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.
For example,
Given nums = [0, 1, 3] return 2.
Note:
Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space
complexity?
"""
__author__ = 'Daniel'
class Solution(object):
def missingNumber(self, nums):
"""
Algorithm:
Hashmap, but to save space, use the array itself as the hashmap
Notice:
nums[i], nums[nums[i]] = nums[nums[i]], nums[i]
Above is wrong, since evaluate from left to right; thus, when nums[nums[i]] on RHS is None, on LHS, nums[i] is
eval to None and nums[nums[i]] indexes by None, causing errors.
Alternatively, it is correct that:
nums[nums[i]], nums[i]= nums[i], nums[nums[i]]
To be safe, just use:
j = nums[i]
nums[i], nums[j] = nums[j], nums[i]
:type nums: List[int]
:rtype: int
"""
num_n = None
n = len(nums)
i = 0
while i < n:
if nums[i] == n:
num_n = nums[i]
nums[i] = None
i += 1
elif nums[i] is not None and nums[i] != i:
j = nums[i]
nums[i], nums[j] = nums[j], nums[i]
else:
i += 1
if not num_n:
return n
return nums.index(None)
if __name__ == "__main__":
assert Solution().missingNumber([2, 0]) == 1
| """
Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.
For example,
Given nums = [0, 1, 3] return 2.
Note:
Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space
complexity?
"""
__author__ = 'Daniel'
class Solution(object):
def missing_number(self, nums):
"""
Algorithm:
Hashmap, but to save space, use the array itself as the hashmap
Notice:
nums[i], nums[nums[i]] = nums[nums[i]], nums[i]
Above is wrong, since evaluate from left to right; thus, when nums[nums[i]] on RHS is None, on LHS, nums[i] is
eval to None and nums[nums[i]] indexes by None, causing errors.
Alternatively, it is correct that:
nums[nums[i]], nums[i]= nums[i], nums[nums[i]]
To be safe, just use:
j = nums[i]
nums[i], nums[j] = nums[j], nums[i]
:type nums: List[int]
:rtype: int
"""
num_n = None
n = len(nums)
i = 0
while i < n:
if nums[i] == n:
num_n = nums[i]
nums[i] = None
i += 1
elif nums[i] is not None and nums[i] != i:
j = nums[i]
(nums[i], nums[j]) = (nums[j], nums[i])
else:
i += 1
if not num_n:
return n
return nums.index(None)
if __name__ == '__main__':
assert solution().missingNumber([2, 0]) == 1 |
while True:
print('Who are you?')
name=input()
if name!='Joe':
continue
print('Hello,Joe.What is the password?(it is a fish)')
password=input()
if password=='swordfish':
break
print('Access granted')
| while True:
print('Who are you?')
name = input()
if name != 'Joe':
continue
print('Hello,Joe.What is the password?(it is a fish)')
password = input()
if password == 'swordfish':
break
print('Access granted') |
"""
Dinghy daily digest tool.
"""
__version__ = "0.12.0"
| """
Dinghy daily digest tool.
"""
__version__ = '0.12.0' |
class SearchQuery(dict):
"""
A specialized dict which has helpers for creating and modifying a Search
Query document.
Example usage:
>>> from globus_sdk import SearchClient, SearchQuery
>>> sc = SearchClient(...)
>>> index_id = ...
>>> query = (SearchQuery(q='example query')
>>> .set_limit(100).set_offset(10)
>>> .add_filter('path.to.field1', ['foo', 'bar']))
>>> result = sc.post_search(index_id, query)
"""
def set_query(self, query):
self["q"] = query
return self
def set_limit(self, limit):
self["limit"] = limit
return self
def set_offset(self, offset):
self["offset"] = offset
return self
def set_advanced(self, advanced):
self["advanced"] = advanced
return self
def add_facet(
self,
name,
field_name,
type="terms",
size=None,
date_interval=None,
histogram_range=None,
**kwargs
):
self["facets"] = self.get("facets", [])
facet = {"name": name, "field_name": field_name, "type": type}
facet.update(kwargs)
if size is not None:
facet["size"] = size
if date_interval is not None:
facet["date_interval"] = date_interval
if histogram_range is not None:
low, high = histogram_range
facet["histogram_range"] = {"low": low, "high": high}
self["facets"].append(facet)
return self
def add_filter(self, field_name, values, type="match_all", **kwargs):
self["filters"] = self.get("filters", [])
new_filter = {"field_name": field_name, "values": values, "type": type}
new_filter.update(kwargs)
self["filters"].append(new_filter)
return self
def add_boost(self, field_name, factor, **kwargs):
self["boosts"] = self.get("boosts", [])
boost = {"field_name": field_name, "factor": factor}
boost.update(kwargs)
self["boosts"].append(boost)
return self
def add_sort(self, field_name, order=None, **kwargs):
self["sort"] = self.get("sort", [])
sort = {"field_name": field_name}
sort.update(kwargs)
if order is not None:
sort["order"] = order
self["sort"].append(sort)
return self
| class Searchquery(dict):
"""
A specialized dict which has helpers for creating and modifying a Search
Query document.
Example usage:
>>> from globus_sdk import SearchClient, SearchQuery
>>> sc = SearchClient(...)
>>> index_id = ...
>>> query = (SearchQuery(q='example query')
>>> .set_limit(100).set_offset(10)
>>> .add_filter('path.to.field1', ['foo', 'bar']))
>>> result = sc.post_search(index_id, query)
"""
def set_query(self, query):
self['q'] = query
return self
def set_limit(self, limit):
self['limit'] = limit
return self
def set_offset(self, offset):
self['offset'] = offset
return self
def set_advanced(self, advanced):
self['advanced'] = advanced
return self
def add_facet(self, name, field_name, type='terms', size=None, date_interval=None, histogram_range=None, **kwargs):
self['facets'] = self.get('facets', [])
facet = {'name': name, 'field_name': field_name, 'type': type}
facet.update(kwargs)
if size is not None:
facet['size'] = size
if date_interval is not None:
facet['date_interval'] = date_interval
if histogram_range is not None:
(low, high) = histogram_range
facet['histogram_range'] = {'low': low, 'high': high}
self['facets'].append(facet)
return self
def add_filter(self, field_name, values, type='match_all', **kwargs):
self['filters'] = self.get('filters', [])
new_filter = {'field_name': field_name, 'values': values, 'type': type}
new_filter.update(kwargs)
self['filters'].append(new_filter)
return self
def add_boost(self, field_name, factor, **kwargs):
self['boosts'] = self.get('boosts', [])
boost = {'field_name': field_name, 'factor': factor}
boost.update(kwargs)
self['boosts'].append(boost)
return self
def add_sort(self, field_name, order=None, **kwargs):
self['sort'] = self.get('sort', [])
sort = {'field_name': field_name}
sort.update(kwargs)
if order is not None:
sort['order'] = order
self['sort'].append(sort)
return self |
def GenerateConfig(context):
resources = []
haEnabled = context.properties['num_instances'] > 1
# Enabling services
services = {
'name': 'enable_services',
'type': 'enable_services.py',
'properties': {
'services': context.properties['services']
}
}
# Networking provisioning
networking = {
'name': 'networking',
'type': 'networking.py',
'properties': {
'ha_enabled': haEnabled,
'region': context.properties['region'],
'mgmt_network': context.properties['mgmt_network'],
'custom_route_tag': context.properties['custom_route_tag'],
# Using email from service_account's output
'service_account': '$(ref.service_accounts.email)',
'service_port': context.properties['service_port'],
'networks': context.properties['networks']
}
}
# Additional networtks
if 'inside_network' in context.properties:
networking['properties']['inside_network'] = context.properties['inside_network']
if 'outside_network' in context.properties:
networking['properties']['outside_network'] = context.properties['outside_network']
if 'dmz1_network' in context.properties:
networking['properties']['dmz1_network'] = context.properties['dmz1_network']
if 'dmz2_network' in context.properties:
networking['properties']['dmz2_network'] = context.properties['dmz2_network']
# Service Account
sa = {
'name': 'service_accounts',
'type': 'service_accounts.py',
'properties': {
'account_id': context.properties['account_id'],
'display_name': context.properties['display_name']
},
'metadata': {
'dependsOn': ['enable_services']
}
}
# Appliance VMs
vm = {
'name': 'vm',
'type': 'vm.py',
'properties': {
'vm_zones': context.properties['vm_zones'],
'num_instances': context.properties['num_instances'],
'cisco_product_version': context.properties['cisco_product_version'],
'vm_machine_type': context.properties['vm_machine_type'],
'vm_instance_labels': context.properties['vm_instance_labels'],
'vm_instance_tags': context.properties['vm_instance_tags'],
'admin_ssh_pub_key': context.properties['admin_ssh_pub_key'],
'day_0_config': context.properties['day_0_config'],
'service_account': '$(ref.service_accounts.email)',
'networks': context.properties['networks']
},
'metadata': {
'dependsOn': ['networking']
}
}
# Prepare all resources to be provisioned
resources += [services, sa, networking, vm]
outputs = [{
'name': 'vm_urls',
'value': '$(ref.vm.instance_urls)'
},{
'name': 'vm_external_ips',
'value': '$(ref.vm.vm_external_ips)'
}]
if haEnabled:
resources.append({
'name': 'load_balancer',
'type': 'load_balancer.py',
'properties': {
'region': context.properties['region'],
'num_instances': context.properties['num_instances'],
'vm_zones': context.properties['vm_zones'],
'named_ports': context.properties['named_ports'],
'service_port': context.properties['service_port'],
'allow_global_access': context.properties['allow_global_access'],
'inside_network': context.properties['inside_network'],
'use_internal_lb': context.properties['use_internal_lb']
# 'instance_urls': '$(ref.vm.instance_urls)'
},
'metadata': {
'dependsOn': ['vm']
}
})
outputs.append({
'name': 'external_lb_ip',
'value': '$(ref.load_balancer.external_lb_ip)'
})
if context.properties['use_internal_lb']:
outputs.append({
'name': 'internal_lb_ip',
'value': '$(ref.load_balancer.internal_lb_ip)'
})
return {'resources': resources, 'outputs': outputs} | def generate_config(context):
resources = []
ha_enabled = context.properties['num_instances'] > 1
services = {'name': 'enable_services', 'type': 'enable_services.py', 'properties': {'services': context.properties['services']}}
networking = {'name': 'networking', 'type': 'networking.py', 'properties': {'ha_enabled': haEnabled, 'region': context.properties['region'], 'mgmt_network': context.properties['mgmt_network'], 'custom_route_tag': context.properties['custom_route_tag'], 'service_account': '$(ref.service_accounts.email)', 'service_port': context.properties['service_port'], 'networks': context.properties['networks']}}
if 'inside_network' in context.properties:
networking['properties']['inside_network'] = context.properties['inside_network']
if 'outside_network' in context.properties:
networking['properties']['outside_network'] = context.properties['outside_network']
if 'dmz1_network' in context.properties:
networking['properties']['dmz1_network'] = context.properties['dmz1_network']
if 'dmz2_network' in context.properties:
networking['properties']['dmz2_network'] = context.properties['dmz2_network']
sa = {'name': 'service_accounts', 'type': 'service_accounts.py', 'properties': {'account_id': context.properties['account_id'], 'display_name': context.properties['display_name']}, 'metadata': {'dependsOn': ['enable_services']}}
vm = {'name': 'vm', 'type': 'vm.py', 'properties': {'vm_zones': context.properties['vm_zones'], 'num_instances': context.properties['num_instances'], 'cisco_product_version': context.properties['cisco_product_version'], 'vm_machine_type': context.properties['vm_machine_type'], 'vm_instance_labels': context.properties['vm_instance_labels'], 'vm_instance_tags': context.properties['vm_instance_tags'], 'admin_ssh_pub_key': context.properties['admin_ssh_pub_key'], 'day_0_config': context.properties['day_0_config'], 'service_account': '$(ref.service_accounts.email)', 'networks': context.properties['networks']}, 'metadata': {'dependsOn': ['networking']}}
resources += [services, sa, networking, vm]
outputs = [{'name': 'vm_urls', 'value': '$(ref.vm.instance_urls)'}, {'name': 'vm_external_ips', 'value': '$(ref.vm.vm_external_ips)'}]
if haEnabled:
resources.append({'name': 'load_balancer', 'type': 'load_balancer.py', 'properties': {'region': context.properties['region'], 'num_instances': context.properties['num_instances'], 'vm_zones': context.properties['vm_zones'], 'named_ports': context.properties['named_ports'], 'service_port': context.properties['service_port'], 'allow_global_access': context.properties['allow_global_access'], 'inside_network': context.properties['inside_network'], 'use_internal_lb': context.properties['use_internal_lb']}, 'metadata': {'dependsOn': ['vm']}})
outputs.append({'name': 'external_lb_ip', 'value': '$(ref.load_balancer.external_lb_ip)'})
if context.properties['use_internal_lb']:
outputs.append({'name': 'internal_lb_ip', 'value': '$(ref.load_balancer.internal_lb_ip)'})
return {'resources': resources, 'outputs': outputs} |
# -*- encoding: utf-8 -*-
class UnWellcomeException(Exception):
"""
Base exception for all exceptions raised by this library.
"""
pass
| class Unwellcomeexception(Exception):
"""
Base exception for all exceptions raised by this library.
"""
pass |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.