content
stringlengths 7
1.05M
|
|---|
n=int(input())
while n:
n-=1
print(pow(*map(int,input().split()),10**9+7))
|
x = float(input('digite o segmento 1: '))
y = float(input('digite o segmento 2: '))
z = float(input('digite o segmento 3: '))
if x < y + z and y < x + z and z < x + y:
print(f'os segmentos {x, y, z} formam um Triangulo')
else:
print(f'os segmentos {x, y, z} NÃO formam um Triangulo')
|
# Wrapper class to make dealing with logs easier
class ChannelLog():
__channel = ""
__logs = []
unread = False
mentioned_in = False
# the index of where to start printing the messages
__index = 0
def __init__(self, channel, logs):
self.__channel = channel
self.__logs = list(logs)
def get_server(self): return self.__channel.server
def get_channel(self): return self.__channel
def get_logs(self):
return self.__logs
def get_name(self):
return self.__channel.name
def get_server_name(self):
return self.__channel.server.name
def append(self, message):
self.__logs.append(message)
def index(self, message):
return self.__logs.index(message)
def insert(self, i, message):
self.__logs.insert(i, message)
def len(self):
return len(self.__logs)
def get_index(self):
return self.__index
def set_index(self, int):
self.__index = int
def inc_index(self, int):
self.__index += int
def dec_index(self, int):
self.__index -= int
|
l= int(input("Enter the size of array \n"))
a=input("Enter the integer inputs\n").split()
c=0
a[0]=int(a[0])
for i in range(1,l):
a[i]=int(a[i])
while a[i]<a[i-1]:
c+=1
a[i]+=1
print(c)
|
1 == 2
segfault()
class Dupe(object):
pass
class Dupe(Dupe):
pass
|
# General Errors
NO_ERROR = 0
USER_EXIT = 1
ERR_SUDO_PERMS = 100
ERR_FOUND = 101
ERR_PYTHON_PKG = 154
# Warnings
WARN_FILE_PERMS = 115
WARN_LOG_ERRS = 126
WARN_LOG_WARNS = 127
WARN_LARGE_FILES = 151
# Installation Errors
ERR_BITS = 102
ERR_OS_VER = 103
ERR_OS = 104
ERR_FINDING_OS = 105
ERR_FREE_SPACE = 106
ERR_PKG_MANAGER = 107
ERR_OMSCONFIG = 108
ERR_OMI = 109
ERR_SCX = 110
ERR_OMS_INSTALL = 111
ERR_OLD_OMS_VER = 112
ERR_GETTING_OMS_VER = 113
ERR_FILE_MISSING = 114
ERR_CERT = 116
ERR_RSA_KEY = 117
ERR_FILE_EMPTY = 118
ERR_INFO_MISSING = 119
ERR_PKG = 152
# Connection Errors
ERR_ENDPT = 120
ERR_GUID = 121
ERR_OMS_WONT_RUN = 122
ERR_OMS_STOPPED = 123
ERR_OMS_DISABLED = 124
ERR_FILE_ACCESS = 125
# Heartbeat Errors
ERR_HEARTBEAT = 128
ERR_MULTIHOMING = 129
ERR_INTERNET = 130
ERR_QUERIES = 131
# High CPU / Memory Usage Errors
ERR_OMICPU = 141
ERR_OMICPU_HOT = 142
ERR_OMICPU_NSSPEM = 143
ERR_OMICPU_NSSPEM_LIKE = 144
ERR_SLAB = 145
ERR_SLAB_BLOATED = 146
ERR_SLAB_NSSSOFTOKN = 147
ERR_SLAB_NSS = 148
ERR_LOGROTATE_SIZE = 149
ERR_LOGROTATE = 150
# Syslog Errors
ERR_SYSLOG_WKSPC = 132
ERR_PT = 133
ERR_PORT_MISMATCH = 134
ERR_PORT_SETUP = 135
ERR_SERVICE_CONTROLLER = 136
ERR_SYSLOG = 137
ERR_SERVICE_STATUS = 138
# Custom Log Errors
ERR_CL_FILEPATH = 139
ERR_CL_UNIQUENUM = 140
ERR_BACKEND_CONFIG = 153
|
"{variable_name:format_description}"
print('{a:<10}|{a:^10}|{a:>10}'.format(a='test'))
print('{a:~<10}|{a:~^10}|{a:~>10}'.format(a='test'))
person = {"first":"Joran","last":"Beasley"}
print("{p[first]} {p[last]}".format(p=person))
data = range(100)
print("{d[0]}...{d[99]}".format(d=data))
print("normal:{num:d}".format(num=33))
print("normal:{num:f}".format(num=33))
print("binary:{num:b}".format(num=33))
print("binary:{num:08b}".format(num=33))
print("hex:{num:x}".format(num=33))
print("hex:0x{num:0<4x}".format(num=33))
print("octal:{num:o}".format(num=33))
print("{num:f}".format(num=22/7))
print("${num:0.2f}".format(num=22/7))
print("{num:.2e}".format(num=22/7))
print("{num:.1%}".format(num=22/7))
print("{num:g}".format(num=5.1200001))
variable=27
print(f"{variable}")
|
def solution(A,B,K):
count = 0
for i in range(A,B):
if(i%K==0):
count += 1
#print(count)
return count
solution(6,11,2)
|
# -*- coding: utf-8 -*-
class Solution:
def getLucky(self, s: str, k: int) -> int:
result = ''.join(str(ord(c) - ord('a') + 1) for c in s)
for _ in range(k):
result = sum(int(digit) for digit in str(result))
return result
if __name__ == '__main__':
solution = Solution()
assert 36 == solution.getLucky('iiii', 1)
assert 6 == solution.getLucky('leetcode', 2)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def getInput():
return input()
def testInput(a):
try:
val = int(a)
except ValueError:
return False
return True
def strToInt(a):
return int(a)
def printInt(a):
print(a)
if __name__ == '__main__':
a = getInput()
isIntable = testInput(a)
if isIntable:
printInt(strToInt(a))
else:
print("Значение не может быть преобразовано к целому числу.")
|
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 3 10:38:41 2018
@author: lenovo
"""
# =============================================================================
# 13. Roman to Integer
# Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
#
# Symbol Value
# I 1
# V 5
# X 10
# L 50
# C 100
# D 500
# M 1000
#
# For example, two is written as II in Roman numeral, just two one's added together. Twelve is written as, XII, which is simply X + II. The number twenty seven is written as XXVII, which is XX + V + II.
#
# Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:
#
# I can be placed before V (5) and X (10) to make 4 and 9.
# X can be placed before L (50) and C (100) to make 40 and 90.
# C can be placed before D (500) and M (1000) to make 400 and 900.
#
# Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999.
#
# Example 1:
#
# Input: "III"
# Output: 3
#
# Example 2:
#
# Input: "IV"
# Output: 4
#
# Example 3:
#
# Input: "IX"
# Output: 9
#
# Example 4:
#
# Input: "LVIII"
# Output: 58
# Explanation: C = 100, L = 50, XXX = 30 and III = 3.
#
# Example 5:
#
# Input: "MCMXCIV"
# Output: 1994
# Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
# =============================================================================
# =============================================================================
# difficulty: easy
# acceptance: 49.0%
# contributor: LeetCode
# =============================================================================
class Solution:
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
length = len(s)
if length == 0:
return 0
d1 = {'IV':4,
'IX':9,
'XL':40,
'XC':90,
'CD':400,
'CM':900}
d2 = {'V':5,
'L':50,
'D':500,
'M':1000}
d3 = {'I':1,
'X':10,
'C':100
}
result = 0
index = 0
while index < length:
# for index, item in enumerate(s):
item = s[index]
if item in d3:
i = index
number = 0
while i + 1 < length and s[i + 1] == item:
i += 1
j = i + 1
if j < length and s[i:j + 1] in d1:
number = d1[s[i:j + 1]] + (j - index - 1) * d3[item]
result += number
index = j + 1
else:
number = (j - index) * d3[item]
result += number
index = j
else:
i = index
number = 0
while i + 1 < length and s[i + 1] == item:
i += 1
j = i + 1
number = (j - index) * d2[item]
result += number
index = j
return result
#------------------------------------------------------------------------------
# note: below is the test code
test = 'IX'
S = Solution()
result = S.romanToInt(test)
print(result)
#------------------------------------------------------------------------------
# note: below is the submission detail
# =============================================================================
# Submission Detail
# 3999 / 3999 test cases passed.
# Status: Accepted
# Runtime: 156 ms
# beats 15.44% python3 submissions
# Submitted: 0 minutes ago
# =============================================================================
|
def calc_average(case):
sum = 0
count = int(case[0])
for i in range(1, count + 1):
sum += int(case[i])
return sum / count
def count_average(case, average):
count = 0
count_num = int(case[0])
for i in range(1, count_num + 1):
if average < int(case[i]):
count += 1
return count
count_case = int(input())
cases = list()
for i in range(0, count_case):
cases.append(list(input().split()))
for case in cases:
average = calc_average(case)
print('%.3f' % round(count_average(case, average) / int(case[0]) * 100, 3) + '%')
|
"""
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
Example 1:
Input: n = 3
Output: ["((()))","(()())","(())()","()(())","()()()"]
Example 2:
Input: n = 1
Output: ["()"]
Constraints:
1 <= n <= 8
"""
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
ans = []
self.helper(0, 0, "", n, ans)
return ans
def helper(self, left, right, current, n, ans):
if left < right:
return
if left == n and right == n:
ans.append(current)
return
if left > n or right > n:
return
new_current = current + "("
self.helper(left + 1, right, new_current, n, ans)
new_current = current + ")"
self.helper(left, right + 1, new_current, n, ans)
|
def decorator(func):
def wrapper():
print("Decoring")
func()
print("Done!")
return wrapper
@decorator
def say_hi():
print("Hi!")
if __name__ == "__main__":
say_hi()
|
class Solution:
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
if (n < 3):
# Special cases
# 0 = 0:
# 1 = 1: 1
# 2 = 2: 2, 1 1
return n
else: # Fibonaci from here onward
# 3 = 3: 1 1 1, 2 1, 1 2
# 4 = 5: 1 1 1 1, 2 1 1, 1 2 1, 1 1 2, 2 2
# 5 = 8: 1 1 1 1 1, 2 1 1 1, 1 2 1 1 , 1 1 2 1, 1 1 1 2, 2 2 1, 1 2 2, 2 1 2
# 6 = 13: 1 1 1 1 1 1, 2 1 1 1 1, 1 2 1 1 1, 1 1 2 1 1, 1 1 1 2 1, 1 1 1 1 2,
# Fibonaci pattern spotted as shown above...
preprev = 1 # Resume from special cases
prev = 2 # Resume from special cases
for i in range(n-2): # omit the first two steps
temp = preprev
preprev = prev # update preprev for next iter
prev = prev + temp # update prev for next iter
return prev
|
s = pd.Series(
data=np.random.randn(NUMBER),
index=pd.date_range('2000-01-01', freq='D', periods=NUMBER))
result = s['2000-02-14':'2000-02']
|
# https://edabit.com/challenge/Yx2a9B57vXRuPevGh
# Create a function that takes length and width and finds the perimeter of a rectangle.
def find_perimeter(x: int, y: int) -> int:
perimeter = (x * 2) + (y * 2)
return perimeter
print(find_perimeter(20, 10))
|
# 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 isSameTree(self, p, q):
"""
:type p: TreeNode
:type q: TreeNode
:rtype: bool
"""
return self.iterative(p, q)
def recursive(self, p, q):
check = self.nodeCheck(p, q)
if check == 0:
return True
elif check == 1:
return False
return self.recursive(p.left, q.left) and self.recursive(p.right, q.right)
def iterative(self, p, q):
queue = [(p, q)]
while queue:
p, q = queue.pop(0)
check = self.nodeCheck(p, q)
if check % 2 == 1:
return False
if p:
queue.append((p.left, q.left))
queue.append((p.right, q.right))
return True
def nodeCheck(self, p, q):
if not p and not q:
return 0
if not p or not q:
return 1
if p.val != q.val:
return 1
return 2
|
"""
Chapter 02 - Problem 01 - remove duplicates - CTCI 6th Edition
Problem Statement:
Write code to remove duplicates from unsorted linked list
FOLLOW UP : How would you solve this problem if temporary buffer is not allowed.
"""
def remove_dups(head): # O(n) speed with O(n) space for hash table
hash_table = {head.value: True}
while head is not None:
if head.next_node is not None:
if hash_table.get(head.next_node.value, None) is not None:
head.next_node = head.next_node.next_node
else:
hash_table[head.next_node.value] = True
head = head.next_node
def remove_dups_alternative(head): # O(n^2) speed with O(1) space due to no hash table
while head is not None:
runner = head
while runner is not None:
if runner.next_node is not None and runner.next_node.value == head.value:
if runner.next_node is None:
break
else:
runner.next_node = runner.next_node.next_node
runner = runner.next_node
head = head.next_node
|
# -*- coding: utf-8 -*-
# This file is generated from NI Switch Executive API metadata version 21.0.0d1
config = {
'api_version': '21.0.0d1',
'c_function_prefix': 'niSE_',
'close_function': 'CloseSession',
'context_manager_name': {
},
'custom_types': [
],
'driver_name': 'NI Switch Executive',
'driver_registry': 'Switch Executive',
'extra_errors_used': [
'InvalidRepeatedCapabilityError'
],
'init_function': 'OpenSession',
'library_info': {
'Linux': {
'64bit': {
'name': 'nise',
'type': 'cdll'
}
},
'Windows': {
'32bit': {
'name': 'nise.dll',
'type': 'windll'
},
'64bit': {
'name': 'nise.dll',
'type': 'cdll'
}
}
},
'metadata_version': '2.0',
'module_name': 'nise',
'repeated_capabilities': [
],
'session_class_description': 'An NI Switch Executive session',
'session_handle_parameter_name': 'vi',
'use_locking': False
}
|
"""A utility module turning English into machine-readable data."""
def oxford_comma_text_to_list(phrase):
"""Examples:
- 'Eeeny, Meeny, Miney, and Moe' --> ['Eeeny', 'Meeny', 'Miney', 'Moe']
- 'Black and White' --> ['Black', 'White']
- 'San Francisco and Saint Francis' -->
['San Francisco', 'Saint Francisco']
"""
items = []
for subphrase in phrase.split(', '):
items.extend(
[item.strip() for item in subphrase.split(' and ')])
return items
|
class DomainServiceBase:
def __init__(self, repository):
self.repository = repository
def update(self, obj, updated_data={}):
self.repository.update(obj, updated_data)
def delete(self, obj):
self.repository.delete(obj)
def create(self, obj):
obj = self.repository.create(obj)
return obj
def get_all(self, query_params={}, orderby=[], select_related=[]):
return self.repository.get_all(query_params, orderby, select_related)
def get(self, query_params={}, select_related=[]):
return self.repository.get(query_params, select_related)
|
# score_manager.py
#Score Manager
ENEMY_SCORE = 300
RUPEE_SCORE = 500
scores = {
"ENEMY": ENEMY_SCORE,
"RUPEE": RUPEE_SCORE,
}
my_scores = {
"ENEMY": 300,
"MONEY": 1000,
"LASER": 1000,
"HP": 200,
"DEFENSE": 100
}
def calculate_score(score_type):
return my_scores[score_type]
|
'''
Created on Mar 1, 2016
@author: kashefy
'''
class Phase:
TRAIN = 'Train'
TEST = 'Test'
|
class Node:
#Initialize node oject
def __init__(self, data):
self.data = data #assign data
self.next = None #declare next as null
class LinkedList:
#Initialize head
def __init__(self):
self.head = None
#### Insert in the beginning
def push(self, content):
#Allocate node, Put data
new_node = Node(content)
#attach head after new_node
new_node.next = self.head
#set new_node as current head
self.head = new_node
#### Insert in the middle
def insertAfter(self, prev_node, content):
if prev_node is None:
print("Prev Node invalid")
return
new_node = Node(content)
new_node.next = prev_node.next
prev_node.next = new_node
#### Insert at last
def append(self, content):
new_node = Node(content)
#If Linkedlist is empty
if self.head is None:
self.head = new_node
return
#Else, traverse to last node
last = self.head
while (last.next):
last = last.next
#attach new node
last.next = new_node
### PRINT LIST
def printlist(self):
temp = self.head
while (temp):
print(temp.data)
temp = temp.next
#### Delete node using key
def deleteNode_key(self, key):
temp = self.head
#for head node
if temp is not None:
if temp.data == key:
self.head = temp.next
temp = None
return
#moving ahead from head node, until key found
while(temp is not None):
if temp.data == key:
break
prev = temp
temp = temp.next
#if not found
if temp == None:
return
#Unlink node
prev.next = temp.next
temp = None
#### Delete node using position
def deleteNode_pos(self, pos):
if self.head is None:
return
temp = self.head
#to delete head
if pos == 0:
self.head = temp.next
temp = None
return
#find previous node of the node to be deleted
for i in range(pos-1):
temp = temp.next
if temp is None:
break
if temp is None:
return
if temp.next is None:
return
#store next to next node to be deleted
next = temp.next.next
#unlink
temp.next = None
temp.next = next
#### Find length
def listlength(self):
len = 0
if self.head is None:
print("Len = ",len)
return
temp = self.head
while temp:
len += 1
temp = temp.next
print("Len = ", len)
#### REVERSE
def reverse(self):
prev = None
current = self.head
while(current is not None):
next = current.next
current.next = prev
prev = current
current = next
self.head = prev
if __name__ == '__main__':
list1 = LinkedList()
list1.append(6)
list1.append(3)
list1.push(4)
list1.insertAfter(list1.head.next, 1)
list1.printlist()
print("______")
list1.listlength()
print("______")
list1.deleteNode_key(4)
list1.printlist()
print("______")
list1.reverse()
list1.printlist()
print("______")
list1.deleteNode_pos(1)
list1.printlist()
print("______")
|
# encoding = utf-8
__author__ = "Ang Li"
class Person:
age = 100
def __init__(self, name):
self.name = name
tom = Person('Tom')
print(tom.age) # tom 中没有定义age,访问的是类的,如果类中没有会接着访问上层的父类的
print(*tom.__dict__.items()) # 但是这种访问,是直接访问,tom实例并不会 并不会新增一个age属性。
|
"""
Lab 7 python file
"""
#
print("\n3.1")
current_number=-1
while current_number<6:
current_number +=1
if (current_number==3 or current_number==6):
continue
print(current_number)
#
print("\n3.2")
n=int(input("Enter a number:"))
factorial=1
while n>=1:
factorial=factorial*n
n=n-1
print(factorial)
#
print("\n3.3")
n=5
sum=0
total_numbers=n
while n>=0:
sum=sum+n
n=n-1
print(sum)
#
print("\n3.4")
x=3
product=1
while x in range(3,9):
product=product*x
x=x+1
print(product)
#
print("\n3.5")
x=1
product=1
while x in range(1,9):
product=product*x
x=x+1
print(product)
y=1
divisor=1
while y in range(1,4):
divisor=divisor*y
y=y+1
print(divisor)
final_answer=(product/divisor)
print(final_answer)
#
print("\n3.6")
num_list=[12,32,43,35]
print(num_list)
while num_list:
num_list.pop(0)
print(num_list)
|
class Solution:
# @param {character[][]} matrix
# @return {integer}
def maximalSquare(self, matrix):
if not matrix:
return 0
max_square = 0
self.visited = []
for line in matrix:
row = []
for c in line:
row.append(0)
self.visited.append(row)
self.visited[0] = [int(c) for c in matrix[0]]
max_square = max(self.visited[0])
for i, row in enumerate(self.visited):
k = int(matrix[i][0])
if k > max_square:
max_square = k
row[0] = k
for i in range(1, len(matrix)):
for j in range(1, len(matrix[0])):
if matrix[i][j] == "1":
self.visited[i][j] = (
min(
self.visited[i - 1][j],
self.visited[i][j - 1],
self.visited[i - 1][j - 1],
)
+ 1
)
if self.visited[i][j] > max_square:
max_square = self.visited[i][j]
return max_square ** 2
|
#!/usr/bin/python
#------------------------------------------------------------------------------
class Solution:
def threeSumClosest(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
nums.sort()
result = float('inf')
# Loop through each index, then use two pointers to close in the rest of the array
for i in range(len(nums)-2):
l, r = i+1, len(nums)-1
while l < r:
# Current sum of the three elements
curr_sum = nums[i] + nums[l] + nums[r]
# If the difference is smaller, make it the result
if abs(target - curr_sum) < abs(target - result):
result = curr_sum
if curr_sum == target:
return curr_sum
elif curr_sum < target:
l += 1
else:
r -= 1
return result
#------------------------------------------------------------------------------
#Testing
main()
|
class Sensores:
def __init__(self, ambiente, simboloCampoVazio, getTodasPecas):
self.IAmbiente = ambiente
self.ISimboloCampoVazio = simboloCampoVazio
self.IJogadorUmPeca, self.IJogadorDoisPeca = getTodasPecas
# retorna a posição do vetor que se jogada, ganha o jogo
def verificaSeGanha(self, pecaQualquerJogador):
simbolo = self.ISimboloCampoVazio
campo = self.IAmbiente.getCampo()
peca = pecaQualquerJogador
if campo[0] == peca and campo[1] == peca:
if campo[2] == simbolo:
return 2
if campo[0] == peca and campo[2] == peca:
if campo[1] == simbolo:
return 1
if campo[1] == peca and campo[2] == peca:
if campo[0] == simbolo:
return 0
if campo[3] == peca and campo[4] == peca:
if campo[5] == simbolo:
return 5
if campo[3] == peca and campo[5] == peca:
if campo[4] == simbolo:
return 4
if campo[4] == peca and campo[5] == peca:
if campo[3] == simbolo:
return 3
if campo[6] == peca and campo[7] == peca:
if campo[8] == simbolo:
return 8
if campo[6] == peca and campo[8] == peca:
if campo[7] == simbolo:
return 7
if campo[7] == peca and campo[8] == peca:
if campo[6] == simbolo:
return 6
if campo[0] == peca and campo[3] == peca:
if campo[6] == simbolo:
return 6
if campo[0] == peca and campo[6] == peca:
if campo[3] == simbolo:
return 3
if campo[3] == peca and campo[6] == peca:
if campo[0] == simbolo:
return 0
if campo[1] == peca and campo[4] == peca:
if campo[7] == simbolo:
return 7
if campo[1] == peca and campo[7] == peca:
if campo[4] == simbolo:
return 4
if campo[4] == peca and campo[7] == peca:
if campo[1] == simbolo:
return 1
if campo[2] == peca and campo[5] == peca:
if campo[8] == simbolo:
return 8
if campo[2] == peca and campo[8] == peca:
if campo[5] == simbolo:
return 5
if campo[5] == peca and campo[8] == peca:
if campo[2] == simbolo:
return 2
if campo[0] == peca and campo[4] == peca:
if campo[8] == simbolo:
return 8
if campo[0] == peca and campo[8] == peca:
if campo[4] == simbolo:
return 4
if campo[4] == peca and campo[8] == peca:
if campo[0] == simbolo:
return 0
if campo[2] == peca and campo[4] == peca:
if campo[6] == simbolo:
return 6
if campo[2] == peca and campo[6] == peca:
if campo[4] == simbolo:
return 4
if campo[4] == peca and campo[6] == peca:
if campo[2] == simbolo:
return 2
return -1
# verifica se o a quantida de X e O no campo são
# iguais para determinar de quem é a vez de jogar
def vezDoJogadorUm(self):
campo = self.IAmbiente.getCampo()
pecaUm = self.IJogadorUmPeca
pecaDois = self.IJogadorDoisPeca
if campo.count(pecaUm) == campo.count(pecaDois):
return True
elif campo.count(pecaUm) != campo.count(pecaDois):
return False
def rodadaAtual(self):
campo = self.IAmbiente.getCampo()
radadaAtual = 9 - campo.count('_')
return radadaAtual
|
#! /usr/bin/python3.7
# soh cah toa
def sin():
o = float(input('What is the oppisite?: '))
h = float(input("What is the hypotnuse?: "))
s = o / h
print("sin = {}".format(s))
def cos():
a = float(input('What is the ajacent?: '))
h = float(input("What is the hypotnuse?: "))
c = a / h
print('cos = {}'.format(c))
def tan():
o = float(input("What is the oppisite?: "))
a = float(input("What is the ajacent?: "))
t = o / a
print("tan = {}".format(t))
def main():
userInt = input('What are we solving for (sin cos or tan)?: ').lower()
if userInt == 'sin':
sin()
elif userInt == 'cos':
cos()
elif userInt == 'tan':
tan()
else:
print('An error has occured please try again')
main()
|
# Scale Settings
# For 005.mp4
SCALE_WIDTH = 25
SCALE_HEIGHT = 50
# SCALE_WIDTH = 100
# SCALE_HEIGHT = 100
# Video Settings
DETECT_AFTER_N = 50
# NMS Settings
NMS_CONFIDENCE = 0.1
NMS_THRESHOLD = 0.1
# Detection Settings
DETECTION_CONFIDENCE = 0.9
# Tracker Settings
MAX_DISAPPEARED = 50
|
a=int(input("Enter the first number:"))
b=int(input("Enter the second number:"))
c=int(input("Enter the third number:"))
if a<b in c>a:
min=a
elif a<b in c>b:
min=b
else:
min=c
print(min)
|
class setx:
def __init__(self, iterable=[]):
self.iterable = set(iterable)
self.size = len(self.iterable)
def __repr__(self):
return f"<{self.__class__.__name__.lower() !a}> {self.iterable}"
def add(self, element):
if element not in self.iterable:
self.iterable.add(element)
self.size += 1
print(element, self.iterable)
def add_s(self, elements):
temp = list(self.iterable)
temp.extend(elements)
self.iterable = set(temp)
self.size = len(self.iterable)
def clear(self):
self.iterable = setx()
self.size = 0
def pop(self):
if self.size < 1:
raise KeyError(
f"Can not pop from empyt {self.__name__.lower()}")
self.iterable.pop()
self.size -= 1
def get_size(self):
return self.size
def get_elements(self):
return self.iterable
def new(self, iterable=[]):
# self.iterable = setx(iterable)
self.iterable = iterable
s = setx(self.iterable)
self.size = s.get_size()
def check_type(self, other):
if type(other) not in [list, set, dict, tuple, setx]:
raise TypeError(
f"{self.__class__.__name__ !a} requires an iterable")
# else:
# return f"{type(other)!a}"
def difference(self, other):
self.check_type(other)
difference = set()
other = set(other)
for element in self.iterable:
if element not in other:
difference.add(element)
return difference
def intersection(self, other):
self.check_type(other)
intersection = set()
other = set(other)
for element in self.iterable:
if element in other:
intersection.add(element)
return intersection
def isdisjoint(self, other):
self.check_type(other)
other = set(other)
if not self.intersection(other):
return True
return False
def issubset(self, other):
self.check_type(other)
other = list(set(other))
size_of_others = 0
for element in other:
if element in self.iterable:
size_of_others += 1
if size_of_others == len(other):
return True
return False
def issuperset(self, other):
self.check_type(other)
other = set(other)
for element in self.iterable:
if element not in other:
return False
return True
def remove(self, element):
if element not in self.iterable:
raise KeyError(f"{element!a} not found {self.get()}")
temp = list(self.iterable)
index = temp.index(element)
del temp[index]
self.iterable = set(temp)
self.size = len(self.iterable)
return index
def symmetric_difference(self, other):
self.check_type(other)
other = set(other)
intersection = self.intersection(other)
symmetric_difference = set()
new_set = list(self.iterable) + list(other)
new_set = set(new_set)
for element in new_set:
if element not in intersection:
symmetric_difference.add(element)
return symmetric_difference
def cartesian_product(self, other):
# A x B = {(a, b)| a in A, b in B}
# |A x B| = |A| x |B| for A, B which are finite
self.check_type(other)
other = set(other)
size_cartesian_product = self.get_size() * len(other)
cartesian_product = set()
for a in self.iterable:
for b in other:
cartesian_product.add((a, b))
return cartesian_product, size_cartesian_product
def addtoAll(self, e, setobj):
for c in setobj:
c.append(e)
return setobj
def power_set(self, temp):
""" https://stackoverflow.com/a/58108857/10051170 """
if len(temp) == 0:
return [[]]
return self.addtoAll(temp[0], self.power_set(temp[1:])) + self.power_set(temp[1:])
# pass
# Let A be a finite set, n = |A | and P(A) be the power set of A
# P(A) = {X: X is a subset of A}, | P(A) | = 2 ** |A | = 2 ** n
#
# From the above there'd be n inserts
# P(A) may have {{}, {{X}: X in A}, ..., {{x1, x2, x3, ..., xn}: x in A}}
# then we'd fill up the ' ... '
#
# if n > 2
# there is no repetition as such {x1, x2} is the same as {x2, x1} and so on
# we could make use of 3 sets, A, tempA and tempB (where tempA and tempB
# are temporary variables)
# have two loops
# 1 - loop(0, n - 2)
# 2 - loop(0, n - 1)
# take from tempA, add from A to from tempB
# add tempB to the power set and make tempA tempB
|
def cycles_until_reseen(bins):
configs = set()
curr = bins
while tuple(curr) not in configs:
configs.add(tuple(curr))
min_idx = 0
for i in range(1, len(curr)):
if curr[i] > curr[min_idx]:
min_idx = i
redistribute = curr[min_idx]
curr[min_idx] = 0
all_gains = redistribute // len(bins)
partial_gain_bins = redistribute % len(bins)
for i in range(len(bins)):
curr[i] += all_gains
if i < partial_gain_bins:
curr[(min_idx+i+1) % len(bins)] += 1
return len(configs), curr
if __name__ == '__main__':
with open('6.txt') as f:
bins = [int(i) for i in f.read().split()]
num_cycles, last_seen = cycles_until_reseen(bins)
print("Part 1: {}".format(num_cycles))
loop_cycles, _ = cycles_until_reseen(last_seen)
print("Part 2: {}".format(loop_cycles))
|
n = int(input())
count_2 = 0
count_5 = 0
for i in range(2,n+1):
num = i
while(1):
if num%2 == 0:
count_2 += 1
num //= 2
elif num%5 == 0:
count_5 += 1
num //= 5
else: break
print(min(count_2,count_5))
|
# Copyright 2016-2020 Blue Marble Analytics LLC. All rights reserved.
"""
**Relevant tables:**
+--------------------------------+----------------------------------------------+
|:code:`scenarios` table column |:code:`project_new_potential_scenario_id` |
+--------------------------------+----------------------------------------------+
|:code:`scenarios` table feature |N/A |
+--------------------------------+----------------------------------------------+
|:code:`subscenario_` table |:code:`subscenarios_project_new_potential` |
+--------------------------------+----------------------------------------------+
|:code:`input_` tables |:code:`inputs_project_new_potential` |
+--------------------------------+----------------------------------------------+
If the project portfolio includes projects of a 'new' capacity type
(:code:`gen_new_bin`, :code:`gen_new_lin`, :code:`stor_new_bin`, or
:code:`stor_new_lin`), the user may specify the minimum and maximum
cumulative new capacity to be built in each period in the
:code:`inputs_project_new_potential` table. For storage project, the minimum
and maximum energy capacity may also be specified. All columns are optional
and NULL values are interpreted by GridPath as no constraint. Projects that
don't either a minimum or maximum cumulative new capacity constraints can be
omitted from this table completely.
"""
|
if 1:
N = int(input())
Q = int(input())
queries = []
for i in range(Q):
queries.append([int(x) for x in input().split()])
else:
N = 100000
queries = [
[2, 1, 2],
[4, 1, 2]
] * 10000
queries.append([4, 1, 2])
Q = len(queries)
isTransposed = False
xs = list(range(N + 1))
ys = list(range(N + 1))
for q in queries:
f = q[0]
if f == 4:
i, j = q[1:]
if isTransposed:
i, j = j, i
print(N * (xs[i] - 1) + ys[j] - 1)
elif f == 3:
isTransposed = not isTransposed
else:
i, j = q[1:]
if (f == 1) ^ isTransposed:
xs[i], xs[j] = xs[j], xs[i]
else:
ys[i], ys[j] = ys[j], ys[i]
|
# Location of the data.
reference_data_path = '/p/cscratch/acme/data/obs_for_acme_diags/'
test_data_path = '/p/cscratch/acme/data/test_model_data_for_acme_diags/'
# Name of the test model data, used to find the climo files.
test_name = '20161118.beta0.FC5COSP.ne30_ne30.edison'
# An optional, shorter name to be used instead of the test_name.
short_test_name = 'beta0.FC5COSP.ne30'
# What plotsets to run the diags on.
sets = ['lat_lon']
# Name of the folder where the results are stored.
results_dir = 'era_tas_land'
# Below are more optional arguments.
# 'mpl' is to create matplotlib plots, 'vcs' is for vcs plots.
backend = 'mpl'
# Title of the difference plots.
diff_title = 'Model - Obs.'
# Save the netcdf files for each of the ref, test, and diff plot.
save_netcdf = True
|
#
# Problem: Given an undirected graph with maximum degree, find a graph coloring using at most D+1 colors.
#
def color_graph_first_available(graph, colors):
"""
Solution: For each graph node, assign to it the first color not in the list of neighbor colors.
Complexity: (where n is # nodes, d is max degrees)
Time: O(n * (d + d+1 + 1)) -> O(n * d)
Space: O(g) -> size of graph
"""
# For every node
for node in graph:
if node in node.neighbors:
raise ValueError('cannot color graph with node loops')
# Look at each neighbor and create a set of their colors
neighbor_colors = set([neighbor.color for neighbor in node.neighbors if neighbor.color])
# Look at each color and create a set of available colors not in the neighbor colors set
available_colors = [color for color in colors if color not in neighbor_colors]
# Take the first available
node.color = available_colors[0]
def color_graph_first_available_slightly_faster(graph, colors):
"""
Solution: For each graph node, assign to it the first available color not used by one of its neighbors.
Complexity: (where n is # nodes, d is max degrees)
Time: O(n * d)
Space: O(g) -> size of graph
"""
for node in graph:
if node in node.neighbors:
raise ValueError('cannot color graph with node loops')
# Look at each neighbor and create a set of their colors
neighbor_colors = set([neighbor.color for neighbor in node.neighbors if neighbor.color])
for color in colors:
if color not in neighbor_colors:
node.color = color
break
|
file_name=str(input("Input the Filename:"))
if(file_name.split('.')[1]=='c'):
print('The extension of the file is C')
if(file_name.split('.')[1]=='cpp'):
print('The extension of the file is C++')
if(file_name.split('.')[1]=='java'):
print('The extension of the file is Java')
if(file_name.split('.')[1]=='py'):
print('The extension of the file is python')
if(file_name.split('.')[1]=='html'):
print('The extension of the file is HTMl')
|
#
# PySNMP MIB module INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:54:55 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")
ConstraintsUnion, SingleValueConstraint, ConstraintsIntersection, ValueSizeConstraint, ValueRangeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "SingleValueConstraint", "ConstraintsIntersection", "ValueSizeConstraint", "ValueRangeConstraint")
chassis, = mibBuilder.importSymbols("INTELCORPORATION-MULTI-FLEX-SERVER-MIB", "chassis")
groups, regModule = mibBuilder.importSymbols("INTELCORPORATION-MULTI-FLEX-SERVER-REG", "groups", "regModule")
Index, INT32withException, Power, PowerLedStates, IdromBinary16, FaultLedStates, FeatureSet, PresenceLedStates, Presence = mibBuilder.importSymbols("INTELCORPORATION-MULTI-FLEX-SERVER-TC", "Index", "INT32withException", "Power", "PowerLedStates", "IdromBinary16", "FaultLedStates", "FeatureSet", "PresenceLedStates", "Presence")
ObjectGroup, ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ObjectGroup", "ModuleCompliance", "NotificationGroup")
Unsigned32, ModuleIdentity, Integer32, NotificationType, MibScalar, MibTable, MibTableRow, MibTableColumn, Gauge32, ObjectIdentity, Counter64, TimeTicks, Counter32, Bits, iso, IpAddress, MibIdentifier = mibBuilder.importSymbols("SNMPv2-SMI", "Unsigned32", "ModuleIdentity", "Integer32", "NotificationType", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Gauge32", "ObjectIdentity", "Counter64", "TimeTicks", "Counter32", "Bits", "iso", "IpAddress", "MibIdentifier")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
multiFlexServerDrivesMibModule = ModuleIdentity((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 1, 1, 15))
multiFlexServerDrivesMibModule.setRevisions(('2007-08-16 12:00', '2007-07-20 16:45', '2007-06-07 20:30', '2007-06-07 13:30', '2007-05-30 17:00', '2007-04-18 19:05', '2007-04-09 15:45', '2007-04-09 15:30', '2007-03-27 11:30', '2007-03-14 11:30', '2007-03-06 10:30', '2007-02-22 17:00', '2006-12-28 17:30', '2006-12-05 10:30', '2006-11-27 15:30', '2006-11-20 13:30', '2006-11-07 11:30', '2006-10-02 10:24',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts: multiFlexServerDrivesMibModule.setRevisionsDescriptions(('Fixed up minor errors causing some managers grief (ommission or addition of commas in lists) Corrected a few entries that were marked as read-write when they should have been read-only', 'Minor edit to make MIB SMIv2 compliant Dropped driveBackplaneBmcFirmwareVersion as there is no BMC for the drive backplane', 'Added the IdromBinary16 to represent the asset tag, part number, and serial number fields within the IDROM fields.', 'Corrected maximum/nominal IDROM parameters and comments', 'Added enumeration for exceptions Added missing Presence column to sharedDriveTable', 'Moved the trees and chassis nodes around to accomodate the unique power supply characteristics', 'Moved driveBackplane IDROM data to sharedDrives tree from storage tree where it makes more logical sense Relocated both tables after the driveBackplane tree', 'Dropped sDriveAlias', 'Renamed all references of Array to StoragePool', 'Renamed all references of Disk to Drive Dropped redundant sDriveIndex (moved and replaced it with sDriveSlotNumber)', "Changed Mask representation from an Opaque to a DisplayString at the request of the architects such that it now is an ASCII representation of bit string reflecting the presence with the left most 'bit' being bit 1 and max* bits being represented.", 'Renamed MIB file and updated internal relevance to formal product name Multi-Flex Server', 'Corrected sharedDiskStatsTable INDEX to AUGMENTS.', "Updated several object types to reflect changes in the OEM objects. sDiskArrayID Integer32 -> INTEGER sDiskSequenceNumber Integer32 -> INTEGER sDiskDriveType DisplayString -> INTEGER Cleaned up some illegal character usage to make it SMIv2 compliant. Renamed all of the *Transfered to *Transferred Renumbered sharedDiskStatsTable to match OEM's.", 'Removed nolonger supported SATA & SAS drive feature tables Renumbered Stats from { sharedDisks 4 } to { sharedDisks 2 }', 'Replaced sharedDisksStats table index with sDiskIndex to be consistent with the rest of the tables. All tables are indexed by the drive ID', "Consolodated use of Presence datatype and changed 'chassis' to 'chassis'", "Partitioned off and created as it's own module",))
if mibBuilder.loadTexts: multiFlexServerDrivesMibModule.setLastUpdated('200708161200Z')
if mibBuilder.loadTexts: multiFlexServerDrivesMibModule.setOrganization('Intel Corporation')
if mibBuilder.loadTexts: multiFlexServerDrivesMibModule.setContactInfo('Brian Kurle Intel Corporation JF5-2-C3 Tel: 503-712-5032 E-Mail: brianx.j.kurle@intel.com')
if mibBuilder.loadTexts: multiFlexServerDrivesMibModule.setDescription('Shared Disks Module of the Multi-Flex Server')
maxSharedDrives = MibScalar((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 15), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: maxSharedDrives.setStatus('current')
if mibBuilder.loadTexts: maxSharedDrives.setDescription('Maximum number of Shared Drives possible in this chassis')
numOfSharedDrives = MibScalar((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 25), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: numOfSharedDrives.setStatus('current')
if mibBuilder.loadTexts: numOfSharedDrives.setDescription('The number of Shared Drives in the system')
sDrivePresenceMask = MibScalar((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 35), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: sDrivePresenceMask.setStatus('current')
if mibBuilder.loadTexts: sDrivePresenceMask.setDescription("ASCII representation of bit string reflecting the presence of the shared drives with the left most 'bit' being bit 1 and maxSharedDrives bits being represented. Thus, '11001111111111' would express that all the shared drives (of fourteen shared drives) are present with exception of drives 3 & 4")
sharedDrives = ObjectIdentity((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205))
if mibBuilder.loadTexts: sharedDrives.setStatus('current')
if mibBuilder.loadTexts: sharedDrives.setDescription('Container for Shared Drive specific information as well as all components logically contained within.')
driveBackplane = ObjectIdentity((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 1))
if mibBuilder.loadTexts: driveBackplane.setStatus('current')
if mibBuilder.loadTexts: driveBackplane.setDescription('IDROM information from the Drive Backplane')
driveBackplaneVendor = MibScalar((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 1, 1), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: driveBackplaneVendor.setStatus('current')
if mibBuilder.loadTexts: driveBackplaneVendor.setDescription('Device manufacturer')
driveBackplaneMfgDate = MibScalar((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 1, 2), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: driveBackplaneMfgDate.setStatus('current')
if mibBuilder.loadTexts: driveBackplaneMfgDate.setDescription('Manufacture date/time')
driveBackplaneDeviceName = MibScalar((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 1, 3), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: driveBackplaneDeviceName.setStatus('current')
if mibBuilder.loadTexts: driveBackplaneDeviceName.setDescription('Device Name')
driveBackplanePart = MibScalar((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 1, 4), IdromBinary16()).setMaxAccess("readonly")
if mibBuilder.loadTexts: driveBackplanePart.setStatus('current')
if mibBuilder.loadTexts: driveBackplanePart.setDescription('Device Part Number')
driveBackplaneSerialNo = MibScalar((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 1, 5), IdromBinary16()).setMaxAccess("readonly")
if mibBuilder.loadTexts: driveBackplaneSerialNo.setStatus('current')
if mibBuilder.loadTexts: driveBackplaneSerialNo.setDescription('Device Serial Number')
driveBackplaneMaximumPower = MibScalar((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 1, 6), Power()).setMaxAccess("readonly")
if mibBuilder.loadTexts: driveBackplaneMaximumPower.setStatus('current')
if mibBuilder.loadTexts: driveBackplaneMaximumPower.setDescription('Static maximum power generation / consumption (in watts): <0 - Negative numbers indicate device consumes power (in watts) >0 - Positive numbers indicate device generates power (in watts) 0 - Device is passive (does not not consume or generate power) -1 - Maximum power generation/consumption not known or specified')
driveBackplaneNominalPower = MibScalar((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 1, 7), Power()).setMaxAccess("readonly")
if mibBuilder.loadTexts: driveBackplaneNominalPower.setStatus('current')
if mibBuilder.loadTexts: driveBackplaneNominalPower.setDescription('Static Nominal power generation / consumption (in watts): <0 - Negative numbers indicate device consumes power (in watts) >0 - Positive numbers indicate device generates power (in watts) 0 - Device is passive (does not not consume or generate power) -1 - Nominal power generation/consumption not known or specified')
driveBackplaneAssetTag = MibScalar((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 1, 8), IdromBinary16()).setMaxAccess("readonly")
if mibBuilder.loadTexts: driveBackplaneAssetTag.setStatus('current')
if mibBuilder.loadTexts: driveBackplaneAssetTag.setDescription('Asset Tag # of device')
sharedDriveTable = MibTable((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 2), )
if mibBuilder.loadTexts: sharedDriveTable.setStatus('current')
if mibBuilder.loadTexts: sharedDriveTable.setDescription('Each row describes a shared drive in the chassis')
sharedDriveEntry = MibTableRow((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 2, 1), ).setIndexNames((0, "INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "sDriveSlotNumber"))
if mibBuilder.loadTexts: sharedDriveEntry.setStatus('current')
if mibBuilder.loadTexts: sharedDriveEntry.setDescription('The parameters of a physical drive.')
sDriveSlotNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 2, 1, 1), Index()).setMaxAccess("readonly")
if mibBuilder.loadTexts: sDriveSlotNumber.setStatus('current')
if mibBuilder.loadTexts: sDriveSlotNumber.setDescription('The slot number on the enclosure where the drive is located (drive ID)')
sDrivePresence = MibTableColumn((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 2, 1, 2), Presence()).setMaxAccess("readonly")
if mibBuilder.loadTexts: sDrivePresence.setStatus('current')
if mibBuilder.loadTexts: sDrivePresence.setDescription('column used to flag the existence of a particular FRU')
sDriveInterface = MibTableColumn((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 2, 1, 3), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: sDriveInterface.setStatus('current')
if mibBuilder.loadTexts: sDriveInterface.setDescription('The Drive Interface of the physical drive.')
sDriveModelNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 2, 1, 4), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: sDriveModelNumber.setStatus('current')
if mibBuilder.loadTexts: sDriveModelNumber.setDescription('The Model Number of the physical drive.')
sDriveSerialNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 2, 1, 5), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: sDriveSerialNumber.setStatus('current')
if mibBuilder.loadTexts: sDriveSerialNumber.setDescription('The Serial Number of the physical drive.')
sDriveFirmwareVersion = MibTableColumn((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 2, 1, 6), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: sDriveFirmwareVersion.setStatus('current')
if mibBuilder.loadTexts: sDriveFirmwareVersion.setDescription('The Firmware Version of the physical drive.')
sDriveProtocolVersion = MibTableColumn((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 2, 1, 7), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: sDriveProtocolVersion.setStatus('current')
if mibBuilder.loadTexts: sDriveProtocolVersion.setDescription('The Protocol Version of the physical drive.')
sDriveOperationalStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 2, 1, 8), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: sDriveOperationalStatus.setStatus('current')
if mibBuilder.loadTexts: sDriveOperationalStatus.setDescription('The Operational Status of the physical drive.')
sDriveCondition = MibTableColumn((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 2, 1, 9), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: sDriveCondition.setStatus('current')
if mibBuilder.loadTexts: sDriveCondition.setDescription('The condition of the physical drive, e.g. PFA.')
sDriveOperation = MibTableColumn((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 2, 1, 10), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: sDriveOperation.setStatus('current')
if mibBuilder.loadTexts: sDriveOperation.setDescription('The current operation on the physical drive, e.g. mediapatrolling, migrating.')
sDriveConfiguration = MibTableColumn((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 2, 1, 11), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: sDriveConfiguration.setStatus('current')
if mibBuilder.loadTexts: sDriveConfiguration.setDescription('The configuration on the physical drive, e.g. array %d seqno %d, or dedicated spare.')
sDriveStoragePoolID = MibTableColumn((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 2, 1, 12), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-32, -16, -1, 256))).clone(namedValues=NamedValues(("notApplicable", -32), ("unknown", -16), ("unavailable", -1), ("notavailable", 256)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: sDriveStoragePoolID.setStatus('current')
if mibBuilder.loadTexts: sDriveStoragePoolID.setDescription('The drive array id, if the physical drive is part of a drive array; the spare id, if the drive is a spare.')
sDriveSequenceNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 2, 1, 13), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-32, -16, -1))).clone(namedValues=NamedValues(("notApplicable", -32), ("unknown", -16), ("unavailable", -1)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: sDriveSequenceNumber.setStatus('current')
if mibBuilder.loadTexts: sDriveSequenceNumber.setDescription('The sequence number of the drive in the drive array. Valid only when the drive is part of a drive array.')
sDriveEnclosureID = MibTableColumn((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 2, 1, 14), INT32withException()).setMaxAccess("readonly")
if mibBuilder.loadTexts: sDriveEnclosureID.setStatus('current')
if mibBuilder.loadTexts: sDriveEnclosureID.setDescription('The id of the enclosure to which the drive is inserted.')
sDriveBlockSize = MibTableColumn((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 2, 1, 15), INT32withException()).setMaxAccess("readonly")
if mibBuilder.loadTexts: sDriveBlockSize.setStatus('current')
if mibBuilder.loadTexts: sDriveBlockSize.setDescription(' The Block Size in bytes of the physical drive.')
sDrivePhysicalCapacity = MibTableColumn((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 2, 1, 16), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: sDrivePhysicalCapacity.setStatus('current')
if mibBuilder.loadTexts: sDrivePhysicalCapacity.setDescription(' The Physical Size in bytes of the physical drive.')
sDriveConfigurableCapacity = MibTableColumn((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 2, 1, 17), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: sDriveConfigurableCapacity.setStatus('current')
if mibBuilder.loadTexts: sDriveConfigurableCapacity.setDescription(' The Configurable Size in bytes of the physical drive.')
sDriveUsedCapacity = MibTableColumn((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 2, 1, 18), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: sDriveUsedCapacity.setStatus('current')
if mibBuilder.loadTexts: sDriveUsedCapacity.setDescription('The Used Size in bytes of the physical drive.')
sDriveType = MibTableColumn((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 2, 1, 19), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-32, -16, -1, 1, 4))).clone(namedValues=NamedValues(("notApplicable", -32), ("unknown", -16), ("unavailable", -1), ("sata", 1), ("sas", 4)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: sDriveType.setStatus('current')
if mibBuilder.loadTexts: sDriveType.setDescription('The type of the physical drive. e.g. SATA or SAS')
sharedDriveStatsTable = MibTable((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 3), )
if mibBuilder.loadTexts: sharedDriveStatsTable.setStatus('current')
if mibBuilder.loadTexts: sharedDriveStatsTable.setDescription('A table of Physical Drive Statistics (augments sharedDriveTable)')
sharedDriveStatsEntry = MibTableRow((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 3, 1), )
sharedDriveEntry.registerAugmentions(("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "sharedDriveStatsEntry"))
sharedDriveStatsEntry.setIndexNames(*sharedDriveEntry.getIndexNames())
if mibBuilder.loadTexts: sharedDriveStatsEntry.setStatus('current')
if mibBuilder.loadTexts: sharedDriveStatsEntry.setDescription('The statistics of a physical drive since its last reset or statistics rest.')
sDriveStatsDataTransferred = MibTableColumn((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 3, 1, 1), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: sDriveStatsDataTransferred.setStatus('current')
if mibBuilder.loadTexts: sDriveStatsDataTransferred.setDescription('The total number of bytes of data transfered to and from the controller.')
sDriveStatsReadDataTransferred = MibTableColumn((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 3, 1, 2), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: sDriveStatsReadDataTransferred.setStatus('current')
if mibBuilder.loadTexts: sDriveStatsReadDataTransferred.setDescription('The total number of bytes of data transfered from the controller.')
sDriveStatsWriteDataTransferred = MibTableColumn((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 3, 1, 3), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: sDriveStatsWriteDataTransferred.setStatus('current')
if mibBuilder.loadTexts: sDriveStatsWriteDataTransferred.setDescription('The total number of bytes of data transfered to the controller.')
sDriveStatsNumOfErrors = MibTableColumn((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 3, 1, 4), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: sDriveStatsNumOfErrors.setStatus('current')
if mibBuilder.loadTexts: sDriveStatsNumOfErrors.setDescription('The total number of errors.')
sDriveStatsNumOfNonRWErrors = MibTableColumn((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 3, 1, 5), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: sDriveStatsNumOfNonRWErrors.setStatus('current')
if mibBuilder.loadTexts: sDriveStatsNumOfNonRWErrors.setDescription('The total number of non-RW errors.')
sDriveStatsNumOfReadErrors = MibTableColumn((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 3, 1, 6), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: sDriveStatsNumOfReadErrors.setStatus('current')
if mibBuilder.loadTexts: sDriveStatsNumOfReadErrors.setDescription('The total number of Read errors.')
sDriveStatsNumOfWriteErrors = MibTableColumn((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 3, 1, 7), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: sDriveStatsNumOfWriteErrors.setStatus('current')
if mibBuilder.loadTexts: sDriveStatsNumOfWriteErrors.setDescription('The total number of Write errors.')
sDriveStatsNumOfIORequests = MibTableColumn((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 3, 1, 8), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: sDriveStatsNumOfIORequests.setStatus('current')
if mibBuilder.loadTexts: sDriveStatsNumOfIORequests.setDescription('The total number of IO requests.')
sDriveStatsNumOfNonRWRequests = MibTableColumn((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 3, 1, 9), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: sDriveStatsNumOfNonRWRequests.setStatus('current')
if mibBuilder.loadTexts: sDriveStatsNumOfNonRWRequests.setDescription('The total number of non-RW requests.')
sDriveStatsNumOfReadRequests = MibTableColumn((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 3, 1, 10), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: sDriveStatsNumOfReadRequests.setStatus('current')
if mibBuilder.loadTexts: sDriveStatsNumOfReadRequests.setDescription('The total number of read requests.')
sDriveStatsNumOfWriteRequests = MibTableColumn((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 3, 1, 11), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: sDriveStatsNumOfWriteRequests.setStatus('current')
if mibBuilder.loadTexts: sDriveStatsNumOfWriteRequests.setDescription('The total number of write requests.')
sDriveStatsStartTime = MibTableColumn((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 3, 1, 12), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: sDriveStatsStartTime.setStatus('current')
if mibBuilder.loadTexts: sDriveStatsStartTime.setDescription('The time when the statistics date starts to accumulate since last statistics reset.')
sDriveStatsCollectionTime = MibTableColumn((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 10, 205, 3, 1, 13), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: sDriveStatsCollectionTime.setStatus('current')
if mibBuilder.loadTexts: sDriveStatsCollectionTime.setDescription('The time when the statistics data was collected or updated last time.')
sDriveGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 343, 2, 19, 1, 2, 2, 2, 15)).setObjects(("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "maxSharedDrives"), ("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "numOfSharedDrives"), ("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "sDrivePresenceMask"), ("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "driveBackplaneVendor"), ("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "driveBackplaneMfgDate"), ("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "driveBackplaneDeviceName"), ("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "driveBackplanePart"), ("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "driveBackplaneSerialNo"), ("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "driveBackplaneMaximumPower"), ("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "driveBackplaneNominalPower"), ("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "driveBackplaneAssetTag"), ("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "sDriveSlotNumber"), ("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "sDrivePresence"), ("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "sDriveInterface"), ("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "sDriveModelNumber"), ("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "sDriveSerialNumber"), ("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "sDriveFirmwareVersion"), ("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "sDriveProtocolVersion"), ("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "sDriveOperationalStatus"), ("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "sDriveCondition"), ("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "sDriveOperation"), ("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "sDriveConfiguration"), ("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "sDriveStoragePoolID"), ("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "sDriveSequenceNumber"), ("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "sDriveEnclosureID"), ("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "sDriveBlockSize"), ("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "sDrivePhysicalCapacity"), ("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "sDriveConfigurableCapacity"), ("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "sDriveUsedCapacity"), ("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "sDriveType"), ("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "sDriveStatsDataTransferred"), ("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "sDriveStatsReadDataTransferred"), ("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "sDriveStatsWriteDataTransferred"), ("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "sDriveStatsNumOfErrors"), ("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "sDriveStatsNumOfNonRWErrors"), ("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "sDriveStatsNumOfReadErrors"), ("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "sDriveStatsNumOfWriteErrors"), ("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "sDriveStatsNumOfIORequests"), ("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "sDriveStatsNumOfNonRWRequests"), ("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "sDriveStatsNumOfReadRequests"), ("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "sDriveStatsNumOfWriteRequests"), ("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "sDriveStatsStartTime"), ("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", "sDriveStatsCollectionTime"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
sDriveGroup = sDriveGroup.setStatus('current')
if mibBuilder.loadTexts: sDriveGroup.setDescription('Description.')
mibBuilder.exportSymbols("INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB", sharedDriveStatsEntry=sharedDriveStatsEntry, sDriveStoragePoolID=sDriveStoragePoolID, driveBackplanePart=driveBackplanePart, multiFlexServerDrivesMibModule=multiFlexServerDrivesMibModule, driveBackplaneMaximumPower=driveBackplaneMaximumPower, driveBackplaneSerialNo=driveBackplaneSerialNo, driveBackplaneAssetTag=driveBackplaneAssetTag, sDriveStatsNumOfWriteErrors=sDriveStatsNumOfWriteErrors, sDriveUsedCapacity=sDriveUsedCapacity, driveBackplaneNominalPower=driveBackplaneNominalPower, sharedDrives=sharedDrives, sDriveStatsCollectionTime=sDriveStatsCollectionTime, sDriveOperationalStatus=sDriveOperationalStatus, sDrivePresence=sDrivePresence, sDriveInterface=sDriveInterface, sDrivePhysicalCapacity=sDrivePhysicalCapacity, maxSharedDrives=maxSharedDrives, sharedDriveStatsTable=sharedDriveStatsTable, sDriveStatsNumOfReadErrors=sDriveStatsNumOfReadErrors, sDriveType=sDriveType, sDriveStatsNumOfIORequests=sDriveStatsNumOfIORequests, sDriveSerialNumber=sDriveSerialNumber, sDriveGroup=sDriveGroup, sDrivePresenceMask=sDrivePresenceMask, sDriveModelNumber=sDriveModelNumber, driveBackplane=driveBackplane, numOfSharedDrives=numOfSharedDrives, sDriveConfiguration=sDriveConfiguration, sDriveStatsNumOfErrors=sDriveStatsNumOfErrors, driveBackplaneVendor=driveBackplaneVendor, sDriveStatsNumOfNonRWRequests=sDriveStatsNumOfNonRWRequests, sDriveStatsNumOfWriteRequests=sDriveStatsNumOfWriteRequests, sharedDriveEntry=sharedDriveEntry, sDriveBlockSize=sDriveBlockSize, sDriveSlotNumber=sDriveSlotNumber, driveBackplaneMfgDate=driveBackplaneMfgDate, sDriveFirmwareVersion=sDriveFirmwareVersion, sDriveSequenceNumber=sDriveSequenceNumber, driveBackplaneDeviceName=driveBackplaneDeviceName, sDriveConfigurableCapacity=sDriveConfigurableCapacity, sDriveStatsStartTime=sDriveStatsStartTime, sDriveProtocolVersion=sDriveProtocolVersion, sDriveEnclosureID=sDriveEnclosureID, sDriveStatsDataTransferred=sDriveStatsDataTransferred, sDriveStatsWriteDataTransferred=sDriveStatsWriteDataTransferred, sDriveStatsNumOfNonRWErrors=sDriveStatsNumOfNonRWErrors, PYSNMP_MODULE_ID=multiFlexServerDrivesMibModule, sDriveStatsNumOfReadRequests=sDriveStatsNumOfReadRequests, sDriveCondition=sDriveCondition, sDriveOperation=sDriveOperation, sDriveStatsReadDataTransferred=sDriveStatsReadDataTransferred, sharedDriveTable=sharedDriveTable)
|
def delUser(cur,con,loginid):
try:
query = "DELETE FROM USER WHERE Login_id='%s'" % (loginid)
#print(query)
cur.execute(query)
con.commit()
print("Deleted from Database")
except Exception as e:
con.rollback()
print("Failed to delete from database")
print(">>>>>>>>>>>>>", e)
return
def delStaff(cur,con):
try:
row = {}
row["Staff_id"] = input("Enter Staff ID to delete: ")
row["Login_id"] = "STAFF" + row["Staff_id"]
query = "SELECT Department_id FROM WORKS_FOR WHERE Staff_id='%s'" % (row["Staff_id"])
cur.execute(query)
row["dep"] = cur.fetchone()['Department_id']
con.commit()
query = "UPDATE DEPARTMENT SET No_of_employees=No_of_employees - 1 WHERE Department_id='%s'" % (row["dep"])
cur.execute(query)
con.commit()
query = "DELETE FROM WORKS_FOR WHERE Staff_id='%s'" % (row["Staff_id"])
#print(query)
cur.execute(query)
con.commit()
query = "DELETE FROM STAFF_SKILLS WHERE Staff_id='%s'" % (row["Staff_id"])
#print(query)
cur.execute(query)
con.commit()
query = "DELETE FROM STAFF WHERE Login_id='%s'" % (row["Login_id"])
#print(query)
cur.execute(query)
con.commit()
delUser(cur,con,row["Login_id"])
except Exception as e:
con.rollback()
print("Failed to delete from database")
print(">>>>>>>>>>>>>", e)
return
def delDonor(cur,con):
try:
row = {}
row["Donor_id"] = input("Enter Donor ID to delete: ")
row["Login_id"] = "DONOR" + row["Donor_id"]
query = "DELETE FROM DONOR WHERE Donor_id='%s'" % (row["Donor_id"])
#print(query)
cur.execute(query)
con.commit()
delUser(cur,con,row["Login_id"])
except Exception as e:
con.rollback()
print("Failed to delete from database")
print(">>>>>>>>>>>>>", e)
return
def delVehi(cur,con):
try:
row = {}
row["Vehicle_id"] = input("Enter Vehicle ID to delete: ")
query = "DELETE FROM LOGISTICS WHERE Vehicle_id='%s'" % (row["Vehicle_id"])
#print(query)
cur.execute(query)
con.commit()
except Exception as e:
con.rollback()
print("Failed to delete from database")
print(">>>>>>>>>>>>>", e)
return
def delDep(cur,con):
try:
row = {}
row["Staff_id"] = input("Enter Staff ID associated: ")
name = (input("Name (Fname Lname): ")).split(' ')
row["Fname"] = name[0]
row["Lname"] = name[1]
query = "DELETE FROM DEPENDENT WHERE Staff_id='%s' AND First_name='%s' AND Last_name='%s'" % (row["Staff_id"], row["Fname"], row["Lname"])
#print(query)
cur.execute(query)
con.commit()
except Exception as e:
con.rollback()
print("Failed to delete from database")
print(">>>>>>>>>>>>>", e)
return
|
# program to generate the combinations of n distinct objects taken from the elements of a given list.
def combination(n, n_list):
if n<=0:
yield []
return
for i in range(len(n_list)):
c_num = n_list[i:i+1]
for a_num in combination(n-1, n_list[i+1:]):
yield c_num + a_num
n_list = [1,2,3,4,5,6,7,8,9]
print("Original list:")
print(n_list)
n = 2
result = combination(n, n_list)
print("\nCombinations of",n,"distinct objects:")
for e in result:
print(e)
|
def install(job):
service = job.service
# create user if it doesn't exists
username = service.model.dbobj.name
password = service.model.data.password
email = service.model.data.email
provider = service.model.data.provider
username = "%s@%s" % (username, provider) if provider else username
password = password if not provider else "fakeeeee"
g8client = service.producers["g8client"][0]
config_instance = "{}_{}".format(g8client.aysrepo.name, g8client.model.data.instance)
client = j.clients.openvcloud.get(instance=config_instance, create=False, die=True, sshkey_path="/root/.ssh/ays_repos_key")
if not client.api.system.usermanager.userexists(name=username):
groups = service.model.data.groups
client.api.system.usermanager.create(username=username, password=password, groups=groups, emails=[email], domain='', provider=provider)
def processChange(job):
service = job.service
g8client = service.producers["g8client"][0]
config_instance = "{}_{}".format(g8client.aysrepo.name, g8client.model.data.instance)
client = j.clients.openvcloud.get(instance=config_instance, create=False, die=True, sshkey_path="/root/.ssh/ays_repos_key")
old_args = service.model.data
new_args = job.model.args
# Process Changing Groups
old_groups = set(old_args.groups)
new_groups = set(new_args.get('groups', []))
if old_groups != new_groups:
username = service.model.dbobj.name
provider = old_args.provider
username = "%s@%s" % (username, provider) if provider else username
# Editing user api requires to send a list contains user's mail
emails = [old_args.email]
new_groups = list(new_groups)
client.api.system.usermanager.editUser(username=username, groups=new_groups, provider=provider, emails=emails)
service.model.data.groups = new_groups
service.save()
def uninstall(job):
service = job.service
# unauthorize user to all consumed vdc
username = service.model.dbobj.name
g8client = service.producers["g8client"][0]
config_instance = "{}_{}".format(g8client.aysrepo.name, g8client.model.data.instance)
client = j.clients.openvcloud.get(instance=config_instance, create=False, die=True, sshkey_path="/root/.ssh/ays_repos_key")
provider = service.model.data.provider
username = "%s@%s" % (username, provider) if provider else username
if client.api.system.usermanager.userexists(name=username):
client.api.system.usermanager.delete(username=username)
|
if condition1:
...
elif condition2:
...
elif condition3:
...
elif condition4:
...
elif condition5:
...
elif condition6:
...
else:
...
|
MIN_DRIVING_AGE = 18
group = {'tim': 17, 'bob': 18, 'ana': 24}
def allowed_driving(name):
"""Print '{name} is allowed to drive' or '{name} is not allowed to drive'
checking the passed in age against the MIN_DRIVING_AGE constant
"""
is_found = False
if name in group:
if group[name] >= MIN_DRIVING_AGE:
print(name + " is allowed to drive")
is_found = True
else:
print(name + " is not allowed to drive")
is_found = True
return is_found
while True:
print("Enter a name: (blank to quit)")
name = str.casefold(input())
if name == '':
break
if not allowed_driving(name):
print("Name is not found")
|
# Python - 3.6.0
test.assert_equals(relatively_prime(8, [1, 2, 3, 4, 5, 6, 7]), [1, 3, 5, 7])
test.assert_equals(relatively_prime(15, [72, 27, 32, 61, 77, 11, 40]), [32, 61, 77, 11])
test.assert_equals(relatively_prime(210, [15, 100, 2222222, 6, 4, 12369, 99]), [])
|
def save_file(contents):
with open("path_to_save_the_file.wav", 'wb') as f:
f.write(contents)
return "path_to_save_the_file.wav"
|
expected_output = {
"main": {
"chassis": {
"ASR1002-X": {
"descr": "Cisco ASR1002-X Chassis",
"name": "Chassis",
"pid": "ASR1002-X",
"sn": "FOX1111P1M1",
"vid": "V07",
}
}
},
"slot": {
"0": {
"lc": {
"ASR1002-X": {
"descr": "Cisco ASR1002-X SPA Interface Processor",
"name": "module 0",
"pid": "ASR1002-X",
"sn": "",
"subslot": {
"0": {
"6XGE-BUILT-IN": {
"descr": "6-port Built-in GE SPA",
"name": "SPA subslot 0/0",
"pid": "6XGE-BUILT-IN",
"sn": "",
"vid": "",
}
},
"0 transceiver 0": {
"GLC-SX-MMD": {
"descr": "GE SX",
"name": "subslot 0/0 transceiver 0",
"pid": "GLC-SX-MMD",
"sn": "AGJ3333R1GC",
"vid": "001",
}
},
"0 transceiver 1": {
"GLC-SX-MMD": {
"descr": "GE SX",
"name": "subslot 0/0 transceiver 1",
"pid": "GLC-SX-MMD",
"sn": "AGJ1111R1G1",
"vid": "001",
}
},
"0 transceiver 2": {
"GLC-SX-MMD": {
"descr": "GE SX",
"name": "subslot 0/0 transceiver 2",
"pid": "GLC-SX-MMD",
"sn": "AGJ9999R1FL",
"vid": "001",
}
},
"0 transceiver 3": {
"GLC-SX-MMD": {
"descr": "GE SX",
"name": "subslot 0/0 transceiver 3",
"pid": "GLC-SX-MMD",
"sn": "AGJ5555RAFM",
"vid": "001",
}
},
},
"vid": "",
}
}
},
"F0": {
"lc": {
"ASR1002-X": {
"descr": "Cisco ASR1002-X Embedded Services Processor",
"name": "module F0",
"pid": "ASR1002-X",
"sn": "",
"vid": "",
}
}
},
"P0": {
"other": {
"ASR1002-PWR-AC": {
"descr": "Cisco ASR1002 AC Power Supply",
"name": "Power Supply Module 0",
"pid": "ASR1002-PWR-AC",
"sn": "ABC111111EJ",
"vid": "V04",
}
}
},
"P1": {
"other": {
"ASR1002-PWR-AC": {
"descr": "Cisco ASR1002 AC Power Supply",
"name": "Power Supply Module 1",
"pid": "ASR1002-PWR-AC",
"sn": "DCB222222EK",
"vid": "V04",
}
}
},
"R0": {
"rp": {
"ASR1002-X": {
"descr": "Cisco ASR1002-X Route Processor",
"name": "module R0",
"pid": "ASR1002-X",
"sn": "JAD333333AQ",
"vid": "V07",
}
}
},
},
}
|
input = """
c(1).
c(2).
c(3).
a(X) | -a(X) :- c(X).
minim(X) :- a(X), #min{ D : a(D) } = X.
"""
output = """
c(1).
c(2).
c(3).
a(X) | -a(X) :- c(X).
minim(X) :- a(X), #min{ D : a(D) } = X.
"""
|
A = 1
connection= {
A : ['B'],
'B' : ['A', 'B', 'D'],
'C' : ['A'],
'D' : ['E','A'],
'E' : ['B']
}
for f in connection:
print(connection['B'])
print(connection[id])
|
#!/usr/bin/env python
#pylint: skip-file
# This source code is licensed under the Apache license found in the
# LICENSE file in the root directory of this project.
class AugmentedTaskDTO(object):
def __init__(self):
"""
Attributes:
swaggerTypes (dict): The key is attribute name and the value is attribute type.
attributeMap (dict): The key is attribute name and the value is json key in definition.
"""
self.swaggerTypes = {
'id': 'str',
'progress': 'str',
'version': 'int',
'startTime': 'date-time',
'endTime': 'date-time',
'data': 'str',
'errorCode': 'str',
'serviceType': 'str',
'username': 'str',
'isError': 'bool',
'lastUpdate': 'date-time',
'operationIdList': 'list[str]',
'parentId': 'str',
'rootId': 'str',
'failureReason': 'str'
}
self.attributeMap = {
'id': 'id',
'progress': 'progress',
'version': 'version',
'startTime': 'startTime',
'endTime': 'endTime',
'data': 'data',
'errorCode': 'errorCode',
'serviceType': 'serviceType',
'username': 'username',
'isError': 'isError',
'lastUpdate': 'lastUpdate',
'operationIdList': 'operationIdList',
'parentId': 'parentId',
'rootId': 'rootId',
'failureReason': 'failureReason'
}
#id
self.id = None # str
#progress
self.progress = None # str
#version
self.version = None # int
#startTime
self.startTime = None # date-time
#endTime
self.endTime = None # date-time
#data
self.data = None # str
#errorCode
self.errorCode = None # str
#serviceType
self.serviceType = None # str
#username
self.username = None # str
#isError
self.isError = None # bool
#lastUpdate
self.lastUpdate = None # date-time
self.operationIdList = None # list[str]
#parentId
self.parentId = None # str
#rootId
self.rootId = None # str
#failureReason
self.failureReason = None # str
|
#entre com 2 notas e calcule a media
n1 = int(input('Entre com a primeira nota : '))
n2 = int(input('Entre com a segun da nota : '))
m = (n1 + n2) / 2
print('A média das notas é: {}'.format(m))
|
"""
EDX_DATABASES = {
'think_101x': {'dbname': 'UQx_Think101x_1T2014', 'mongoname': 'UQx/Think101x/1T2014', 'discussiontable': 'UQx-HYPERS301x-1T2014-prod', 'icon': 'fa-heart'},
'hypers_301x': {'dbname': 'UQx_HYPERS301x_1T2014', 'mongoname': 'UQx/HYPERS301x/1T2014', 'discussiontable': 'UQx-HYPERS301x-1T2014-prod', 'icon': 'fa-plane'},
'tropic_101x': {'dbname': 'UQx_TROPIC101x_1T2014', 'mongoname': 'UQx/TROPIC101x/1T2014', 'discussiontable': 'UQx-TROPIC101x-1T2014-prod', 'icon': 'fa-tree'},
'bioimg_101x': {'dbname': 'UQx_BIOIMG101x_1T2014', 'mongoname': 'UQx/BIOIMG101x/1T2014', 'discussiontable': 'UQx-BIOIMG101x-1T2014-prod', 'icon': 'fa-desktop'},
'crime_101x': {'dbname': 'UQx_Crime101x_3T2014', 'mongoname': 'UQx/Crime101x/3T2014', 'discussiontable': 'UQx-Crime101x-3T2014-prod', 'icon': 'fa-gavel'},
'world_101x': {'dbname': 'UQx_World101x_3T2014', 'mongoname': 'UQx/World101x/3T2014', 'discussiontable': 'UQx-World101x-3T2014-prod', 'icon': 'fa-map-marker'},
'write_101x': {'dbname': 'UQx_Write101x_3T2014', 'mongoname': 'UQx/Write101x/3T2014', 'discussiontable': 'UQx-Write101x-3T2014-prod', 'icon': 'fa-pencil'},
'sense_101x': {'dbname': 'UQx_Sense101x_3T2014', 'mongoname': 'UQx/Sense101x/3T2014', 'discussiontable': 'UQx-Sense101x-3T2014-prod', 'icon': 'fa-power-off'}
}
"""
EDX_DATABASES = {
'think_101x_1T2014': {'dbname': 'UQx_Think101x_1T2014', 'mongoname': 'UQx/Think101x/1T2014', 'discussiontable': 'UQx-HYPERS301x-1T2014-prod', 'icon': 'fa-heart'},
'hypers_301x_1T2014': {'dbname': 'UQx_HYPERS301x_1T2014', 'mongoname': 'UQx/HYPERS301x/1T2014', 'discussiontable': 'UQx-HYPERS301x-1T2014-prod', 'icon': 'fa-plane'},
'tropic_101x_1T2014': {'dbname': 'UQx_TROPIC101x_1T2014', 'mongoname': 'UQx/TROPIC101x/1T2014', 'discussiontable': 'UQx-TROPIC101x-1T2014-prod', 'icon': 'fa-tree'},
'bioimg_101x_1T2014': {'dbname': 'UQx_BIOIMG101x_1T2014', 'mongoname': 'UQx/BIOIMG101x/1T2014', 'discussiontable': 'UQx-BIOIMG101x-1T2014-prod', 'icon': 'fa-desktop'},
'crime_101x_3T2014': {'dbname': 'UQx_Crime101x_3T2014', 'mongoname': 'UQx/Crime101x/3T2014', 'discussiontable': 'UQx-Crime101x-3T2014-prod', 'icon': 'fa-gavel'},
'world_101x_3T2014': {'dbname': 'UQx_World101x_3T2014', 'mongoname': 'UQx/World101x/3T2014', 'discussiontable': 'UQx-World101x-3T2014-prod', 'icon': 'fa-map-marker'},
'write_101x_3T2014': {'dbname': 'UQx_Write101x_3T2014', 'mongoname': 'UQx/Write101x/3T2014', 'discussiontable': 'UQx-Write101x-3T2014-prod', 'icon': 'fa-pencil'},
'sense_101x_3T2014': {'dbname': 'UQx_Sense101x_3T2014', 'mongoname': 'UQx/Sense101x/3T2014', 'discussiontable': 'UQx-Sense101x-3T2014-prod', 'icon': 'fa-power-off'},
}
|
def insertion_sort(the_list):
"""
In-place list sorting method
"""
i = 1
while i < len(the_list):
elem = the_list[i]
sorted_iterator = i-1
while elem < the_list[sorted_iterator] and sorted_iterator >= 0:
the_list[sorted_iterator+1] = the_list[sorted_iterator]
sorted_iterator -= 1
the_list[sorted_iterator + 1] = elem
i += 1
|
# emacs: -*- mode: python-mode; py-indent-offset: 2; tab-width: 2; indent-tabs-mode: nil -*-
# ex: set sts=2 ts=2 sw=2 et:
__all__ = ['classify', 'cluster', 'decode', 'meta', 'network', 'reduce', 'stats']
|
def f1(x, *args):
pass
f1(42, 'spam')
|
{
'includes': [
'./common.gypi'
],
'target_defaults': {
'defines' : [
'PNG_PREFIX',
'PNGPREFIX_H',
'PNG_USE_READ_MACROS',
],
# 'include_dirs': [
# '<(DEPTH)/third_party/pdfium',
# '<(DEPTH)/third_party/pdfium/third_party/freetype/include',
# ],
'conditions': [
['OS=="linux"', {
'conditions': [
['target_arch=="x64"', {
'defines' : [ '_FX_CPU_=_FX_X64_', ],
'cflags': [ '-fPIC', ],
}],
['target_arch=="ia32"', {
'defines' : [ '_FX_CPU_=_FX_X86_', ],
}],
],
}]
],
'msvs_disabled_warnings': [
4005, 4018, 4146, 4333, 4345, 4267
]
},
'targets': [
{
'target_name': 'node_pdfium',
'dependencies' : [
'fx_lpng',
'./third_party/pdfium/pdfium.gyp:pdfium'
],
'sources': [
# is like "ls -1 src/*.cc", but gyp does not support direct patterns on
# sources
'<!@(["python", "tools/getSourceFiles.py", "src", "cc"])'
]
},
{
'target_name': 'fx_lpng',
'type': 'static_library',
'dependencies': [
'third_party/pdfium/pdfium.gyp:fxcodec',
],
'include_dirs': [
'third_party/pdfium/core/src/fxcodec/fx_zlib/include/',
],
'sources': [
'third_party/fx_lpng/include/fx_png.h',
'third_party/fx_lpng/src/fx_png.c',
'third_party/fx_lpng/src/fx_pngerror.c',
'third_party/fx_lpng/src/fx_pngget.c',
'third_party/fx_lpng/src/fx_pngmem.c',
'third_party/fx_lpng/src/fx_pngpread.c',
'third_party/fx_lpng/src/fx_pngread.c',
'third_party/fx_lpng/src/fx_pngrio.c',
'third_party/fx_lpng/src/fx_pngrtran.c',
'third_party/fx_lpng/src/fx_pngrutil.c',
'third_party/fx_lpng/src/fx_pngset.c',
'third_party/fx_lpng/src/fx_pngtrans.c',
'third_party/fx_lpng/src/fx_pngwio.c',
'third_party/fx_lpng/src/fx_pngwrite.c',
'third_party/fx_lpng/src/fx_pngwtran.c',
'third_party/fx_lpng/src/fx_pngwutil.c',
]
}
]
}
|
def normalizer(x, norm):
if norm == 'l2':
norm_val = sum(xi ** 2 for xi in x) ** .5
elif norm == 'l1':
norm_val = sum(abs(xi) for xi in x)
elif norm == 'max':
norm_val = max(abs(xi) for xi in x)
return [xi / norm_val for xi in x]
def standard_scaler(x, mean_, var_, with_mean, with_std):
def scale(x, m, v):
if with_mean:
x -= m
if with_std:
x /= v ** .5
return x
return [scale(xi, m, v) for xi, m, v in zip(x, mean_, var_)]
|
def pascal_case(text):
"""Returns text converted to PascalCase"""
if text.count('_') == 0:
return text
s1 = text.split('_')
return ''.join([s.lower().capitalize() for s in s1])
def integral_type(member):
type = {
'char': 'char',
'signed char': 'sbyte',
'unsigned char': 'byte',
'short': 'short',
'unsigned short': 'ushort',
'int': 'int',
'unsigned int': 'uint',
'long': 'int',
'unsigned long': 'uint',
'long long': 'long',
'unsigned long long': 'ulong',
'float': 'float',
'double': 'double'
}[member.type]
return type
def csharp_type(member, show_length=False):
if member.type == 'char' and member.length > 1:
return 'string'
type = integral_type(member)
if member.length > 1:
return f'{type}[{member.length if show_length else ""}]'
return type
def reader_method(member):
type = integral_type(member)
method = {
'char': 'ReadChar',
'sbyte': 'ReadSByte',
'byte': 'ReadByte',
'short': 'ReadInt16',
'ushort': 'ReadUInt16',
'int': 'ReadInt32',
'uint': 'ReadUInt32',
'long': 'ReadInt64',
'ulong': 'ReadUInt64',
'float': 'ReadSingle',
'double': 'ReadDouble'
}[type]
return method
def lines(text):
ls = text.split('\n')
if not ls:
return []
if ls[0].strip() == '':
ls = ls[1:]
if not ls:
return []
if ls[-1].strip() == '':
ls = ls[:-1]
return ls
def leading_spaces(text):
return len(text) - len(text.lstrip())
def remove_miniumum_whitespace(lines):
try:
minimum_whitespace = min([leading_spaces(l) for l in lines])
return [l[minimum_whitespace:] for l in lines]
except ValueError:
return []
def xml_comment(text):
ls = lines(text)
ls = remove_miniumum_whitespace(ls)
return '\n'.join([f'/// {l}' for l in ls])
def comment(text):
if text.count('\n') == 0:
return single_line_comment(text)
return multi_line_comment(text)
def single_line_comment(text):
ls = lines(text)
ls = remove_miniumum_whitespace(ls)
return '\n'.join([f'// {l}' for l in ls])
def multi_line_comment(text):
ls = lines(text)
ls = remove_miniumum_whitespace(ls)
ls = [f' * {l}' for l in ls]
ls.insert(0, '/*')
ls.append(' */')
return '\n'.join(ls)
filters = {
'pascalcase': pascal_case,
'csharptype': csharp_type,
'readermethod': reader_method,
'comment': comment,
'singlelinecomment': single_line_comment,
'multilinecomment': multi_line_comment,
'xmlcomment': xml_comment
}
|
print('Enter any integer: ')
n = str(input().strip())
num_places = len(n)
for i in range(num_places) :
x = num_places - i
if x >= 10 :
suffix = "Billion "
elif x <= 9 and x >= 7 :
suffix = "Million "
elif x == 6 :
suffix = "Hundred "
elif x == 5 :
suffix = "Thousand "
elif x == 4:
suffix = "Thousand "
elif x == 3 :
suffix = "Hundred "
else :
suffix = ""
# the second to last digit will always be the tens, which have special naming
if i != num_places - 2 :
if n[i] == '1' :
# don't make newline
print("One " + suffix, end='')
elif n[i] == '2' :
print("Two " + suffix, end='')
elif n[i] == '3' :
print("Three " + suffix, end='')
elif n[i] == '4':
print("Four " + suffix, end='')
elif n[i] == '5':
print("Five " + suffix, end='')
elif n[i] == '6':
print("Six " + suffix, end='')
elif n[i] == '7':
print("Seven " + suffix, end='')
elif n[i] == '8':
print("Eight " + suffix, end='')
elif n[i] == '9':
print("Nine " + suffix, end='')
else :
# if n[i] is 0, print "and"
print(" and ", end='')
else :
if n[i] == '1' :
if n[i+1] == '0' :
print("Ten ", end='')
if n[i+1] == '1' :
print("Eleven ", end='')
if n[i+1] == '2' :
print("Twelve ", end='')
else :
if n[i+1] == '3' :
print("Thir", end='')
if n[i+1] == '4' :
print("Four", end='')
if n[i+1] == '5' :
print("Fif", end='')
if n[i+1] == '6' :
print("Six", end='')
if n[i+1] == '7' :
print("Seven", end='')
if n[i+1] == '8' :
print("Eigh", end='')
if n[i+1] == '9' :
print("Nine", end='')
print("teen")
break
elif n[i] == '2' :
print("Twenty ", end='')
elif n[i] == '3' :
print("Thirty ", end='')
elif n[i] == '4':
print("Fourty ", end='')
elif n[i] == '5':
print("Fifty ", end='')
elif n[i] == '6':
print("Sixty ", end='')
elif n[i] == '7':
print("Seventy ", end='')
elif n[i] == '8':
print("Eighty ", end='')
elif n[i] == '9':
print("Ninety ", end='')
else :
# if n[i] is 0, print "and"
print(" and ", end='')
|
def search(arr, d, y):
for m in range(0, d):
if (arr[m] == y):
return m;
return -1;
arr = [4, 8, 26, 30, 13];
p = 30;
k = len(arr);
result = search(arr, k, p)
if (result == -1):
print("Element is not present in array")
else:
print("Element is present at index", result);
|
# Turns an RPN expression to normal mathematical notation
_VARIABLES = {
"0": "0",
"1": "1",
"P": "pi",
"a": "x0",
"b": "x1",
"c": "x2",
"d": "x3",
"e": "x4",
"f": "x5",
"g": "x6",
"h": "x7",
"i": "x8",
"j": "x9",
"k": "x10",
"l": "x11",
"m": "x12",
"n": "x13",
}
_OPS_UNARY = {
">": "({}+1)",
"<": "({}-1)",
"~": "(-{})",
"\\": "({})**(-1)",
"L": "log({})",
"E": "exp({})",
"S": "sin({})",
"C": "cos({})",
"A": "abs({})",
"N": "asin({})",
"T": "atan({})",
"R": "sqrt({})",
"O": "(2*({}))",
"J": "(2*({})+1)",
}
_OPS_BINARY = set("+*-/")
def RPN_to_eq(expr: str) -> str:
stack = []
for i in expr:
if i in _VARIABLES:
stack.append(_VARIABLES[i])
elif i in _OPS_BINARY:
a1 = stack.pop()
a2 = stack.pop()
stack.append(f"({a2}{i}{a1})")
elif i in _OPS_UNARY:
a = stack.pop()
stack.append(_OPS_UNARY[i].format(a))
return stack[0]
|
#converts the pixel bytes to binary
def decToBin(dec):
secret_bin = []
for i in dec:
secret_bin.append(f'{i:08b}')
return secret_bin
#gets the last 2 LSB of each byte
def get2LSB(secret_bin):
last2 = []
for i in secret_bin:
for j in i[6:8]:
last2.append(j)
return last2
def filter2LSB(listdict, last2):
piclsb = []
replaceNum = 0
index = 0
#the lower even or odd occurence gets replaced
if listdict['0']<2 or listdict['1']<2:
replaceNum = 0
listdict['2'] = '01'
elif listdict['0'] <= listdict['1']:
replaceNum = 0
else:
replaceNum = 1
#filters the right matching bits out of the image
for i in last2:
if int(listdict['2'][index])%2 == replaceNum:
piclsb.append(i)
index += 1
if index >= len(listdict['2']):
index = 0
else:
index += 1
if index >= len(listdict['2']):
index = 0
return piclsb
|
# Do not edit this file directly.
# It was auto-generated by: code/programs/reflexivity/reflexive_refresh
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
def buildfarm():
http_archive(
name="buildfarm" ,
build_file="//bazel/deps/buildfarm:build.BUILD" ,
sha256="de2a18bbe1e6770be0cd54e93630fb1ee7bce937bff708eed16329033fbfe32b" ,
strip_prefix="bazel-buildfarm-355f816acf3531e9e37d860acf9ebbb89c9041c2" ,
urls = [
"https://github.com/Unilang/bazel-buildfarm/archive/355f816acf3531e9e37d860acf9ebbb89c9041c2.tar.gz",
],
)
|
"""
Choose i/o filename here:
- a_example
- b_should_be_easy
- c_no_hurry
- d_metropolis
- e_high_bonus
"""
filename = 'b_should_be_easy' # choose input and output file names here
ride_pool = []
ride_id = 0
with open(filename + '.in', 'r') as file:
args = file.readline().split()
for line in file:
r = line.split()
ride_pool.append((ride_id, (int(r[0]), int(r[1])), (int(r[2]), int(r[3])), int(r[4]), int(r[5])))
ride_id += 1
R = int(args[0])
C = int(args[1])
F = int(args[2])
N = int(args[3])
B = int(args[4])
T = int(args[5])
# RIDE: ((rideID, (startx, starty), (endx, endy), start_time, finish_time)
finished_cars_IDs = [] # this will contain all the cars that have no more eligible rides
class Car:
def __init__(self, id):
self.carID = id
self.currRide = None
self.posx = 0
self.posy = 0
self.ride_dist = 0 # distance till current ride is finished
self.pickup_dist = 0 # distance till the pickup spot - (startx, starty) of ride
def assignRide(self, Ride):
self.currRide = Ride
self.ride_dist = manhattanDistance((Ride[1][0], Ride[1][1]), (Ride[2][0], Ride[2][1]))
self.pickup_dist = manhattanDistance((self.posx, self.posy), (Ride[1][0], Ride[1][1]))
def chooseRideBasedOnStartTime(self, t): # greedily minimize start_time for rides
global R, C, ride_pool
if self.carID in finished_cars_IDs:
return
mintimes = float('inf')
minride = None
finished = True
for ride in ride_pool:
dt = calculate_start_time((self.posx, self.posy), t, ride)
if ride_would_be_in_vain(ride, dt, t):
continue
finished = False
if dt < mintimes:
mintimes = dt
minride = ride
if finished:
finished_cars_IDs.append(self.carID)
if minride is None: # better pass
return
ride_pool.remove(minride)
self.assignRide(minride)
def chooseRideBasedOnMixedScore(self, t): # greedily maximaze the ratio of score / start_time for rides
global R, C, ride_pool, B
if self.carID in finished_cars_IDs:
return
maxmixedscore = float('-inf')
maxride = None
finished = True
for ride in ride_pool:
mixed_score = calculate_mixed_score((self.posx, self.posy), t, ride)
if ride_would_be_in_vain_2(ride, (self.posx, self.posy), t):
continue
finished = False
if mixed_score > maxmixedscore:
maxmixedscore = mixed_score
maxride = ride
if finished:
finished_cars_IDs.append(self.carID)
if maxride is None: # better pass
return
ride_pool.remove(maxride)
self.assignRide(maxride)
def act(self, t):
if self.currRide is None: # no rides assigned
self.chooseRideBasedOnMixedScore(t) # greedy choice -> we have implemented 2 options
if self.currRide is None: # choose returned none -> pass this round
return None
if self.pickup_dist > 0: # hasn't reached the pickup spot yet
self.pickup_dist -= 1
elif self.pickup_dist == 0: # has reached the pickup spot
if t < self.currRide[3]: # time to start is not here yet
pass # wait
elif self.ride_dist > 0: # still working on given ride
self.ride_dist -= 1
elif self.ride_dist == 0:
res = self.currRide
self.currRide = None
return res
else:
print("Unexpected Error")
else:
print("Unexpected Error")
return None
def manhattanDistance( xy1, xy2 ):
"""Returns the Manhattan distance between points xy1 and xy2"""
return abs( xy1[0] - xy2[0] ) + abs( xy1[1] - xy2[1] )
def calculate_start_time(pos, t, ride):
pickuptime = manhattanDistance(pos, ride[1])
wait_time = ride[3] - (t + pickuptime)
if wait_time < 0:
wait_time = 0
# journey_time = manhattanDistance(ride[1], ride[2])
return pickuptime + wait_time
def calculate_mixed_score(pos, t, ride):
pickuptime = manhattanDistance(pos, ride[1])
wait_time = ride[3] - (t + pickuptime)
if wait_time < 0:
wait_time = 0
journey_time = manhattanDistance(ride[1], ride[2])
completion_time = pickuptime + wait_time + journey_time
score = 0
if t + pickuptime <= ride[3]:
score += B
if t + completion_time < ride[4]:
score += journey_time
if float(pickuptime + wait_time) != 0:
ratio = float(score) / (float(pickuptime + wait_time))
else:
ratio = float(score)
return ratio
def ride_would_be_in_vain(ride, start_time, t):
completion_time = start_time + manhattanDistance(ride[1], ride[2])
return t + completion_time >= ride[4]
def ride_would_be_in_vain_2(ride, pos, t): # second version of this
pickuptime = manhattanDistance(pos, ride[1])
wait_time = ride[3] - (t + pickuptime)
if wait_time < 0:
wait_time = 0
completion_time = pickuptime + wait_time + manhattanDistance(ride[1], ride[2])
return t + completion_time >= ride[4]
def simulation():
global T, F, N, B, R, C
car_history = {} # the solution
cars = []
for i in range(0, F):
cars.append(Car(i))
car_history[i] = []
for t in range(0, T):
# print(t)
for car in cars:
finished_ride = car.act(t)
if finished_ride is not None:
car_history[car.carID].append(finished_ride[0])
return car_history
# main():
car_history = simulation()
with open(filename + '.out', 'w') as file:
for carID in range(0, F):
num_of_rides = len(car_history[carID])
file.write(str(num_of_rides))
for ridenum in range(0, num_of_rides):
file.write(' ' + str(car_history[carID][ridenum]))
file.write('\n')
|
class ReporterInterface(object):
def notify_before_console_output(self):
pass
def notify_after_console_output(self):
pass
def report_session_start(self, session):
pass
def report_session_end(self, session):
pass
def report_file_start(self, filename):
pass
def report_file_end(self, filename):
pass
def report_collection_start(self):
pass
def report_test_collected(self, all_tests, test):
pass
def report_collection_end(self, collected):
pass
def report_test_start(self, test):
pass
def report_test_end(self, test, result):
if result.is_success():
self.report_test_success(test, result)
elif result.is_skip():
self.report_test_skip(test, result)
elif result.is_error():
self.report_test_error(test, result)
else:
assert result.is_failure()
self.report_test_failure(test, result)
def report_test_success(self, test, result):
pass
def report_test_skip(self, test, result):
pass
def report_test_error(self, test, result):
pass
def report_test_failure(self, test, result):
pass
|
def read_as_strings(filename):
f = open(filename, "r")
res = f.read().split("\n")
return res
def read_as_ints(filename):
f = open(filename, "r")
res = map(int, f.read().split("\n"))
return list(res)
|
#num1 = int(input('qual tabuada você deseja?'))
#num2 = 1
#while True:
# if num1 <= 0:
# break
# print(f'{num2} X {num1} ={num2*num1}')
# num2 += 1
# if num2>=11:
# num1 = int(input('qual tabuada você deseja?'))
# num2 = 1
#print('programa encerrado!')
while True:
num1 = int(input('qual tabuada você deseja?'))
if num1 < 0:
break
print(30 * '-')
for c in range(1,11):
print(f'{num1} X {c} = {c*num1}')
print(30*'-')
print('programa encerrado')
|
n = int(input("Qual o tamanho do vetor?"))
x = [int(input()) for x in range(n)]
for i in range(0, n, 2):
print(x[i])
|
# Vasya is very upset that many people on the Net mix uppercase and lowercase letters in one word.
# That's why he decided to invent an extension for his favorite browser that would change the letters' register
# in every word so that it either only consisted of lowercase letters or, vice versa, only of uppercase ones.
# At that as little as possible letters should be changed in the word. For example, the word HoUse must be replaced
# with house, and the word ViP — with VIP. If a word contains an equal number of uppercase and lowercase letters,
# you should replace all the letters with lowercase ones. For example, maTRIx should be replaced by matrix.
# Your task is to use the given method on one given word.
# Input
# The first line contains a word s — it consists of uppercase and lowercase Latin letters and possesses the length
# from 1 to 100.
# Output
# Print the corrected word s. If the given word s has strictly more uppercase letters, make the word written in the
# uppercase register, otherwise - in the lowercase one.
# Examples
# input
# HoUse
# output
# house
# input
# ViP
# output
# VIP
# input
# maTRIx
# output
# matrix
word = input()
upper = 0
lower = 0
for i in word:
if i.isupper():
upper += 1
else:
lower += 1
if upper > lower:
print(word.upper())
else:
print(word.lower())
|
# function for merge sort
def merge_sort(arr):
if len(arr) > 1:
# mid element of array
mid = len(arr) // 2
# Dividing the array and calling merge sort on array
left = arr[:mid]
# into 2 halves
right = arr[mid:]
# merge sort for array first
merge_sort(left)
# merge sort for array second
merge_sort(right)
# merging function
merge_array(arr, left, right)
def merge_array(arr, left, right):
i = j = k = 0
# merging two array left right in sorted order
while i < len(left) and j < len(right):
if left[i] < right[j]:
arr[k] = left[i]
i += 1
else:
arr[k] = right[j]
j += 1
k += 1
# merging any remaining element
while i < len(left):
arr[k] = left[i]
i += 1
k += 1
while j < len(right):
arr[k] = right[j]
j += 1
k += 1
# printing array
def print_array(arr):
for i in range(len(arr)):
print(arr[i], end=" ")
print()
total_element = int(input("Number of element in array "))
arr = []
for i in range(total_element):
arr.append(int(input(f"Enter {i}th element ")))
print("Input array is ", end="\n")
print_array(arr)
merge_sort(arr)
print("array after sort is: ", end="\n")
print_array(arr)
|
def test_fake_hash(fake_hash):
assert fake_hash(b'rainstorms') == b"HASH(brainstorms)"
|
"""Constants for Fama
RANKS(list of str): taxonomical ranks, top to bottom
LOWER_RANKS(dict of str): rank as key, child rank as value
ROOT_TAXONOMY_ID (str): taxonomy identifier of root node
UNKNOWN_TAXONOMY_ID (str): taxonomy identifier of 'Unknown' node
ENDS (list of str): identifiers of first and second end for paired-end sequences.
First end identifier also used for any other sequence types (like
single-end reads and proteins)
STATUS_CAND (str): status assigned to pre-selected reads
STATUS_GOOD (str): status assigned to reads with assigned function
STATUS_BAD (str): status assigned to rejected reads
"""
RANKS = ['norank', 'superkingdom', 'phylum', 'class', 'order', 'family', 'genus', 'species']
LOWER_RANKS = {'norank': 'superkingdom',
'superkingdom': 'phylum',
'phylum': 'class',
'class': 'order',
'order': 'family',
'family': 'genus',
'genus': 'species'}
ROOT_TAXONOMY_ID = '1'
UNKNOWN_TAXONOMY_ID = '0'
ENDS = ['pe1', 'pe2']
STATUS_CAND = 'unaccounted'
STATUS_GOOD = 'function'
STATUS_BAD = 'nofunction'
|
supported_browsers = (
"system_default",
"chrome",
"chromium",
"chromium-browser",
"google-chrome",
"safari",
"firefox",
"opera",
"mozilla",
"netscape",
"galeon",
"epiphany",
"skipstone",
"kfmclient",
"konqueror",
"kfm",
"mosaic",
"grail",
"links",
"elinks",
"lynx",
"w3m",
"windows-default",
"macosx",
)
supported_image_extensions = (
"apng",
"avif",
"bmp",
"gif",
"ico",
"jpg",
"jpeg",
"jfif",
"pjpeg",
"pjp",
"png",
"svg",
"webp",
"cur",
"tif",
"tiff",
)
|
class BasePermission:
def __init__(self, user):
self.user = user
def has_permission(self, action):
raise NotImplementedError
class AllowAny:
def has_permission(self, action):
return True
class IsAuthenticated(BasePermission):
def has_permission(self, action):
return self.user.id is not None and self.user.is_authenticated()
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 17-4-17 下午10:25
# @Author : YANGz1J
# @Site :
# @File : urls_manage.py
# @Software: PyCharm
class Urlmanager(object):
def __init__(self):
self.new_urls = set()
self.old_urls = set()
def add_new_url(self, url):
if url is None:
return
if url not in self.new_urls and url not in self.old_urls:
self.new_urls.add(url)
def get_new_url(self):
if len(self.new_urls) == 0:
return
new_url = self.new_urls.pop()
self.old_urls.add(new_url)
return new_url
def has_new_url(self):
return len(self.new_urls) != 0
def add_new_urls(self, urls):
if urls is None or len(urls)==0:
return
for url in urls:
self.add_new_url(url)
def urls_clear(self):
if self.old_urls is None and self.new_urls is None:
return
self.old_urls.clear()
self.new_urls.clear()
|
# Description: Count number of *.log files in current directory.
# Source: placeHolder
"""
cmd.do('print("Count the number of log image files in current directory.");')
cmd.do('print("Usage: cntlogs");')
cmd.do('myPath = os.getcwd();')
cmd.do('logCounter = len(glob.glob1(myPath,"*.log"));')
cmd.do('print("Number of number of log image files in the current directory: ", logCounter);')
"""
cmd.do('print("Count the number of log image files in current directory.");')
cmd.do('print("Usage: cntlogs");')
cmd.do('myPath = os.getcwd();')
cmd.do('logCounter = len(glob.glob1(myPath,"*.log"));')
cmd.do('print("Number of number of log image files in the current directory: ", logCounter);')
|
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 28 06:33:05 2020
@author: ucobiz
"""
def happy():
print("Happy Bday to you!")
def sing(person, age):
happy()
happy()
print("Happy Bday,", person)
print("You're already", age, "years old")
happy()
def main():
sing("Fred", 30)
main()
|
#counter part of inheritance
#inheritance means by this program- a bookself is a book
#composition is -
class Bookself:
def __init__(self, *books):
self.books=books
def __str__(self):
return f"Bookself with {len(self.books)} books."
class Book:
def __init__(self,name):
self.name=name
def __str__(self):
return f"Book {self.name}"
book=Book("Harry potter")
book2=Book("Python")
shelf=Bookself(book,book2)
print(shelf)
|
def fake_get_value_from_db():
return 5
def check_outdated():
total = fake_get_value_from_db()
return total > 10
def task_put_more_stuff_in_db():
def put_stuff(): pass
return {'actions': [put_stuff],
'uptodate': [check_outdated],
}
|
#!/usr/bin/env python3
def solution(s: str, p: list, q: list) -> list:
"""
>>> solution('CAGCCTA', [2, 5, 0], [4, 5, 6])
[2, 4, 1]
"""
response = ['T'] * len(p)
for i, s in enumerate(s):
for k, (p, q) in enumerate(zip(p, q)):
if p <= i <= q and s < response[k]:
response[k] = s
impact_factor = {'A': 1, 'C': 2, 'G': 3, 'T': 4}
return [impact_factor[n] for n in response]
def solution(s: str, p: list, q: list) -> list:
"""
>>> solution('CAGCCTA', [2, 5, 0, 0, 6], [4, 5, 6, 0, 6])
[2, 4, 1, 2, 1]
"""
counters = {
'A': [0] * len(s),
'C': [0] * len(s),
'G': [0] * len(s),
'T': [0] * len(s)
}
for i, s in enumerate(s):
for count in counters.values():
count[i] = count[i - 1]
counters[s][i] += 1
impact_factor = {'A': 1, 'C': 2, 'G': 3, 'T': 4}
answers = []
for p, q in zip(p, q):
for k, count in counters.items():
if count[q] > count[p if p == 0 else p - 1]:
answers.append(impact_factor[k])
break
if p == q:
answers.append(impact_factor[s[p]])
break
else:
raise Exception('Unexpected error')
return answers
|
'''
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
'''
def solution(A,target):
hash1 = dict()
for i in range(len(A)):
hash1[A[i]] = i
print(hash1)
lenght_dict = len(hash1.keys())
print(lenght_dict)
count = 0
for key,value in hash1.items():
index1 = hash1[key]
key1 = target - key
count += 1
if(key1==key):
continue
else:
index2 = hash1.get(key1)
if(index2!= None):
out_list = [index1,index2]
print(out_list)
return(out_list)
break
A = [3,2,4,3]
target = 6
solution(A,target)
|
# coding:utf-8
unconfirmed_users = ['liuhanyu', 'luoliuzhou', 'wangyue', 'xiaolizi']
confirmed_users = []
while unconfirmed_users:
user = unconfirmed_users.pop()
confirmed_users.append(user)
print(confirmed_users)
print(unconfirmed_users)
|
# link: https://leetcode.com/problems/longest-string-chain/
"""
Sort the words by word's length. (also can apply bucket sort)
For each word, loop on all possible previous word with 1 letter missing.
If we have seen this previous word, update the longest chain for the current word.
Finally return the longest word chain.
"""
class Solution(object):
def longestStrChain(self, words):
"""
:type words: List[str]
:rtype: int
"""
words = sorted(words, key = len)
dic = {}
result = 0
for word in words:
dic[word]=1
curr_len = len(word)
for i in range(curr_len):
new_word = word[:i]+word[i+1:]
if new_word in dic and dic[new_word] + 1 > dic[word]:
dic[word] = dic[new_word]+1
# print(dic)
result = max(result, dic[word])
return result
|
#
# @lc app=leetcode.cn id=111 lang=python3
#
# [111] 二叉树的最小深度
#
# @lc code=start
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def minDepth(self, root: TreeNode) -> int:
if not root:
return 0
if not root.left and not root.right:
return 1
min_depth = 10**9
if root.left:
min_depth = min(self.minDepth(root.left), min_depth)
if root.right:
min_depth = min(self.minDepth(root.right), min_depth)
return min_depth + 1
# @lc code=end
|
# Доступ к тренировочным тестам урока без авторизации
def test_opening_TT_without_authorization (app):
app.Button_menu.Test_Button_Videocourses() # кнопка "Видеокурсы"
result = app.List_items_before_autorization.Test_list_of_all_items_for_TT(TEXT='УРОК') # нажимает на тренировочные тесты в предмете по порядку
total_number_tests = result[0]
total_number_tests_with_access = result[1]
assert total_number_tests == total_number_tests_with_access
|
"""typecats"""
__version__ = "1.7.0"
__author__ = "Peter Gaultney"
__author_email__ = "pgaultney@xoi.io"
|
num = int(input("Enter a number: "))
if ((num % 2 == 0) and (num % 3 == 0) and (num % 5 == 0)):
print("Divisible")
else:
print("Not Divisible")
|
"""Environment Variables to be used inside the CloudConvert-Python-REST-SDK"""
CLOUDCONVERT_API_KEY = "API_KEY"
"""Environment variable defining the Cloud Convert REST API default
credentials as Access Token."""
CLOUDCONVERT_SANDBOX = "true"
"""Environment variable defining if the sandbox API is used instead of the live API"""
|
# f[i][j] = f[i - 1][j - 1] where s[i - 1] == p[j - 1] || p[j - 1] == '.' case p[j - 1] != '*'
# f[i][j] = f[i][j - 2] or f[i - 1][j] where s[i - 1] == p[j - 2] || p[j - 2] == '.' case p[j - 1] == '*'
class Solution(object):
def isMatch(self, s, p):
"""
:type s: str
:type p: str
:rtype: bool
"""
m = len(s)
n = len(p)
table = [[False for _ in range(n + 1)] for _ in range(m + 1)]
for i in range(m + 1):
for j in range(n + 1):
if i == 0 and j == 0:
table[i][j] = True
continue
if j == 0:
table[i][j] = False
continue
if p[j - 1] != '*':
if i - 1 >= 0 and (p[j - 1] == '.' or p[j - 1] == s[i- 1]):
table[i][j] = table[i - 1][j - 1]
else:
if j - 2 >= 0:
table[i][j] = table[i][j - 2]
if i - 1 >= 0 and (p[j - 2] == '.' or p[j - 2] == s[i - 1]):
table[i][j] = table[i][j] or table[i - 1][j]
return table[m][n]
|
'''
Descripttion:
version:
Author: HuSharp
Date: 2021-02-21 22:59:41
LastEditors: HuSharp
LastEditTime: 2021-02-21 23:12:36
@Email: 8211180515@csu.edu.cn
'''
def countdown_1(k):
if k > 0:
yield k
for i in countdown_1(k-1):
yield i
def countdown(k):
if k > 0:
yield k
yield from countdown(k-1)
else:
yield 'Blast off'
|
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param root, a tree node
# @return a list of lists of integers
def levelOrderBottom(self, root):
x = self.solve(root)
return list(reversed(x))
def solve(self, root):
if root is None: return []
l = self.solve(root.left)
r = self.solve(root.right)
m = [ (l[i] if i < len(l) else []) + (r[i] if i < len(r) else [])
for i in xrange(max(len(l), len(r)))]
return [[root.val]] + m
|
"""
Author: Eda AYDIN
"""
T = int(input())
answer = []
for i in range(T):
size = int(input())
blocks = list(map(int, input().split()))
for j in range(size - 1):
if blocks[0] >= blocks[len(blocks) - 1]:
a = blocks[0]
blocks.pop(0)
elif blocks[0] < blocks[len(blocks) - 1]:
a = blocks[len(blocks) - 1]
blocks.pop(len(blocks) - 1)
else:
pass
if len(blocks) == 1:
answer.append("Yes")
if (blocks[0] > a) or (blocks[len(blocks) - 1] > a):
answer.append("No")
break
print("\n".join(answer))
|
# THIS FILE IS AUTO-GENERATED. PLEASE DO NOT MODIFY# version file for ldap3
# generated on 2018-08-01 17:55:24.174707
# on system uname_result(system='Windows', node='ELITE10GC', release='10', version='10.0.17134', machine='AMD64', processor='Intel64 Family 6 Model 58 Stepping 9, GenuineIntel')
# with Python 3.7.0 - ('v3.7.0:1bf9cc5093', 'Jun 27 2018 04:59:51') - MSC v.1914 64 bit (AMD64)
#
__version__ = '2.5.1'
__author__ = 'Giovanni Cannata'
__email__ = 'cannatag@gmail.com'
__url__ = 'https://github.com/cannatag/ldap3'
__description__ = 'A strictly RFC 4510 conforming LDAP V3 pure Python client library'
__status__ = '5 - Production/Stable'
__license__ = 'LGPL v3'
|
even = [2, 4, 6, 8]
odd = [1, 3, 5, 7, 9]
print(min(even))
print(max(even))
print(min(odd))
print(max(odd))
print()
print(len(even))
print(len(odd))
print()
# to count how many times s is repeated in the word
print("mississippi".count("s")) #4
print("mississippi".count("issi")) #1
even.extend(odd)
print(even)
another_even = even
print(another_even)
even.sort()
print(even)
even.sort(reverse=True)
print(even)
print(another_even)
# mutated the list by sorting it first
# https://docs.python.org/3.8/library/functions.html#any
|
class Solution:
def prefixesDivBy5(self, A: List[int]) -> List[bool]:
val = 0
res = [None] * len(A)
for i, v in enumerate(A):
val = ((val << 1) + v) % 5
res[i] = (val == 0)
return res
|
t=int(input())
for i in range(t):
s=input()
if s[:int(len(s)/2)]==s[int(len(s)/2):]:
print("YES")
else:
print("NO")
|
__all__ = [
'feature_audio_opus', \
'feature_audio_opus_conf'
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.