content
stringlengths 7
1.05M
|
|---|
def Scenario_Generation():
# first restricting the data to April 2020 when we are predicting six weeks out from april 2020
popularity_germany = np.load("./popularity_germany.npy")
popularity_germany = np.copy(popularity_germany[:,0:63,:]) # april 20th is the 63rd index in the popularity number
#
one = np.multiply(np.ones((16,42,6)),popularity_germany[:,62:63,:])
popularity_germany = np.append(popularity_germany,one,axis=1)
# bus movement is kept as 0 after march 18
# we keep the flight data same as what was observed on april 20th
# there has been no change in the trucj movement pattern (sp we keep as a weekly pattern)
# the data contains placeholder for 158 countries (so that we can capture the movement from all the countries)
bus_movement = np.load("./bus_movement.npy")
truck_movement = np.load("./truck_movement.npy")
flight_movement = np.load("./flight_movement.npy")
car_movement = np.load("./car_movement.npy")
train_movement = np.load("./train_movement.npy")
bus_move = bus_movement[:,0:63,:]
truck_move = truck_movement[:,0:63,:]
flight_move = flight_movement[:,0:63,:]
static_car_move = car_movement[:,0:63,:]
static_train_move = train_movement[:,0:63,:]
one = np.multiply(np.ones((16,42,158)),bus_move[:,62:63,:])
bus_move = np.append(bus_move,one,axis=1)
one = np.multiply(np.ones((16,42,158)),truck_move[:,62:63,:])
truck_move = np.append(truck_move,one,axis=1)
one = np.multiply(np.ones((16,42,158)),flight_move[:,62:63,:])
flight_move = np.append(flight_move,one,axis=1)
one = np.multiply(np.ones((16,42,158)),static_car_move[:,62:63,:])
static_car_move = np.append(static_car_move,one,axis=1)
one = np.multiply(np.ones((16,42,158)),static_train_move[:,62:63,:])
static_train_move = np.append(static_train_move,one,axis=1)
for t in range(63,63+42):
truck_move[:,t,:] = truck_move[:,t-7,:]
popularity_o = np.copy(popularity_germany)
policy_o = pd.read_csv("./policy.csv")
policy_o_life = pd.read_csv("./policy_lift.csv")
cols = ['Border Closure', 'Initial business closure',
'Educational facilities closed', 'Non-essential services closed',
'Stay at home order', 'contact restriction',
'retails closed','trend','tmax','frustration']
policy = pd.read_csv("./policy.csv")
policy_lift = pd.read_csv("./policy_lift.csv")
popularity = np.load("./popularity_germany.npy")
weather = pd.read_csv("./weather_predict.csv")
trend = pd.read_csv("./trend_predict.csv") # cumulative trend numbers
PTV = pd.read_csv("./PTV_predict.csv")
# there are 9 scenarios
# in first scenario, no change in policy and all policies remain in place
# in the next 7 scenarios, we switch off (relax) one of the policy if it was implemented in that respective state
# in the last scenario, we relax all the policies (however, we do not show this in paper as it lead to a very sharp rise)
# each of these 9 scenarios is tested twice - one when for april 21, 2020 and once for april 28, 2020
for pp in range(9):
popularity = np.copy(popularity_o)
car_movement = np.copy(static_car_move)
train_movement = np.copy(static_train_move)
for w in range(2):
policy1 = pd.DataFrame.copy(pd.read_csv("./policy.csv") )
policy2 = pd.DataFrame.copy(pd.read_csv("./policy.csv") )
policy3 = pd.DataFrame.copy(pd.read_csv("./policy.csv") )
name = '_P_'+str(pp)+'_W_'+str(w+1)
if pp == 0:
name = ''
# when relaxing a policy, we keep the date very high (1000) so that the return value is 0 (not implemented post april 21 or april 28)
elif pp == 8:
if w == 0:
name = '_P_8_W_1'
for xx in range(7):
policy1[cols[xx]] = 1000
policy2[cols[xx]] = 1000
policy3[cols[xx]] = 1000
if w == 1:
name = '_P_8_W_2'
for xx in range(7):
policy2[cols[xx]] = 1000
policy3[cols[xx]] = 1000
else:
if w == 0:
policy1[cols[pp-1]] = 1000
policy2[cols[pp-1]] = 1000
policy3[cols[pp-1]] = 1000
elif w==1:
policy2[cols[pp-1]] = 1000
policy3[cols[pp-1]] = 1000
X = []
for j in range(16):
# first week
for t in range(63,70):
c = []
for p in range(7):
c.append(int(policy1[cols[p]].iloc[j] <= t+79))
c.append(trend.iloc[t,j+1])
c.append(weather.iloc[t,j+1])
c.append(PTV.iloc[t,1])
X.append(c)
# second week
for t in range(70,77):
c = []
for p in range(7):
c.append(int(policy2[cols[p]].iloc[j] <= t+79))
c.append(trend.iloc[t,j+1])
c.append(weather.iloc[t,j+1])
c.append(PTV.iloc[t,1])
X.append(c)
# rest of the four weeks
for ww in range(4):
for t in range(77+7*ww,84+7*ww):
c = []
for p in range(7):
c.append(int(policy3[cols[p]].iloc[j] <= t+79))
c.append(trend.iloc[t,j+1])
c.append(weather.iloc[t,j+1])
c.append(PTV.iloc[t,1])
X.append(c)
x = pd.DataFrame(X,columns=cols)
models = RegressionModels()
y_pred = models[0].predict(x)
y_car = models[1].predict(x)
y_train = models[2].predict(x)
for j in range(16):
for t in range(63,63+42):
popularity[j,t,0] = y_pred[42*j+t-63]
popularity[j,t,3] = y_car[42*j+t-63]
popularity[j,t,4] = y_train[42*j+t-63]
wtrain = popularity[:,:,3]
wtrain = (wtrain)/100+1
wcars = popularity[:,:,4]
wcars = (wcars)/100+1
numbee = 63+42
for i in range(16):
car_movement[i] = np.multiply(car_movement[i],wcars[i].reshape([numbee,1])*np.ones([numbee,158]))
train_movement[i] = np.multiply(train_movement[i],wtrain[i].reshape([numbee,1])*np.ones([numbee,158]))
# the files can be saved
#np.save('popularity_germany'+name,popularity)
#np.save('train_movement'+name,train_movement)
#np.save('car_movement'+name,car_movement)
return()
|
def L1(y_output, y_input):
""" L1 Loss Function calculates the sum of the absolute difference between the predicted and the input"""
return sum(abs(y_input - y_output))
|
# loendur dictionary
counter_dict = {}
# loe failist ridade kaupa ja loendab dictionarisse erinevad nimed
with open('/Users/mikksillaste/Downloads/aima-python/nameslist.txt') as f:
line = f.readline()
while line:
line = line.strip()
if line in counter_dict:
counter_dict[line] += 1
else:
counter_dict[line] = 1
line = f.readline()
# loeb failist ridade kaupa ja loendab dictionarisse erinevad kategooriad, mille jaoks on vaja kindlat osa reast [3:-26]
counter_dict2 = {}
with open('/Users/mikksillaste/Downloads/aima-python/Training_01.txt') as f:
line = f.readline()
while line:
line = line[3:-26]
if line in counter_dict2:
counter_dict2[line] += 1
else:
counter_dict2[line] = 1
line = f.readline()
print(counter_dict)
print(counter_dict2)
|
def eight_is_great(a, b):
if a == 8 or b == 8:
print(":)")
elif (a + b) == 8:
print(":)")
else:
print(":(")
|
'''53 Crie um programa que leia uma frase qualquer e diga se ela é um palíndromo, desconsiderando os espaços. '''
frase = str(input('Digite uma frase: ')).replace(' ', '').upper()
print(f'O inverso de {frase} é {frase[::-1]}')
if frase == frase[::-1]:
print('A frase digitada é um palíndromo!')
else:
print('A frase digitada não é um palíndromo!')
|
#ChangeRenderSetting.py
##This only use in the maya software render , not in arnold
#Three main Node of Maya Render:
# ->defaultRenderGlobals, defaultRenderQuality and defaultResolution
# ->those are separate nodes in maya
'''
import maya.cmds as cmds
#Function : getRenderGlobals()
#Usage : get the Value of Render Globals and print it
def getRenderGlobals() :
render_glob = "defaultRenderGlobals"
list_Attr = cmds.listAttr(render_glob,r = True,s = True)
#loop the list
print 'defaultRenderSetting As follows :'
for attr in list_Attr:
get_attr_name = "%s.%s"%(render_glob, attr)
print "setAttr %s %s"%(get_attr_name, cmds.getAttr(get_attr_name))
#Function : getRenderResolution()
#Usage : get the Value of Render Resolution and print it
def getRenderResolution() :
resolu_list = "defaultResolution"
list_Attr = cmds.listAttr(resolu_list,r = True , s = True)
print 'defaultResolution As follows :'
for attr in list_Attr:
get_attr_name = "%s.%s"%(resolu_list, attr)
print "setAttr %s %s"%(get_attr_name, cmds.getAttr(get_attr_name))
#defaultRenderGlobals.startFrame = 2.0
#Function : startEndFrame
#Usage : to change the Global value(startFrame,endFrame) of the Render
#use for set the render startFrame,endFrame,byframe
#Example : startEndFrame(3.0,7.0)
def startEndFrame(startTime,endTime) :
cmds.setAttr("defaultRenderGlobals.startFrame",startTime)
cmds.setAttr("defaultRenderGlobals.endFrame",endTime)
#Function : setWidthAndHeight
#Usage : to change the Resolution value(width,height) of the Render
#Example : setWidthAndHeight(960,540)
def setWidthAndHeight(width,height) :
cmds.setAttr("defaultResolution.width",width)
cmds.setAttr("defaultResolution.height",height)
'''
|
x = int(input())
y = int(input())
if (2 * y + 1 - x) % (y - x + 1) == 0:
print("YES")
else:
print("NO")
|
# Description
# Count how many nodes in a linked list.
# Example
# Example 1:
# Input: 1->3->5->null
# Output: 3
# Explanation:
# return the length of the list.
# Example 2:
# Input: null
# Output: 0
# Explanation:
# return the length of list.
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param head: the first node of linked list.
@return: An integer
"""
def countNodes(self, head):
# write your code here
counter = 0
current = head
while current != None:
counter = counter + 1
current = current.next
return counter
|
class Solution:
def longestPalindrome(self, s: str) -> str:
result = ''
pal_s = set(s)
if len(pal_s) == 1:
return s
for ind_c in range(len(s)):
pal = ''
ind_l = ind_c
ind_r = ind_c + 1
while ind_l > -1 and ind_r < len(s):
if s[ind_l] == s[ind_r]:
pal = s[ind_l] + pal + s[ind_r]
ind_l -= 1
ind_r += 1
else:
break
if len(result) < len(pal):
result = pal
pal = s[ind_c]
ind_l = ind_c - 1
ind_r = ind_c + 1
while ind_l > -1 and ind_r < len(s):
if s[ind_l] == s[ind_r]:
pal = s[ind_l] + pal + s[ind_r]
ind_l -= 1
ind_r += 1
else:
break
if len(result) < len(pal):
result = pal
return result
|
print("@function from_script:thing")
for i in range(10):
print(f"say {i}")
|
nombre = input("Nombre: ")
apellido = input("Apellido: ")
edad_nac = input("Edad de nacimiento: ")
correo1 = nombre[0] + "." + apellido + edad_nac[-2:] + "@uma.es"
correo2 = nombre[:3] + apellido[:3] + edad_nac[-2:] + "@uma.es"
print("Correos:", correo1, "y", correo2)
|
lista = list()
for count in range(5):
while True:
num = str(input('Digite um número:\t')).strip()
v = 0
for n in num:
if n not in '0123456789':
v += 1
if v == 0:
num = int(num)
break
else:
print("\033[31mDigite apenas um número inteiro!\033[m")
if count == 0:
lista.append(num)
print(f"\033[32m{num} foi adicionado no começo da lista!\033[m")
elif num <= min(lista):
lista.insert(0,num)
print(f"\033[32m{num} foi adicionado no começo da lista!\033[m")
elif num >= max(lista):
lista.append(num)
print(f"\033[32m{num} foi adicionado no final da lista!\033[m")
else:
ants = lista[0]
for atual in lista:
atual
if ants < num <= atual:
lista.insert(lista.index(atual),num)
break
ants = atual
print(f"\033[32m{num} foi adicionado na posição {lista.index(num)}!\033[m")
print(lista)
|
#crie um porgrama que leia duas notas de um aluno e calcule sua media,
#mostrando uma mensagem no final, de acordo com a media atingida:
# Média abaixo de 5.0: reprovado
# Média entre 5.0 e 6.9: Recuperação
# Média 7.0 ou superior: Aprovado
nota1 = float(input('Primeira nota '))
nota2 = float(input('Segunda Nota'))
media = (nota1 + nota2) / 2
if media < 5:
print(f'Aluno REPROVADO sua media foi {media} ')
elif media > 5 and media <= 7:
print(f'Aluno RECUPERAÇÃO sua media foi {media} ')
else:
print(f'Aluno APROVADO sua media foi {media}')
|
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param head, a ListNode
# @return a ListNode
def sortList(self, head):
if head is None or head.next is None:
return head
fast, slow = head, head
while fast.next and fast.next.next:
slow = slow.next
fast = fast.next.next
slow.next, slow = None, slow.next
slow, fast = self.sortList(head), self.sortList(slow)
return self.merge(slow, fast)
def merge(self, head1, head2):
if head1 is None:
return head2
if head2 is None:
return head1
p = ListNode(0)
res = p
while head1 and head2:
if head1.val < head2.val:
p.next = head1
head1 = head1.next
else:
p.next = head2
head2 = head2.next
p = p.next
if head1:
p.next = head1
elif head2:
p.next = head2
return res.next
|
class DiscreteActionWrapper:
def __init__(self, env, n):
self.env = env
self.action_cont = [
# [l + (_+0.5)*(h-l)/n for _ in range(n)]
# [l + _*(h-l)/(n+1) for _ in range(n)]
[l + _*(h-l)/(n-1) for _ in range(n)]
for h, l in zip(self.env.action_space.high, self.env.action_space.low)
]
self.env.action_space.shape = [n] * len(self.env.action_space.high)
delattr(self.env.action_space, "low")
delattr(self.env.action_space, "high")
def step(self, a):
action_cont = [_[i] for _, i in zip(self.action_cont, a)]
return self.env.step(action_cont)
def __getattr__(self, name):
return getattr(self.env, name)
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def compare(self, lleft, rright):
if (not lleft) and (not rright):
return True
elif (not lleft) or (not rright):
return False
else:
if lleft.val != rright.val:
return False
else:
return self.compare(lleft.left, rright.right) and self.compare(lleft.right, rright.left)
def isSymmetric(self, root: TreeNode) -> bool:
if not root:
return True
else:
return self.compare(root.left, root.right)
|
class AbstractObserver(object):
"""Abstract Observer"""
def __init__(self):
self.is_stopped = False
def next(self, value):
raise NotImplementedError
def error(self, error):
raise NotImplementedError
def completed(self):
raise NotImplementedError
def on_next(self, value):
"""Notifies the observer of a new element in the sequence.
Keyword arguments:
value -- Next element in the sequence.
"""
if not self.is_stopped:
self.next(value)
def on_error(self, error):
"""Notifies the observer that an exception has occurred.
Keyword arguments:
error -- The error that has occurred.
"""
if not self.is_stopped:
self.is_stopped = True
self.error(error)
def on_completed(self):
"""Notifies the observer of the end of the sequence."""
if not self.is_stopped:
self.is_stopped = True
self.completed()
def dispose(self):
"""Disposes the observer, causing it to transition to the stopped
state."""
self.is_stopped = True
def fail(self, exn):
if not self.is_stopped:
self.is_stopped = True
self.error(exn)
return True
return False
|
# -*- coding: utf-8 -*-
def main():
n = int(input())
if n == 1:
print("Hello World")
else:
a = int(input())
b = int(input())
print(a + b)
if __name__ == '__main__':
main()
|
class Message:
def __init__(self, response, type_):
self.response = response
self.type = type_
|
#!/usr/bin/python3
MAXIMIZE = 1
MINIMIZE = 2
|
class StyleMapping:
def __init__(self, opts):
self._opts = opts
def __getitem__(self, key):
return getattr(self._opts, "style_{}".format(key), "").encode().decode("unicode_escape")
def apply_styles(opts, command):
return command.format_map(StyleMapping(opts))
|
#
# @lc app=leetcode id=199 lang=python3
#
# [199] Binary Tree Right Side View
#
# https://leetcode.com/problems/binary-tree-right-side-view/description/
#
# algorithms
# Medium (52.74%)
# Likes: 1951
# Dislikes: 117
# Total Accepted: 264K
# Total Submissions: 500.2K
# Testcase Example: '[1,2,3,null,5,null,4]'
#
# Given a binary tree, imagine yourself standing on the right side of it,
# return the values of the nodes you can see ordered from top to bottom.
#
# Example:
#
#
# Input: [1,2,3,null,5,null,4]
# Output: [1, 3, 4]
# Explanation:
#
# 1 <---
# / \
# 2 3 <---
# \ \
# 5 4 <---
#
#
# @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 rightSideView(self, root: TreeNode) -> List[int]:
if root is None:
return []
right_view = []
dfs = [(root, 0)]
while len(dfs) > 0:
curr_node, curr_level = dfs.pop()
if curr_level == len(right_view):
right_view.append(curr_node.val)
if curr_node.left is not None:
dfs.append((curr_node.left, curr_level + 1))
if curr_node.right is not None:
dfs.append((curr_node.right, curr_level + 1))
return right_view
# @lc code=end
|
# -*- coding: utf-8 -*-
"""
File Name: fib.py
Author : jynnezhang
Date: 2020/4/30 11:16 上午
Description:
斐波那契
递归会超时!
https://leetcode-cn.com/problems/fei-bo-na-qi-shu-lie-lcof/
https://leetcode-cn.com/problems/fibonacci-number/
"""
class Solution:
def fib(self, n: int) -> int:
if n == 0:
return 0
if n == 1:
return 1
return self.fib(n-1) + self.fib(n-2)
def fib2(self, n):
if n == 0 or n == 1:
return n
a, b = 0, 1
for i in range(1, n):
a, b = b, a + b
return b
print(Solution().fib2(5))
|
#!/usr/bin/env python
# _*_ coding:utf-8 _*_
'''
函数的参数
'''
print("===============================默认参数====================================")
def enroll(name, age, sex='男', city='上海'):
print("姓名:" + str(name) + ",年龄:" + str(age) + ",性别:" + str(sex) + ",地址:" + str(city))
enroll("jack", "12", "女")
enroll("tony", "10", city='北京')
print("\n==========================默认参数为可变对象============================")
def add(L=[]):
L.append("end")
return L
print(add())
print("\n==========================可变参数============================")
def add_sum(*number):
sum = 0
for x in number:
sum = sum + x;
return str(sum)
print(add_sum(1, 2, 3, 4, 5, 6, 7, 8))
# 当实参为list或tuple时传值方式
l = [1, 2, 4, 5, 6, 7, 8, 9]
t = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
print("实参为list:" + add_sum(*l))
print("实参为tuple:" + add_sum(*t))
print("\n==========================关键字参数============================")
def student_info(name, age, **kwargs):
print("name:", name, ",age:", age, ",other_info:", kwargs)
# 自己传入实参
student_info("kevin", 20, address='xi\'an', sex='boy')
# 现有字典参数
d = {'first-name': 'monkey', 'date': '2017-12-02'}
student_info("kevin", 20, **d)
print("\n==========================命名关键字参数============================")
def person_info(name, age, *, city='BeiJin', job):
print(name, age, city, job)
# 函数有几个形参就要传几个实参,如形参有默认值,则可不传对应实参
person_info('jack', 12, job='driver')
print("\n==========================组合参数============================")
def f1(a, b, c='23', *args, city, **kwargs):
print('a:', a, 'b:', b, 'c:', c, 'args:', args, 'city:', city, 'kw:', kwargs)
def f2(a, b, *, city, age, **kwargs):
print('a:', a, 'b:', b, 'city:', city, 'age:', age, 'kw:', kwargs)
f1('aaa', 'bbb', 'ccc', 'sss', 'sd', city='ddd', xx='fff', yy='ds')
f2('aaa', 'bbb', city='ddd', xx='fff', yy='ds', age='19')
print("\n==========================练习============================")
def product(*number):
if len(number) == 0:
return "请输入至少一个数字"
else:
pro = 1;
for x in number:
pro *= x;
return pro
l = [5, 6, 7, 9]
print(product(*l))
|
class Calculation:
def __init__(cls, a, b, op):
cls.a = float(a)
cls.b = float(b)
cls.op = op
def getResult(cls):
return cls.op(cls.a, cls.b)
|
"""Find the nth root of a number with the bisection method."""
__author__ = 'Nicola Moretto'
__license__ = "MIT"
def rootBisection(x, power, precision):
'''
Find the nth root of a number with the bisection method.
:param x: Number
:param power: Root
:param precision: Precision
:return: power-th root of x
'''
if power < 1 or precision < 0:
return None
if power == 1:
return x
if x < 0 and power%2 == 0:
return None
low = min(-1, x)
high = max(1, x)
value = (low+high)/2.0
while abs(value**power-x) > precision:
if value**power < x:
low = value
else:
high = value
value = (low+high)/2.0
return value
|
a = type('a_fyerr', (Exception,), {})
try:
raise a('aa')
except Exception as e:
print(type(e))
|
#Desenvolva um programa que leia quatro valores pelo teclado e guarde-os em uma tupla. No final, mostre:
#A) Quantas vezes apareceu o valor 9.
#B) Em que posição foi digitado o primeiro valor 3.
#C) Quais foram os números pares.
números = (int(input('Primeiro número: ')), int(input('Segundo número: ')), int(input('Terceiro número: ')), int(input('Quarto número: ')))
print(f'O número nove apareceu {números.count(9)} vezes')
if 3 in números:
print(f'O valor 3 apareceu primeiramente na {números.index(3)+1}° posição')
else:
print('O valor 3 não foi digitado')
print('Os números pares digitados foram: ', end='')
for n in números:
if n % 2 == 0:
print(n, end=' ')
|
expected_output = {
"Tunnel0": {
"nhs_ip": {
"111.0.0.100": {
"nhs_state": "E",
"nbma_address": "111.1.1.1",
"priority": 0,
"cluster": 0,
"req_sent": 0,
"req_failed": 0,
"reply_recv": 0,
"current_request_id": 94,
"protection_socket_requested": "FALSE",
}
}
},
"Tunnel100": {
"nhs_ip": {
"100.0.0.100": {
"nhs_state": "RE",
"nbma_address": "101.1.1.1",
"priority": 0,
"cluster": 0,
"req_sent": 105434,
"req_failed": 0,
"reply_recv": 105434,
"receive_time": "00:00:49",
"current_request_id": 35915,
"ack": 35914,
"protection_socket_requested": "FALSE",
}
}
},
"Tunnel111": {
"nhs_ip": {
"111.0.0.100": {
"nhs_state": "E",
"nbma_address": "111.1.1.1",
"priority": 0,
"cluster": 0,
"req_sent": 184399,
"req_failed": 0,
"reply_recv": 0,
"current_request_id": 35916,
}
}
},
"pending_registration_requests": {
"req_id": {
"16248": {
"ret": 64,
"nhs_ip": "111.0.0.100",
"nhs_state": "expired",
"tunnel": "Tu111",
},
"57": {
"ret": 64,
"nhs_ip": "172.16.0.1",
"nhs_state": "expired",
"tunnel": "Tu100",
},
}
},
}
|
def main():
with open("emotions.txt", "r") as f:
count = set(f.readlines())
print(count)
print(len(count))
if __name__ == '__main__':
main()
|
environmentdefs = {
"local": ["localhost"],
"other": ["localhost"]
}
roledefs = {
"role": ["localhost"]
}
componentdefs = {
"role": ["component"]
}
|
class QueryUser:
CREATE_TABLE_USERS: str = """
CREATE TABLE IF NOT EXISTS users (
user_id INTEGER PRIMARY KEY NOT NULL,
name TEXT NOT NULL,
email TEXT NOT NULL,
phone TEXT NOT NULL,
address TEXT NOT NULL,
country TEXT NOT NULL
);
"""
INSERT_USER: str = """
INSERT INTO users (name, email, phone, address, country) VALUES (?, ?, ?, ?, ?)
"""
GET_USER_BY_ID: str = """
SELECT * FROM users WHERE user_id = ?
"""
GET_USERS: str = """
SELECT * FROM users
"""
UPDATE_USER_BY_ID: str = """
UPDATE users SET name = ?, email = ?, phone = ?, address = ?, country = ? WHERE user_id =?
"""
DELETE_USER_BY_ID: str = """
DELETE from users WHERE user_id = ?
"""
query_user = QueryUser()
|
# https://leetcode.com/problems/palindrome-linked-list/submissions/
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def isPalindrome(self, head):
"""
:type head: ListNode
:rtype: bool
"""
# p1 = first
# p2 = last -> for storing lst nodes use a stack
# traverse till mid
# check if p1 == p2
# if not break
stack = []
temp = head
# stack to store prev nodes
while(temp):
stack.append(temp.val)
temp = temp.next
# find mid
curr = head
counter = 0
while(curr):
counter += 1
curr = curr.next
mid = counter // 2
# Traverse till mid and compare the first and last nodes
p1 = head
p2 = stack.pop()
while(mid):
if(p1.val != p2):
return False
p1 = p1.next
p2 = stack.pop()
mid -= 1
return True
|
# 打印输出位的逻辑与运算的结果、逻辑或运算的结果、逻辑异或运算的结果以及取反的结果
a = int(input('正整数a:'))
b = int(input('正整数b:'))
w = int(input('表示位数:'))
f = '{{:0{}b}}'.format(w)
m = 2 ** w - 1 # w位都相当于二进制数的1
print('a = ' + f.format(a))
print('b = ' + f.format(b))
print('a & b = ' + f.format(a & b))
print('a | b = ' + f.format(a | b))
print('a ^ b = ' + f.format(a ^ b))
print('~a = ' + f.format(~a & m))
print('~b = ' + f.format(~b & m))
|
class Solution:
def XXX(self, nums: List[int]) -> List[List[int]]:
res = [[]]
for num in nums:
res.append([num])
for temp in res[1:-1]:
res.append(temp+[num])
return res
|
class LCRecommendation:
TURN_LEFT = -1
TURN_RIGHT = 1
STRAIGHT_AHEAD = 0
CHANGE_TO_EITHER_WAY = 2
change_lane = True
change_to_either_way = False
recommendation = 0
def __init__(self, lane, recommendation):
self.lane = lane
self.recommendation = recommendation
if recommendation == self.TURN_RIGHT:
self.target_lane = lane - 1
elif recommendation == self.TURN_LEFT:
self.target_lane = lane + 1
elif recommendation == self.CHANGE_TO_EITHER_WAY:
self.change_to_either_way = True
elif recommendation == self.STRAIGHT_AHEAD:
self.change_lane = False
|
##
## this file autogenerated
## 8.4(6)5
##
jmp_esp_offset = "125.63.32.8"
saferet_offset = "166.11.228.8"
fix_ebp = "72"
pmcheck_bounds = "0.176.88.9"
pmcheck_offset = "96.186.88.9"
pmcheck_code = "85.49.192.137"
admauth_bounds = "0.32.8.8"
admauth_offset = "240.33.8.8"
admauth_code = "85.137.229.87"
# "8.4(6)5" = ["125.63.32.8","166.11.228.8","72","0.176.88.9","96.186.88.9","85.49.192.137","0.32.8.8","240.33.8.8","85.137.229.87"],
|
# -*- coding: utf-8 -*-
# (C) shan weijia, 2018
# All rights reserved
'''Description '''
__author__ = 'shan weijia <shanweijia@jiaaocap.com>'
__time__ = '2018/12/22 8:10 PM'
SQLALCHEMY_DATABASE_URI = "mysql://root:root@127.0.0.1:3306/test" # 配置数据库连接地址
SECRET_KEY = "cd17cb5e-fa95-45bd-98b8-fd6a8dd45957"
SALT = "GooDoss"
|
# 격자판의 숫자 이어 붙이기
# DFS를 이용한 풀이
# https://swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AV7I5fgqEogDFAXB&categoryId=AV7I5fgqEogDFAXB&categoryType=CODE
t=int(input())
def dfs(x, y, l, s):
s+=lis[x][y]
if not l:
result.add(s)
return
idx_x=[1,0,-1,0]
idx_y=[0,1,0,-1]
# visit[x][y]=1
for i in range(4):
n_x=x+idx_x[i]
n_y=y+idx_y[i]
if (n_x<4 and n_x>=0) and (n_y<4 and n_y>=0):
# if not visit[n_x][n_y]:
dfs(n_x, n_y, l-1,s)
# visit[x][y]=0
for tc in range(1, t+1):
lis=[list(map(str,input().split())) for _ in range(4)]
result=set()
for i in range(4):
for j in range(4):
# visit=[[0]*4 for _ in range(4)]
dfs(i,j,6,"")
print("#{} {}".format(tc, len(result)))
|
print('=ˆ= ' * 8)
print(' TAULA DE MULTIPLICACIÓ')
print('=ˆ= ' * 8)
num = int(input('introduïu un número per trobar\nla taula de multiplicació: '))
print(' ' * 7, '-' * 13)
x = 1
for c in range(1, 11):
print(' ' * 7, '{} x {:2} = {:3}'.format(num, x, num*x))
x += 1
print(' ' * 7, '-' * 13)
|
# -*- encoding: utf-8 -*-
"""
KERI
keri.vdr Package
"""
__all__ = ["issuing", "eventing", "registering", "viring", "verifying"]
|
# class with __init__
class C1:
def __init__(self):
self.x = 1
c1 = C1()
print(type(c1) == C1)
print(c1.x)
class C2:
def __init__(self, x):
self.x = x
c2 = C2(4)
print(type(c2) == C2)
print(c2.x)
|
'''
Crie um programa que leia o nome de uma cidade diga se ela começa ou não com o nome "SANTO".
'''
nome_cidade = str(input('Digite o nome de uma cidade: ')).strip()
primeiro_nome = nome_cidade.split()
print('{}'.format('Santo' in primeiro_nome[0].capitalize()))
|
class Fail_AuthUwU(Exception):
"""Thrown when when authentication fails
Attrs: objName
"""
def __init__(self, objName, message='sowwy {self.objName} has failed auwthenication..'):
self.objName = objName
self.message = message
super().__init__(message)
def __str__(self):
return f'{self.objName} -> {self.message}'
class UwUNoAccess(Exception):
"""Thrown when when authentication fails
Attrs: objName
"""
def __init__(self, objName, message='sowwy {self.objName} Can not hit me here..'):
self.objName = objName
self.message = message
super().__init__(message)
def __str__(self):
return f'{self.objName} -> {self.message}'
class UwUMemberAccessException(Exception):
"""Thrown when when authentication fails
Attrs: objName
"""
def __init__(self, objName, message='sowwy {self.objName} does not have access to this..'):
self.objName = objName
self.message = message
super().__init__(message)
def __str__(self):
return f'{self.objName} -> {self.message}'
class UwUPolicies(Exception):
"""Thrown when when authentication fails
Attrs: objName
"""
def __init__(self, objName, message='sowwy {self.objName} our powicies do not permit this..'):
self.objName = objName
self.message = message
super().__init__(message)
def __str__(self):
return f'{self.objName} -> {self.message}'
|
"""
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
Find the minimum element.
You may assume no duplicate exists in the array.
Example 1:
Input: [3,4,5,1,2]
Output: 1
Example 2:
Input: [4,5,6,7,0,1,2]
Output: 0
"""
class Solution(object):
def findMin(self, nums):
"""
Strategy is to use binary search.
For a given element, if the previous value is greater than it, the current element must be the minimum.
If the current element is not the minimum value to find the next range to search check
1. If current element is greater than or equal to left value and greater than right value
then minimum value must be on right side. The GTE for left value is to handle case for two values
where first value is > second value but minimum index calculation rounds down (to 0).
2. Else minimum value is on left side
:type nums: List[int]
:rtype: int
"""
if nums is None:
return 0
if len(nums) == 1:
return nums[0]
start_index = 0
end_index = len(nums) - 1
while start_index < end_index:
middle_index = (start_index + end_index) // 2
start_value = nums[start_index]
end_value = nums[end_index]
middle_value = nums[middle_index]
if middle_index >= 1:
previous_index = middle_index - 1
previous_value = nums[previous_index]
if previous_value > middle_value:
return middle_value
if middle_value >= start_value and middle_value > end_value:
start_index = middle_index + 1
else:
end_index = middle_index - 1
return nums[start_index]
|
class Solution:
ops = ['*', '/', '+', '-']
def clumsy(self, N: int) -> int:
answer = [N]
i = N - 1
j = 0
while i > 0:
op = self.ops[j % 4]
j += 1
if op == '*':
n = answer.pop(-1)
val = n * i
answer.append(val)
i -= 1
continue
if op == '/':
n = answer.pop(-1)
val = int(n / i)
answer.append(val)
i -= 1
continue
if op == '+':
answer.append(i)
i -= 1
continue
if op == '-':
answer.append(-i)
i -= 1
continue
answer = sum(answer)
if answer < -2 ** 31:
return -2 ** 31
if answer > 2 ** 31 - 1:
return 2 ** 31 - 1
return answer
|
s = input()
s = s[::-1]
ans = 0
b = 0
for i in range(len(s)):
if s[i] == "B":
ans += i
ans -= b
b += 1
print(ans)
|
"""This py describe the class the could be accessed by other."""
__author__ = "Gustavo Figueiredo"
__copyright__ = "CASA"
__version__ = "1.0.1"
__maintainer__ = "Gustavo Figueiredo"
__email__ = "gustavodsf1@gmail.com"
__status__ = "Development"
|
class PongError(Exception):
pass
class RoomError(PongError):
def __init__(self, room, msg, **kwargs):
err_msg = '{} room info : {}'.format(msg, room)
super().__init__(err_msg, **kwargs)
class PlayerError(PongError):
def __init__(self, player, msg, **kwargs):
err_msg = '{} player info : {}'.format(msg, player)
super().__init__(err_msg, **kwargs)
class LobbyError(PongError):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
class ProtocolError(PongError):
def __init__(self, payload, msg, **kwargs):
err_msg = '{} message: {}'.format(msg, payload)
super().__init__(err_msg, **kwargs)
class UnexpectedProtocolError(ProtocolError):
def __init__(self, payload, expected, **kwargs):
err_msg = 'Unexpected payload type {}'.format(expected)
super().__init__(payload, err_msg, **kwargs)
|
BASE_HELIX_URL = "https://api.twitch.tv/helix/"
# token url will return a 404 if trailing slash is added
BASE_AUTH_URL = "https://id.twitch.tv/oauth2/token"
TOKEN_VALIDATION_URL = "https://id.twitch.tv/oauth2/validate"
WEBHOOKS_HUB_URL = "https://api.twitch.tv/helix/webhooks/hub"
|
def main():
t = int(input())
# t = 1
for _ in range(t):
n, m = sorted(map(int, input().split()))
# n, m = 5, 7
if n % 3 == 0 or m % 3 == 0:
print(n * m // 3)
continue
if n % 3 == 1 and m % 3 == 1:
print((m // 3) * n + n // 3 + 1)
continue
if n % 3 == 2 and m % 3 == 2:
print((m // 3) * n + 2 * (n // 3 + 1))
continue
if n % 3 == 2:
print((m // 3) * n + n // 3 + 1)
continue
print((m // 3) * n + 2 * (n // 3 + 1) - 1)
main()
|
numbers = range(1, 10)
for number in numbers:
if number == 1:
print (str(number) + 'st')
elif number == 2:
print (str(number) + 'nd')
elif number == 3:
print (str(number) + 'rd')
else:
print (str(number) + 'th')
|
# 107
# Open the Names.txt file and display the data in Python.
with open('Names.txt', 'r') as f:
names = f.readlines()
for index, name in enumerate(names): # To remove /n
names[index] = name[:-1]
print(names)
|
__all__ = ['jazBegin', 'jazEnd', 'jazReturn', 'jazCall', 'jazStackInfo']
class jazBegin:
def __init__(self):
self.command = "begin";
def call(self, interpreter, arg):
interpreter.BeginSubroutine()
return None
class jazEnd:
def __init__(self):
self.command = "end";
def call(self, interpreter, arg):
interpreter.EndSubroutine()
return None
class jazReturn:
def __init__(self):
self.command = "return";
def call(self, interpreter, arg):
interpreter.ReturnSubroutine()
return None
class jazCall:
def __init__(self):
self.command = "call";
def call(self, interpreter, arg):
interpreter.CallSubroutine(arg)
return None
class jazStackInfo:
def __init__(self):
self.command = "stackinfo"
def call(self, interpreter, arg):
if arg is not None and len(arg) > 0:
try:
scope = interpreter.scopes[int(arg)]
info = "Scope: "+str(scope.name)+"\n"
info += "* PC : " + str(scope.pc) + "\n"
info += "* Labels : " + str(interpreter.labels) + "\n"
info += "* Vars : " + str(scope.variables) + "\n"
info += "* Stack: " + str(scope.stack) + "\n"
if scope.name == scope.lvalue.name:
info += "* LScope : self\n"
else:
info += "* LScope : " + str(scope.lvalue.name) + "\n"
if scope.name == scope.rvalue.name:
info += "* RScope : self\n"
else:
info += "* RScope : " + str(scope.rvalue.name) + "\n"
except Exception as e:
print(e)
return "Index is not valid"
else:
info = "Scopes: ("+str(len(interpreter.scopes))+")\n"
i = 0
for s in interpreter.scopes:
info = info + "["+str(i)+"] : "+ str(s.name)+"\n"
i = i+1;
return info
# A dictionary of the classes in this file
# used to autoload the functions
Functions = {'jazBegin': jazBegin,'jazEnd': jazEnd, 'jazReturn': jazReturn, 'jazCall':jazCall,'jazStackInfo': jazStackInfo}
|
# New tokens can be found at https://archive.org/account/s3.php
DOI_FORMAT = '10.70102/fk2osf.io/{guid}'
DATACITE_USERNAME = ''
DATACITE_PASSWORD = ''
DATACITE_URL = 'https://doi.test.datacite.org/'
DATACITE_PREFIX = '10.70102' # Datacite's test DOI prefix -- update in production
CHUNK_SIZE = 1000
PAGE_SIZE = 100
OSF_COLLECTION_NAME = 'cos-dev-sandbox'
OSF_BEARER_TOKEN = ''
IA_ACCESS_KEY = ''
IA_SECRET_KEY = ''
OSF_API_URL = 'http://localhost:8000/'
OSF_FILES_URL = 'http://localhost:7777/'
OSF_LOGS_URL = 'v2/registrations/{}/logs/?page[size]={}'
IA_URL = 's3.us.archive.org'
|
b, br, bs, a, ass = map(int, input().split())
bobMoney = (br - b) * bs
aliceMoney = 0
while aliceMoney <= bobMoney:
aliceMoney += ass
a += 1
print(a)
|
# This is a config file for CCI data and CMIP5 sea surface temperature diagnostics
# generell flags
regionalization = True
shape = "Seas_v"
shapeNames = 1 #column of the name values
# flags for basic diagnostics
globmeants = False
mima_globmeants=[255,305]
cmap_globmeants='jet'
mima_ts=[288,292]
mima_mts=[270,310]
portrait = True
globmeandiff =True
mima_globmeandiff=[-10,10]
mima_globmeandiff_r=[-0.03,0.03]
trend = False# True
anomalytrend =False#True
trend_p=False
# flags for specific diagnostics
percentile = False#True
mima_percentile=[255,305]
# percentile parameters
percentile_pars = [0,1,0.25] #start,stop,increment
#plotting parameters
projection={'projection': 'robin', 'lon_0': 180., 'lat_0': 0.}
|
# ------------------------------
# 229. Majority Element II
#
# Description:
# Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times.
# Note: The algorithm should run in linear time and in O(1) space.
# Example 1:
# Input: [3,2,3]
# Output: [3]
#
# Example 2:
# Input: [1,1,1,3,3,2,2,2]
# Output: [1,2]
#
# Version: 1.0
# 09/26/18 by Jianfa
# ------------------------------
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
since the requirement is finding the majority for more than ceiling of [n/3],
the answer would be less than or equal to two numbers.
"""
if not nums:
return []
count1, count2, candidate1, candidate2 = 0, 0, 0, 1
for n in nums:
if n == candidate1:
count1 += 1
elif n == candidate2:
count2 += 1
elif count1 == 0:
candidate1, count1 = n, 1
elif count2 == 0:
candidate2, count2 = n, 1
else:
count1 -= 1
count2 -= 1
res = []
for i in (candidate1, candidate2):
if nums.count(i) > len(nums) / 3:
res.append(i)
return res
# Used for testing
if __name__ == "__main__":
test = Solution()
# ------------------------------
# Summary:
# Get idea from https://leetcode.com/problems/majority-element-ii/discuss/63520/Boyer-Moore-Majority-Vote-algorithm-and-my-elaboration
# Boyer-Moore Majority Vote algorithm: http://goo.gl/64Nams
|
#
# Created on Fri Apr 10 2020
#
# Title: Leetcode - Middle of the Linked List
#
# Author: Vatsal Mistry
# Web: mistryvatsal.github.io
#
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def middleNode(self, head: ListNode) -> ListNode:
p1 = p2 = head
while p1 != None and p1.next != None:
p1, p2 = p1.next.next, p2.next
return p2
|
async def f():
return 0
def f():
return 0
async for x in test:
print(x)
for x in test:
print(x)
for (x, y, z) in test:
print(x)
with test as f:
print(x)
async with test as f:
print(x)
if (x):
print(x)
x = [1, 2, 3]
try:
raise x
except D:
print(x)
except C:
print(x)
except B:
print(x)
x = [x, y, z]
(x, y, z)
x
x,
(1)
(1,)
[x for (x, y, z) in test if x > 0 for (a, b, c) in test2]
def main():
if (x > 1):
print(x)
else:
print(y)
[(x, y, z) for (x, y, z) in test]
x = {"test" : 1}
x = {1, 2, 3}
x = {x for x in test}
x = {**x, **y}
x = {1}
x ={1, 2}
call(x, y, *varargs, x=3, y=3, **kwargs)
class Test:
def __init__(self):
pass
def fun(x, y, *varargs, a, b, c, **kwargs):
return 0
(yield x)
x = lambda a: a + 1
b"test" b"test"
"test"
|
num = (int(input('digite um numero: ')),
int(input('digite um numero: ')),
int(input('digite um numero: ')),
int(input('digite um numero: ')))
print(f'vc digitou {num}')
print(f'o valor 9 apareceu {num.count(9)} vezes')
if 3 in num:
print(f'o valor 3 apareceu na {num.index(3)+1} posição')
else:
print('o valor 3 não foi digitado em nenhuma posição')
print('os valores pares listados foram:', end='')
for n in num:
if n % 2 == 0:
print(n, end=' ')
|
tabs = int(input())
salary = float(input())
for tab in range(tabs):
current_tab = input()
if current_tab == "Facebook":
salary -= 150
elif current_tab == "Instagram":
salary -= 100
elif current_tab == "Reddit":
salary -= 50
if salary <= 0:
print("You have lost your salary.")
break
if salary > 0:
print(int(salary))
|
while True:
try:
a=input()
except:
break
while "BUG" in a:
a=a.replace("BUG","")
print(a)
|
class Solution:
"""
@param a: The first integer
@param b: The second integer
@return: The sum of a and b
"""
# Actually both of these methods fail to work in Python
# because Python supports infinite integer
# Non-recursive
def aplusb(self, a, b):
# write your code here, try to do it without arithmetic operators.
while b != 0:
carry = a & b
a = a ^ b
b = carry << 1
return a
# Recursive
def aplusb(self, a, b):
carry = a & b
result = a ^ b
return result if carry == 0 else self.aplusb(result, carry << 1)
|
class Stack:
def __init__(self):
self.items = []
self.head = -1
def push(self, x):
self.head+=1
self.items.insert(self.head, x)
def pop(self):
if self.isEmpty():
print("Stack is empty !!!")
else:
x = self.items[self.head]
self.items.pop(self.head)
self.head-=1
return x
def size(self):
return len(self.items)
def isEmpty(self):
return self.head == -1
s = Stack()
x = s.pop()
for i in range(1,6):
s.push(i)
print(s.items, s.head)
x = s.pop()
print(s.items)
print(s.isEmpty())
print(s.size())
|
class AttribDesc:
def __init__(self, name, default, datatype = 'string', params = {}):
self.name = name
self.default = default
self.datatype = datatype
self.params = params
def getName(self):
return self.name
def getDefaultValue(self):
return self.default
def getDatatype(self):
return self.datatype
def getParams(self):
return self.params
def __str__(self):
return self.name
def __repr__(self):
return 'AttribDesc(%s, %s, %s, %s)' % (repr(self.name),
repr(self.default),
repr(self.datatype),
repr(self.params))
|
print ("Em que classe o seu terreno se encaixa?")
largura = float (input("Insira aqui a largura do seu terreno :"))
comprimento = float (input("Insira aqui o comprimento do seu terreno :"))
m2 = largura*comprimento
if m2 <=100:
print ("Terreno Popular")
elif m2 <= 500:
print ("Terreno Master")
if m2 >= 500:
print ("Terreno VIP")
|
def mortgage_calculator(P,r,N):
if r == 0:
return P / N
else:
return ((r * P) / (1 - (1 + r)**-N))
if __name__ == '__main__':
P = float(input('Enter the amount borrowed: '))
R = float(input('Enter the interest rate: '))
N = int(input("Enter the number of monthly payments: "))
r = R / (12*100)
print(f'Your fixed monthly payment equal to {round(mortgage_calculator(P,r,N),2)} per month.')
|
{
"target_defaults": {
"make_global_settings": [
[ "CC", "echo" ],
[ "LD", "echo" ],
],
},
"targets": [{
"target_name": "test",
"type": "executable",
"sources": [
"main.c",
],
}],
}
|
#
# PySNMP MIB module SNMP-USM-HMAC-SHA2-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SNMP-USM-HMAC-SHA2-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:00:31 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols("ASN1", "OctetString", "ObjectIdentifier", "Integer")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueSizeConstraint, SingleValueConstraint, ConstraintsUnion, ConstraintsIntersection, ValueRangeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "SingleValueConstraint", "ConstraintsUnion", "ConstraintsIntersection", "ValueRangeConstraint")
snmpAuthProtocols, = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "snmpAuthProtocols")
NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance")
ModuleIdentity, Bits, mib_2, Gauge32, MibScalar, MibTable, MibTableRow, MibTableColumn, TimeTicks, ObjectIdentity, NotificationType, IpAddress, Counter32, Integer32, MibIdentifier, Counter64, Unsigned32, iso = mibBuilder.importSymbols("SNMPv2-SMI", "ModuleIdentity", "Bits", "mib-2", "Gauge32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "TimeTicks", "ObjectIdentity", "NotificationType", "IpAddress", "Counter32", "Integer32", "MibIdentifier", "Counter64", "Unsigned32", "iso")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
snmpUsmHmacSha2MIB = ModuleIdentity((1, 3, 6, 1, 2, 1, 235))
snmpUsmHmacSha2MIB.setRevisions(('2016-04-18 00:00', '2015-10-14 00:00',))
if mibBuilder.loadTexts: snmpUsmHmacSha2MIB.setLastUpdated('201604180000Z')
if mibBuilder.loadTexts: snmpUsmHmacSha2MIB.setOrganization('SNMPv3 Working Group')
usmHMAC128SHA224AuthProtocol = ObjectIdentity((1, 3, 6, 1, 6, 3, 10, 1, 1, 4))
if mibBuilder.loadTexts: usmHMAC128SHA224AuthProtocol.setStatus('current')
usmHMAC192SHA256AuthProtocol = ObjectIdentity((1, 3, 6, 1, 6, 3, 10, 1, 1, 5))
if mibBuilder.loadTexts: usmHMAC192SHA256AuthProtocol.setStatus('current')
usmHMAC256SHA384AuthProtocol = ObjectIdentity((1, 3, 6, 1, 6, 3, 10, 1, 1, 6))
if mibBuilder.loadTexts: usmHMAC256SHA384AuthProtocol.setStatus('current')
usmHMAC384SHA512AuthProtocol = ObjectIdentity((1, 3, 6, 1, 6, 3, 10, 1, 1, 7))
if mibBuilder.loadTexts: usmHMAC384SHA512AuthProtocol.setStatus('current')
mibBuilder.exportSymbols("SNMP-USM-HMAC-SHA2-MIB", usmHMAC384SHA512AuthProtocol=usmHMAC384SHA512AuthProtocol, usmHMAC256SHA384AuthProtocol=usmHMAC256SHA384AuthProtocol, usmHMAC192SHA256AuthProtocol=usmHMAC192SHA256AuthProtocol, PYSNMP_MODULE_ID=snmpUsmHmacSha2MIB, usmHMAC128SHA224AuthProtocol=usmHMAC128SHA224AuthProtocol, snmpUsmHmacSha2MIB=snmpUsmHmacSha2MIB)
|
#
# PySNMP MIB module XEDIA-FRAME-RELAY-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/XEDIA-FRAME-RELAY-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:42:46 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)
#
Integer, OctetString, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueSizeConstraint, ValueRangeConstraint, ConstraintsIntersection, ConstraintsUnion, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "ValueRangeConstraint", "ConstraintsIntersection", "ConstraintsUnion", "SingleValueConstraint")
frCircuitEntry, = mibBuilder.importSymbols("RFC1315-MIB", "frCircuitEntry")
ObjectGroup, NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "ObjectGroup", "NotificationGroup", "ModuleCompliance")
Integer32, MibIdentifier, Bits, IpAddress, iso, Unsigned32, MibScalar, MibTable, MibTableRow, MibTableColumn, Counter64, Counter32, ModuleIdentity, Gauge32, ObjectIdentity, TimeTicks, NotificationType = mibBuilder.importSymbols("SNMPv2-SMI", "Integer32", "MibIdentifier", "Bits", "IpAddress", "iso", "Unsigned32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Counter64", "Counter32", "ModuleIdentity", "Gauge32", "ObjectIdentity", "TimeTicks", "NotificationType")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
xediaMibs, = mibBuilder.importSymbols("XEDIA-REG", "xediaMibs")
xediaFrameRelayMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 838, 3, 19))
if mibBuilder.loadTexts: xediaFrameRelayMIB.setLastUpdated('9808242155Z')
if mibBuilder.loadTexts: xediaFrameRelayMIB.setOrganization('Xedia Corp.')
if mibBuilder.loadTexts: xediaFrameRelayMIB.setContactInfo('support@xedia.com')
if mibBuilder.loadTexts: xediaFrameRelayMIB.setDescription("This module defines additional objects for management of Frame Relay in Xedia devices, above and beyond what is defined in the IETF's Frame Relay MIBs.")
xfrObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 838, 3, 19, 1))
xfrNotifications = MibIdentifier((1, 3, 6, 1, 4, 1, 838, 3, 19, 2))
xfrConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 838, 3, 19, 3))
xfrArpTable = MibTable((1, 3, 6, 1, 4, 1, 838, 3, 19, 1, 1), )
if mibBuilder.loadTexts: xfrArpTable.setStatus('current')
if mibBuilder.loadTexts: xfrArpTable.setDescription('The IP Address Translation table used for mapping from IP addresses to physical addresses, in this case frame relay DLCIs. This table contains much of the same information that is in the ipNetToMediaTable.')
xfrArpEntry = MibTableRow((1, 3, 6, 1, 4, 1, 838, 3, 19, 1, 1, 1), ).setIndexNames((0, "XEDIA-FRAME-RELAY-MIB", "xfrArpIfIndex"), (0, "XEDIA-FRAME-RELAY-MIB", "xfrArpNetAddress"))
if mibBuilder.loadTexts: xfrArpEntry.setStatus('current')
if mibBuilder.loadTexts: xfrArpEntry.setDescription("Each entry contains one IpAddress to `physical' address equivalence.")
xfrArpIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 838, 3, 19, 1, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: xfrArpIfIndex.setStatus('current')
if mibBuilder.loadTexts: xfrArpIfIndex.setDescription("The interface on which this entry's equivalence is effective. The interface identified by a particular value of this index is the same interface as identified by the same value of RFC 1573's ifIndex.")
xfrArpNetAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 838, 3, 19, 1, 1, 1, 2), IpAddress()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: xfrArpNetAddress.setStatus('current')
if mibBuilder.loadTexts: xfrArpNetAddress.setDescription('The IpAddress corresponding to the frame relay DLCI.')
xfrArpType = MibTableColumn((1, 3, 6, 1, 4, 1, 838, 3, 19, 1, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("other", 1), ("invalid", 2), ("dynamic", 3), ("static", 4))).clone('static')).setMaxAccess("readcreate")
if mibBuilder.loadTexts: xfrArpType.setStatus('current')
if mibBuilder.loadTexts: xfrArpType.setDescription('The type of mapping. Setting this object to the value invalid(2) has the effect of invalidating the corresponding entry in the xfrArpEntryTable. That is, it effectively disassociates the interface identified with said entry from the mapping identified with said entry. It is an implementation- specific matter as to whether the agent removes an invalidated entry from the table. Accordingly, management stations must be prepared to receive tabular information from agents that corresponds to entries not currently in use. Proper interpretation of such entries requires examination of the relevant xfrArpEntryType object.')
xfrArpDlci = MibTableColumn((1, 3, 6, 1, 4, 1, 838, 3, 19, 1, 1, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(16, 991)).clone(16)).setMaxAccess("readcreate")
if mibBuilder.loadTexts: xfrArpDlci.setStatus('current')
if mibBuilder.loadTexts: xfrArpDlci.setDescription('The DLCI attached to the IP address.')
xfrArpIfStack = MibTableColumn((1, 3, 6, 1, 4, 1, 838, 3, 19, 1, 1, 1, 5), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: xfrArpIfStack.setStatus('current')
if mibBuilder.loadTexts: xfrArpIfStack.setDescription('A description of the interface stack containing this frame relay interface, with the IP interface, the frame relay interface, and the device interface.')
xFrCircuitTable = MibTable((1, 3, 6, 1, 4, 1, 838, 3, 19, 1, 2), )
if mibBuilder.loadTexts: xFrCircuitTable.setStatus('current')
if mibBuilder.loadTexts: xFrCircuitTable.setDescription('A table containing additional information about specific Data Link Connection Identifiers and corresponding virtual circuits.')
xFrCircuitEntry = MibTableRow((1, 3, 6, 1, 4, 1, 838, 3, 19, 1, 2, 1), )
frCircuitEntry.registerAugmentions(("XEDIA-FRAME-RELAY-MIB", "xFrCircuitEntry"))
xFrCircuitEntry.setIndexNames(*frCircuitEntry.getIndexNames())
if mibBuilder.loadTexts: xFrCircuitEntry.setStatus('current')
if mibBuilder.loadTexts: xFrCircuitEntry.setDescription('The additional information regarding a single Data Link Connection Identifier.')
xfrCircuitType = MibTableColumn((1, 3, 6, 1, 4, 1, 838, 3, 19, 1, 2, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("dynamic", 1), ("static", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: xfrCircuitType.setStatus('current')
if mibBuilder.loadTexts: xfrCircuitType.setDescription('The type of DLCI ')
xfrCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 838, 3, 19, 3, 1))
xfrGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 838, 3, 19, 3, 2))
xfrCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 838, 3, 19, 3, 1, 1)).setObjects(("XEDIA-FRAME-RELAY-MIB", "xfrAllGroup"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
xfrCompliance = xfrCompliance.setStatus('current')
if mibBuilder.loadTexts: xfrCompliance.setDescription('The compliance statement for all agents that support this MIB. A compliant agent implements all objects defined in this MIB.')
xfrAllGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 838, 3, 19, 3, 2, 1)).setObjects(("XEDIA-FRAME-RELAY-MIB", "xfrArpIfIndex"), ("XEDIA-FRAME-RELAY-MIB", "xfrArpNetAddress"), ("XEDIA-FRAME-RELAY-MIB", "xfrArpDlci"), ("XEDIA-FRAME-RELAY-MIB", "xfrArpIfStack"), ("XEDIA-FRAME-RELAY-MIB", "xfrArpType"), ("XEDIA-FRAME-RELAY-MIB", "xfrCircuitType"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
xfrAllGroup = xfrAllGroup.setStatus('current')
if mibBuilder.loadTexts: xfrAllGroup.setDescription('The set of all accessible objects in this MIB.')
mibBuilder.exportSymbols("XEDIA-FRAME-RELAY-MIB", xfrArpEntry=xfrArpEntry, xfrArpNetAddress=xfrArpNetAddress, xFrCircuitEntry=xFrCircuitEntry, xfrCircuitType=xfrCircuitType, xFrCircuitTable=xFrCircuitTable, xfrArpIfIndex=xfrArpIfIndex, xfrArpDlci=xfrArpDlci, xfrConformance=xfrConformance, xfrNotifications=xfrNotifications, xediaFrameRelayMIB=xediaFrameRelayMIB, xfrArpTable=xfrArpTable, xfrArpIfStack=xfrArpIfStack, xfrCompliances=xfrCompliances, xfrArpType=xfrArpType, PYSNMP_MODULE_ID=xediaFrameRelayMIB, xfrObjects=xfrObjects, xfrAllGroup=xfrAllGroup, xfrGroups=xfrGroups, xfrCompliance=xfrCompliance)
|
### Основные функции
def is_correct_triangle(A, B, C):
line12 = line_equation(A, B)
line23 = line_equation(B, C)
return matrix_det(line12[0], line12[1], line23[0], line23[1])
def line_len(A, B):
return ((A['x'] - B['x'])**2 + (A['y'] - B['y'])**2)**0.5
def line_equation(M, N):
A = N['y'] - M['y']
B = M['x'] - N['x']
C = -M['x'] * A - M['y'] * B
return A, B, C
def find_cross(A1, B1, C1, A2, B2, C2):
P = {}
print(A1, B1, C1, A2, B2, C2)
z = matrix_det(A2, B2, A1, B1)
P['x'] = -matrix_det(C2, B2, C1, B1) / z
P['y'] = -matrix_det(A2, C2, A1, C1) / z
return P
def matrix_det(a, b, c, d):
return a * d - b * c
### Функции поиска
# Поиск CH
def find_height(AB, BC, CA):
p = (AB + BC + CA) / 2
return 2/AB * (p*(p-AB)*(p-BC)*(p-CA))**0.5
# Поиск треугольник с максимальной высотой
def find_max_height(points):
n = len(points)
max_h = None
max_triangle = None
for A in range(n):
for B in range(A + 1, n):
AB = line_len(points[A], points[B])
for C in range(B + 1, n):
if (not is_correct_triangle(points[A], points[B], points[C])):
continue
AC = line_len(points[A], points[C])
BC = line_len(points[B], points[C])
min_line = min(AB, BC, AC)
if (min_line == AB):
h = find_height(AB, BC, AC)
triangle = [C, A, B]
elif (min_line == AC):
h = find_height(AC, AB, BC)
triangle = [B, A, C]
else:
h = find_height(BC, AC, AB)
triangle = [A, B, C]
if (max_h is None or max_h < h):
max_h = h
max_triangle = triangle
print(h)
return max_h, max_triangle
# Поиск координат точки H (MH - высота)
def find_h_xy(M, N, K):
print(M, N, K)
A_1, B_1, C_1 = line_equation(N, K) # Линия NK
A_2, B_2 = -B_1, A_1
C_2 = A_2*(-M['x']) + B_2*(-M['y']) # Линия MH
return find_cross(A_1, B_1, C_1, A_2, B_2, C_2)
|
def num():
a=int(input('input a : '))
b=int(input('input b : '))
return a, b
def func(a,b):
add = a+b
multi = a*b
devi = a/b
return add, multi, devi
if __name__=='__main__':
try:
a, b=num()
add,_,_=func(a,b)
_,multi,_=func(a,b)
_,_,devi=func(a,b)
except ZeroDivisionError:
print('can not devide by zero')
devi=func(a,1)
pass
finally:
print(add, multi, devi)
pass
|
#############################################################
# FILE : additional_file.py
# WRITER : Nadav Weisler , Weisler , 316493758
# EXERCISE : intro2cs ex1 2019
# DESCRIPTION: include function called "secret_function"
# that print "My username is weisler and I read the submission response."
#############################################################
def secret_function():
print("My username is weisler and I read the submission response.")
|
def subsetsum(array,num):
if num == 0 or num < 1:
return None
elif len(array) == 0:
return None
else:
if array[0].marks == num:
return [array[0]]
else:
x = subsetsum(array[1:],(num - array[0].marks))
if x:
return [array[0]] + x
else:
return subsetsum(array[1:],num)
|
# File: imap_consts.py
#
# Copyright (c) 2016-2022 Splunk Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software distributed under
# the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
# either express or implied. See the License for the specific language governing permissions
# and limitations under the License.
IMAP_JSON_USE_SSL = "use_ssl"
IMAP_JSON_DATE = "date"
IMAP_JSON_FILES = "files"
IMAP_JSON_BODIES = "bodies"
IMAP_JSON_FROM = "from"
IMAP_JSON_MAIL = "mail"
IMAP_JSON_SUBJECT = "subject"
IMAP_JSON_TO = "to"
IMAP_JSON_START_TIME = "start_time"
IMAP_JSON_EXTRACT_ATTACHMENTS = "extract_attachments"
IMAP_JSON_EXTRACT_URLS = "extract_urls"
IMAP_JSON_EXTRACT_IPS = "extract_ips"
IMAP_JSON_EXTRACT_DOMAINS = "extract_domains"
IMAP_JSON_EXTRACT_HASHES = "extract_hashes"
IMAP_JSON_TOTAL_EMAILS = "total_emails"
IMAP_JSON_IPS = "ips"
IMAP_JSON_HASHES = "hashes"
IMAP_JSON_URLS = "urls"
IMAP_JSON_DOMAINS = "domains"
IMAP_JSON_EMAIL_ADDRESSES = "email_addresses"
IMAP_JSON_DEF_NUM_DAYS = "interval_days"
IMAP_JSON_MAX_EMAILS = "max_emails"
IMAP_JSON_FIRST_RUN_MAX_EMAILS = "first_run_max_emails"
IMAP_JSON_VAULT_IDS = "vault_ids"
IMAP_JSON_INGEST_MANNER = "ingest_manner"
IMAP_JSON_EMAIL_HEADERS = "email_headers"
IMAP_JSON_FOLDER = "folder"
IMAP_JSON_ID = "id"
IMAP_JSON_CONTAINER_ID = "container_id"
IMAP_JSON_INGEST_EMAIL = "ingest_email"
IMAP_INGEST_LATEST_EMAILS = "latest first"
IMAP_INGEST_OLDEST_EMAILS = "oldest first"
IMAP_CONNECTED_TO_SERVER = "Initiated connection to server"
IMAP_ERR_CONNECTING_TO_SERVER = "Error connecting to server"
IMAP_ERR_LISTING_FOLDERS = "Error listing folders"
IMAP_ERR_LOGGING_IN_TO_SERVER = "Error logging in to server"
IMAP_ERR_SELECTING_FOLDER = "Error selecting folder '{folder}'"
IMAP_GOT_LIST_FOLDERS = "Got folder listing"
IMAP_LOGGED_IN = "User logged in"
IMAP_SELECTED_FOLDER = "Selected folder '{folder}'"
IMAP_SUCC_CONNECTIVITY_TEST = "Connectivity test passed"
IMAP_ERR_CONNECTIVITY_TEST = "Connectivity test failed"
IMAP_ERR_END_TIME_LT_START_TIME = "End time less than start time"
IMAP_ERR_MAILBOX_SEARCH_FAILED = "Mailbox search failed"
IMAP_ERR_MAILBOX_SEARCH_FAILED_RESULT = "Mailbox search failed, result: {result} data: {data}"
IMAP_FETCH_ID_FAILED = "Fetch for uuid: {muuid} failed, reason: {excep}"
IMAP_FETCH_ID_FAILED_RESULT = "Fetch for uuid: {muuid} failed, result: {result}, data: {data}"
IMAP_VALIDATE_INTEGER_MESSAGE = "Please provide a valid integer value in the {key} parameter"
IMAP_ERR_CODE_MESSAGE = "Error code unavailable"
IMAP_ERR_MESSAGE = "Unknown error occurred. Please check the asset configuration and|or action parameters"
IMAP_EXCEPTION_ERR_MESSAGE = "Error Code: {0}. Error Message: {1}"
IMAP_REQUIRED_PARAM_OAUTH = "ERROR: {0} is a required parameter for OAuth Authentication, please specify one."
IMAP_REQUIRED_PARAM_BASIC = "ERROR: {0} is a required parameter for Basic Authentication, please specify one."
IMAP_GENERAL_ERR_MESSAGE = "{}. Details: {}"
IMAP_STATE_FILE_CORRUPT_ERR = "Error occurred while loading the state file due to its unexpected format. " \
"Resetting the state file with the default format. Please try again."
IMAP_MILLISECONDS_IN_A_DAY = 86400000
IMAP_NUMBER_OF_DAYS_BEFORE_ENDTIME = 10
IMAP_CONTENT_TYPE_MESSAGE = "message/rfc822"
IMAP_DEFAULT_ARTIFACT_COUNT = 100
IMAP_DEFAULT_CONTAINER_COUNT = 100
MAX_COUNT_VALUE = 4294967295
DEFAULT_REQUEST_TIMEOUT = 30 # in seconds
|
"""
1792. Maximum Average Pass Ratio
Medium
There is a school that has classes of students and each class will be having a final exam. You are given a 2D integer array classes, where classes[i] = [passi, totali]. You know beforehand that in the ith class, there are totali total students, but only passi number of students will pass the exam.
You are also given an integer extraStudents. There are another extraStudents brilliant students that are guaranteed to pass the exam of any class they are assigned to. You want to assign each of the extraStudents students to a class in a way that maximizes the average pass ratio across all the classes.
The pass ratio of a class is equal to the number of students of the class that will pass the exam divided by the total number of students of the class. The average pass ratio is the sum of pass ratios of all the classes divided by the number of the classes.
Return the maximum possible average pass ratio after assigning the extraStudents students. Answers within 10-5 of the actual answer will be accepted.
Example 1:
Input: classes = [[1,2],[3,5],[2,2]], extraStudents = 2
Output: 0.78333
Explanation: You can assign the two extra students to the first class. The average pass ratio will be equal to (3/4 + 3/5 + 2/2) / 3 = 0.78333.
Example 2:
Input: classes = [[2,4],[3,9],[4,5],[2,10]], extraStudents = 4
Output: 0.53485
Constraints:
1 <= classes.length <= 105
classes[i].length == 2
1 <= passi <= totali <= 105
1 <= extraStudents <= 105
"""
class Solution:
def maxAverageRatio(self, classes: List[List[int]], extraStudents: int) -> float:
def profit(a, b):
return (a + 1) / (b + 1) - a / b
maxHeap = []
for a, b in classes:
a, b = a * 1.0, b * 1.0 # Convert int to double
maxHeap.append((-profit(a, b), a, b))
heapq.heapify(maxHeap) # Heapify maxHeap cost O(N)
for _ in range(extraStudents):
d, a, b = heapq.heappop(maxHeap)
heapq.heappush(maxHeap, (-profit(a + 1, b + 1), a + 1, b + 1))
return mean(a / b for d, a, b in maxHeap)
|
# One day n friends met at a party, they hadn't seen each other for a long time and so they decided
# to make a group photo together. Simply speaking, the process of taking photos can be described as
# follows. On the photo, each photographed friend occupies a rectangle of pixels: the i-th of them
# occupies the rectangle of width w[i] pixels and height h[i] pixels. On the group photo everybody
# stands in a line, thus the minimum pixel size of the photo including all the photographed friends,
# is W x H, where W is the total sum of all widths and H is the maximum height of all the photographed
# friends. As is usually the case, the friends made n photos — the j-th (1 <= j <= n) photo had everybody
# except for the j-th friend as he was the photographer. Return the minimum size of each made photo
# in pixels. Return n numbers b1, b2, ..., bn where bi — the total number of pixels on the minimum
# photo containing all friends expect for the i-th one.
def photo_to_remember(T):
heights = []
total_width = 0
for i in range(len(T)):
total_width += T[i][0]
heights.append(T[i][1])
heights.sort()
for i in range(len(T)):
actual_width = total_width - T[i][0]
actual_height = heights[-1]
if actual_height == T[i][1]:
actual_height = heights[-2]
print(actual_width * actual_height)
T = [(3, 123), (1, 456), (2, 789)]
photo_to_remember(T)
|
# The SavingsAccount class represents a
# savings account.
class SavingsAccount:
# The __init__ method accepts arguments for the
# account number, interest rate, and balance.
def __init__(self, account_num, int_rate, bal):
self.__account_num = account_num
self.__interest_rate = int_rate
self.__balance = bal
# The following methods are mutators for the
# data attributes.
def set_account_num(self, account_num):
self.__account_num = account_num
def set_interest_rate(self, int_rate):
self.__interest_rate = int_rate
def set_balance(self, bal):
self.__balance = bal
# The following methods are accessors for the
# data attributes.
def get_account_num(self):
return self.__account_num
def get_interest_rate(self):
return self.__interest_rate
def get_balance(self):
return self.__balance
# The CD account represents a certificate of
# deposit (CD) account. It is a subclass of
# the SavingsAccount class.
class CD(SavingsAccount):
# The init method accepts arguments for the
# account number, interest rate, balance, and
# maturity date.
def __init__(self, account_num, int_rate, bal, mat_date):
# Call the superclass __init__ method.
SavingsAccount.__init__(self, account_num, int_rate, bal)
# Initialize the __maturity_date attribute.
self.__maturity_date = mat_date
# The set_maturity_date is a mutator for the
# __maturity_date attribute.
def set_maturity_date(self, mat_date):
self.__maturity_date = mat_date
# The get_maturity_date method is an accessor
# for the __maturity_date attribute.
def get_maturity_date(self):
return self.__maturity_date
|
class memoize(object):
"""
Memoize wrapper for python
Usage:
@memoize
def fib(n):
pass
"""
def __init__(self, function):
self.function = function
self.memoized = {}
def __call__(self, *args):
try:
return self.memoized[args]
except KeyError:
self.memoized[args] = self.function(*args)
return self.memoized[args]
|
#Crie um programa que tenha uma tupla com VARIAS PALAVRAS.
# Depois disso vc deve mostrar, para cada palavra, quais sao suas vogais.
palavras = ('Olho', 'Cabeça', 'ombro', 'Joelho', 'pe', 'boca', 'nariz', 'mao', 'cotovelo', 'pescoço')
for p in palavras:
print('\n', '-=-' * 15)
print(f'A palavra {str(p).title()} tem as seguintes vogais:', end=' ')
for letra in p:
if letra.lower() in 'aeiou':
print(letra.upper(), end=' ')
""" if 'a' in p: # preciso pegar o P e descobrir quais vogais tem nele
print('A', end='')
if 'e' in p:
print('E', end='')
if 'i' in p:
print('I', end='')
if 'o' in p:
print('O', end='')
if 'u' in p:
print('U', end='')"""
|
#Desafio029: A aplicação recebe a velocidade fo carro, se a mesma for superior a 80KM/h,
# retorna uma mensagem dizendo que foi multado , com o valor total de cada km acima dos 80.
#entrada da velocidade.
vel = int(input('qual era a velocidade do seu carro? Km/h '))-80
multa = (vel*7)
if vel >= 0:
print(f'Você nao viu o radar de 80Km/h?\nAcabou de ser Multado em R${multa} Reais. tem o prazo de 15 dias para recorrer.' )
else:print('parabens!!!\nContinue dirigindo assim.')
|
with open("input_9.txt", "r") as f:
lines = f.readlines()
nums = [int(line.strip()) for line in lines]
# for i, num in enumerate(nums[25:]):
# preamble = set(nums[i:25 + i])
# found_pair = False
# for prenum in preamble:
# diff = num - prenum
# if diff in preamble:
# found_pair = True
# break
# if not found_pair:
# print(num)
# break
invalid_num = 29221323
start_idx = 0
end_idx = -1
expand_upper = True # either expand the upper or the lower
cur_sum = 0
while True:
if expand_upper:
end_idx += 1
cur_sum += nums[end_idx]
else:
cur_sum -= nums[start_idx]
start_idx += 1
if cur_sum > invalid_num:
expand_upper = False
elif cur_sum < invalid_num:
expand_upper = True
else:
break
included_range = nums[start_idx : end_idx+1]
ans = min(included_range) + max(included_range)
print(ans)
|
__VERSION__ = "0.0.1"
__AUTHOR__ = "helloqiu"
__LICENSE__ = "MIT"
__URL__ = "https://github.com/helloqiu/SillyServer"
|
# Faça um programa que leia um número qualquer e mostre seu fatorial.
numero = int(input('Digite um número: '))
fatorial = 1
i = 1
while i <= numero:
fatorial *= i
i += 1
print('{}! = '.format(numero), end='')
j = 1
k = 1
if numero == 0 or numero == 1:
print('{}'.format(fatorial))
else:
while numero >= j:
if k == 1:
print('{}'.format(numero), end='')
k = 2
numero -= 1
print(' x {}'.format(numero), end='')
numero -= 1
print(' = {}'.format(fatorial))
|
"""
Python solution for CCC '17 S1 - Sum Game
"""
n = int(input())
a = [int(i) for i in input().split()]
b = [int(i) for i in input().split()]
k = 0
a_sum = 0
b_sum = 0
for i in range(n):
a_sum += a[i]
b_sum += b[i]
if a_sum == b_sum:
k = i + 1
print(k)
|
""" Created by Chantal Worp, 24/01/2017
Solution to Problem Set 1
Introduction to Computer Science and
Programming using Python (EDX)
Problem Set 1:
Assume s is a string of lower case characters.
Write a program that prints the longest substring of s in which the letters occur in alphabetical order.
For example, if s = 'azcbobobegghakl', then your program should print
Longest substring in alphabetical order is: beggh
In the case of ties, print the first substring. For example, if s = 'abcbcd', then your program should print
Longest substring in alphabetical order is: abc
"""
s = input('Type a string: ')
s = s.lower()
#Variable 'overall_answer' will contain substring of strings in which the letters are in alphabetical order
overall_answer = []
#Maximum number of outermost loops is determined by number of letters in s
for letters in range(len(s)):
search_string = s[letters:] #search_string slices s to ensure that every substring of s is investigated
i = 0 # i is used as counter, set to zero in every outermost loop
subanswer = "" #re-initialising subanswer
subanswer += s[letters] #the first letter of every new subset is added to subanswer
while i < (len(search_string)-1): #Innerloop, will loop as long as i is smaller than the number of letters in search_string minus 1 (to avoid index getting out of range)
first_letter = search_string[i] # Determines first letter to be compared
second_letter = search_string[i+1] # Determines second letter to be compared
if first_letter <= second_letter: # If first letter is smaller than or equal to second letter, it means they are in alphabetical order
subanswer += second_letter # second letter will be added to subanswer (first letter was already added)
i += 1 # counter increases with 1
else:
overall_answer.append(subanswer) # If first letter is greater than second letter, then they are not in alphabetical order. Second letter does not get added to subanswer
break # subanswer gets added to list overall_answer and inner loop breaks, a new outerloop starts
if i == (len(search_string)-1): # If counter i equals the length of search_string, then subanswer gets appended to overall_answer and a new outerloop starts
overall_answer.append(subanswer)
# after running the code above, overall_answer will be a list with substrings in alphabetical order
# the answer is then the longest substring in list overall_answer
ans = max(overall_answer, key=len)
print("Longest substring in alphabetical order is: " + ans)
|
# -*- coding: utf-8 -*-
#
# Copyright (c) 2021, SkyFoundry LLC
# Licensed under the Academic Free License version 3.0
#
# History:
# 07 Dec 2021 Matthew Giannini Creation
#
class Ref:
@staticmethod
def make_handle(handle):
time = (handle >> 32) & 0xffff_ffff
rand = handle & 0xffff_ffff
return Ref(f"{format(time, '08x')}-{format(rand, '08x')}")
def __init__(self, id, dis=None):
self._id = id
self._dis = dis
def id(self):
return self._id
def dis(self):
return self._dis
def __str__(self):
return f'{self.id()}'
def __eq__(self, other):
if isinstance(other, Ref):
return self.id() == other.id()
return False
# Ref
|
class Solution:
def getMaximumGenerated(self, n: int) -> int:
if n < 2:
return n
ans = [None for _ in range(n + 1)]
ans[0] = 0
ans[1] = 1
for i in range(1, n // 2 + 1):
ans[2 * i] = ans[i]
if 2 * i + 1 < n + 1:
ans[2 * i + 1] = ans[i] + ans[i + 1]
return max(ans)
|
echo = "echo"
gcc = "gcc"
gpp = "g++"
emcc = "emcc"
empp = "em++"
cl = "cl"
clang = "clang"
clangpp = "clang++"
|
# Accept the marks of 5 subjects
m1 = input(" Enter the Marks of first subject: ")
m2 = input(" Enter the Marks of second subject: ")
m3 = input(" Enter the Marks of third subject: ")
m4 = input(" Enter the Marks of forth subject: ")
m5 = input(" Enter the Marks of fifth subject: ")
# Total Marks
Total = int(m1)+int(m2)+int(m3)+int(m4)+int(m5)
#Percentage:
Percentage = (Total/500)*100
#Print the Answer
print(' Percentage is {0} %'.format(Percentage))
|
h = int(input())
w = int(input())
no_paint = int(input())
litres_paint = input()
space = round((h * w * 4) * ((100 - no_paint) / 100))
while not litres_paint == "Tired!":
space -= int(litres_paint)
if space <= 0:
break
litres_paint = input()
if space < 0:
print(f"All walls are painted and you have {abs(space)} l paint left!")
elif space == 0:
print(f"All walls are painted! Great job, Pesho!")
else:
print(f"{space} quadratic m left.")
# 2
# 3
# 25
# 6
# 7
# 8
# 2
# 3
# 25
# 6
# 7
# 5
# 2
# 3
# 0
# 6
# 7
# 5
# 6
# 2
# 3
# 25
# 17
# Tired!
|
media_stats = {
'type': 'object',
'properties': {
'count': {'type': 'integer', 'minimum': 0},
'download_size': {'type': 'integer', 'minimum': 0},
'total_size': {'type': 'integer', 'minimum': 0},
'duration': {'type': 'number', 'minimum': 0},
},
}
|
#!/usr/bin/env python3
#
# vsim_defines.py
# Francesco Conti <f.conti@unibo.it>
#
# Copyright (C) 2015-2017 ETH Zurich, University of Bologna
# All rights reserved.
#
# This software may be modified and distributed under the terms
# of the BSD license. See the LICENSE file for details.
#
# templates for vcompile.csh scripts
VSIM_PREAMBLE = """#!/bin/tcsh
source ${PULP_PATH}/%s/vcompile/setup.csh
##############################################################################
# Settings
##############################################################################
set IP=%s
##############################################################################
# Check settings
##############################################################################
# check if environment variables are defined
if (! $?MSIM_LIBS_PATH ) then
echo "${Red} MSIM_LIBS_PATH is not defined ${NC}"
exit 1
endif
if (! $?IPS_PATH ) then
echo "${Red} IPS_PATH is not defined ${NC}"
exit 1
endif
set LIB_NAME="${IP}_lib"
set LIB_PATH="${MSIM_LIBS_PATH}/${LIB_NAME}"
set IP_PATH="${IPS_PATH}/%s"
set RTL_PATH="${RTL_PATH}"
##############################################################################
# Preparing library
##############################################################################
echo "${Green}--> Compiling ${IP}... ${NC}"
rm -rf $LIB_PATH
vlib $LIB_PATH
vmap $LIB_NAME $LIB_PATH
##############################################################################
# Compiling RTL
##############################################################################
"""
VSIM_POSTAMBLE ="""
echo "${Cyan}--> ${IP} compilation complete! ${NC}"
exit 0
##############################################################################
# Error handler
##############################################################################
error:
echo "${NC}"
exit 1
"""
VSIM_PREAMBLE_SUBIP = """
echo "${Green}Compiling component: ${Brown} %s ${NC}"
echo "${Red}"
"""
VSIM_VLOG_INCDIR_CMD = "+incdir+"
## Add -suppress 2583 to remove warning about always_comb|ff wrapped with
# generate struct that can be only checked after elaboration at vopt stage
VSIM_VLOG_CMD = "vlog -quiet -sv -suppress 2583 -work ${LIB_PATH} %s %s %s || goto error\n"
VSIM_VCOM_CMD = "vcom -quiet -suppress 2583 -work ${LIB_PATH} %s %s || goto error\n"
# templates for vsim.tcl
VSIM_TCL_PREAMBLE = """set VSIM_%s_LIBS " \\\
"""
VSIM_TCL_CMD = " -L %s_lib \\\n"
VSIM_TCL_POSTAMBLE = """"
"""
# templates for vcompile_libs.tc
VCOMPILE_LIBS_PREAMBLE = """#!/usr/bin/tcsh
echo \"\"
echo \"${Green}--> Compiling PULP IPs libraries... ${NC}\"
"""
VCOMPILE_LIBS_CMD = "tcsh ${PULP_PATH}/%s/vcompile/ips/vcompile_%s.csh || exit 1\n"
VCOMPILE_LIBS_XILINX_CMD = "tcsh ${PULP_PATH}/fpga/sim/vcompile/ips/vcompile_%s.csh || exit 1\n"
|
################################################################################################
# Python authorisation
# Write a program that asks the user for a username and password. (7 marks)
# -> The program keeps asking for the username and password until the correct username and
# password have been entered.
# -> The username should be admin and the password 1234abc.
# -> Once you have logged in (i.e. entered the correct username and password), the program
# should respond with a message like (“Hello, <username>. You have successfully logged in”)
################################################################################################
## Made by Oliver Parry
##
## 14/04/2021
################################################################################################
logins = {
# 'username': 'password'
'admin': '1234abc'
}
# Authorise user
username = None # Define username in the global scope so it can be changed both inside and out of a deeper scope
# Repeat authorisation loop until broken
while True:
# User input
username = input('Username: ')
password = input('Password: ')
# Validation
if username in logins and logins[username] == password:
# Break the authorisation loop once the correct credentials have been provided
break
else:
print('Your username or password was incorrect. Try again.')
# Executed when logged in
print('Hello, %s. You have successfully logged in.' % (username))
|
class Solution:
# my solution
def numPairsDivisibleBy60(self, time: List[int]) -> int:
dct = {}
res = 0
for i, n in enumerate(time):
dct[n % 60] = dct.get(n%60, []) + [i]
print(dct)
for left in dct.keys():
if left % 60 == 0 or left % 60 == 30:
res += len(dct[left]) * (len(dct[left])-1) / 2
elif 60 - left in dct.keys():
res += len(dct[left]) * len(dct[60-left]) / 2
return int(res)
# optimal solution
# https://leetcode.com/problems/pairs-of-songs-with-total-durations-divisible-by-60/discuss/642553/Python-O(n)-with-simple-math-explanation
'''
1. We are given that (a+b) % c = (a%c + b%c) % c = 0
2. So, (a%c + b%c) = n*c where n is an integer multiple.
3. We know that (a%c + b%c) has max of c-1 + c-1 = 2c - 2 < 2c
4. But rhs says it has to be an integer multiple of c, and we are bounded by the fact that this has to be less than 2. so only option is either 0 or 1 (no negative cuz song durations arent negative)
5. So given a, we look for b%c = n*c - a%c, where n = 0 or 1.
6. Can do this easily with hashmap, for each number a, take modulo of it, look for that in the hashmap where it maps number of occurance of b%c.
7. Update answer and the hashmap accordingly.
'''
def numPairsDivisibleBy60(self, time: List[int]) -> int:
res = 0
dct = {}
for t in time:
t_mod = t % 60
find = 0 if t_mod == 0 else 60 - t_mod
res += dct.get(find, 0)
dct[t_mod] = dct.get(t_mod, 0) + 1
return res
|
def glyphs():
return 96
_font =\
b'\x00\x4a\x5a\x08\x4d\x57\x52\x46\x52\x54\x20\x52\x52\x59\x51'\
b'\x5a\x52\x5b\x53\x5a\x52\x59\x05\x4a\x5a\x4e\x46\x4e\x4d\x20'\
b'\x52\x56\x46\x56\x4d\x0b\x48\x5d\x53\x42\x4c\x62\x20\x52\x59'\
b'\x42\x52\x62\x20\x52\x4c\x4f\x5a\x4f\x20\x52\x4b\x55\x59\x55'\
b'\x1a\x48\x5c\x50\x42\x50\x5f\x20\x52\x54\x42\x54\x5f\x20\x52'\
b'\x59\x49\x57\x47\x54\x46\x50\x46\x4d\x47\x4b\x49\x4b\x4b\x4c'\
b'\x4d\x4d\x4e\x4f\x4f\x55\x51\x57\x52\x58\x53\x59\x55\x59\x58'\
b'\x57\x5a\x54\x5b\x50\x5b\x4d\x5a\x4b\x58\x1f\x46\x5e\x5b\x46'\
b'\x49\x5b\x20\x52\x4e\x46\x50\x48\x50\x4a\x4f\x4c\x4d\x4d\x4b'\
b'\x4d\x49\x4b\x49\x49\x4a\x47\x4c\x46\x4e\x46\x50\x47\x53\x48'\
b'\x56\x48\x59\x47\x5b\x46\x20\x52\x57\x54\x55\x55\x54\x57\x54'\
b'\x59\x56\x5b\x58\x5b\x5a\x5a\x5b\x58\x5b\x56\x59\x54\x57\x54'\
b'\x22\x45\x5f\x5c\x4f\x5c\x4e\x5b\x4d\x5a\x4d\x59\x4e\x58\x50'\
b'\x56\x55\x54\x58\x52\x5a\x50\x5b\x4c\x5b\x4a\x5a\x49\x59\x48'\
b'\x57\x48\x55\x49\x53\x4a\x52\x51\x4e\x52\x4d\x53\x4b\x53\x49'\
b'\x52\x47\x50\x46\x4e\x47\x4d\x49\x4d\x4b\x4e\x4e\x50\x51\x55'\
b'\x58\x57\x5a\x59\x5b\x5b\x5b\x5c\x5a\x5c\x59\x07\x4d\x57\x52'\
b'\x48\x51\x47\x52\x46\x53\x47\x53\x49\x52\x4b\x51\x4c\x0a\x4b'\
b'\x59\x56\x42\x54\x44\x52\x47\x50\x4b\x4f\x50\x4f\x54\x50\x59'\
b'\x52\x5d\x54\x60\x56\x62\x0a\x4b\x59\x4e\x42\x50\x44\x52\x47'\
b'\x54\x4b\x55\x50\x55\x54\x54\x59\x52\x5d\x50\x60\x4e\x62\x08'\
b'\x4a\x5a\x52\x4c\x52\x58\x20\x52\x4d\x4f\x57\x55\x20\x52\x57'\
b'\x4f\x4d\x55\x05\x45\x5f\x52\x49\x52\x5b\x20\x52\x49\x52\x5b'\
b'\x52\x07\x4e\x56\x53\x57\x52\x58\x51\x57\x52\x56\x53\x57\x53'\
b'\x59\x51\x5b\x02\x45\x5f\x49\x52\x5b\x52\x05\x4e\x56\x52\x56'\
b'\x51\x57\x52\x58\x53\x57\x52\x56\x02\x47\x5d\x5b\x42\x49\x62'\
b'\x11\x48\x5c\x51\x46\x4e\x47\x4c\x4a\x4b\x4f\x4b\x52\x4c\x57'\
b'\x4e\x5a\x51\x5b\x53\x5b\x56\x5a\x58\x57\x59\x52\x59\x4f\x58'\
b'\x4a\x56\x47\x53\x46\x51\x46\x04\x48\x5c\x4e\x4a\x50\x49\x53'\
b'\x46\x53\x5b\x0e\x48\x5c\x4c\x4b\x4c\x4a\x4d\x48\x4e\x47\x50'\
b'\x46\x54\x46\x56\x47\x57\x48\x58\x4a\x58\x4c\x57\x4e\x55\x51'\
b'\x4b\x5b\x59\x5b\x0f\x48\x5c\x4d\x46\x58\x46\x52\x4e\x55\x4e'\
b'\x57\x4f\x58\x50\x59\x53\x59\x55\x58\x58\x56\x5a\x53\x5b\x50'\
b'\x5b\x4d\x5a\x4c\x59\x4b\x57\x06\x48\x5c\x55\x46\x4b\x54\x5a'\
b'\x54\x20\x52\x55\x46\x55\x5b\x11\x48\x5c\x57\x46\x4d\x46\x4c'\
b'\x4f\x4d\x4e\x50\x4d\x53\x4d\x56\x4e\x58\x50\x59\x53\x59\x55'\
b'\x58\x58\x56\x5a\x53\x5b\x50\x5b\x4d\x5a\x4c\x59\x4b\x57\x17'\
b'\x48\x5c\x58\x49\x57\x47\x54\x46\x52\x46\x4f\x47\x4d\x4a\x4c'\
b'\x4f\x4c\x54\x4d\x58\x4f\x5a\x52\x5b\x53\x5b\x56\x5a\x58\x58'\
b'\x59\x55\x59\x54\x58\x51\x56\x4f\x53\x4e\x52\x4e\x4f\x4f\x4d'\
b'\x51\x4c\x54\x05\x48\x5c\x59\x46\x4f\x5b\x20\x52\x4b\x46\x59'\
b'\x46\x1d\x48\x5c\x50\x46\x4d\x47\x4c\x49\x4c\x4b\x4d\x4d\x4f'\
b'\x4e\x53\x4f\x56\x50\x58\x52\x59\x54\x59\x57\x58\x59\x57\x5a'\
b'\x54\x5b\x50\x5b\x4d\x5a\x4c\x59\x4b\x57\x4b\x54\x4c\x52\x4e'\
b'\x50\x51\x4f\x55\x4e\x57\x4d\x58\x4b\x58\x49\x57\x47\x54\x46'\
b'\x50\x46\x17\x48\x5c\x58\x4d\x57\x50\x55\x52\x52\x53\x51\x53'\
b'\x4e\x52\x4c\x50\x4b\x4d\x4b\x4c\x4c\x49\x4e\x47\x51\x46\x52'\
b'\x46\x55\x47\x57\x49\x58\x4d\x58\x52\x57\x57\x55\x5a\x52\x5b'\
b'\x50\x5b\x4d\x5a\x4c\x58\x0b\x4e\x56\x52\x4f\x51\x50\x52\x51'\
b'\x53\x50\x52\x4f\x20\x52\x52\x56\x51\x57\x52\x58\x53\x57\x52'\
b'\x56\x0d\x4e\x56\x52\x4f\x51\x50\x52\x51\x53\x50\x52\x4f\x20'\
b'\x52\x53\x57\x52\x58\x51\x57\x52\x56\x53\x57\x53\x59\x51\x5b'\
b'\x03\x46\x5e\x5a\x49\x4a\x52\x5a\x5b\x05\x45\x5f\x49\x4f\x5b'\
b'\x4f\x20\x52\x49\x55\x5b\x55\x03\x46\x5e\x4a\x49\x5a\x52\x4a'\
b'\x5b\x14\x49\x5b\x4c\x4b\x4c\x4a\x4d\x48\x4e\x47\x50\x46\x54'\
b'\x46\x56\x47\x57\x48\x58\x4a\x58\x4c\x57\x4e\x56\x4f\x52\x51'\
b'\x52\x54\x20\x52\x52\x59\x51\x5a\x52\x5b\x53\x5a\x52\x59\x37'\
b'\x45\x60\x57\x4e\x56\x4c\x54\x4b\x51\x4b\x4f\x4c\x4e\x4d\x4d'\
b'\x50\x4d\x53\x4e\x55\x50\x56\x53\x56\x55\x55\x56\x53\x20\x52'\
b'\x51\x4b\x4f\x4d\x4e\x50\x4e\x53\x4f\x55\x50\x56\x20\x52\x57'\
b'\x4b\x56\x53\x56\x55\x58\x56\x5a\x56\x5c\x54\x5d\x51\x5d\x4f'\
b'\x5c\x4c\x5b\x4a\x59\x48\x57\x47\x54\x46\x51\x46\x4e\x47\x4c'\
b'\x48\x4a\x4a\x49\x4c\x48\x4f\x48\x52\x49\x55\x4a\x57\x4c\x59'\
b'\x4e\x5a\x51\x5b\x54\x5b\x57\x5a\x59\x59\x5a\x58\x20\x52\x58'\
b'\x4b\x57\x53\x57\x55\x58\x56\x08\x49\x5b\x52\x46\x4a\x5b\x20'\
b'\x52\x52\x46\x5a\x5b\x20\x52\x4d\x54\x57\x54\x17\x47\x5c\x4b'\
b'\x46\x4b\x5b\x20\x52\x4b\x46\x54\x46\x57\x47\x58\x48\x59\x4a'\
b'\x59\x4c\x58\x4e\x57\x4f\x54\x50\x20\x52\x4b\x50\x54\x50\x57'\
b'\x51\x58\x52\x59\x54\x59\x57\x58\x59\x57\x5a\x54\x5b\x4b\x5b'\
b'\x05\x48\x5c\x4b\x46\x59\x5b\x20\x52\x4b\x5b\x59\x46\x08\x49'\
b'\x5b\x52\x46\x4a\x5b\x20\x52\x52\x46\x5a\x5b\x20\x52\x4a\x5b'\
b'\x5a\x5b\x0b\x48\x5b\x4c\x46\x4c\x5b\x20\x52\x4c\x46\x59\x46'\
b'\x20\x52\x4c\x50\x54\x50\x20\x52\x4c\x5b\x59\x5b\x14\x48\x5c'\
b'\x52\x46\x52\x5b\x20\x52\x50\x4b\x4d\x4c\x4c\x4d\x4b\x4f\x4b'\
b'\x52\x4c\x54\x4d\x55\x50\x56\x54\x56\x57\x55\x58\x54\x59\x52'\
b'\x59\x4f\x58\x4d\x57\x4c\x54\x4b\x50\x4b\x05\x48\x59\x4c\x46'\
b'\x4c\x5b\x20\x52\x4c\x46\x58\x46\x08\x47\x5d\x4b\x46\x4b\x5b'\
b'\x20\x52\x59\x46\x59\x5b\x20\x52\x4b\x50\x59\x50\x02\x4e\x56'\
b'\x52\x46\x52\x5b\x05\x50\x55\x52\x51\x52\x52\x53\x52\x53\x51'\
b'\x52\x51\x08\x47\x5c\x4b\x46\x4b\x5b\x20\x52\x59\x46\x4b\x54'\
b'\x20\x52\x50\x4f\x59\x5b\x05\x49\x5b\x52\x46\x4a\x5b\x20\x52'\
b'\x52\x46\x5a\x5b\x0b\x46\x5e\x4a\x46\x4a\x5b\x20\x52\x4a\x46'\
b'\x52\x5b\x20\x52\x5a\x46\x52\x5b\x20\x52\x5a\x46\x5a\x5b\x08'\
b'\x47\x5d\x4b\x46\x4b\x5b\x20\x52\x4b\x46\x59\x5b\x20\x52\x59'\
b'\x46\x59\x5b\x15\x47\x5d\x50\x46\x4e\x47\x4c\x49\x4b\x4b\x4a'\
b'\x4e\x4a\x53\x4b\x56\x4c\x58\x4e\x5a\x50\x5b\x54\x5b\x56\x5a'\
b'\x58\x58\x59\x56\x5a\x53\x5a\x4e\x59\x4b\x58\x49\x56\x47\x54'\
b'\x46\x50\x46\x08\x47\x5d\x4b\x46\x4b\x5b\x20\x52\x59\x46\x59'\
b'\x5b\x20\x52\x4b\x46\x59\x46\x18\x47\x5d\x50\x46\x4e\x47\x4c'\
b'\x49\x4b\x4b\x4a\x4e\x4a\x53\x4b\x56\x4c\x58\x4e\x5a\x50\x5b'\
b'\x54\x5b\x56\x5a\x58\x58\x59\x56\x5a\x53\x5a\x4e\x59\x4b\x58'\
b'\x49\x56\x47\x54\x46\x50\x46\x20\x52\x4f\x50\x55\x50\x0d\x47'\
b'\x5c\x4b\x46\x4b\x5b\x20\x52\x4b\x46\x54\x46\x57\x47\x58\x48'\
b'\x59\x4a\x59\x4d\x58\x4f\x57\x50\x54\x51\x4b\x51\x09\x49\x5b'\
b'\x4b\x46\x52\x50\x4b\x5b\x20\x52\x4b\x46\x59\x46\x20\x52\x4b'\
b'\x5b\x59\x5b\x05\x4a\x5a\x52\x46\x52\x5b\x20\x52\x4b\x46\x59'\
b'\x46\x12\x49\x5b\x4b\x4b\x4b\x49\x4c\x47\x4d\x46\x4f\x46\x50'\
b'\x47\x51\x49\x52\x4d\x52\x5b\x20\x52\x59\x4b\x59\x49\x58\x47'\
b'\x57\x46\x55\x46\x54\x47\x53\x49\x52\x4d\x0d\x4b\x59\x51\x46'\
b'\x4f\x47\x4e\x49\x4e\x4b\x4f\x4d\x51\x4e\x53\x4e\x55\x4d\x56'\
b'\x4b\x56\x49\x55\x47\x53\x46\x51\x46\x10\x48\x5c\x4b\x5b\x4f'\
b'\x5b\x4c\x54\x4b\x50\x4b\x4c\x4c\x49\x4e\x47\x51\x46\x53\x46'\
b'\x56\x47\x58\x49\x59\x4c\x59\x50\x58\x54\x55\x5b\x59\x5b\x08'\
b'\x49\x5b\x4b\x46\x59\x46\x20\x52\x4f\x50\x55\x50\x20\x52\x4b'\
b'\x5b\x59\x5b\x11\x47\x5d\x52\x46\x52\x5b\x20\x52\x49\x4c\x4a'\
b'\x4c\x4b\x4d\x4c\x51\x4d\x53\x4e\x54\x51\x55\x53\x55\x56\x54'\
b'\x57\x53\x58\x51\x59\x4d\x5a\x4c\x5b\x4c\x08\x48\x5c\x59\x46'\
b'\x4b\x5b\x20\x52\x4b\x46\x59\x46\x20\x52\x4b\x5b\x59\x5b\x0b'\
b'\x4b\x59\x4f\x42\x4f\x62\x20\x52\x50\x42\x50\x62\x20\x52\x4f'\
b'\x42\x56\x42\x20\x52\x4f\x62\x56\x62\x02\x4b\x59\x4b\x46\x59'\
b'\x5e\x0b\x4b\x59\x54\x42\x54\x62\x20\x52\x55\x42\x55\x62\x20'\
b'\x52\x4e\x42\x55\x42\x20\x52\x4e\x62\x55\x62\x05\x4a\x5a\x52'\
b'\x44\x4a\x52\x20\x52\x52\x44\x5a\x52\x02\x49\x5b\x49\x62\x5b'\
b'\x62\x07\x4e\x56\x53\x4b\x51\x4d\x51\x4f\x52\x50\x53\x4f\x52'\
b'\x4e\x51\x4f\x17\x48\x5d\x51\x4d\x4f\x4e\x4d\x50\x4c\x52\x4b'\
b'\x55\x4b\x58\x4c\x5a\x4e\x5b\x50\x5b\x52\x5a\x55\x57\x57\x54'\
b'\x59\x50\x5a\x4d\x20\x52\x51\x4d\x53\x4d\x54\x4e\x55\x50\x57'\
b'\x58\x58\x5a\x59\x5b\x5a\x5b\x1e\x49\x5c\x55\x46\x53\x47\x51'\
b'\x49\x4f\x4d\x4e\x50\x4d\x54\x4c\x5a\x4b\x62\x20\x52\x55\x46'\
b'\x57\x46\x59\x48\x59\x4b\x58\x4d\x57\x4e\x55\x4f\x52\x4f\x20'\
b'\x52\x52\x4f\x54\x50\x56\x52\x57\x54\x57\x57\x56\x59\x55\x5a'\
b'\x53\x5b\x51\x5b\x4f\x5a\x4e\x59\x4d\x56\x0d\x49\x5b\x4b\x4d'\
b'\x4d\x4d\x4f\x4f\x55\x60\x57\x62\x59\x62\x20\x52\x5a\x4d\x59'\
b'\x4f\x57\x52\x4d\x5d\x4b\x60\x4a\x62\x17\x49\x5b\x54\x4d\x51'\
b'\x4d\x4f\x4e\x4d\x50\x4c\x53\x4c\x56\x4d\x59\x4e\x5a\x50\x5b'\
b'\x52\x5b\x54\x5a\x56\x58\x57\x55\x57\x52\x56\x4f\x54\x4d\x52'\
b'\x4b\x51\x49\x51\x47\x52\x46\x54\x46\x56\x47\x58\x49\x12\x4a'\
b'\x5a\x57\x4f\x56\x4e\x54\x4d\x51\x4d\x4f\x4e\x4f\x50\x50\x52'\
b'\x53\x53\x20\x52\x53\x53\x4f\x54\x4d\x56\x4d\x58\x4e\x5a\x50'\
b'\x5b\x53\x5b\x55\x5a\x57\x58\x14\x47\x5d\x4f\x4e\x4d\x4f\x4b'\
b'\x51\x4a\x54\x4a\x57\x4b\x59\x4c\x5a\x4e\x5b\x51\x5b\x54\x5a'\
b'\x57\x58\x59\x55\x5a\x52\x5a\x4f\x58\x4d\x56\x4d\x54\x4f\x52'\
b'\x53\x50\x58\x4d\x62\x10\x49\x5c\x4a\x50\x4c\x4e\x4e\x4d\x4f'\
b'\x4d\x51\x4e\x52\x4f\x53\x52\x53\x56\x52\x5b\x20\x52\x5a\x4d'\
b'\x59\x50\x58\x52\x52\x5b\x50\x5f\x4f\x62\x12\x48\x5c\x49\x51'\
b'\x4a\x4f\x4c\x4d\x4e\x4d\x4f\x4e\x4f\x50\x4e\x54\x4c\x5b\x20'\
b'\x52\x4e\x54\x50\x50\x52\x4e\x54\x4d\x56\x4d\x58\x4f\x58\x52'\
b'\x57\x57\x54\x62\x08\x4c\x57\x52\x4d\x50\x54\x4f\x58\x4f\x5a'\
b'\x50\x5b\x52\x5b\x54\x59\x55\x57\x05\x47\x5d\x4b\x4b\x59\x59'\
b'\x20\x52\x59\x4b\x4b\x59\x12\x49\x5b\x4f\x4d\x4b\x5b\x20\x52'\
b'\x59\x4e\x58\x4d\x57\x4d\x55\x4e\x51\x52\x4f\x53\x4e\x53\x20'\
b'\x52\x4e\x53\x50\x54\x51\x55\x53\x5a\x54\x5b\x55\x5b\x56\x5a'\
b'\x08\x4a\x5a\x4b\x46\x4d\x46\x4f\x47\x50\x48\x58\x5b\x20\x52'\
b'\x52\x4d\x4c\x5b\x14\x48\x5d\x4f\x4d\x49\x62\x20\x52\x4e\x51'\
b'\x4d\x56\x4d\x59\x4f\x5b\x51\x5b\x53\x5a\x55\x58\x57\x54\x20'\
b'\x52\x59\x4d\x57\x54\x56\x58\x56\x5a\x57\x5b\x59\x5b\x5b\x59'\
b'\x5c\x57\x0d\x49\x5b\x4c\x4d\x4f\x4d\x4e\x53\x4d\x58\x4c\x5b'\
b'\x20\x52\x59\x4d\x58\x50\x57\x52\x55\x55\x52\x58\x4f\x5a\x4c'\
b'\x5b\x11\x4a\x5b\x52\x4d\x50\x4e\x4e\x50\x4d\x53\x4d\x56\x4e'\
b'\x59\x4f\x5a\x51\x5b\x53\x5b\x55\x5a\x57\x58\x58\x55\x58\x52'\
b'\x57\x4f\x56\x4e\x54\x4d\x52\x4d\x0c\x47\x5d\x50\x4d\x4c\x5b'\
b'\x20\x52\x55\x4d\x56\x53\x57\x58\x58\x5b\x20\x52\x49\x50\x4b'\
b'\x4e\x4e\x4d\x5b\x4d\x1a\x47\x5c\x48\x51\x49\x4f\x4b\x4d\x4d'\
b'\x4d\x4e\x4e\x4e\x50\x4d\x55\x4d\x58\x4e\x5a\x4f\x5b\x51\x5b'\
b'\x53\x5a\x55\x57\x56\x55\x57\x52\x58\x4d\x58\x4a\x57\x47\x55'\
b'\x46\x53\x46\x52\x48\x52\x4a\x53\x4d\x55\x50\x57\x52\x5a\x54'\
b'\x12\x49\x5b\x4d\x53\x4d\x56\x4e\x59\x4f\x5a\x51\x5b\x53\x5b'\
b'\x55\x5a\x57\x58\x58\x55\x58\x52\x57\x4f\x56\x4e\x54\x4d\x52'\
b'\x4d\x50\x4e\x4e\x50\x4d\x53\x49\x62\x11\x49\x5d\x5b\x4d\x51'\
b'\x4d\x4f\x4e\x4d\x50\x4c\x53\x4c\x56\x4d\x59\x4e\x5a\x50\x5b'\
b'\x52\x5b\x54\x5a\x56\x58\x57\x55\x57\x52\x56\x4f\x55\x4e\x53'\
b'\x4d\x07\x48\x5c\x53\x4d\x50\x5b\x20\x52\x4a\x50\x4c\x4e\x4f'\
b'\x4d\x5a\x4d\x0f\x48\x5c\x49\x51\x4a\x4f\x4c\x4d\x4e\x4d\x4f'\
b'\x4e\x4f\x50\x4d\x56\x4d\x59\x4f\x5b\x51\x5b\x54\x5a\x56\x58'\
b'\x58\x54\x59\x50\x59\x4d\x0e\x45\x5f\x52\x49\x51\x4a\x52\x4b'\
b'\x53\x4a\x52\x49\x20\x52\x49\x52\x5b\x52\x20\x52\x52\x59\x51'\
b'\x5a\x52\x5b\x53\x5a\x52\x59\x16\x46\x5d\x4e\x4d\x4c\x4e\x4a'\
b'\x51\x49\x54\x49\x57\x4a\x5a\x4b\x5b\x4d\x5b\x4f\x5a\x51\x57'\
b'\x20\x52\x52\x53\x51\x57\x52\x5a\x53\x5b\x55\x5b\x57\x5a\x59'\
b'\x57\x5a\x54\x5a\x51\x59\x4e\x58\x4d\x1c\x4a\x5a\x54\x46\x52'\
b'\x47\x51\x48\x51\x49\x52\x4a\x55\x4b\x58\x4b\x20\x52\x55\x4b'\
b'\x52\x4c\x50\x4d\x4f\x4f\x4f\x51\x51\x53\x54\x54\x56\x54\x20'\
b'\x52\x54\x54\x50\x55\x4e\x56\x4d\x58\x4d\x5a\x4f\x5c\x53\x5e'\
b'\x54\x5f\x54\x61\x52\x62\x50\x62\x13\x46\x5d\x56\x46\x4e\x62'\
b'\x20\x52\x47\x51\x48\x4f\x4a\x4d\x4c\x4d\x4d\x4e\x4d\x50\x4c'\
b'\x55\x4c\x58\x4d\x5a\x4f\x5b\x51\x5b\x54\x5a\x56\x58\x58\x55'\
b'\x5a\x50\x5b\x4d\x16\x4a\x59\x54\x46\x52\x47\x51\x48\x51\x49'\
b'\x52\x4a\x55\x4b\x58\x4b\x20\x52\x58\x4b\x54\x4d\x51\x4f\x4e'\
b'\x52\x4d\x55\x4d\x57\x4e\x59\x50\x5b\x53\x5d\x54\x5f\x54\x61'\
b'\x53\x62\x51\x62\x50\x60\x27\x4b\x59\x54\x42\x52\x43\x51\x44'\
b'\x50\x46\x50\x48\x51\x4a\x52\x4b\x53\x4d\x53\x4f\x51\x51\x20'\
b'\x52\x52\x43\x51\x45\x51\x47\x52\x49\x53\x4a\x54\x4c\x54\x4e'\
b'\x53\x50\x4f\x52\x53\x54\x54\x56\x54\x58\x53\x5a\x52\x5b\x51'\
b'\x5d\x51\x5f\x52\x61\x20\x52\x51\x53\x53\x55\x53\x57\x52\x59'\
b'\x51\x5a\x50\x5c\x50\x5e\x51\x60\x52\x61\x54\x62\x02\x4e\x56'\
b'\x52\x42\x52\x62\x27\x4b\x59\x50\x42\x52\x43\x53\x44\x54\x46'\
b'\x54\x48\x53\x4a\x52\x4b\x51\x4d\x51\x4f\x53\x51\x20\x52\x52'\
b'\x43\x53\x45\x53\x47\x52\x49\x51\x4a\x50\x4c\x50\x4e\x51\x50'\
b'\x55\x52\x51\x54\x50\x56\x50\x58\x51\x5a\x52\x5b\x53\x5d\x53'\
b'\x5f\x52\x61\x20\x52\x53\x53\x51\x55\x51\x57\x52\x59\x53\x5a'\
b'\x54\x5c\x54\x5e\x53\x60\x52\x61\x50\x62\x17\x46\x5e\x49\x55'\
b'\x49\x53\x4a\x50\x4c\x4f\x4e\x4f\x50\x50\x54\x53\x56\x54\x58'\
b'\x54\x5a\x53\x5b\x51\x20\x52\x49\x53\x4a\x51\x4c\x50\x4e\x50'\
b'\x50\x51\x54\x54\x56\x55\x58\x55\x5a\x54\x5b\x51\x5b\x4f\x22'\
b'\x4a\x5a\x4a\x46\x4a\x5b\x4b\x5b\x4b\x46\x4c\x46\x4c\x5b\x4d'\
b'\x5b\x4d\x46\x4e\x46\x4e\x5b\x4f\x5b\x4f\x46\x50\x46\x50\x5b'\
b'\x51\x5b\x51\x46\x52\x46\x52\x5b\x53\x5b\x53\x46\x54\x46\x54'\
b'\x5b\x55\x5b\x55\x46\x56\x46\x56\x5b\x57\x5b\x57\x46\x58\x46'\
b'\x58\x5b\x59\x5b\x59\x46\x5a\x46\x5a\x5b'
_index =\
b'\x00\x00\x03\x00\x16\x00\x23\x00\x3c\x00\x73\x00\xb4\x00\xfb'\
b'\x00\x0c\x01\x23\x01\x3a\x01\x4d\x01\x5a\x01\x6b\x01\x72\x01'\
b'\x7f\x01\x86\x01\xab\x01\xb6\x01\xd5\x01\xf6\x01\x05\x02\x2a'\
b'\x02\x5b\x02\x68\x02\xa5\x02\xd6\x02\xef\x02\x0c\x03\x15\x03'\
b'\x22\x03\x2b\x03\x56\x03\xc7\x03\xda\x03\x0b\x04\x18\x04\x2b'\
b'\x04\x44\x04\x6f\x04\x7c\x04\x8f\x04\x96\x04\xa3\x04\xb6\x04'\
b'\xc3\x04\xdc\x04\xef\x04\x1c\x05\x2f\x05\x62\x05\x7f\x05\x94'\
b'\x05\xa1\x05\xc8\x05\xe5\x05\x08\x06\x1b\x06\x40\x06\x53\x06'\
b'\x6c\x06\x73\x06\x8c\x06\x99\x06\xa0\x06\xb1\x06\xe2\x06\x21'\
b'\x07\x3e\x07\x6f\x07\x96\x07\xc1\x07\xe4\x07\x0b\x08\x1e\x08'\
b'\x2b\x08\x52\x08\x65\x08\x90\x08\xad\x08\xd2\x08\xed\x08\x24'\
b'\x09\x4b\x09\x70\x09\x81\x09\xa2\x09\xc1\x09\xf0\x09\x2b\x0a'\
b'\x54\x0a\x83\x0a\xd4\x0a\xdb\x0a\x2c\x0b\x5d\x0b'
_mvfont = memoryview(_font)
def _chr_addr(ordch):
offset = 2 * (ordch - 32)
return int.from_bytes(_index[offset:offset + 2], 'little')
def get_ch(ordch):
offset = _chr_addr(ordch if 32 <= ordch <= 127 else ord('?'))
count = _font[offset]
return _mvfont[offset:offset+(count+2)*2-1]
|
'''
Time: 2015.10.2
Author: Lionel
Content: Company
'''
class Company(object):
def __init__(self, name=None):
self.__name = name
@property
def name(self):
return self.__name
@name.setter
def name(self, name):
self.__name = name
|
#!/usr/bin/env python
class Solution:
def nearestPalindromic(self, n):
mid = len(n) // 2
if len(n) % 2 == 0:
s1 = n[0:mid] + n[0:mid][::-1]
else:
s1 = n[0:mid+1] + n[0:mid][::-1]
s2, s3, s2_list, s3_list = '0', '9'*len(n), list(s1), list(s1)
# This is wrong, e.g. 230032, the smaller one should be 229932, not 220022
# So needs to use awice's method
for i in range(mid, len(n)):
if s2_list[i] != '0':
s2_list[len(n)-1-i] = s2_list[i] = chr(ord(s1[i])-1)
s2 = ''.join(s2_list)
if s2 == '0' * len(n) and len(n) > 1:
s2 = '9' * (len(n)-1)
break
for i in range(mid, len(n)):
if s3_list[i] != '9':
s3_list[len(n)-1-i] = s3_list[i] = chr(ord(s1[i])+1)
s3 = ''.join(s3_list)
break
if s1 == '9' * len(n):
s3 = '1' + '0'*(len(n)-1) + '1'
slist = [s2, s1, s3] if s1 != n else [s2, s3]
l = [max(abs(int(s)-int(n)), 1) for s in slist]
return slist, l, slist[l.index(min(l))]
sol = Solution()
n = '123'
n = '81'
n = '21'
n = '10'
n = '1'
n = '22'
n = '99'
n = '9'
print(sol.nearestPalindromic(n))
|
new_model = tf.keras.models.load_model('my_first_model.h5')
cap = cv2.VideoCapture(0)
faceCascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
while 1:
# get a frame
ret, frame = cap.read()
# show a frame
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(gray, 1.1, 4)
for x, y, w, h in faces:
roi_gray = gray[y:y + h, x:x + h]
roi_color = frame[y:y + h, x:x + h]
# cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 0, 0), 2)
faces = faceCascade.detectMultiScale(roi_gray)
for (ex, ey, ew, eh) in faces:
face_roi = roi_color[ey:ey + eh, ex:ex + eh]
final_image = cv2.resize(face_roi, (224, 224))
final_image = final_image.reshape(-1, 224, 224, 3) # return the image with shaping that TF wants.
fianl_image = np.expand_dims(final_image, axis=0) # need forth dimension
final_image = final_image / 225.0
Predictions = new_model.predict(final_image)
print(Predictions)
if (Predictions > 0.5):
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
cv2.putText(frame, 'Wearing Mask!', (x, y), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 255, 0), 1)
# cv2.putText(img, str,origin,font,size,color,thickness)
else:
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 255), 2)
cv2.putText(frame, 'No Mask!', (x, y), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 0, 255), 1)
# if(Predictions<0.45):
# print("No mask")
# elif(Predictions>0.55):
# print("With mask")
# else:
# print("Can not determine")
cv2.imshow("capture", frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.