content stringlengths 7 1.05M |
|---|
number =int(raw_input("enter number:"))
word =str(raw_input("enter word:"))
if number == 0 or number > 1:
print ("%s %ss." % (number,word))
else:
print("%s %s." % (number,word))
if word[-3:] == "ife":
print( word[:-3] + "ives")
elif word[-2:] == "sh":
print(word[:-2] + "shes" )
elif word[-2:] == "ch":
print(word[:-2] + "ches")
elif word[-2:] == "us":
print(word[:-2] + "i")
elif word[-2:] == "ay":
print(word[:-2] + "ays")
elif word[-2:] == "oy":
print(word[:-2] + "oys")
elif word[-2:] == "ey":
print(word[:-2] + "eys")
elif word[-2:] == "uy":
print(word[:-2] + "uys")
elif word[-1:] == "y":
print(word[:-1] + "ies")
else:
print(word + "s")
|
FIELDS_EN = {
'title': lambda **kwargs: ' renamed project from "{from}" to "{to}"'.format(**kwargs),
'short': lambda **kwargs: ' changed short name of project from "{from}" to "{to}"'.format(**kwargs),
'description': lambda **kwargs: ' changed description of project from "{from}" to "{to}"'.format(**kwargs),
'creator': lambda **kwargs: ' changed creator of project from "@{from}" to "@{to}"'.format(**kwargs),
'telegramChannel': lambda **kwargs: ' changed Telegram channel setting from "{from}" to "{to}"'.format(**kwargs),
'slackChannel': lambda **kwargs: ' changed Slack channel setting from "{from}" to "{to}"'.format(**kwargs),
}
|
# -*- coding: utf-8 -*-
class PeekableGenerator(object):
def __init__(self, generator):
self.__generator = generator
self.__element = None
self.__isset = False
self.__more = False
try:
self.__element = generator.next()
self.__more = True
self.__isset = True
except StopIteration:
pass
def hasMore(self):
return self.__more or self.__isset
def peek(self):
if not self.hasMore():
assert "Shouldn't happen"
raise StopIteration
return self.__element
def next(self):
if not self.hasMore():
assert "Shouldn't happen"
raise StopIteration
self.__more == self.__isset
element = self.__element
self.__isset = False
try:
self.__element = self.__generator.next()
self.__isset = True
except StopIteration:
self.__isset = False
return element |
def get_member_guaranteed(ctx, lookup):
if len(ctx.message.mentions) > 0:
return ctx.message.mentions[0]
if lookup.isdigit():
result = ctx.guild.get_member(int(lookup))
if result:
return result
if "#" in lookup:
result = ctx.guild.get_member_named(lookup)
if result:
return result
for member in ctx.guild.members:
if member.display_name.lower() == lookup.lower():
return member
return None
def get_member_guaranteed_custom_guild(ctx, guild, lookup):
if len(ctx.message.mentions) > 0:
return ctx.message.mentions[0]
if lookup.isdigit():
result = guild.get_member(int(lookup))
if result:
return result
if "#" in lookup:
result = guild.get_member_named(lookup)
if result:
return result
for member in guild.members:
if member.display_name.lower() == lookup.lower():
return member
return None
|
class Solution:
def isIsomorphic(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False
s_t_dic = {}
t_s_dic = {}
n = len(s)
for i in range(n):
if (s[i] not in s_t_dic) and (t[i] not in t_s_dic):
s_t_dic[s[i]] = t[i]
t_s_dic[t[i]] = s[i]
elif s_t_dic.get(s[i]) != t[i] or t_s_dic.get(t[i]) != s[i]:
return False
return True
s = Solution()
print(s.isIsomorphic("egg", "add"))
print(s.isIsomorphic("foo", "bar"))
print(s.isIsomorphic("paper", "title"))
|
class RandomListNode():
def __init__(self, x: int):
self.label = x
self.next = None
self.random = None
class Solution():
def copy_random_list(self, root: RandomListNode) -> RandomListNode:
head = None
if root is not None:
pointers = {}
new_root = RandomListNode(root.label)
pointers[id(root)] = new_root
head = new_root
while (root is not None and
(root.next is not None or root.random is not None)):
if root.next is not None:
if id(root.next) not in pointers:
new_root.next = RandomListNode(root.next.label)
pointers[id(root.next)] = new_root.next
else:
new_root.next = pointers[id(root.next)]
if root.random is not None:
if id(root.random) not in pointers:
new_root.random = RandomListNode(root.random.label)
pointers[id(root.random)] = new_root.random
else:
new_root.random = pointers[id(root.random)]
root = root.next
new_root = new_root.next
return head
|
soma = 0
pares = 0
for i in range(6):
numeros = int(input('Digite um número: '))
if numeros % 2 == 0:
pares +=1
soma += numeros
print(f'A soma dos {pares} números pares entre os números digitados é {soma}')
|
# Copyright 2016 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# These devices are ina3221 (3-channels/i2c address) devices
inas = [('0x40:0', 'pp3300_edp_dx', 3.30, 0.020, 'rem', True), #R367
('0x40:1', 'pp3300_a', 3.30, 0.002, 'rem', True), #R422
('0x40:2', 'pp1800_a', 1.80, 0.020, 'rem', True), #R416
#
('0x41:0', 'pp1240_a', 1.24, 0.020, 'rem', True), #R417
('0x41:1', 'pp1800_dram_u', 1.80, 0.020, 'rem', True), #R403
('0x41:2', 'pp1050_s', 1.05, 0.010, 'rem', True), #R412
#
('0x42:0', 'pp3300_pd_a', 3.30, 0.100, 'rem', True), #R384
('0x42:1', 'pp3300_wlan_dx', 3.30, 0.020, 'rem', True), #R389
('0x42:2', 'pp3300_soc_a', 3.30, 0.020, 'rem', True), #R383
#
('0x43:0', 'pp1100_vddq', 1.10, 0.002, 'rem', True), #R425
('0x43:1', 'pp3300_ec', 3.30, 2.200, 'rem', True), #R415
('0x43:2', 'pp5000_a', 5.00, 0.002, 'rem', True), #R421
]
|
class _PortfolioMemberships:
"""This object determines if a user is a member of a portfolio.
"""
def __init__(self, client=None):
self.client = client
def find_all(self, params={}, **options):
"""Returns the compact portfolio membership records for the portfolio. You must
specify `portfolio`, `portfolio` and `user`, or `workspace` and `user`.
Parameters
----------
[params] : {Object} Parameters for the request
- [portfolio] : {Gid} The portfolio for which to fetch memberships.
- [workspace] : {Gid} The workspace for which to fetch memberships.
- [user] : {String} The user to filter the memberships to.
"""
return self.client.get_collection("/portfolio_memberships", params, **options)
def find_by_portfolio(self, portfolio, params={}, **options):
"""Returns the compact portfolio membership records for the portfolio.
Parameters
----------
portfolio : {Gid} The portfolio for which to fetch memberships.
[params] : {Object} Parameters for the request
- [user] : {String} If present, the user to filter the memberships to.
"""
path = "/portfolios/%s/portfolio_memberships" % (portfolio)
return self.client.get_collection(path, params, **options)
def find_by_id(self, portfolio_membership, params={}, **options):
"""Returns the portfolio membership record.
Parameters
----------
portfolio_membership : {Gid} Globally unique identifier for the portfolio membership.
[params] : {Object} Parameters for the request
"""
path = "/portfolio_memberships/%s" % (portfolio_membership)
return self.client.get(path, params, **options)
|
n = int(input())
lst = []
for _ in range(n):
a, b = [int(i) for i in input().split()]
lst.append((a,b))
lst.sort(key = lambda x: x[1])
index = 0
coordinates = []
while index < n:
curr = lst[index]
while index < n-1 and curr[1]>=lst[index+1][0]:
index += 1
coordinates.append(curr[1])
index += 1
print(len(coordinates))
print(' '.join([str(i) for i in coordinates]))
|
# -*- coding: utf-8 -*-
class Solution:
def numDifferentIntegers(self, word: str) -> int:
result = set()
number = None
for char in word:
if char.isdigit() and number is None:
number = int(char)
elif char.isdigit() and number is not None:
number = 10 * number + int(char)
elif number is not None:
result.add(number)
number = None
if number is not None:
result.add(number)
number = None
return len(result)
if __name__ == '__main__':
solution = Solution()
assert 3 == solution.numDifferentIntegers('a123bc34d8ef34')
assert 2 == solution.numDifferentIntegers('leet1234code234')
assert 1 == solution.numDifferentIntegers('a1b01c001')
|
def fibo(n):
return n if n <= 1 else (fibo(n-1) + fibo(n-2))
nums = [1,2,3,4,5,6]
[fibo(x) for x in nums]
# [1, 1, 2 ,3 ,5, 8]
[y for x in nums if (y:= fibo(x)) % 2 == 0]
# [2, 8]
|
__version__ = '1.12.0'
__author__ = 'nety'
DEFAULT_DATABASE = {
"tokens": [],
"secret_code": "",
"delete_all_notify": False,
"ru_captcha_key": "",
"ignored_members": [],
"ignored_global_members": [],
"muted_members": [],
"aliases": [],
"service_prefixes": [
"!слп",
".слп"
],
"self_prefixes": [
"!л",
".л"
],
"duty_prefixes": [
"!лд",
".лд"
],
"sloumo": [],
"auto_exit_from_chat": False,
"auto_exit_from_chat_delete_chat": False,
"auto_exit_from_chat_add_to_black_list": False,
"disable_notifications": False,
}
CONFIG_PATH = "config.json"
USE_APP_DATA = False
LOGGER_LEVEL = 'INFO'
VKBOTTLE_LOGGER_LEVEL = 'ERROR'
LOG_TO_PATH = False
CALLBACK_LINK = "https://irisduty.ru/callback/"
GITHUB_LINK = "https://github.com/Egor2005l/cho"
VERSION_REST = "https://raw.githubusercontent.com/lordralinc/idmmulti_lp-rest/master/version.json"
ALIASES_REST = "https://raw.githubusercontent.com/lordralinc/idmmulti_lp-rest/master/aliases.json"
ROLE_PLAY_COMMANDS_REST = "https://raw.githubusercontent.com/lordralinc/idmmulti_lp-rest/master/role_play_commands.json"
ROLE_PLAY_COMMANDS_USE_REST = True
ENABLE_EVAL = False
ALLOW_SENTRY = True
SENTRY_URL = "https://7a3f1b116c67453c91600ad54d4b7087@o481403.ingest.sentry.io/5529960"
|
#!/usr/bin/env python
# encoding: utf-8
name = "Singlet_Carbene_Intra_Disproportionation/rules"
shortDesc = u"Convert a singlet carbene to a closed-shell molecule through a concerted 1,2-H shift + 1,2-bond formation"
longDesc = u"""
Reaction site *1 should always be a singlet in this family.
"""
|
BUTTON_LEFT = 0
BUTTON_MIDDLE = 1
BUTTON_RIGHT = 2
|
def main():
file_log = open("hostapd.log",'r').read()
address = file_log.find("AP-STA-CONNECTED")
mac = set()
while address >= 0:
mac.add(file_log[address+17:address+34])
address=file_log.find("AP-STA-CONNECTED",address+1)
for addr in mac:
print(addr)
# For the sake of not using global variables
if __name__ == "__main__":
main() |
"""
问题描述:在一个二维坐标系中,所有的值都是double类型,那么一个三角形可以由3个点来代表,
给定3个点代表的三角形,再给定一个点(x,y),判断(x,y)是否在三角形中.
"""
class PointInTriangle:
@classmethod
def cross_product(cls, x1, y1, x2, y2):
return x1 * y2 - x2 * y1
@classmethod
def is_inside(cls, x1, y1, x2, y2, x3, y3, x, y):
if cls.cross_product(x3-x1, y3-y1, x2-x1, y2-y1) >= 0:
x2, x3 = x3, x2
y2, y3 = y3, y2
if cls.cross_product(x2-x1, y2-y1, x-x1, y-y1) < 0:
return False
if cls.cross_product(x3-x2, y3-y2, x-x2, y-y2) < 0:
return False
if cls.cross_product(x1-x3, y1-y3, x-x3, y-y3) < 0:
return False
return True
if __name__ == '__main__':
x1 = -5
y1 = 0
x2 = 0
y2 = 8
x3 = 5
y3 = 0
x = 0
y = 5
print(PointInTriangle.is_inside(x1, y1, x2, y2, x3, y3, x, y)) |
COURSE = "Python for Everybody"
def which_course_is_this():
print("The course is:", COURSE)
|
DATASOURCE_NAME = "Coderepos"
GITHUB_DATASOURCE_NAME = "github"
|
def readDataIntoMatrix(fileName):
f = open(fileName, 'r')
i = 0
data = []
for line in f.readlines():
j = 0
row = []
values = line.split()
for value in values:
row.append(int(value))
j += 1
data.append(row)
i += 1
return data |
# -*- coding: UTF-8 -*-
logger.info("Loading 2 objects to table invoicing_tariff...")
# fields: id, designation, number_of_events, min_asset, max_asset
loader.save(create_invoicing_tariff(1,['By presence', 'Pro Anwesenheit', 'By presence'],1,None,None))
loader.save(create_invoicing_tariff(2,['Maximum 10', 'Maximum 10', 'Maximum 10'],1,None,10))
loader.flush_deferred_objects()
|
#!/usr/bin/env python3
# Write a program that computes the GC% of a DNA sequence
# Format the output for 2 decimal places
# Use all three formatting methods
print('Method 1: printf()')
seq = 'ACAGAGCCAGCAGATATACAGCAGATACTAT' # feel free to change
gc_count = 0
for i in range(0, len(seq)):
if seq[i] == 'G' or seq[i] == 'C':
gc_count += 1
print ('%.2f' % (gc_count / len(seq)))
print('-----')
print('Method 2: str.format()')
gc_count = 0
for i in range(0, len(seq)):
if seq[i] == 'G' or seq[i] == 'C':
gc_count += 1
print ('{:.2f}'.format (gc_count / len(seq)))
print('------')
print('Method 3: f-strings')
gc_count = 0
for i in range(0, len(seq)):
if seq[i] == 'G' or seq[i] == 'C':
gc_count += 1
print (f'{gc_count / len(seq):.2f}')
print('------')
print('Korfs method')
gc_count = 0
for c in seq:
if c == 'G' or c == 'C':
gc_count += 1
print(f'{gc_count / len(seq):.2f}')
'''
0.42
0.42
0.42
''' |
'''
solve amazing problem:
Given a 2D array of mines, replace the question mark with the number of mines that immediately surround it.
This includes the diagonals, meaning it is possible for it to be surrounded by 8 mines maximum.
The key is as follows:
An empty space: "-"
A mine: "#"
Number showing number of mines surrounding it: "?"
sample:
(["-","#","-"],
["-","?","-"],
["-","-","-"])
(["-","#","#"],
["?","#",""],
["#","?","-"])
output:
[["-","#","-"],
["-","1","-"],
["-","-","-"]]
[["-","#","#"],
["3","#",""],
["#","2","-"]]
'''
tupli1 = (["-","#","-"],
["-","?","-"],
["-","-","-"])
tupli2 = (["-","#","-"],
["#","-","?"],
["#","#","-"])
tupli3 = (["-","#","#"],
["?","#",""],
["#","?","-"])
tupli4 = (["-","?","#"],
["?","#","?"],
["#","?","-"])
tupli5 = (["#","?","#"],
["#","#","?"],
["#","?","-"])
tupli6 = (["#","#","#"],
["#","?","#"],
["#","#","#"])
tupli7 = (["#","#","#"],
["#","#","#"],
["#","?","#"])
tupli8 = (["#","#","#"],
["#","#","?"],
["#","#","#"])
print()
result = [[],[],[]]
count = 0
liicount = []
def solveProblem(tp):
global count, liicount
for i in tp:
if '?' in i:
if tp[0][0] == '?':
if tp[0][1] == '#':
count += 1
if tp[1][0] == '#':
count += 1
if tp[1][1] == '#':
count += 1
liicount.append(count)
if tp[0][1] == '?':
count = 0
if tp[0][0] == '#':
count += 1
if tp[0][2] == '#':
count += 1
if tp[1][0] == '#':
count += 1
if tp[1][1] == '#':
count += 1
if tp[1][2] == '#':
count += 1
liicount.append(count)
if tp[0][2] == '?':
count = 0
if tp[0][1] == '#':
count += 1
if tp[1][1] == '#':
count += 1
if tp[1][2] == '#':
count += 1
liicount.append(count)
# ========================================= 1
if tp[1][0] == '?':
count = 0
if tp[0][0] == '#':
count += 1
if tp[0][1] == '#':
count += 1
if tp[1][1] == '#':
count += 1
if tp[2][0] == '#':
count += 1
if tp[2][1] == '#':
count += 1
liicount.append(count)
if tp[1][1] == '?':
count = 0
if tp[0][0] == '#':
count += 1
if tp[0][1] == '#':
count += 1
if tp[0][2] == '#':
count += 1
if tp[1][0] == '#':
count += 1
if tp[1][2] == '#':
count += 1
if tp[2][0] == '#':
count += 1
if tp[2][1] == '#':
count += 1
if tp[2][2] == '#':
count += 1
liicount.append(count)
if tp[1][2] == '?':
count = 0
if tp[0][1] == '#':
count += 1
if tp[0][2] == '#':
count += 1
if tp[1][1] == '#':
count += 1
if tp[2][1] == '#':
count += 1
if tp[2][2] == '#':
count += 1
liicount.append(count)
# ========================================= 2
if tp[2][0] == '?':
count = 0
if tp[1][0] == '#':
count += 1
if tp[1][1] == '#':
count += 1
if tp[2][1] == '#':
count += 1
liicount.append(count)
if tp[2][1] == '?':
count = 0
if tp[1][0] == '#':
count += 1
if tp[1][1] == '#':
count += 1
if tp[1][2] == '#':
count += 1
if tp[2][0] == '#':
count += 1
if tp[2][2] == '#':
count += 1
liicount.append(count)
if tp[2][2] == '?':
count = 0
if tp[1][1] == '#':
count += 1
if tp[1][2] == '#':
count += 1
if tp[2][1] == '#':
count += 1
liicount.append(count)
def numOfQuest(numq):
o = 0
for i in numq:
for g in i:
if g == '?':
o += 1
else:
pass
return o
liicount = [liicount[i] for i in range(numOfQuest(numq=tp))]
def replace_questionMark(tup):
solveProblem(tup)
y = 0
m = 0
for u in tup:
for a in u:
if a == '?':
result[y].append(a.replace('?', str(liicount[m])))
m += 1
else: result[y].append(a)
y += 1
return result
if __name__ == '__main__':
#print(replace_questionMark(tup=tupli1))
#print(replace_questionMark(tup=tupli2))
#print(replace_questionMark(tup=tupli3))
#print(replace_questionMark(tup=tupli4))
#print(replace_questionMark(tup=tupli5))
#print(replace_questionMark(tup=tupli6))
#print(replace_questionMark(tup=tupli7))
print(replace_questionMark(tup=tupli8))
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
@AUTHOR:Joselyn Zhao
@CONTACT:zhaojing17@foxmail.com
@HOME_PAGE:joselynzhao.top
@SOFTWERE:PyCharm
@FILE:tiqu.py
@TIME:2020/4/29 22:35
@DES: 使用字典推导式提取字典子集
'''
prices = {
'asp':49.9,
'python':69.9,
'java':59.9,
'c':45.9,
'php':79.9
}
p1 = {key:value for key,value in prices.items() if value>50}
print(p1)
tech_names ={'python','java','c'}
p2 = {key:value for key,value in prices.items() if key in tech_names}
print(p2)
# 相比之下后面两种方法更慢
p3 = dict((key,value) for key,value in prices.items() if value>50)
p4 = {key:prices[key] for key in prices.keys() if key in tech_names}
print(p3)
print(p4) |
#when many condition fullfil use all.
subs = 1000
likes = 400
comments = 500
condition = [subs>150,likes>150,comments>50]
if all(condition):
print('Great Content') |
class Solution:
def findMedianSortedArrays(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: float
"""
tmp = nums1 + nums2
tmp.sort()
if len(tmp)%2 == 0:
# print(tmp[len(tmp)//2 - 1] + tmp[len(tmp)//2] / 2)
return (tmp[len(tmp)//2 - 1] + tmp[len(tmp)//2]) / 2
else:
# print(tmp[(len(tmp)-1) // 2])
return tmp[(len(tmp)-1) // 2]
|
def write_to(filename:str,text:str):
with open(f'{filename}.txt','w') as file1:
file1.write(text)
write_to('players','zarinaemirbaizak')
|
def main():
# input
S = input()
N, M = map(int, input().split())
# compute
# output
print(S[:N-1] + S[M-1] + S[N:M-1] + S[N-1] + S[M:])
if __name__ == '__main__':
main()
|
class PropertyMonitor(object):
__slots__ = (
'_lock', # concurrency control
'_state', # currently active state
'_pool', # MsgRecord deque to hold temporary records
'witness', # MsgRecord list of observed events
'on_enter_scope', # callback upon entering the scope
'on_exit_scope', # callback upon exiting the scope
'on_violation', # callback upon verdict of False
'on_success', # callback upon verdict of True
'time_launch', # when was the monitor launched
'time_shutdown', # when was the monitor shutdown
'time_state', # when did the last state transition occur
'cb_map', # mapping of topic names to callback functions
)
PROP_ID = 'None'
PROP_TITLE = '''None'''
PROP_DESC = '''None'''
HPL_PROPERTY = r'''globally: /a { True } forbids /b { True }'''
def __init__(self):
self._lock = Lock()
self._reset()
self.on_enter_scope = self._noop
self.on_exit_scope = self._noop
self.on_violation = self._noop
self.on_success = self._noop
self._state = 0
self.cb_map = {
'/b': self.on_msg__b,
'/a': self.on_msg__a,
}
@property
def verdict(self):
with self._lock:
if self._state == -1:
return True
if self._state == -2:
return False
return None
def on_launch(self, stamp):
with self._lock:
if self._state != 0:
raise RuntimeError('monitor is already turned on')
self._reset()
self.time_launch = stamp
self._state = 3
self.time_state = stamp
self.on_enter_scope(stamp)
return True
def on_shutdown(self, stamp):
with self._lock:
if self._state == 0:
raise RuntimeError('monitor is already turned off')
self.time_shutdown = stamp
self._state = 0
self.time_state = stamp
return True
def on_timer(self, stamp):
return True
def on_msg__b(self, msg, stamp):
with self._lock:
if self._state == 2:
assert len(self._pool) >= 1, 'missing trigger event'
rec = self._pool[0]
self.witness.append(rec)
self.witness.append(MsgRecord('/b', stamp, msg))
self._pool.clear()
self._state = -2
self.time_state = stamp
self.on_violation(stamp, self.witness)
return True
return False
def on_msg__a(self, msg, stamp):
with self._lock:
if self._state == 2:
return False # nothing to do
if self._state == 3:
self._pool.append(MsgRecord('/a', stamp, msg))
self._state = 2
self.time_state = stamp
return True
return False
def _reset(self):
self.witness = []
self._pool = deque((), 1)
self.time_launch = -1
self.time_shutdown = -1
self.time_state = -1
def _noop(self, *args):
pass
class PropertyMonitor(object):
__slots__ = (
'_lock', # concurrency control
'_state', # currently active state
'_pool', # MsgRecord deque to hold temporary records
'witness', # MsgRecord list of observed events
'on_enter_scope', # callback upon entering the scope
'on_exit_scope', # callback upon exiting the scope
'on_violation', # callback upon verdict of False
'on_success', # callback upon verdict of True
'time_launch', # when was the monitor launched
'time_shutdown', # when was the monitor shutdown
'time_state', # when did the last state transition occur
'cb_map', # mapping of topic names to callback functions
)
PROP_ID = 'None'
PROP_TITLE = '''None'''
PROP_DESC = '''None'''
HPL_PROPERTY = r'''globally: /a { True } forbids /b { True } within 0.1s'''
def __init__(self):
self._lock = Lock()
self._reset()
self.on_enter_scope = self._noop
self.on_exit_scope = self._noop
self.on_violation = self._noop
self.on_success = self._noop
self._state = 0
self.cb_map = {
'/b': self.on_msg__b,
'/a': self.on_msg__a,
}
@property
def verdict(self):
with self._lock:
if self._state == -1:
return True
if self._state == -2:
return False
return None
def on_launch(self, stamp):
with self._lock:
if self._state != 0:
raise RuntimeError('monitor is already turned on')
self._reset()
self.time_launch = stamp
self._state = 3
self.time_state = stamp
self.on_enter_scope(stamp)
return True
def on_shutdown(self, stamp):
with self._lock:
if self._state == 0:
raise RuntimeError('monitor is already turned off')
self.time_shutdown = stamp
self._state = 0
self.time_state = stamp
return True
def on_timer(self, stamp):
with self._lock:
if self._state == 2:
assert len(self._pool) >= 1, 'missing trigger event'
while self._pool and (stamp - self._pool[0].timestamp) >= 0.1:
self._pool.popleft()
if not self._pool:
self._state = 3
self.time_state = stamp
return True
def on_msg__b(self, msg, stamp):
with self._lock:
if self._state == 2:
assert len(self._pool) >= 1, 'missing trigger event'
while self._pool and (stamp - self._pool[0].timestamp) >= 0.1:
self._pool.popleft()
if not self._pool:
self._state = 3
self.time_state = stamp
if self._state == 2:
assert len(self._pool) >= 1, 'missing trigger event'
rec = self._pool[0]
self.witness.append(rec)
self.witness.append(MsgRecord('/b', stamp, msg))
self._pool.clear()
self._state = -2
self.time_state = stamp
self.on_violation(stamp, self.witness)
return True
return False
def on_msg__a(self, msg, stamp):
with self._lock:
if self._state == 2:
assert len(self._pool) >= 1, 'missing trigger event'
while self._pool and (stamp - self._pool[0].timestamp) >= 0.1:
self._pool.popleft()
if not self._pool:
self._state = 3
self.time_state = stamp
if self._state == 2:
self._pool.append(MsgRecord('/a', stamp, msg))
return True
if self._state == 3:
self._pool.append(MsgRecord('/a', stamp, msg))
self._state = 2
self.time_state = stamp
return True
return False
def _reset(self):
self.witness = []
self._pool = deque((), 1)
self.time_launch = -1
self.time_shutdown = -1
self.time_state = -1
def _noop(self, *args):
pass
class PropertyMonitor(object):
__slots__ = (
'_lock', # concurrency control
'_state', # currently active state
'_pool', # MsgRecord deque to hold temporary records
'witness', # MsgRecord list of observed events
'on_enter_scope', # callback upon entering the scope
'on_exit_scope', # callback upon exiting the scope
'on_violation', # callback upon verdict of False
'on_success', # callback upon verdict of True
'time_launch', # when was the monitor launched
'time_shutdown', # when was the monitor shutdown
'time_state', # when did the last state transition occur
'cb_map', # mapping of topic names to callback functions
)
PROP_ID = 'None'
PROP_TITLE = '''None'''
PROP_DESC = '''None'''
HPL_PROPERTY = r'''globally: /a { (data > 0) } forbids /b { (data < 0) }'''
def __init__(self):
self._lock = Lock()
self._reset()
self.on_enter_scope = self._noop
self.on_exit_scope = self._noop
self.on_violation = self._noop
self.on_success = self._noop
self._state = 0
self.cb_map = {
'/b': self.on_msg__b,
'/a': self.on_msg__a,
}
@property
def verdict(self):
with self._lock:
if self._state == -1:
return True
if self._state == -2:
return False
return None
def on_launch(self, stamp):
with self._lock:
if self._state != 0:
raise RuntimeError('monitor is already turned on')
self._reset()
self.time_launch = stamp
self._state = 3
self.time_state = stamp
self.on_enter_scope(stamp)
return True
def on_shutdown(self, stamp):
with self._lock:
if self._state == 0:
raise RuntimeError('monitor is already turned off')
self.time_shutdown = stamp
self._state = 0
self.time_state = stamp
return True
def on_timer(self, stamp):
return True
def on_msg__b(self, msg, stamp):
with self._lock:
if self._state == 2:
assert len(self._pool) >= 1, 'missing trigger event'
rec = self._pool[0]
if (msg.data < 0):
self.witness.append(rec)
self.witness.append(MsgRecord('/b', stamp, msg))
self._pool.clear()
self._state = -2
self.time_state = stamp
self.on_violation(stamp, self.witness)
return True
return False
def on_msg__a(self, msg, stamp):
with self._lock:
if self._state == 2:
return False # nothing to do
if self._state == 3:
if (msg.data > 0):
self._pool.append(MsgRecord('/a', stamp, msg))
self._state = 2
self.time_state = stamp
return True
return False
def _reset(self):
self.witness = []
self._pool = deque((), 1)
self.time_launch = -1
self.time_shutdown = -1
self.time_state = -1
def _noop(self, *args):
pass
class PropertyMonitor(object):
__slots__ = (
'_lock', # concurrency control
'_state', # currently active state
'_pool', # MsgRecord deque to hold temporary records
'witness', # MsgRecord list of observed events
'on_enter_scope', # callback upon entering the scope
'on_exit_scope', # callback upon exiting the scope
'on_violation', # callback upon verdict of False
'on_success', # callback upon verdict of True
'time_launch', # when was the monitor launched
'time_shutdown', # when was the monitor shutdown
'time_state', # when did the last state transition occur
'cb_map', # mapping of topic names to callback functions
)
PROP_ID = 'None'
PROP_TITLE = '''None'''
PROP_DESC = '''None'''
HPL_PROPERTY = r'''globally: /a { (data > 0) } forbids /b { (data < 0) } within 0.1s'''
def __init__(self):
self._lock = Lock()
self._reset()
self.on_enter_scope = self._noop
self.on_exit_scope = self._noop
self.on_violation = self._noop
self.on_success = self._noop
self._state = 0
self.cb_map = {
'/b': self.on_msg__b,
'/a': self.on_msg__a,
}
@property
def verdict(self):
with self._lock:
if self._state == -1:
return True
if self._state == -2:
return False
return None
def on_launch(self, stamp):
with self._lock:
if self._state != 0:
raise RuntimeError('monitor is already turned on')
self._reset()
self.time_launch = stamp
self._state = 3
self.time_state = stamp
self.on_enter_scope(stamp)
return True
def on_shutdown(self, stamp):
with self._lock:
if self._state == 0:
raise RuntimeError('monitor is already turned off')
self.time_shutdown = stamp
self._state = 0
self.time_state = stamp
return True
def on_timer(self, stamp):
with self._lock:
if self._state == 2:
assert len(self._pool) >= 1, 'missing trigger event'
while self._pool and (stamp - self._pool[0].timestamp) >= 0.1:
self._pool.popleft()
if not self._pool:
self._state = 3
self.time_state = stamp
return True
def on_msg__b(self, msg, stamp):
with self._lock:
if self._state == 2:
assert len(self._pool) >= 1, 'missing trigger event'
while self._pool and (stamp - self._pool[0].timestamp) >= 0.1:
self._pool.popleft()
if not self._pool:
self._state = 3
self.time_state = stamp
if self._state == 2:
assert len(self._pool) >= 1, 'missing trigger event'
rec = self._pool[0]
if (msg.data < 0):
self.witness.append(rec)
self.witness.append(MsgRecord('/b', stamp, msg))
self._pool.clear()
self._state = -2
self.time_state = stamp
self.on_violation(stamp, self.witness)
return True
return False
def on_msg__a(self, msg, stamp):
with self._lock:
if self._state == 2:
assert len(self._pool) >= 1, 'missing trigger event'
while self._pool and (stamp - self._pool[0].timestamp) >= 0.1:
self._pool.popleft()
if not self._pool:
self._state = 3
self.time_state = stamp
if self._state == 2:
if (msg.data > 0):
self._pool.append(MsgRecord('/a', stamp, msg))
return True
if self._state == 3:
if (msg.data > 0):
self._pool.append(MsgRecord('/a', stamp, msg))
self._state = 2
self.time_state = stamp
return True
return False
def _reset(self):
self.witness = []
self._pool = deque((), 1)
self.time_launch = -1
self.time_shutdown = -1
self.time_state = -1
def _noop(self, *args):
pass
class PropertyMonitor(object):
__slots__ = (
'_lock', # concurrency control
'_state', # currently active state
'_pool', # MsgRecord deque to hold temporary records
'witness', # MsgRecord list of observed events
'on_enter_scope', # callback upon entering the scope
'on_exit_scope', # callback upon exiting the scope
'on_violation', # callback upon verdict of False
'on_success', # callback upon verdict of True
'time_launch', # when was the monitor launched
'time_shutdown', # when was the monitor shutdown
'time_state', # when did the last state transition occur
'cb_map', # mapping of topic names to callback functions
)
PROP_ID = 'None'
PROP_TITLE = '''None'''
PROP_DESC = '''None'''
HPL_PROPERTY = r'''globally: (/a1 { (data > 0) } or /a2 { (data < 0) }) forbids /b { True } within 0.1s'''
def __init__(self):
self._lock = Lock()
self._reset()
self.on_enter_scope = self._noop
self.on_exit_scope = self._noop
self.on_violation = self._noop
self.on_success = self._noop
self._state = 0
self.cb_map = {
'/b': self.on_msg__b,
'/a1': self.on_msg__a1,
'/a2': self.on_msg__a2,
}
@property
def verdict(self):
with self._lock:
if self._state == -1:
return True
if self._state == -2:
return False
return None
def on_launch(self, stamp):
with self._lock:
if self._state != 0:
raise RuntimeError('monitor is already turned on')
self._reset()
self.time_launch = stamp
self._state = 3
self.time_state = stamp
self.on_enter_scope(stamp)
return True
def on_shutdown(self, stamp):
with self._lock:
if self._state == 0:
raise RuntimeError('monitor is already turned off')
self.time_shutdown = stamp
self._state = 0
self.time_state = stamp
return True
def on_timer(self, stamp):
with self._lock:
if self._state == 2:
assert len(self._pool) >= 1, 'missing trigger event'
while self._pool and (stamp - self._pool[0].timestamp) >= 0.1:
self._pool.popleft()
if not self._pool:
self._state = 3
self.time_state = stamp
return True
def on_msg__b(self, msg, stamp):
with self._lock:
if self._state == 2:
assert len(self._pool) >= 1, 'missing trigger event'
while self._pool and (stamp - self._pool[0].timestamp) >= 0.1:
self._pool.popleft()
if not self._pool:
self._state = 3
self.time_state = stamp
if self._state == 2:
assert len(self._pool) >= 1, 'missing trigger event'
rec = self._pool[0]
self.witness.append(rec)
self.witness.append(MsgRecord('/b', stamp, msg))
self._pool.clear()
self._state = -2
self.time_state = stamp
self.on_violation(stamp, self.witness)
return True
return False
def on_msg__a1(self, msg, stamp):
with self._lock:
if self._state == 2:
assert len(self._pool) >= 1, 'missing trigger event'
while self._pool and (stamp - self._pool[0].timestamp) >= 0.1:
self._pool.popleft()
if not self._pool:
self._state = 3
self.time_state = stamp
if self._state == 2:
if (msg.data > 0):
self._pool.append(MsgRecord('/a1', stamp, msg))
return True
if self._state == 3:
if (msg.data > 0):
self._pool.append(MsgRecord('/a1', stamp, msg))
self._state = 2
self.time_state = stamp
return True
return False
def on_msg__a2(self, msg, stamp):
with self._lock:
if self._state == 2:
assert len(self._pool) >= 1, 'missing trigger event'
while self._pool and (stamp - self._pool[0].timestamp) >= 0.1:
self._pool.popleft()
if not self._pool:
self._state = 3
self.time_state = stamp
if self._state == 2:
if (msg.data < 0):
self._pool.append(MsgRecord('/a2', stamp, msg))
return True
if self._state == 3:
if (msg.data < 0):
self._pool.append(MsgRecord('/a2', stamp, msg))
self._state = 2
self.time_state = stamp
return True
return False
def _reset(self):
self.witness = []
self._pool = deque((), 1)
self.time_launch = -1
self.time_shutdown = -1
self.time_state = -1
def _noop(self, *args):
pass
class PropertyMonitor(object):
__slots__ = (
'_lock', # concurrency control
'_state', # currently active state
'_pool', # MsgRecord deque to hold temporary records
'witness', # MsgRecord list of observed events
'on_enter_scope', # callback upon entering the scope
'on_exit_scope', # callback upon exiting the scope
'on_violation', # callback upon verdict of False
'on_success', # callback upon verdict of True
'time_launch', # when was the monitor launched
'time_shutdown', # when was the monitor shutdown
'time_state', # when did the last state transition occur
'cb_map', # mapping of topic names to callback functions
)
PROP_ID = 'None'
PROP_TITLE = '''None'''
PROP_DESC = '''None'''
HPL_PROPERTY = r'''globally: /a { True } forbids (/b1 { (data > 0) } or /b2 { (data < 0) }) within 0.1s'''
def __init__(self):
self._lock = Lock()
self._reset()
self.on_enter_scope = self._noop
self.on_exit_scope = self._noop
self.on_violation = self._noop
self.on_success = self._noop
self._state = 0
self.cb_map = {
'/b2': self.on_msg__b2,
'/a': self.on_msg__a,
'/b1': self.on_msg__b1,
}
@property
def verdict(self):
with self._lock:
if self._state == -1:
return True
if self._state == -2:
return False
return None
def on_launch(self, stamp):
with self._lock:
if self._state != 0:
raise RuntimeError('monitor is already turned on')
self._reset()
self.time_launch = stamp
self._state = 3
self.time_state = stamp
self.on_enter_scope(stamp)
return True
def on_shutdown(self, stamp):
with self._lock:
if self._state == 0:
raise RuntimeError('monitor is already turned off')
self.time_shutdown = stamp
self._state = 0
self.time_state = stamp
return True
def on_timer(self, stamp):
with self._lock:
if self._state == 2:
assert len(self._pool) >= 1, 'missing trigger event'
while self._pool and (stamp - self._pool[0].timestamp) >= 0.1:
self._pool.popleft()
if not self._pool:
self._state = 3
self.time_state = stamp
return True
def on_msg__b2(self, msg, stamp):
with self._lock:
if self._state == 2:
assert len(self._pool) >= 1, 'missing trigger event'
while self._pool and (stamp - self._pool[0].timestamp) >= 0.1:
self._pool.popleft()
if not self._pool:
self._state = 3
self.time_state = stamp
if self._state == 2:
assert len(self._pool) >= 1, 'missing trigger event'
rec = self._pool[0]
if (msg.data < 0):
self.witness.append(rec)
self.witness.append(MsgRecord('/b2', stamp, msg))
self._pool.clear()
self._state = -2
self.time_state = stamp
self.on_violation(stamp, self.witness)
return True
return False
def on_msg__a(self, msg, stamp):
with self._lock:
if self._state == 2:
assert len(self._pool) >= 1, 'missing trigger event'
while self._pool and (stamp - self._pool[0].timestamp) >= 0.1:
self._pool.popleft()
if not self._pool:
self._state = 3
self.time_state = stamp
if self._state == 2:
self._pool.append(MsgRecord('/a', stamp, msg))
return True
if self._state == 3:
self._pool.append(MsgRecord('/a', stamp, msg))
self._state = 2
self.time_state = stamp
return True
return False
def on_msg__b1(self, msg, stamp):
with self._lock:
if self._state == 2:
assert len(self._pool) >= 1, 'missing trigger event'
while self._pool and (stamp - self._pool[0].timestamp) >= 0.1:
self._pool.popleft()
if not self._pool:
self._state = 3
self.time_state = stamp
if self._state == 2:
assert len(self._pool) >= 1, 'missing trigger event'
rec = self._pool[0]
if (msg.data > 0):
self.witness.append(rec)
self.witness.append(MsgRecord('/b1', stamp, msg))
self._pool.clear()
self._state = -2
self.time_state = stamp
self.on_violation(stamp, self.witness)
return True
return False
def _reset(self):
self.witness = []
self._pool = deque((), 1)
self.time_launch = -1
self.time_shutdown = -1
self.time_state = -1
def _noop(self, *args):
pass
class PropertyMonitor(object):
__slots__ = (
'_lock', # concurrency control
'_state', # currently active state
'_pool', # MsgRecord deque to hold temporary records
'witness', # MsgRecord list of observed events
'on_enter_scope', # callback upon entering the scope
'on_exit_scope', # callback upon exiting the scope
'on_violation', # callback upon verdict of False
'on_success', # callback upon verdict of True
'time_launch', # when was the monitor launched
'time_shutdown', # when was the monitor shutdown
'time_state', # when did the last state transition occur
'cb_map', # mapping of topic names to callback functions
)
PROP_ID = 'None'
PROP_TITLE = '''None'''
PROP_DESC = '''None'''
HPL_PROPERTY = r'''after /p { True }: /a { True } forbids /b { True } within 0.1s'''
def __init__(self):
self._lock = Lock()
self._reset()
self.on_enter_scope = self._noop
self.on_exit_scope = self._noop
self.on_violation = self._noop
self.on_success = self._noop
self._state = 0
self.cb_map = {
'/b': self.on_msg__b,
'/a': self.on_msg__a,
'/p': self.on_msg__p,
}
@property
def verdict(self):
with self._lock:
if self._state == -1:
return True
if self._state == -2:
return False
return None
def on_launch(self, stamp):
with self._lock:
if self._state != 0:
raise RuntimeError('monitor is already turned on')
self._reset()
self.time_launch = stamp
self._state = 1
self.time_state = stamp
return True
def on_shutdown(self, stamp):
with self._lock:
if self._state == 0:
raise RuntimeError('monitor is already turned off')
self.time_shutdown = stamp
self._state = 0
self.time_state = stamp
return True
def on_timer(self, stamp):
with self._lock:
if self._state == 2:
assert len(self._pool) >= 1, 'missing trigger event'
while self._pool and (stamp - self._pool[0].timestamp) >= 0.1:
self._pool.popleft()
if not self._pool:
self._state = 3
self.time_state = stamp
return True
def on_msg__b(self, msg, stamp):
with self._lock:
if self._state == 2:
assert len(self._pool) >= 1, 'missing trigger event'
while self._pool and (stamp - self._pool[0].timestamp) >= 0.1:
self._pool.popleft()
if not self._pool:
self._state = 3
self.time_state = stamp
if self._state == 2:
assert len(self._pool) >= 1, 'missing trigger event'
rec = self._pool[0]
self.witness.append(rec)
self.witness.append(MsgRecord('/b', stamp, msg))
self._pool.clear()
self._state = -2
self.time_state = stamp
self.on_violation(stamp, self.witness)
return True
return False
def on_msg__a(self, msg, stamp):
with self._lock:
if self._state == 2:
assert len(self._pool) >= 1, 'missing trigger event'
while self._pool and (stamp - self._pool[0].timestamp) >= 0.1:
self._pool.popleft()
if not self._pool:
self._state = 3
self.time_state = stamp
if self._state == 2:
self._pool.append(MsgRecord('/a', stamp, msg))
return True
if self._state == 3:
self._pool.append(MsgRecord('/a', stamp, msg))
self._state = 2
self.time_state = stamp
return True
return False
def on_msg__p(self, msg, stamp):
with self._lock:
if self._state == 2:
assert len(self._pool) >= 1, 'missing trigger event'
while self._pool and (stamp - self._pool[0].timestamp) >= 0.1:
self._pool.popleft()
if not self._pool:
self._state = 3
self.time_state = stamp
if self._state == 1:
self.witness.append(MsgRecord('/p', stamp, msg))
self._state = 3
self.time_state = stamp
self.on_enter_scope(stamp)
return True
return False
def _reset(self):
self.witness = []
self._pool = deque((), 1)
self.time_launch = -1
self.time_shutdown = -1
self.time_state = -1
def _noop(self, *args):
pass
class PropertyMonitor(object):
__slots__ = (
'_lock', # concurrency control
'_state', # currently active state
'_pool', # MsgRecord deque to hold temporary records
'witness', # MsgRecord list of observed events
'on_enter_scope', # callback upon entering the scope
'on_exit_scope', # callback upon exiting the scope
'on_violation', # callback upon verdict of False
'on_success', # callback upon verdict of True
'time_launch', # when was the monitor launched
'time_shutdown', # when was the monitor shutdown
'time_state', # when did the last state transition occur
'cb_map', # mapping of topic names to callback functions
)
PROP_ID = 'None'
PROP_TITLE = '''None'''
PROP_DESC = '''None'''
HPL_PROPERTY = r'''after /p { phi }: /a { (data > 0) } forbids /b { (data < 0) } within 0.1s'''
def __init__(self):
self._lock = Lock()
self._reset()
self.on_enter_scope = self._noop
self.on_exit_scope = self._noop
self.on_violation = self._noop
self.on_success = self._noop
self._state = 0
self.cb_map = {
'/b': self.on_msg__b,
'/a': self.on_msg__a,
'/p': self.on_msg__p,
}
@property
def verdict(self):
with self._lock:
if self._state == -1:
return True
if self._state == -2:
return False
return None
def on_launch(self, stamp):
with self._lock:
if self._state != 0:
raise RuntimeError('monitor is already turned on')
self._reset()
self.time_launch = stamp
self._state = 1
self.time_state = stamp
return True
def on_shutdown(self, stamp):
with self._lock:
if self._state == 0:
raise RuntimeError('monitor is already turned off')
self.time_shutdown = stamp
self._state = 0
self.time_state = stamp
return True
def on_timer(self, stamp):
with self._lock:
if self._state == 2:
assert len(self._pool) >= 1, 'missing trigger event'
while self._pool and (stamp - self._pool[0].timestamp) >= 0.1:
self._pool.popleft()
if not self._pool:
self._state = 3
self.time_state = stamp
return True
def on_msg__b(self, msg, stamp):
with self._lock:
if self._state == 2:
assert len(self._pool) >= 1, 'missing trigger event'
while self._pool and (stamp - self._pool[0].timestamp) >= 0.1:
self._pool.popleft()
if not self._pool:
self._state = 3
self.time_state = stamp
if self._state == 2:
assert len(self._pool) >= 1, 'missing trigger event'
rec = self._pool[0]
if (msg.data < 0):
self.witness.append(rec)
self.witness.append(MsgRecord('/b', stamp, msg))
self._pool.clear()
self._state = -2
self.time_state = stamp
self.on_violation(stamp, self.witness)
return True
return False
def on_msg__a(self, msg, stamp):
with self._lock:
if self._state == 2:
assert len(self._pool) >= 1, 'missing trigger event'
while self._pool and (stamp - self._pool[0].timestamp) >= 0.1:
self._pool.popleft()
if not self._pool:
self._state = 3
self.time_state = stamp
if self._state == 2:
if (msg.data > 0):
self._pool.append(MsgRecord('/a', stamp, msg))
return True
if self._state == 3:
if (msg.data > 0):
self._pool.append(MsgRecord('/a', stamp, msg))
self._state = 2
self.time_state = stamp
return True
return False
def on_msg__p(self, msg, stamp):
with self._lock:
if self._state == 2:
assert len(self._pool) >= 1, 'missing trigger event'
while self._pool and (stamp - self._pool[0].timestamp) >= 0.1:
self._pool.popleft()
if not self._pool:
self._state = 3
self.time_state = stamp
if self._state == 1:
if msg.phi:
self.witness.append(MsgRecord('/p', stamp, msg))
self._state = 3
self.time_state = stamp
self.on_enter_scope(stamp)
return True
return False
def _reset(self):
self.witness = []
self._pool = deque((), 1)
self.time_launch = -1
self.time_shutdown = -1
self.time_state = -1
def _noop(self, *args):
pass
class PropertyMonitor(object):
__slots__ = (
'_lock', # concurrency control
'_state', # currently active state
'_pool', # MsgRecord deque to hold temporary records
'witness', # MsgRecord list of observed events
'on_enter_scope', # callback upon entering the scope
'on_exit_scope', # callback upon exiting the scope
'on_violation', # callback upon verdict of False
'on_success', # callback upon verdict of True
'time_launch', # when was the monitor launched
'time_shutdown', # when was the monitor shutdown
'time_state', # when did the last state transition occur
'cb_map', # mapping of topic names to callback functions
)
PROP_ID = 'None'
PROP_TITLE = '''None'''
PROP_DESC = '''None'''
HPL_PROPERTY = r'''until /q { True }: /a { phi } forbids /b { psi } within 0.1s'''
def __init__(self):
self._lock = Lock()
self._reset()
self.on_enter_scope = self._noop
self.on_exit_scope = self._noop
self.on_violation = self._noop
self.on_success = self._noop
self._state = 0
self.cb_map = {
'/b': self.on_msg__b,
'/q': self.on_msg__q,
'/a': self.on_msg__a,
}
@property
def verdict(self):
with self._lock:
if self._state == -1:
return True
if self._state == -2:
return False
return None
def on_launch(self, stamp):
with self._lock:
if self._state != 0:
raise RuntimeError('monitor is already turned on')
self._reset()
self.time_launch = stamp
self._state = 3
self.time_state = stamp
self.on_enter_scope(stamp)
return True
def on_shutdown(self, stamp):
with self._lock:
if self._state == 0:
raise RuntimeError('monitor is already turned off')
self.time_shutdown = stamp
self._state = 0
self.time_state = stamp
return True
def on_timer(self, stamp):
with self._lock:
if self._state == 2:
assert len(self._pool) >= 1, 'missing trigger event'
while self._pool and (stamp - self._pool[0].timestamp) >= 0.1:
self._pool.popleft()
if not self._pool:
self._state = 3
self.time_state = stamp
return True
def on_msg__b(self, msg, stamp):
with self._lock:
if self._state == 2:
assert len(self._pool) >= 1, 'missing trigger event'
while self._pool and (stamp - self._pool[0].timestamp) >= 0.1:
self._pool.popleft()
if not self._pool:
self._state = 3
self.time_state = stamp
if self._state == 2:
assert len(self._pool) >= 1, 'missing trigger event'
rec = self._pool[0]
if msg.psi:
self.witness.append(rec)
self.witness.append(MsgRecord('/b', stamp, msg))
self._pool.clear()
self._state = -2
self.time_state = stamp
self.on_violation(stamp, self.witness)
return True
return False
def on_msg__q(self, msg, stamp):
with self._lock:
if self._state == 2:
assert len(self._pool) >= 1, 'missing trigger event'
while self._pool and (stamp - self._pool[0].timestamp) >= 0.1:
self._pool.popleft()
if not self._pool:
self._state = 3
self.time_state = stamp
if self._state == 2:
self._pool.clear()
self.witness.append(MsgRecord('/q', stamp, msg))
self._state = -1
self.time_state = stamp
self.on_exit_scope(stamp)
self.on_success(stamp, self.witness)
return True
if self._state == 3:
self._pool.clear()
self.witness.append(MsgRecord('/q', stamp, msg))
self._state = -1
self.time_state = stamp
self.on_exit_scope(stamp)
self.on_success(stamp, self.witness)
return True
return False
def on_msg__a(self, msg, stamp):
with self._lock:
if self._state == 2:
assert len(self._pool) >= 1, 'missing trigger event'
while self._pool and (stamp - self._pool[0].timestamp) >= 0.1:
self._pool.popleft()
if not self._pool:
self._state = 3
self.time_state = stamp
if self._state == 2:
if msg.phi:
self._pool.append(MsgRecord('/a', stamp, msg))
return True
if self._state == 3:
if msg.phi:
self._pool.append(MsgRecord('/a', stamp, msg))
self._state = 2
self.time_state = stamp
return True
return False
def _reset(self):
self.witness = []
self._pool = deque((), 1)
self.time_launch = -1
self.time_shutdown = -1
self.time_state = -1
def _noop(self, *args):
pass
class PropertyMonitor(object):
__slots__ = (
'_lock', # concurrency control
'_state', # currently active state
'_pool', # MsgRecord deque to hold temporary records
'witness', # MsgRecord list of observed events
'on_enter_scope', # callback upon entering the scope
'on_exit_scope', # callback upon exiting the scope
'on_violation', # callback upon verdict of False
'on_success', # callback upon verdict of True
'time_launch', # when was the monitor launched
'time_shutdown', # when was the monitor shutdown
'time_state', # when did the last state transition occur
'cb_map', # mapping of topic names to callback functions
)
PROP_ID = 'None'
PROP_TITLE = '''None'''
PROP_DESC = '''None'''
HPL_PROPERTY = r'''until /b { True }: /a { True } forbids /b { True } within 0.1s'''
def __init__(self):
self._lock = Lock()
self._reset()
self.on_enter_scope = self._noop
self.on_exit_scope = self._noop
self.on_violation = self._noop
self.on_success = self._noop
self._state = 0
self.cb_map = {
'/b': self.on_msg__b,
'/a': self.on_msg__a,
}
@property
def verdict(self):
with self._lock:
if self._state == -1:
return True
if self._state == -2:
return False
return None
def on_launch(self, stamp):
with self._lock:
if self._state != 0:
raise RuntimeError('monitor is already turned on')
self._reset()
self.time_launch = stamp
self._state = 3
self.time_state = stamp
self.on_enter_scope(stamp)
return True
def on_shutdown(self, stamp):
with self._lock:
if self._state == 0:
raise RuntimeError('monitor is already turned off')
self.time_shutdown = stamp
self._state = 0
self.time_state = stamp
return True
def on_timer(self, stamp):
with self._lock:
if self._state == 2:
assert len(self._pool) >= 1, 'missing trigger event'
while self._pool and (stamp - self._pool[0].timestamp) >= 0.1:
self._pool.popleft()
if not self._pool:
self._state = 3
self.time_state = stamp
return True
def on_msg__b(self, msg, stamp):
with self._lock:
if self._state == 2:
assert len(self._pool) >= 1, 'missing trigger event'
while self._pool and (stamp - self._pool[0].timestamp) >= 0.1:
self._pool.popleft()
if not self._pool:
self._state = 3
self.time_state = stamp
if self._state == 2:
self._pool.clear()
self.witness.append(MsgRecord('/b', stamp, msg))
self._state = -1
self.time_state = stamp
self.on_exit_scope(stamp)
self.on_success(stamp, self.witness)
return True
assert len(self._pool) >= 1, 'missing trigger event'
rec = self._pool[0]
self.witness.append(rec)
self.witness.append(MsgRecord('/b', stamp, msg))
self._pool.clear()
self._state = -2
self.time_state = stamp
self.on_violation(stamp, self.witness)
return True
if self._state == 3:
self._pool.clear()
self.witness.append(MsgRecord('/b', stamp, msg))
self._state = -1
self.time_state = stamp
self.on_exit_scope(stamp)
self.on_success(stamp, self.witness)
return True
return False
def on_msg__a(self, msg, stamp):
with self._lock:
if self._state == 2:
assert len(self._pool) >= 1, 'missing trigger event'
while self._pool and (stamp - self._pool[0].timestamp) >= 0.1:
self._pool.popleft()
if not self._pool:
self._state = 3
self.time_state = stamp
if self._state == 2:
self._pool.append(MsgRecord('/a', stamp, msg))
return True
if self._state == 3:
self._pool.append(MsgRecord('/a', stamp, msg))
self._state = 2
self.time_state = stamp
return True
return False
def _reset(self):
self.witness = []
self._pool = deque((), 1)
self.time_launch = -1
self.time_shutdown = -1
self.time_state = -1
def _noop(self, *args):
pass
class PropertyMonitor(object):
__slots__ = (
'_lock', # concurrency control
'_state', # currently active state
'_pool', # MsgRecord deque to hold temporary records
'witness', # MsgRecord list of observed events
'on_enter_scope', # callback upon entering the scope
'on_exit_scope', # callback upon exiting the scope
'on_violation', # callback upon verdict of False
'on_success', # callback upon verdict of True
'time_launch', # when was the monitor launched
'time_shutdown', # when was the monitor shutdown
'time_state', # when did the last state transition occur
'cb_map', # mapping of topic names to callback functions
)
PROP_ID = 'None'
PROP_TITLE = '''None'''
PROP_DESC = '''None'''
HPL_PROPERTY = r'''until /a { True }: /a { True } forbids /b { True } within 0.1s'''
def __init__(self):
self._lock = Lock()
self._reset()
self.on_enter_scope = self._noop
self.on_exit_scope = self._noop
self.on_violation = self._noop
self.on_success = self._noop
self._state = 0
self.cb_map = {
'/b': self.on_msg__b,
'/a': self.on_msg__a,
}
@property
def verdict(self):
with self._lock:
if self._state == -1:
return True
if self._state == -2:
return False
return None
def on_launch(self, stamp):
with self._lock:
if self._state != 0:
raise RuntimeError('monitor is already turned on')
self._reset()
self.time_launch = stamp
self._state = 3
self.time_state = stamp
self.on_enter_scope(stamp)
return True
def on_shutdown(self, stamp):
with self._lock:
if self._state == 0:
raise RuntimeError('monitor is already turned off')
self.time_shutdown = stamp
self._state = 0
self.time_state = stamp
return True
def on_timer(self, stamp):
with self._lock:
if self._state == 2:
assert len(self._pool) >= 1, 'missing trigger event'
while self._pool and (stamp - self._pool[0].timestamp) >= 0.1:
self._pool.popleft()
if not self._pool:
self._state = 3
self.time_state = stamp
return True
def on_msg__b(self, msg, stamp):
with self._lock:
if self._state == 2:
assert len(self._pool) >= 1, 'missing trigger event'
while self._pool and (stamp - self._pool[0].timestamp) >= 0.1:
self._pool.popleft()
if not self._pool:
self._state = 3
self.time_state = stamp
if self._state == 2:
assert len(self._pool) >= 1, 'missing trigger event'
rec = self._pool[0]
self.witness.append(rec)
self.witness.append(MsgRecord('/b', stamp, msg))
self._pool.clear()
self._state = -2
self.time_state = stamp
self.on_violation(stamp, self.witness)
return True
return False
def on_msg__a(self, msg, stamp):
with self._lock:
if self._state == 2:
assert len(self._pool) >= 1, 'missing trigger event'
while self._pool and (stamp - self._pool[0].timestamp) >= 0.1:
self._pool.popleft()
if not self._pool:
self._state = 3
self.time_state = stamp
if self._state == 2:
self._pool.clear()
self.witness.append(MsgRecord('/a', stamp, msg))
self._state = -1
self.time_state = stamp
self.on_exit_scope(stamp)
self.on_success(stamp, self.witness)
return True
self._pool.append(MsgRecord('/a', stamp, msg))
return True
if self._state == 3:
self._pool.clear()
self.witness.append(MsgRecord('/a', stamp, msg))
self._state = -1
self.time_state = stamp
self.on_exit_scope(stamp)
self.on_success(stamp, self.witness)
return True
self._pool.append(MsgRecord('/a', stamp, msg))
self._state = 2
self.time_state = stamp
return True
return False
def _reset(self):
self.witness = []
self._pool = deque((), 1)
self.time_launch = -1
self.time_shutdown = -1
self.time_state = -1
def _noop(self, *args):
pass
class PropertyMonitor(object):
__slots__ = (
'_lock', # concurrency control
'_state', # currently active state
'_pool', # MsgRecord deque to hold temporary records
'witness', # MsgRecord list of observed events
'on_enter_scope', # callback upon entering the scope
'on_exit_scope', # callback upon exiting the scope
'on_violation', # callback upon verdict of False
'on_success', # callback upon verdict of True
'time_launch', # when was the monitor launched
'time_shutdown', # when was the monitor shutdown
'time_state', # when did the last state transition occur
'cb_map', # mapping of topic names to callback functions
)
PROP_ID = 'None'
PROP_TITLE = '''None'''
PROP_DESC = '''None'''
HPL_PROPERTY = r'''after /p { phi } until /q { psi }: /a { alpha } forbids /b { beta }'''
def __init__(self):
self._lock = Lock()
self._reset()
self.on_enter_scope = self._noop
self.on_exit_scope = self._noop
self.on_violation = self._noop
self.on_success = self._noop
self._state = 0
self.cb_map = {
'/a': self.on_msg__a,
'/b': self.on_msg__b,
'/q': self.on_msg__q,
'/p': self.on_msg__p,
}
@property
def verdict(self):
with self._lock:
if self._state == -1:
return True
if self._state == -2:
return False
return None
def on_launch(self, stamp):
with self._lock:
if self._state != 0:
raise RuntimeError('monitor is already turned on')
self._reset()
self.time_launch = stamp
self._state = 1
self.time_state = stamp
return True
def on_shutdown(self, stamp):
with self._lock:
if self._state == 0:
raise RuntimeError('monitor is already turned off')
self.time_shutdown = stamp
self._state = 0
self.time_state = stamp
return True
def on_timer(self, stamp):
return True
def on_msg__a(self, msg, stamp):
with self._lock:
if self._state == 2:
return False # nothing to do
if self._state == 3:
if msg.alpha:
self._pool.append(MsgRecord('/a', stamp, msg))
self._state = 2
self.time_state = stamp
return True
return False
def on_msg__b(self, msg, stamp):
with self._lock:
if self._state == 2:
assert len(self._pool) >= 1, 'missing trigger event'
rec = self._pool[0]
if msg.beta:
self.witness.append(rec)
self.witness.append(MsgRecord('/b', stamp, msg))
self._pool.clear()
self._state = -2
self.time_state = stamp
self.on_violation(stamp, self.witness)
return True
return False
def on_msg__q(self, msg, stamp):
with self._lock:
if self._state == 2:
if msg.psi:
self._pool.clear()
self.witness = []
self._state = 1
self.time_state = stamp
self.on_exit_scope(stamp)
return True
if self._state == 3:
if msg.psi:
self._pool.clear()
self.witness = []
self._state = 1
self.time_state = stamp
self.on_exit_scope(stamp)
return True
return False
def on_msg__p(self, msg, stamp):
with self._lock:
if self._state == 1:
if msg.phi:
self.witness.append(MsgRecord('/p', stamp, msg))
self._state = 3
self.time_state = stamp
self.on_enter_scope(stamp)
return True
return False
def _reset(self):
self.witness = []
self._pool = deque((), 1)
self.time_launch = -1
self.time_shutdown = -1
self.time_state = -1
def _noop(self, *args):
pass
class PropertyMonitor(object):
__slots__ = (
'_lock', # concurrency control
'_state', # currently active state
'_pool', # MsgRecord deque to hold temporary records
'witness', # MsgRecord list of observed events
'on_enter_scope', # callback upon entering the scope
'on_exit_scope', # callback upon exiting the scope
'on_violation', # callback upon verdict of False
'on_success', # callback upon verdict of True
'time_launch', # when was the monitor launched
'time_shutdown', # when was the monitor shutdown
'time_state', # when did the last state transition occur
'cb_map', # mapping of topic names to callback functions
)
PROP_ID = 'None'
PROP_TITLE = '''None'''
PROP_DESC = '''None'''
HPL_PROPERTY = r'''after /p { phi } until /q { psi }: /a { alpha } forbids /b { beta } within 0.1s'''
def __init__(self):
self._lock = Lock()
self._reset()
self.on_enter_scope = self._noop
self.on_exit_scope = self._noop
self.on_violation = self._noop
self.on_success = self._noop
self._state = 0
self.cb_map = {
'/a': self.on_msg__a,
'/b': self.on_msg__b,
'/q': self.on_msg__q,
'/p': self.on_msg__p,
}
@property
def verdict(self):
with self._lock:
if self._state == -1:
return True
if self._state == -2:
return False
return None
def on_launch(self, stamp):
with self._lock:
if self._state != 0:
raise RuntimeError('monitor is already turned on')
self._reset()
self.time_launch = stamp
self._state = 1
self.time_state = stamp
return True
def on_shutdown(self, stamp):
with self._lock:
if self._state == 0:
raise RuntimeError('monitor is already turned off')
self.time_shutdown = stamp
self._state = 0
self.time_state = stamp
return True
def on_timer(self, stamp):
with self._lock:
if self._state == 2:
assert len(self._pool) >= 1, 'missing trigger event'
while self._pool and (stamp - self._pool[0].timestamp) >= 0.1:
self._pool.popleft()
if not self._pool:
self._state = 3
self.time_state = stamp
return True
def on_msg__a(self, msg, stamp):
with self._lock:
if self._state == 2:
assert len(self._pool) >= 1, 'missing trigger event'
while self._pool and (stamp - self._pool[0].timestamp) >= 0.1:
self._pool.popleft()
if not self._pool:
self._state = 3
self.time_state = stamp
if self._state == 2:
if msg.alpha:
self._pool.append(MsgRecord('/a', stamp, msg))
return True
if self._state == 3:
if msg.alpha:
self._pool.append(MsgRecord('/a', stamp, msg))
self._state = 2
self.time_state = stamp
return True
return False
def on_msg__b(self, msg, stamp):
with self._lock:
if self._state == 2:
assert len(self._pool) >= 1, 'missing trigger event'
while self._pool and (stamp - self._pool[0].timestamp) >= 0.1:
self._pool.popleft()
if not self._pool:
self._state = 3
self.time_state = stamp
if self._state == 2:
assert len(self._pool) >= 1, 'missing trigger event'
rec = self._pool[0]
if msg.beta:
self.witness.append(rec)
self.witness.append(MsgRecord('/b', stamp, msg))
self._pool.clear()
self._state = -2
self.time_state = stamp
self.on_violation(stamp, self.witness)
return True
return False
def on_msg__q(self, msg, stamp):
with self._lock:
if self._state == 2:
assert len(self._pool) >= 1, 'missing trigger event'
while self._pool and (stamp - self._pool[0].timestamp) >= 0.1:
self._pool.popleft()
if not self._pool:
self._state = 3
self.time_state = stamp
if self._state == 2:
if msg.psi:
self._pool.clear()
self.witness = []
self._state = 1
self.time_state = stamp
self.on_exit_scope(stamp)
return True
if self._state == 3:
if msg.psi:
self._pool.clear()
self.witness = []
self._state = 1
self.time_state = stamp
self.on_exit_scope(stamp)
return True
return False
def on_msg__p(self, msg, stamp):
with self._lock:
if self._state == 2:
assert len(self._pool) >= 1, 'missing trigger event'
while self._pool and (stamp - self._pool[0].timestamp) >= 0.1:
self._pool.popleft()
if not self._pool:
self._state = 3
self.time_state = stamp
if self._state == 1:
if msg.phi:
self.witness.append(MsgRecord('/p', stamp, msg))
self._state = 3
self.time_state = stamp
self.on_enter_scope(stamp)
return True
return False
def _reset(self):
self.witness = []
self._pool = deque((), 1)
self.time_launch = -1
self.time_shutdown = -1
self.time_state = -1
def _noop(self, *args):
pass
class PropertyMonitor(object):
__slots__ = (
'_lock', # concurrency control
'_state', # currently active state
'_pool', # MsgRecord deque to hold temporary records
'witness', # MsgRecord list of observed events
'on_enter_scope', # callback upon entering the scope
'on_exit_scope', # callback upon exiting the scope
'on_violation', # callback upon verdict of False
'on_success', # callback upon verdict of True
'time_launch', # when was the monitor launched
'time_shutdown', # when was the monitor shutdown
'time_state', # when did the last state transition occur
'cb_map', # mapping of topic names to callback functions
)
PROP_ID = 'None'
PROP_TITLE = '''None'''
PROP_DESC = '''None'''
HPL_PROPERTY = r'''globally: /a as A { True } forbids /b { (x < @A.x) }'''
def __init__(self):
self._lock = Lock()
self._reset()
self.on_enter_scope = self._noop
self.on_exit_scope = self._noop
self.on_violation = self._noop
self.on_success = self._noop
self._state = 0
self.cb_map = {
'/b': self.on_msg__b,
'/a': self.on_msg__a,
}
@property
def verdict(self):
with self._lock:
if self._state == -1:
return True
if self._state == -2:
return False
return None
def on_launch(self, stamp):
with self._lock:
if self._state != 0:
raise RuntimeError('monitor is already turned on')
self._reset()
self.time_launch = stamp
self._state = 3
self.time_state = stamp
self.on_enter_scope(stamp)
return True
def on_shutdown(self, stamp):
with self._lock:
if self._state == 0:
raise RuntimeError('monitor is already turned off')
self.time_shutdown = stamp
self._state = 0
self.time_state = stamp
return True
def on_timer(self, stamp):
return True
def on_msg__b(self, msg, stamp):
with self._lock:
if self._state == 2:
assert len(self._pool) >= 1, 'missing trigger event'
for rec in self._pool:
v_A = rec.msg
if (msg.x < v_A.x):
self.witness.append(rec)
self.witness.append(MsgRecord('/b', stamp, msg))
self._pool.clear()
self._state = -2
self.time_state = stamp
self.on_violation(stamp, self.witness)
return True
return False
def on_msg__a(self, msg, stamp):
with self._lock:
if self._state == 2:
rec = MsgRecord('/a', stamp, msg)
self._pool_insert(rec)
return True
if self._state == 3:
rec = MsgRecord('/a', stamp, msg)
self._pool_insert(rec)
self._state = 2
self.time_state = stamp
return True
return False
def _reset(self):
self.witness = []
self._pool = deque()
self.time_launch = -1
self.time_shutdown = -1
self.time_state = -1
def _pool_insert(self, rec):
# this method is only needed to ensure Python 2.7 compatibility
if not self._pool:
return self._pool.append(rec)
stamp = rec.timestamp
if len(self._pool) == 1:
if stamp >= self._pool[0].timestamp:
return self._pool.append(rec)
return self._pool.appendleft(rec)
for i in range(len(self._pool), 0, -1):
if stamp >= self._pool[i-1].timestamp:
try:
self._pool.insert(i, rec) # Python >= 3.5
except AttributeError as e:
tmp = [self._pool.pop() for j in range(i, len(self._pool))]
self._pool.append(rec)
self._pool.extend(reversed(tmp))
break
else:
self._pool.appendleft(rec)
def _noop(self, *args):
pass
class PropertyMonitor(object):
__slots__ = (
'_lock', # concurrency control
'_state', # currently active state
'_pool', # MsgRecord deque to hold temporary records
'witness', # MsgRecord list of observed events
'on_enter_scope', # callback upon entering the scope
'on_exit_scope', # callback upon exiting the scope
'on_violation', # callback upon verdict of False
'on_success', # callback upon verdict of True
'time_launch', # when was the monitor launched
'time_shutdown', # when was the monitor shutdown
'time_state', # when did the last state transition occur
'cb_map', # mapping of topic names to callback functions
)
PROP_ID = 'None'
PROP_TITLE = '''None'''
PROP_DESC = '''None'''
HPL_PROPERTY = r'''globally: /a as A { (x > 0) } forbids /b { (x < @A.x) } within 0.1s'''
def __init__(self):
self._lock = Lock()
self._reset()
self.on_enter_scope = self._noop
self.on_exit_scope = self._noop
self.on_violation = self._noop
self.on_success = self._noop
self._state = 0
self.cb_map = {
'/b': self.on_msg__b,
'/a': self.on_msg__a,
}
@property
def verdict(self):
with self._lock:
if self._state == -1:
return True
if self._state == -2:
return False
return None
def on_launch(self, stamp):
with self._lock:
if self._state != 0:
raise RuntimeError('monitor is already turned on')
self._reset()
self.time_launch = stamp
self._state = 3
self.time_state = stamp
self.on_enter_scope(stamp)
return True
def on_shutdown(self, stamp):
with self._lock:
if self._state == 0:
raise RuntimeError('monitor is already turned off')
self.time_shutdown = stamp
self._state = 0
self.time_state = stamp
return True
def on_timer(self, stamp):
with self._lock:
if self._state == 2:
assert len(self._pool) >= 1, 'missing trigger event'
while self._pool and (stamp - self._pool[0].timestamp) >= 0.1:
self._pool.popleft()
if not self._pool:
self._state = 3
self.time_state = stamp
return True
def on_msg__b(self, msg, stamp):
with self._lock:
if self._state == 2:
assert len(self._pool) >= 1, 'missing trigger event'
while self._pool and (stamp - self._pool[0].timestamp) >= 0.1:
self._pool.popleft()
if not self._pool:
self._state = 3
self.time_state = stamp
if self._state == 2:
assert len(self._pool) >= 1, 'missing trigger event'
for rec in self._pool:
v_A = rec.msg
if (msg.x < v_A.x):
self.witness.append(rec)
self.witness.append(MsgRecord('/b', stamp, msg))
self._pool.clear()
self._state = -2
self.time_state = stamp
self.on_violation(stamp, self.witness)
return True
return False
def on_msg__a(self, msg, stamp):
with self._lock:
if self._state == 2:
assert len(self._pool) >= 1, 'missing trigger event'
while self._pool and (stamp - self._pool[0].timestamp) >= 0.1:
self._pool.popleft()
if not self._pool:
self._state = 3
self.time_state = stamp
if self._state == 2:
if (msg.x > 0):
rec = MsgRecord('/a', stamp, msg)
self._pool_insert(rec)
return True
if self._state == 3:
if (msg.x > 0):
rec = MsgRecord('/a', stamp, msg)
self._pool_insert(rec)
self._state = 2
self.time_state = stamp
return True
return False
def _reset(self):
self.witness = []
self._pool = deque()
self.time_launch = -1
self.time_shutdown = -1
self.time_state = -1
def _pool_insert(self, rec):
# this method is only needed to ensure Python 2.7 compatibility
if not self._pool:
return self._pool.append(rec)
stamp = rec.timestamp
if len(self._pool) == 1:
if stamp >= self._pool[0].timestamp:
return self._pool.append(rec)
return self._pool.appendleft(rec)
for i in range(len(self._pool), 0, -1):
if stamp >= self._pool[i-1].timestamp:
try:
self._pool.insert(i, rec) # Python >= 3.5
except AttributeError as e:
tmp = [self._pool.pop() for j in range(i, len(self._pool))]
self._pool.append(rec)
self._pool.extend(reversed(tmp))
break
else:
self._pool.appendleft(rec)
def _noop(self, *args):
pass
class PropertyMonitor(object):
__slots__ = (
'_lock', # concurrency control
'_state', # currently active state
'_pool', # MsgRecord deque to hold temporary records
'witness', # MsgRecord list of observed events
'on_enter_scope', # callback upon entering the scope
'on_exit_scope', # callback upon exiting the scope
'on_violation', # callback upon verdict of False
'on_success', # callback upon verdict of True
'time_launch', # when was the monitor launched
'time_shutdown', # when was the monitor shutdown
'time_state', # when did the last state transition occur
'cb_map', # mapping of topic names to callback functions
)
PROP_ID = 'None'
PROP_TITLE = '''None'''
PROP_DESC = '''None'''
HPL_PROPERTY = r'''globally: /a as A { (x > 0) } forbids (/b1 { (x < @A.x) } or /b2 { (y < @A.y) }) within 0.1s'''
def __init__(self):
self._lock = Lock()
self._reset()
self.on_enter_scope = self._noop
self.on_exit_scope = self._noop
self.on_violation = self._noop
self.on_success = self._noop
self._state = 0
self.cb_map = {
'/b2': self.on_msg__b2,
'/a': self.on_msg__a,
'/b1': self.on_msg__b1,
}
@property
def verdict(self):
with self._lock:
if self._state == -1:
return True
if self._state == -2:
return False
return None
def on_launch(self, stamp):
with self._lock:
if self._state != 0:
raise RuntimeError('monitor is already turned on')
self._reset()
self.time_launch = stamp
self._state = 3
self.time_state = stamp
self.on_enter_scope(stamp)
return True
def on_shutdown(self, stamp):
with self._lock:
if self._state == 0:
raise RuntimeError('monitor is already turned off')
self.time_shutdown = stamp
self._state = 0
self.time_state = stamp
return True
def on_timer(self, stamp):
with self._lock:
if self._state == 2:
assert len(self._pool) >= 1, 'missing trigger event'
while self._pool and (stamp - self._pool[0].timestamp) >= 0.1:
self._pool.popleft()
if not self._pool:
self._state = 3
self.time_state = stamp
return True
def on_msg__b2(self, msg, stamp):
with self._lock:
if self._state == 2:
assert len(self._pool) >= 1, 'missing trigger event'
while self._pool and (stamp - self._pool[0].timestamp) >= 0.1:
self._pool.popleft()
if not self._pool:
self._state = 3
self.time_state = stamp
if self._state == 2:
assert len(self._pool) >= 1, 'missing trigger event'
for rec in self._pool:
v_A = rec.msg
if (msg.y < v_A.y):
self.witness.append(rec)
self.witness.append(MsgRecord('/b2', stamp, msg))
self._pool.clear()
self._state = -2
self.time_state = stamp
self.on_violation(stamp, self.witness)
return True
return False
def on_msg__a(self, msg, stamp):
with self._lock:
if self._state == 2:
assert len(self._pool) >= 1, 'missing trigger event'
while self._pool and (stamp - self._pool[0].timestamp) >= 0.1:
self._pool.popleft()
if not self._pool:
self._state = 3
self.time_state = stamp
if self._state == 2:
if (msg.x > 0):
rec = MsgRecord('/a', stamp, msg)
self._pool_insert(rec)
return True
if self._state == 3:
if (msg.x > 0):
rec = MsgRecord('/a', stamp, msg)
self._pool_insert(rec)
self._state = 2
self.time_state = stamp
return True
return False
def on_msg__b1(self, msg, stamp):
with self._lock:
if self._state == 2:
assert len(self._pool) >= 1, 'missing trigger event'
while self._pool and (stamp - self._pool[0].timestamp) >= 0.1:
self._pool.popleft()
if not self._pool:
self._state = 3
self.time_state = stamp
if self._state == 2:
assert len(self._pool) >= 1, 'missing trigger event'
for rec in self._pool:
v_A = rec.msg
if (msg.x < v_A.x):
self.witness.append(rec)
self.witness.append(MsgRecord('/b1', stamp, msg))
self._pool.clear()
self._state = -2
self.time_state = stamp
self.on_violation(stamp, self.witness)
return True
return False
def _reset(self):
self.witness = []
self._pool = deque()
self.time_launch = -1
self.time_shutdown = -1
self.time_state = -1
def _pool_insert(self, rec):
# this method is only needed to ensure Python 2.7 compatibility
if not self._pool:
return self._pool.append(rec)
stamp = rec.timestamp
if len(self._pool) == 1:
if stamp >= self._pool[0].timestamp:
return self._pool.append(rec)
return self._pool.appendleft(rec)
for i in range(len(self._pool), 0, -1):
if stamp >= self._pool[i-1].timestamp:
try:
self._pool.insert(i, rec) # Python >= 3.5
except AttributeError as e:
tmp = [self._pool.pop() for j in range(i, len(self._pool))]
self._pool.append(rec)
self._pool.extend(reversed(tmp))
break
else:
self._pool.appendleft(rec)
def _noop(self, *args):
pass
class PropertyMonitor(object):
__slots__ = (
'_lock', # concurrency control
'_state', # currently active state
'_pool', # MsgRecord deque to hold temporary records
'witness', # MsgRecord list of observed events
'on_enter_scope', # callback upon entering the scope
'on_exit_scope', # callback upon exiting the scope
'on_violation', # callback upon verdict of False
'on_success', # callback upon verdict of True
'time_launch', # when was the monitor launched
'time_shutdown', # when was the monitor shutdown
'time_state', # when did the last state transition occur
'cb_map', # mapping of topic names to callback functions
)
PROP_ID = 'None'
PROP_TITLE = '''None'''
PROP_DESC = '''None'''
HPL_PROPERTY = r'''after /p as P { True } until /q { (x > @P.x) }: /a as A { (x = @P.x) } forbids (/b1 { (x < (@A.x + @P.x)) } or /b2 { (x in {@P.x, @A.x}) }) within 0.1s'''
def __init__(self):
self._lock = Lock()
self._reset()
self.on_enter_scope = self._noop
self.on_exit_scope = self._noop
self.on_violation = self._noop
self.on_success = self._noop
self._state = 0
self.cb_map = {
'/b1': self.on_msg__b1,
'/b2': self.on_msg__b2,
'/a': self.on_msg__a,
'/q': self.on_msg__q,
'/p': self.on_msg__p,
}
@property
def verdict(self):
with self._lock:
if self._state == -1:
return True
if self._state == -2:
return False
return None
def on_launch(self, stamp):
with self._lock:
if self._state != 0:
raise RuntimeError('monitor is already turned on')
self._reset()
self.time_launch = stamp
self._state = 1
self.time_state = stamp
return True
def on_shutdown(self, stamp):
with self._lock:
if self._state == 0:
raise RuntimeError('monitor is already turned off')
self.time_shutdown = stamp
self._state = 0
self.time_state = stamp
return True
def on_timer(self, stamp):
with self._lock:
if self._state == 2:
assert len(self._pool) >= 1, 'missing trigger event'
while self._pool and (stamp - self._pool[0].timestamp) >= 0.1:
self._pool.popleft()
if not self._pool:
self._state = 3
self.time_state = stamp
return True
def on_msg__b1(self, msg, stamp):
with self._lock:
if self._state == 2:
assert len(self._pool) >= 1, 'missing trigger event'
while self._pool and (stamp - self._pool[0].timestamp) >= 0.1:
self._pool.popleft()
if not self._pool:
self._state = 3
self.time_state = stamp
if self._state == 2:
assert len(self._pool) >= 1, 'missing trigger event'
assert len(self.witness) >= 1, 'missing activator event'
v_P = self.witness[0].msg
for rec in self._pool:
v_A = rec.msg
if (msg.x < (v_A.x + v_P.x)):
self.witness.append(rec)
self.witness.append(MsgRecord('/b1', stamp, msg))
self._pool.clear()
self._state = -2
self.time_state = stamp
self.on_violation(stamp, self.witness)
return True
return False
def on_msg__b2(self, msg, stamp):
with self._lock:
if self._state == 2:
assert len(self._pool) >= 1, 'missing trigger event'
while self._pool and (stamp - self._pool[0].timestamp) >= 0.1:
self._pool.popleft()
if not self._pool:
self._state = 3
self.time_state = stamp
if self._state == 2:
assert len(self._pool) >= 1, 'missing trigger event'
assert len(self.witness) >= 1, 'missing activator event'
v_P = self.witness[0].msg
for rec in self._pool:
v_A = rec.msg
if (msg.x in (v_P.x, v_A.x)):
self.witness.append(rec)
self.witness.append(MsgRecord('/b2', stamp, msg))
self._pool.clear()
self._state = -2
self.time_state = stamp
self.on_violation(stamp, self.witness)
return True
return False
def on_msg__a(self, msg, stamp):
with self._lock:
if self._state == 2:
assert len(self._pool) >= 1, 'missing trigger event'
while self._pool and (stamp - self._pool[0].timestamp) >= 0.1:
self._pool.popleft()
if not self._pool:
self._state = 3
self.time_state = stamp
if self._state == 2:
assert len(self.witness) >= 1, 'missing activator'
v_P = self.witness[0].msg
if (msg.x == v_P.x):
rec = MsgRecord('/a', stamp, msg)
self._pool_insert(rec)
return True
if self._state == 3:
assert len(self.witness) >= 1, 'missing activator'
v_P = self.witness[0].msg
if (msg.x == v_P.x):
rec = MsgRecord('/a', stamp, msg)
self._pool_insert(rec)
self._state = 2
self.time_state = stamp
return True
return False
def on_msg__q(self, msg, stamp):
with self._lock:
if self._state == 2:
assert len(self._pool) >= 1, 'missing trigger event'
while self._pool and (stamp - self._pool[0].timestamp) >= 0.1:
self._pool.popleft()
if not self._pool:
self._state = 3
self.time_state = stamp
if self._state == 2:
assert len(self.witness) >= 1, 'missing activator event'
v_P = self.witness[0].msg
if (msg.x > v_P.x):
self._pool.clear()
self.witness = []
self._state = 1
self.time_state = stamp
self.on_exit_scope(stamp)
return True
if self._state == 3:
assert len(self.witness) >= 1, 'missing activator event'
v_P = self.witness[0].msg
if (msg.x > v_P.x):
self._pool.clear()
self.witness = []
self._state = 1
self.time_state = stamp
self.on_exit_scope(stamp)
return True
return False
def on_msg__p(self, msg, stamp):
with self._lock:
if self._state == 2:
assert len(self._pool) >= 1, 'missing trigger event'
while self._pool and (stamp - self._pool[0].timestamp) >= 0.1:
self._pool.popleft()
if not self._pool:
self._state = 3
self.time_state = stamp
if self._state == 1:
self.witness.append(MsgRecord('/p', stamp, msg))
self._state = 3
self.time_state = stamp
self.on_enter_scope(stamp)
return True
return False
def _reset(self):
self.witness = []
self._pool = deque()
self.time_launch = -1
self.time_shutdown = -1
self.time_state = -1
def _pool_insert(self, rec):
# this method is only needed to ensure Python 2.7 compatibility
if not self._pool:
return self._pool.append(rec)
stamp = rec.timestamp
if len(self._pool) == 1:
if stamp >= self._pool[0].timestamp:
return self._pool.append(rec)
return self._pool.appendleft(rec)
for i in range(len(self._pool), 0, -1):
if stamp >= self._pool[i-1].timestamp:
try:
self._pool.insert(i, rec) # Python >= 3.5
except AttributeError as e:
tmp = [self._pool.pop() for j in range(i, len(self._pool))]
self._pool.append(rec)
self._pool.extend(reversed(tmp))
break
else:
self._pool.appendleft(rec)
def _noop(self, *args):
pass
|
le = 0
notas = 0
while le != 2:
n = float(input())
if 0 <= n <= 10:
notas = notas+n
le += 1
else:
print('nota invalida')
print('media = {:.2f}'.format((notas/2)))
|
class CustomHandling:
"""
A decorator that wraps the passed in function. Will push exceptions to
a queue.
"""
def __init__(self, queue):
self.queue = queue
def __call__(self, func):
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except (KeyboardInterrupt, SystemExit):
pass
except Exception as error:
err = func.__name__
self.queue.put((err, error))
raise
return wrapper
|
def ipaddr(interface=None):
'''
Returns the IP address for a given interface
CLI Example::
salt '*' network.ipaddr eth0
'''
iflist = interfaces()
out = None
if interface:
data = iflist.get(interface) or dict()
if data.get('inet'):
return data.get('inet')[0]['address']
if data.get('inet6'):
return data.get('inet6')[0]['address']
return out
out = dict()
for iface, data in iflist.items():
if data.get('inet'):
out[iface] = data.get('inet')[0]['address']
continue
if data.get('inet6'):
out[iface] = data.get('inet6')[0]['address']
continue
return out
def netmask(interface):
'''
Returns the netmask for a given interface
CLI Example::
salt '*' network.netmask eth0
'''
out = list()
data = interfaces().get(interface)
if data.get('inet'):
for addrinfo in data.get('inet'):
if addrinfo.get('netmask'):
out.append(addrinfo['netmask'])
if data.get('inet6'):
# TODO: This should return the prefix for the address
pass
return out or None
def hwaddr(interface):
'''
Returns the hwaddr for a given interface
CLI Example::
salt '*' network.hwaddr eth0
'''
data = interfaces().get(interface) or {}
return data.get('hwaddr')
def up(interface):
'''
Returns True if interface is up, otherwise returns False
CLI Example::
salt '*' network.up eth0
'''
data = interfaces().get(interface) or {}
return data.get('up')
|
def generate(env, **kw):
if not kw.get('depsOnly',0):
env.Tool('addLibrary', library=['astro'], package = 'astro')
if env['PLATFORM'] == 'win32'and env.get('CONTAINERNAME','')=='GlastRelease':
env.Tool('findPkgPath', package = 'astro')
env.Tool('facilitiesLib')
env.Tool('tipLib')
env.Tool('addLibrary', library=env['clhepLibs'])
env.Tool('addLibrary', library=env['cfitsioLibs'])
# EAC, add wcslib and healpix as externals
env.Tool('addLibrary', library=env['wcslibs'])
env.Tool('addLibrary', library=env['healpixlibs'])
def exists(env):
return 1
|
def cvt(s):
if isinstance(s, str):
return unicode(s)
return s
class GWTCanvasImplDefault:
def createElement(self):
e = DOM.createElement("CANVAS")
try:
# This results occasionally in an error:
# AttributeError: XPCOM component '<unknown>' has no attribute 'MozGetIPCContext'
self.setCanvasContext(e.MozGetIPCContext(u'2d'))
except AttributeError:
# In which case this seems to work:
self.setCanvasContext(e.getContext('2d'))
return e
|
def create_category(base_cls):
class Category(base_cls):
__tablename__ = 'category'
__table_args__ = {'autoload': True}
@property
def serialize(self):
"""Return object data in easily serializeable format"""
return {
'Category_name': self.name,
'Category_id': self.id
}
return Category |
"""
File: boggle.py
Name:
----------------------------------------
TODO:
"""
# This is the file name of the dictionary txt file
# we will be checking if a word exists by searching through it
FILE = 'dictionary.txt'
lst = []
enter_lst = []
d = {} # A dict contain the alphabets in boggle games
ans_lst = []
found_words = 0
def main():
"""
TODO:
# """
global lst, enter_lst, d
read_dictionary()
row_num = 1
while True:
if row_num <= 4:
enter = input(f'{row_num} row of letters: ')
if enter == '-1':
break
enter = enter.lower() # Case Insensitive
enter = enter.split(' ')
if illegal_input(enter):
print('Illegal input')
break
enter_lst += enter
row_num += 1
else:
break
created_boggle(enter_lst)
for key in d:
x = key[0]
y = key[1]
play_boggle(x, y, d[(x, y)], [(x, y)])
print(f'There are {found_words} words in total.')
def play_boggle(x, y, ans, previous_lst):
global lst, ans_lst, found_words
if len(ans) >= 4:
if ans in lst:
# Base Case
if ans not in ans_lst:
print(f'Found: "{ans}"')
ans_lst.append(ans)
found_words += 1
if has_prefix(ans):
# For ans has prefix e.g room -> roomy
b_lst = beside_dict(x, y, previous_lst)
for i in range(len(b_lst)):
ans += d[b_lst[i]]
new_x = b_lst[i][0]
new_y = b_lst[i][1]
previous_lst.append((new_x, new_y))
play_boggle(new_x, new_y, ans, previous_lst)
previous_lst.pop()
ans = ans[:len(ans) - 1]
return ans_lst
else:
if has_prefix(ans):
b_lst = beside_dict(x, y, previous_lst)
for i in range(len(b_lst)):
ans += d[b_lst[i]]
new_x = b_lst[i][0]
new_y = b_lst[i][1]
previous_lst.append((new_x, new_y))
play_boggle(new_x, new_y, ans, previous_lst)
previous_lst.pop()
ans = ans[:len(ans) - 1]
return ans_lst
else:
if has_prefix(ans):
b_lst = beside_dict(x, y, previous_lst)
# chose
for i in range(len(b_lst)):
ans += d[b_lst[i]]
# Update the new x, y position
new_x = b_lst[i][0]
new_y = b_lst[i][1]
previous_lst.append((new_x, new_y))
# explore
play_boggle(new_x, new_y, ans, previous_lst)
# Un-choose
previous_lst.pop()
ans = ans[:len(ans) - 1]
return ans_lst
def beside_dict(x, y, previous_lst):
"""
:param x: x position in boggle
:param y: y position in boggle
:param previous_lst: to save the alphabet already use
:return: a list of position need to be explore in boggle game
"""
beside_lst = []
for i in range(-1, 2, 1):
for j in range(-1, 2, 1):
if i == 0 and j == 0:
# For the self position
pass
else:
position_x = x + i
position_y = y + j
if 0 <= position_x < 4:
if 0 <= position_y < 4:
if (position_x, position_y) in previous_lst:
# To prevent adding the alphabet that already used
pass
else:
beside_lst.append((position_x, position_y))
return beside_lst
def created_boggle(e_lst):
"""
:param e_lst: List which contains the enter 16 alphabets
:return: A dict contain the alphabets in boggle games and also thew position for each alphabets
"""
global d
for j in range(4):
for i in range(4):
d[(i, j)] = e_lst[4*j + i]
return d
def illegal_input(enter):
if len(enter) != 4:
return True
for ch in enter:
if len(ch) != 1:
return True
return False
def read_dictionary():
"""
This function reads file "dictionary.txt" stored in FILE
and appends words in each line into a Python list
"""
global lst
with open(FILE, 'r') as f:
for line in f:
line = line.split()
lst += line
def has_prefix(sub_s):
"""
:param sub_s: (str) A substring that is constructed by neighboring letters on a 4x4 square grid
:return: (bool) If there is any words with prefix stored in sub_s
"""
global lst
for word in lst:
if word.startswith(sub_s):
return True
return False
if __name__ == '__main__':
main()
|
# DSAME prob #40
class Node:
def __init__(self, data=None, next=None):
self.data = data
self.next = next
def get_josephus_pos():
q = p = Node()
n = int(input("Enter no of players: "))
m = int(input("Enter which player needs to be eliminated each time:"))
# create cll containing all players
p.data = 1
p.next = Node()
for i in range(2, n):
p.next = Node()
p = p.next
p.data = i
p.next = q
for count in range (n, 1, -1):
for i in range(0, m-1):
p = p.next
p.next = p.next.next
print("Last player standing is {}".format(p.data))
if __name__ == '__main__':
get_josephus_pos()
|
'''LC459:Repeated Substr pattern
https://leetcode.com/problems/repeated-substring-pattern/
Given a non-empty string check if it can be constructed by
taking a substring of it and appending multiple copies of the
substring together. You may assume the given string consists
of lowercase English letters only and its length will not exceed 10000.
Example 1:
Input: "abab"
Output: True
Explanation: It's the substring "ab" twice.
Example 2:
Input: "aba"
Output: False
Example 3:
Input: "abcabcabcabc"
Output: True
Explanation: It's the substring "abc" four times. (And the substring "abcabc" twice.)'''
class Sln:
def repeatedSubstringPattern(self, str):
"""
:type str: str
:rtype: bool
"""
if not str:
return False
ss = (str + str)[1:-1]
return ss.find(str) != -1 |
a=float(input())
b=float(input())
if a<b:
print(a)
else:
print(b) |
# -*- coding: utf-8 -*-
print(""" Atm'ye Hoşgeldiniz....
Para Çekmek için : 1
Para Yatırmak için : 2
Bakiye Sorgulamak İçin : 3
Kart iadesi için : "ç"
""")
bakiye = 0
while True:
islem = input("Yapmak istediğiniz işlemi seçiniz...")
if islem == "1":
miktar = int(input("Çekmek istediğiniz Miktar? : "))
if miktar > bakiye:
print("Bakiye Yetersiz Menüye Yönlendiriliyorsunuz...")
continue
bakiye -= miktar
elif islem == "2":
miktar1 = int(input("Yatırmak istediğiniz Miktar? : "))
bakiye += miktar1
elif islem == "3":
print("Bakiyeniz",bakiye)
elif islem == "ç":
print("Kartınız İade Ediliyor...")
break
else:
print("Geçersiz İşlem") |
def grammar():
return [
'progStructure',
'name',
'body',
'instruction',
'moreInstruction',
'functionCall',
'parameter',
'moreParameter',
'parameterType'
]
def progStructure(self):
self.name()
self.match( ('reserved_word', 'INICIO') )
self.body()
self.match( ('reserved_word', 'FIN') )
def name(self):
self.match( ('reserved_word', 'PROGRAMA') )
self.match( 'id' )
def body(self):
self.instruction()
self.moreInstruction()
def instruction(self):
self.functionCall()
def moreInstruction(self):
if( self.token['type'] == 'function' ):
self.body()
def functionCall(self):
func_call = {}
self.logger.info('function')
func_call['type'] = self.token['type']
func_call['name'] = self.token['lexeme']
self.match('function')
self.match('parentesis_a')
func_call['parameters'] = self.parameter()
self.match('parentesis_c')
self.semantic.analyze(func_call)
def parameter(self):
parameters = []
parameters.append( self.parameterType() )
if(self.token['type'] == 'coma'):
self.match('coma')
parameters.extend( self.moreParameter() )
print(parameters)
return parameters
def moreParameter(self):
if( self.token['type'] in ['entero', 'cadena', 'id'] ):
return self.parameter()
def parameterType(self):
value = (self.token['type'], self.token['lexeme'])
self.match( ['entero', 'cadena', 'id'] )
return value
|
class GeneratorCache(object):
"""Cache for cached_generator to store SharedGenerators and exception info.
"""
# Private attributes:
# list<dict> _shared_generators - A list of the SharedGenerator and
# exception info maps stored in this GeneratorCache.
def __init__(self):
self._shared_generators = []
def clear(self):
"""Clear the SharedGenerators from all functions using this.
Clear the SharedGenerators and exception info we are using for
all of the functions decorated with this GeneratorCache. This
clears any cached results of such functions.
"""
for shared_generators in self._shared_generators:
shared_generators.clear()
self._shared_generators = []
def _create_shared_generators_map(self):
"""Return a new map for storing SharedGenerators and exception info.
"""
shared_generators = {}
self._shared_generators.append(shared_generators)
return shared_generators
|
n,m=map(int,input().split())
l1=list(map(int,input().split()))
minindex=l1.index(min(l1))
l2=list(map(int,input().split()))
maxindex=l2.index(max(l2))
for i in range(0,m):
print(minindex,i)
for j in range(0,minindex):
print(j,maxindex)
for j in range(minindex+1,n):
print(j,maxindex)
|
class TempSensor:
__sensor_path = '/sys/bus/w1/devices/28-00000652b8e4/w1_slave'
def __init__(self):
self.__recent_values = []
def read(self):
data = self.__read_sensor_file()
temp_value = self.__parse_sensor_data(data)
fahrenheit_value = self.__convert_to_fahrenheit(temp_value)
self.__recent_values.append(fahrenheit_value)
while len(self.__recent_values) > 5:
self.__recent_values.pop(0)
return sum(self.__recent_values) / float(len(self.__recent_values))
def __read_sensor_file(self):
f = open(TempSensor.__sensor_path,'r')
contents = f.read()
f.close()
return contents
def __parse_sensor_data(self, data):
return int(data.split('t=')[-1])/1000
def __convert_to_fahrenheit(self, celsius):
return (celsius * 1.8) + 32
|
#Question 14
power = int(input('Enter power:'))
number = 2**power
print('Two last digits:', number%100)
|
def distance(strand_a, strand_b):
if len(strand_a) != len(strand_b):
raise ValueError('strands are not of equal length')
count = 0
for i in range(len(strand_a)):
if strand_a[i] != strand_b[i]:
count += 1
return count
|
# 367. Valid Perfect Square
class Solution:
# Binary Search
def isPerfectSquare(self, num: int) -> bool:
if num < 2:
return True
left, right = 2, num // 2
while left <= right:
mid = left + (right - left) // 2
sqr = mid ** 2
if sqr == num:
return True
elif sqr < num:
left = mid + 1
else:
right = mid - 1
return False |
class BuySellEnum:
BUY_SELL_UNSET = 0
BUY = 1
SELL = 2
|
'''Crie um programa que simule o funcionamento de um caixa eletrônico. No início, pergunte ao
usuário qual será o valor a ser sacado (número inteiro) e o programa vai informar quantas cédulas
de cada valor serão entregues. OBS: considere que o caixa possui cédulas de R$50, R$20, R$10 e R$1.'''
valor = int(input('Digite quanto deseja sacar R$ '))
tot = valor
ced = 50
totced = 0
while True:
if tot >= ced:
tot -= ced
totced += 1
else:
if totced > 0:
print(f'Total de {totced} cédulas de R$ {ced}')
if ced == 50:
ced = 20
elif ced == 20:
ced = 10
elif ced == 10:
ced = 1
totced = 0
if tot == 0:
break
|
# -*- coding: utf-8 -*-
"""
logbook._termcolors
~~~~~~~~~~~~~~~~~~~
Provides terminal color mappings.
:copyright: (c) 2010 by Armin Ronacher, Georg Brandl.
:license: BSD, see LICENSE for more details.
"""
esc = "\x1b["
codes = {"": "", "reset": esc + "39;49;00m"}
dark_colors = ["black", "darkred", "darkgreen", "brown", "darkblue",
"purple", "teal", "lightgray"]
light_colors = ["darkgray", "red", "green", "yellow", "blue",
"fuchsia", "turquoise", "white"]
x = 30
for d, l in zip(dark_colors, light_colors):
codes[d] = esc + "%im" % x
codes[l] = esc + "%i;01m" % x
x += 1
del d, l, x
codes["darkteal"] = codes["turquoise"]
codes["darkyellow"] = codes["brown"]
codes["fuscia"] = codes["fuchsia"]
def _str_to_type(obj, strtype):
"""Helper for ansiformat and colorize"""
if isinstance(obj, type(strtype)):
return obj
return obj.encode('ascii')
def colorize(color_key, text):
"""Returns an ANSI formatted text with the given color."""
return (_str_to_type(codes[color_key], text) + text +
_str_to_type(codes["reset"], text))
|
STATS = [
{
"num_node_expansions": 653,
"plan_length": 167,
"search_time": 0.49,
"total_time": 0.49
},
{
"num_node_expansions": 978,
"plan_length": 167,
"search_time": 0.72,
"total_time": 0.72
},
{
"num_node_expansions": 1087,
"plan_length": 194,
"search_time": 17.44,
"total_time": 17.44
},
{
"num_node_expansions": 923,
"plan_length": 198,
"search_time": 14.63,
"total_time": 14.63
},
{
"num_node_expansions": 667,
"plan_length": 142,
"search_time": 14.3,
"total_time": 14.3
},
{
"num_node_expansions": 581,
"plan_length": 156,
"search_time": 13.29,
"total_time": 13.29
},
{
"num_node_expansions": 505,
"plan_length": 134,
"search_time": 3.04,
"total_time": 3.04
},
{
"num_node_expansions": 953,
"plan_length": 165,
"search_time": 6.84,
"total_time": 6.84
},
{
"num_node_expansions": 792,
"plan_length": 163,
"search_time": 0.45,
"total_time": 0.45
},
{
"num_node_expansions": 554,
"plan_length": 160,
"search_time": 0.44,
"total_time": 0.44
},
{
"num_node_expansions": 706,
"plan_length": 156,
"search_time": 4.71,
"total_time": 4.71
},
{
"num_node_expansions": 620,
"plan_length": 138,
"search_time": 3.2,
"total_time": 3.2
},
{
"num_node_expansions": 661,
"plan_length": 169,
"search_time": 0.41,
"total_time": 0.41
},
{
"num_node_expansions": 774,
"plan_length": 178,
"search_time": 0.66,
"total_time": 0.66
},
{
"num_node_expansions": 615,
"plan_length": 171,
"search_time": 0.76,
"total_time": 0.76
},
{
"num_node_expansions": 516,
"plan_length": 134,
"search_time": 0.93,
"total_time": 0.93
},
{
"num_node_expansions": 1077,
"plan_length": 221,
"search_time": 0.9,
"total_time": 0.9
},
{
"num_node_expansions": 1029,
"plan_length": 213,
"search_time": 0.93,
"total_time": 0.93
},
{
"num_node_expansions": 753,
"plan_length": 173,
"search_time": 0.71,
"total_time": 0.71
},
{
"num_node_expansions": 814,
"plan_length": 210,
"search_time": 0.66,
"total_time": 0.66
},
{
"num_node_expansions": 569,
"plan_length": 134,
"search_time": 4.8,
"total_time": 4.8
},
{
"num_node_expansions": 899,
"plan_length": 176,
"search_time": 6.19,
"total_time": 6.19
},
{
"num_node_expansions": 531,
"plan_length": 144,
"search_time": 3.85,
"total_time": 3.85
},
{
"num_node_expansions": 631,
"plan_length": 164,
"search_time": 4.22,
"total_time": 4.22
},
{
"num_node_expansions": 479,
"plan_length": 138,
"search_time": 0.11,
"total_time": 0.11
},
{
"num_node_expansions": 941,
"plan_length": 148,
"search_time": 0.21,
"total_time": 0.21
},
{
"num_node_expansions": 1023,
"plan_length": 197,
"search_time": 9.89,
"total_time": 9.89
},
{
"num_node_expansions": 1152,
"plan_length": 196,
"search_time": 12.89,
"total_time": 12.89
},
{
"num_node_expansions": 629,
"plan_length": 147,
"search_time": 3.24,
"total_time": 3.24
},
{
"num_node_expansions": 697,
"plan_length": 160,
"search_time": 2.33,
"total_time": 2.33
},
{
"num_node_expansions": 646,
"plan_length": 158,
"search_time": 3.94,
"total_time": 3.94
},
{
"num_node_expansions": 741,
"plan_length": 152,
"search_time": 4.03,
"total_time": 4.03
},
{
"num_node_expansions": 486,
"plan_length": 136,
"search_time": 1.99,
"total_time": 1.99
},
{
"num_node_expansions": 602,
"plan_length": 146,
"search_time": 3.41,
"total_time": 3.41
},
{
"num_node_expansions": 774,
"plan_length": 186,
"search_time": 1.47,
"total_time": 1.47
},
{
"num_node_expansions": 1512,
"plan_length": 209,
"search_time": 3.74,
"total_time": 3.74
},
{
"num_node_expansions": 791,
"plan_length": 180,
"search_time": 14.14,
"total_time": 14.14
},
{
"num_node_expansions": 1019,
"plan_length": 211,
"search_time": 21.35,
"total_time": 21.35
},
{
"num_node_expansions": 450,
"plan_length": 133,
"search_time": 1.76,
"total_time": 1.76
},
{
"num_node_expansions": 526,
"plan_length": 135,
"search_time": 1.98,
"total_time": 1.98
},
{
"num_node_expansions": 1329,
"plan_length": 182,
"search_time": 6.8,
"total_time": 6.8
},
{
"num_node_expansions": 655,
"plan_length": 134,
"search_time": 3.31,
"total_time": 3.31
},
{
"num_node_expansions": 636,
"plan_length": 159,
"search_time": 5.99,
"total_time": 5.99
},
{
"num_node_expansions": 1403,
"plan_length": 196,
"search_time": 13.75,
"total_time": 13.75
},
{
"num_node_expansions": 664,
"plan_length": 175,
"search_time": 3.62,
"total_time": 3.62
},
{
"num_node_expansions": 760,
"plan_length": 150,
"search_time": 5.2,
"total_time": 5.2
},
{
"num_node_expansions": 593,
"plan_length": 163,
"search_time": 8.61,
"total_time": 8.61
},
{
"num_node_expansions": 1043,
"plan_length": 179,
"search_time": 16.05,
"total_time": 16.05
},
{
"num_node_expansions": 390,
"plan_length": 103,
"search_time": 0.33,
"total_time": 0.33
},
{
"num_node_expansions": 419,
"plan_length": 120,
"search_time": 0.35,
"total_time": 0.35
},
{
"num_node_expansions": 606,
"plan_length": 160,
"search_time": 15.03,
"total_time": 15.03
},
{
"num_node_expansions": 525,
"plan_length": 146,
"search_time": 0.2,
"total_time": 0.2
},
{
"num_node_expansions": 522,
"plan_length": 147,
"search_time": 0.22,
"total_time": 0.22
},
{
"num_node_expansions": 652,
"plan_length": 165,
"search_time": 10.35,
"total_time": 10.35
},
{
"num_node_expansions": 1188,
"plan_length": 178,
"search_time": 13.19,
"total_time": 13.19
},
{
"num_node_expansions": 450,
"plan_length": 136,
"search_time": 1.56,
"total_time": 1.56
},
{
"num_node_expansions": 1179,
"plan_length": 209,
"search_time": 3.46,
"total_time": 3.46
},
{
"num_node_expansions": 834,
"plan_length": 204,
"search_time": 20.33,
"total_time": 20.33
},
{
"num_node_expansions": 1133,
"plan_length": 187,
"search_time": 12.76,
"total_time": 12.76
},
{
"num_node_expansions": 777,
"plan_length": 181,
"search_time": 8.97,
"total_time": 8.97
},
{
"num_node_expansions": 591,
"plan_length": 136,
"search_time": 1.58,
"total_time": 1.58
},
{
"num_node_expansions": 580,
"plan_length": 143,
"search_time": 1.56,
"total_time": 1.56
},
{
"num_node_expansions": 977,
"plan_length": 173,
"search_time": 5.94,
"total_time": 5.94
},
{
"num_node_expansions": 694,
"plan_length": 167,
"search_time": 5.26,
"total_time": 5.26
},
{
"num_node_expansions": 861,
"plan_length": 188,
"search_time": 1.15,
"total_time": 1.15
},
{
"num_node_expansions": 790,
"plan_length": 160,
"search_time": 0.81,
"total_time": 0.81
},
{
"num_node_expansions": 841,
"plan_length": 188,
"search_time": 4.87,
"total_time": 4.87
},
{
"num_node_expansions": 436,
"plan_length": 128,
"search_time": 1.77,
"total_time": 1.77
},
{
"num_node_expansions": 550,
"plan_length": 127,
"search_time": 0.03,
"total_time": 0.03
},
{
"num_node_expansions": 434,
"plan_length": 134,
"search_time": 0.03,
"total_time": 0.03
},
{
"num_node_expansions": 990,
"plan_length": 191,
"search_time": 26.16,
"total_time": 26.16
},
{
"num_node_expansions": 987,
"plan_length": 248,
"search_time": 27.03,
"total_time": 27.03
},
{
"num_node_expansions": 958,
"plan_length": 195,
"search_time": 6.81,
"total_time": 6.81
},
{
"num_node_expansions": 658,
"plan_length": 174,
"search_time": 4.83,
"total_time": 4.83
},
{
"num_node_expansions": 370,
"plan_length": 126,
"search_time": 0.06,
"total_time": 0.06
},
{
"num_node_expansions": 440,
"plan_length": 119,
"search_time": 0.06,
"total_time": 0.06
},
{
"num_node_expansions": 648,
"plan_length": 168,
"search_time": 7.05,
"total_time": 7.05
},
{
"num_node_expansions": 832,
"plan_length": 178,
"search_time": 9.96,
"total_time": 9.96
},
{
"num_node_expansions": 355,
"plan_length": 116,
"search_time": 0.6,
"total_time": 0.6
},
{
"num_node_expansions": 495,
"plan_length": 123,
"search_time": 0.73,
"total_time": 0.73
},
{
"num_node_expansions": 612,
"plan_length": 148,
"search_time": 2.91,
"total_time": 2.91
},
{
"num_node_expansions": 1067,
"plan_length": 174,
"search_time": 4.37,
"total_time": 4.37
},
{
"num_node_expansions": 821,
"plan_length": 185,
"search_time": 2.51,
"total_time": 2.51
},
{
"num_node_expansions": 625,
"plan_length": 153,
"search_time": 2.22,
"total_time": 2.22
},
{
"num_node_expansions": 304,
"plan_length": 99,
"search_time": 0.15,
"total_time": 0.15
},
{
"num_node_expansions": 477,
"plan_length": 133,
"search_time": 0.41,
"total_time": 0.41
},
{
"num_node_expansions": 651,
"plan_length": 160,
"search_time": 0.19,
"total_time": 0.19
},
{
"num_node_expansions": 594,
"plan_length": 147,
"search_time": 0.17,
"total_time": 0.17
},
{
"num_node_expansions": 524,
"plan_length": 134,
"search_time": 5.8,
"total_time": 5.8
},
{
"num_node_expansions": 400,
"plan_length": 127,
"search_time": 5.23,
"total_time": 5.23
},
{
"num_node_expansions": 825,
"plan_length": 185,
"search_time": 5.71,
"total_time": 5.71
},
{
"num_node_expansions": 613,
"plan_length": 156,
"search_time": 4.13,
"total_time": 4.13
},
{
"num_node_expansions": 427,
"plan_length": 121,
"search_time": 0.08,
"total_time": 0.08
},
{
"num_node_expansions": 362,
"plan_length": 116,
"search_time": 0.07,
"total_time": 0.07
},
{
"num_node_expansions": 459,
"plan_length": 119,
"search_time": 0.6,
"total_time": 0.6
},
{
"num_node_expansions": 501,
"plan_length": 132,
"search_time": 0.72,
"total_time": 0.72
},
{
"num_node_expansions": 697,
"plan_length": 156,
"search_time": 2.94,
"total_time": 2.94
},
{
"num_node_expansions": 1024,
"plan_length": 162,
"search_time": 6.43,
"total_time": 6.43
},
{
"num_node_expansions": 501,
"plan_length": 122,
"search_time": 4.23,
"total_time": 4.23
},
{
"num_node_expansions": 577,
"plan_length": 126,
"search_time": 4.8,
"total_time": 4.8
},
{
"num_node_expansions": 633,
"plan_length": 152,
"search_time": 15.85,
"total_time": 15.85
},
{
"num_node_expansions": 833,
"plan_length": 186,
"search_time": 20.61,
"total_time": 20.61
},
{
"num_node_expansions": 996,
"plan_length": 183,
"search_time": 3.53,
"total_time": 3.53
},
{
"num_node_expansions": 1246,
"plan_length": 206,
"search_time": 4.34,
"total_time": 4.34
},
{
"num_node_expansions": 466,
"plan_length": 137,
"search_time": 1.19,
"total_time": 1.19
},
{
"num_node_expansions": 530,
"plan_length": 142,
"search_time": 1.5,
"total_time": 1.5
},
{
"num_node_expansions": 923,
"plan_length": 189,
"search_time": 13.9,
"total_time": 13.9
},
{
"num_node_expansions": 799,
"plan_length": 167,
"search_time": 11.96,
"total_time": 11.96
},
{
"num_node_expansions": 651,
"plan_length": 173,
"search_time": 0.82,
"total_time": 0.82
},
{
"num_node_expansions": 590,
"plan_length": 159,
"search_time": 0.56,
"total_time": 0.56
},
{
"num_node_expansions": 542,
"plan_length": 155,
"search_time": 0.06,
"total_time": 0.06
},
{
"num_node_expansions": 418,
"plan_length": 130,
"search_time": 0.05,
"total_time": 0.05
},
{
"num_node_expansions": 881,
"plan_length": 182,
"search_time": 7.23,
"total_time": 7.23
},
{
"num_node_expansions": 1256,
"plan_length": 205,
"search_time": 11.35,
"total_time": 11.35
},
{
"num_node_expansions": 612,
"plan_length": 146,
"search_time": 1.83,
"total_time": 1.83
},
{
"num_node_expansions": 567,
"plan_length": 145,
"search_time": 2.49,
"total_time": 2.49
},
{
"num_node_expansions": 655,
"plan_length": 152,
"search_time": 6.73,
"total_time": 6.73
},
{
"num_node_expansions": 499,
"plan_length": 133,
"search_time": 4.83,
"total_time": 4.83
},
{
"num_node_expansions": 500,
"plan_length": 137,
"search_time": 0.24,
"total_time": 0.24
},
{
"num_node_expansions": 869,
"plan_length": 156,
"search_time": 0.35,
"total_time": 0.35
},
{
"num_node_expansions": 522,
"plan_length": 161,
"search_time": 0.05,
"total_time": 0.05
},
{
"num_node_expansions": 712,
"plan_length": 181,
"search_time": 0.07,
"total_time": 0.07
},
{
"num_node_expansions": 708,
"plan_length": 142,
"search_time": 3.52,
"total_time": 3.52
},
{
"num_node_expansions": 642,
"plan_length": 163,
"search_time": 3.84,
"total_time": 3.84
},
{
"num_node_expansions": 426,
"plan_length": 134,
"search_time": 0.11,
"total_time": 0.11
},
{
"num_node_expansions": 471,
"plan_length": 129,
"search_time": 0.12,
"total_time": 0.12
},
{
"num_node_expansions": 520,
"plan_length": 135,
"search_time": 1.06,
"total_time": 1.06
},
{
"num_node_expansions": 666,
"plan_length": 144,
"search_time": 1.74,
"total_time": 1.74
},
{
"num_node_expansions": 563,
"plan_length": 159,
"search_time": 1.27,
"total_time": 1.27
},
{
"num_node_expansions": 566,
"plan_length": 162,
"search_time": 1.71,
"total_time": 1.71
},
{
"num_node_expansions": 1356,
"plan_length": 212,
"search_time": 24.23,
"total_time": 24.23
},
{
"num_node_expansions": 836,
"plan_length": 203,
"search_time": 15.08,
"total_time": 15.08
},
{
"num_node_expansions": 604,
"plan_length": 145,
"search_time": 0.9,
"total_time": 0.9
},
{
"num_node_expansions": 506,
"plan_length": 124,
"search_time": 0.75,
"total_time": 0.75
},
{
"num_node_expansions": 851,
"plan_length": 203,
"search_time": 0.89,
"total_time": 0.89
},
{
"num_node_expansions": 603,
"plan_length": 166,
"search_time": 0.67,
"total_time": 0.67
},
{
"num_node_expansions": 497,
"plan_length": 118,
"search_time": 0.25,
"total_time": 0.25
},
{
"num_node_expansions": 590,
"plan_length": 117,
"search_time": 0.23,
"total_time": 0.23
},
{
"num_node_expansions": 409,
"plan_length": 129,
"search_time": 0.07,
"total_time": 0.07
},
{
"num_node_expansions": 669,
"plan_length": 165,
"search_time": 0.11,
"total_time": 0.11
},
{
"num_node_expansions": 786,
"plan_length": 161,
"search_time": 15.63,
"total_time": 15.63
},
{
"num_node_expansions": 474,
"plan_length": 144,
"search_time": 11.44,
"total_time": 11.44
},
{
"num_node_expansions": 579,
"plan_length": 165,
"search_time": 0.76,
"total_time": 0.76
},
{
"num_node_expansions": 620,
"plan_length": 160,
"search_time": 0.71,
"total_time": 0.71
},
{
"num_node_expansions": 1523,
"plan_length": 221,
"search_time": 26.01,
"total_time": 26.01
},
{
"num_node_expansions": 961,
"plan_length": 207,
"search_time": 15.01,
"total_time": 15.01
},
{
"num_node_expansions": 444,
"plan_length": 127,
"search_time": 3.52,
"total_time": 3.52
},
{
"num_node_expansions": 464,
"plan_length": 127,
"search_time": 4.44,
"total_time": 4.44
},
{
"num_node_expansions": 773,
"plan_length": 194,
"search_time": 0.8,
"total_time": 0.8
},
{
"num_node_expansions": 676,
"plan_length": 161,
"search_time": 0.86,
"total_time": 0.86
},
{
"num_node_expansions": 414,
"plan_length": 127,
"search_time": 0.43,
"total_time": 0.43
},
{
"num_node_expansions": 623,
"plan_length": 165,
"search_time": 0.47,
"total_time": 0.47
},
{
"num_node_expansions": 703,
"plan_length": 163,
"search_time": 0.89,
"total_time": 0.89
},
{
"num_node_expansions": 785,
"plan_length": 176,
"search_time": 0.99,
"total_time": 0.99
},
{
"num_node_expansions": 986,
"plan_length": 167,
"search_time": 13.69,
"total_time": 13.69
},
{
"num_node_expansions": 955,
"plan_length": 205,
"search_time": 12.42,
"total_time": 12.42
},
{
"num_node_expansions": 417,
"plan_length": 118,
"search_time": 0.05,
"total_time": 0.05
},
{
"num_node_expansions": 521,
"plan_length": 141,
"search_time": 0.07,
"total_time": 0.07
},
{
"num_node_expansions": 815,
"plan_length": 182,
"search_time": 23.26,
"total_time": 23.26
}
]
num_timeouts = 13
num_timeouts = 0
num_problems = 172
|
class Command(object):
def __init__(self, command, description, callback):
"""
Construct command
:param command: The command
:param description: The description
:param callback: The callback
"""
self.command = command
self.description = description
self.callback = callback
self.given = False
self.arguments = None
def reset(self):
"""
Reset option
:return: void
"""
self.given = False
self.arguments = None
|
# List
dog_names = ["tom", "sean", "sally", "mark"]
print(type(dog_names))
print(dog_names)
# Adding Item On Last Position
dog_names.append("sam")
print(dog_names)
# Adding Item On First Position
dog_names.insert(0, "bruz")
print(dog_names)
# Delete Items
del(dog_names[0])
print(dog_names)
# Length Of List
print('Length Of List: ',len(dog_names)) |
class BTNode:
def __init__(self, data = -1, left = None, right = None):
self.data = data
self.left = left
self.right = right
class BTree:
def __init__(self):
self.root = None
self.found = False
def is_empty(self):
return self.root is None
def build(self, vals):
self.root = BTNode(int(vals.pop(0)))
queue = [self.root]
while len(queue) != 0:
node = queue.pop(0)
if len(vals) != 0:
val = vals.pop(0)
if val != "None":
node.left = BTNode(int(val))
queue.append(node.left)
if len(vals) != 0:
val = vals.pop(0)
if val != "None":
node.right = BTNode(int(val))
queue.append(node.right)
def find(self, num):
self.dfs(self.root, 0, num)
if self.found:
print("True")
else:
print("False")
def dfs(self, node, val, num):
val += node.data
if val == num:
self.found = True
if node.left:
self.dfs(node.left, val, num)
if node.right:
self.dfs(node.right, val, num)
def main():
n = int(input())
s = input().split()
tree = BTree()
tree.build(s)
tree.find(n)
main() |
# FAZER UM PROGRAMA QUE LEIA O PRIMEIRO TERMO E UMA RAZÃO DE UMA PROGRESSÃO ARITMÉTICA
# MOSTRAR OS 10 PRIMEIROS TERMOS DA PROGRESSÃO ARITMÉTICA
pa = int(input('Digite o primeiro termo: '))
razao = int(input('Digite a razão: '))
n = 0
verificacao = False
vezes = 10
while verificacao == False:
while n != vezes:
n += 1
print(pa , '-> ', end='')
pa += razao
print('PAUSA')
n_vezes = int(input('Mais quantos números: '))
vezes += n_vezes
if n_vezes <= 0:
verificacao = True
print('Forão mostrados {} resultados.'.format(vezes)) |
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 13 11:30:05 2019
@author: Jongmin Sung
import functions and variables into our notebooks and scripts:
from projectname import something
"""
|
"""Module with bad __all__
To test https://github.com/ipython/ipython/issues/9678
"""
def evil():
pass
def puppies():
pass
__all__ = [evil, # Bad
'puppies', # Good
]
|
# -- Project information -----------------------------------------------------
project = "Test"
copyright = "Test"
author = "Test"
# -- General configuration ---------------------------------------------------
master_doc = "index"
# -- Options for HTML output -------------------------------------------------
html_theme = "pydata_sphinx_theme"
|
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def countUnivalSubtrees(self, root):
"""
:type root: TreeNode
:rtype: int
"""
self.count = 0
def helper(node, val):
if not node:
return True
left = helper(node.left, node.val)
right = helper(node.right, node.val)
if not left or not right:
return False
self.count += 1
return node.val == val
helper(root, 0)
return self.count |
# coding: utf8
"""
题目链接: https://leetcode.com/problems/flatten-nested-list-iterator/description.
题目描述:
Given a nested list of integers, implement an iterator to flatten it.
Each element is either an integer, or a list -- whose elements may also be integers or other lists.
Example 1:
Given the list [[1,1],2,[1,1]],
By calling next repeatedly until hasNext returns false, the order of elements returned by next should be:
[1,1,2,1,1].
Example 2:
Given the list [1,[4,[6]]],
By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,4,6].
"""
# """
# This is the interface that allows for creating nested lists.
# You should not implement it, or speculate about its implementation
# """
# class NestedInteger(object):
# def isInteger(self):
# """
# @return True if this NestedInteger holds a single integer, rather than a nested list.
# :rtype bool
# """
#
# def getInteger(self):
# """
# @return the single integer that this NestedInteger holds, if it holds a single integer
# Return None if this NestedInteger holds a nested list
# :rtype int
# """
#
# def getList(self):
# """
# @return the nested list that this NestedInteger holds, if it holds a nested list
# Return None if this NestedInteger holds a single integer
# :rtype List[NestedInteger]
# """
class NestedIterator(object):
def __init__(self, nestedList):
"""
Initialize your data structure here.
:type nestedList: List[NestedInteger]
"""
self.stack = []
for n in nestedList[::-1]:
self.stack.append(n)
def next(self):
"""
:rtype: int
"""
return self.stack.pop()
def hasNext(self):
"""
:rtype: bool
"""
while self.stack:
# 内嵌列表, 出栈, 继续平铺展开
# 直至栈顶为整数
while self.stack and not self.stack[-1].isInteger():
s = self.stack.pop().getList()
for i in s[::-1]:
self.stack.append(i)
if self.stack and self.stack[-1].isInteger():
return True
return False
# Your NestedIterator object will be instantiated and called as such:
# i, v = NestedIterator(nestedList), []
# while i.hasNext(): v.append(i.next())
|
# Reads the UA list from the file "ua_list.txt"
# Refer this site for list of UAs: https://developers.whatismybrowser.com/useragents/explore/
ua_file = open("ua_list.txt", "r")
lines = ua_file.readlines()
ua_list = []
for line in lines:
line_cleaned = line.replace("\n","").lower()
ua_list.append(line_cleaned)
ua_list.sort()
ua_list = list(dict.fromkeys(ua_list))
ua_list_count = len(ua_list)
print(ua_list)
print("Identified ",ua_list_count," UAs in the file.")
ua_file.close()
# Write the sorted list back to the file "ua_list.txt"
ua_file_sorted = open("ua_list.txt", "w")
for ua in ua_list:
ua_line = ua + "\n"
ua_file_sorted.write(ua_line)
ua_file_sorted.close
# Generate Cloudflare configuration in the string "ua_list_cf"
# Using Cloudflare case insensitive matching lower()
ua_list_cf = ""
i = 0
for ua in ua_list:
if (i < ua_list_count - 1):
cf_single_rule = "(lower(http.user_agent) contains \"" + ua + "\") or "
else:
cf_single_rule = "(lower(http.user_agent) contains \"" + ua + "\")"
ua_list_cf = ua_list_cf + cf_single_rule
i += 1
# Write Cloudflare configuration to the file "ua_list_cf.txt"
ua_file_cf = open("ua_list_cf.txt", "w")
ua_file_cf.write(ua_list_cf)
ua_file_cf.close
print("Cloudflare firewall rules generated in the file 'ua_list_cf.txt'")
# Generate nginx configuration in the string "ua_list_nginx"
# Using nginx case insensitive matching
ua_list_nginx = "if ($http_user_agent ~* ("
i = 0
for ua in ua_list:
ua_escaped = ua.replace(" ","\ ")
if (i < ua_list_count - 1):
nginx_single_rule = ua_escaped + "|"
else:
nginx_single_rule = ua_escaped
i += 1
ua_list_nginx = ua_list_nginx + nginx_single_rule
ua_list_nginx = ua_list_nginx + ")) {\n return 403;\n}"
# Write nginx configuration to the file "ua_list_nginx.conf"
ua_file_nginx = open("ua_list_nginx.conf", "w")
ua_file_nginx.write(ua_list_nginx)
ua_file_nginx.close
print("Nginx file generated in the file 'ua_list_nginx.conf', please insert this into your Nginx configuration within server{} block")
|
# greatest of three
def greatest(a,b,c):
return max(a,b,c)
print(greatest(2,4,3)) |
def LCSBackTrack(v, w):
v = '-' + v
w = '-' + w
S = [[0 for i in range(len(w))] for j in range(len(v))]
Backtrack = [[0 for i in range(len(w))] for j in range(len(v))]
for i in range(1, len(v)):
for j in range(1, len(w)):
tmp = S[i - 1][j - 1] + (1 if v[i] == w[j] else 0)
S[i][j] = max([S[i - 1][j], S[i][j - 1], tmp])
if S[i][j] == S[i - 1][j]:
Backtrack[i][j] = 1
elif S[i][j] == S[i][j - 1]:
Backtrack[i][j] = 2
else:
Backtrack[i][j] = 4
LCS = []
while i > 0 and j > 0:
if Backtrack[i][j] == 4:
LCS.append(v[i])
i -= 1
j -= 1
elif Backtrack[i][j] == 2:
j -= 1
else:
i -= 1
return Backtrack
# def OutputLCS(Backtrack, V, i, j):
# # print(str(i) + ' ' + str(j))
# if i == 0 or j == 0:
# return V[i]
# if Backtrack[i][j] == 1:
# return OutputLCS(Backtrack, V, i - 1, j)
# elif Backtrack[i][j] == 2:
# return OutputLCS(Backtrack, V, i, j - 1)
# else:
# return OutputLCS(Backtrack, V, i - 1, j - 1) + V[i]
def OutputLCS(Backtrack, V, i, j):
LCS = []
while i > 0 and j > 0:
if Backtrack[i][j] == 4:
LCS.append(V[i])
i -= 1
j -= 1
elif Backtrack[i][j] == 2:
j -= 1
else:
i -= 1
return LCS
if __name__ == "__main__":
v = input().rstrip()
w = input().rstrip()
Backtrack = LCSBackTrack(v, w)
i = len(Backtrack) - 1
j = len(Backtrack[0]) - 1
res = OutputLCS(Backtrack, v, i, j)
print(''.join(res[::-1])) |
{
"targets": [
{
"target_name": "boost-parameter",
"type": "none",
"include_dirs": [
"1.57.0/parameter-boost-1.57.0/include"
],
"all_dependent_settings": {
"include_dirs": [
"1.57.0/parameter-boost-1.57.0/include"
]
},
"dependencies": [
"../boost-config/boost-config.gyp:*",
"../boost-detail/boost-detail.gyp:*",
"../boost-optional/boost-optional.gyp:*",
"../boost-core/boost-core.gyp:*",
"../boost-preprocessor/boost-preprocessor.gyp:*",
"../boost-mpl/boost-mpl.gyp:*"
#"../boost-python/boost-python.gyp:*"
]
},
{
"target_name": "boost-parameter_test_deduced",
"type": "executable",
"test": {},
"sources": [ "1.57.0/parameter-boost-1.57.0/test/deduced.cpp" ],
"dependencies": [ "boost-parameter" ],
# this disables building the example on iOS
"conditions": [
["OS=='iOS'",
{
"type": "none"
}
]
]
},
{
"target_name": "boost-parameter_tutorial",
"type": "executable",
"test": {},
"sources": [ "1.57.0/parameter-boost-1.57.0/test/tutorial.cpp" ],
"dependencies": [ "boost-parameter"],
# this disables building the example on iOS
"conditions": [
["OS=='iOS'",
{
"type": "none"
}
]
]
}
]
}
|
# -*- coding: utf-8 -*-
{
'name': "WooCommerce Connector",
'summary': """This module enables users to connect woocommerce api to odoo modules of sales, partners and inventory""",
'description': """
Following are the steps to use this module effectively:
1) Put in the KEY and SECRET in the connection menu.
2) Click Sync Button on the list.
3) Orders, Customers and Products will be Imported from WooCommerce to Odoo.
Data will be displayed on the WooCommerce Connector App as well as the odoo modules.
More updates will be pushed frequently. Contributors are invited and appreciated.
This is a free module and for more information contact on WhatsApp +923340239555.
""",
'author': "Saad Mujeeb - ISAA TECH",
'website': "https://www.isaatech.com",
'category': 'Connectors',
'version': '0.1',
# any module necessary for this one to work correctly
'depends': [],
'images': ['static/description/banner.png'],
# always loaded
'data': [
'security/ir.model.access.csv',
'data/sequence.xml',
'views/views.xml',
'views/orders.xml',
'views/products.xml',
'views/customers.xml',
],
'installable': True,
'application': True,
'auto_install': False
}
|
class AbstractBatchifier(object):
def filter(self, games):
return games
def apply(self, games):
return games
|
"""https://leetcode.com/problems/permutations-ii/
47. Permutations II
Medium
Given a collection of numbers, nums, that might contain duplicates,
return all possible unique permutations in any order.
Examples:
>>> Solution().permuteUnique([])
[[]]
Constraints:
1 <= nums.length <= 8
-10 <= nums[i] <= 10
Restrict insertion past the first occurrence of a duplicate value (if one exists)
To prevent adding a duplicate permutation,
we only allow insertion of a duplicate element once,
immediately to the left of the first already-existing duplicate value in the permutation
and break out of the loop since further iterations will create duplicate permutations.
---
Very smart way to eliminate the duplicate.
Here is my understanding about the eliminate process.
After several times of append and other operations,
#here I just pay attention to one element, 2's position in the inner list
We get the current list like below:
[2,x,x,x]
[x,2,x,x]
[x,x,2,x]
[x,x,x,2]
Of course if we replace the "x" with other elements,
there should be several other lists in each row,
but the position of "2" should just be same,
[0],[1],[2],[3] for each row.
The approach will traverse each list and insert the new element.
If the new element is "2", the current "for loop" will break.
Therefor,after the two loops,the "2" 's position in the list should be:
[0,1]
[0,2],[1,2]
[0,3],[1,3],[2,3]
[0,4],[1,4],[2,4],[3,4]
It will actually cover all the situation of the two 2's distribution.
subsets = [[]]
for num in [1,2,1,1]:
[] start
[(1)] ins(1)
[(2),1],[1,(2)] ins(2)
implicit break => avoids [1,(1),2]
v v
[(1),2,1],[2,(1),1],[(1),1,2] ins(1)
=> avoids [1,(1),2,1]... => avoids [2,1,(1),1]... => avoids [1,(1),1,2]...
v v v
[(1),1,2,1],[(1),2,1,1],[2,(1),1,1], [(1),1,1,2] ins(1)
return [1,1,2,1],[1,2,1,1],[2,1,1,1],[1,1,1,2]
---
Great solution! Here is a short (casual) proof about why break can avoid the duplication.
Argument: Assume curr_unique_permutations is a list of unique permutations
with each item length k,
then new_unique_permutations is a list of unique permutation with length k+1.
When k=0, it holds.
Then we prove it will also holds in each iteration using proof by contradiction.
Suppose duplicate happens when inserting num into the jth location,
the result is [l2[:char_idx], num, l2[char_idx:]],
and it duplicates with the item [l1[:j], num, l1[j:]]
- Suppose char_idx < j,
then we have l1[char_idx]==num,
however, we will break when l1[char_idx]==num,
and thus num will not be inserted after l1[:j] -> contradiction,
- Suppose char_idx > j,
then we have l2[j] == num,
however we will break when l2[j] == num,
and thus num will not be inserted after l2[:char_idx] -> contradiction.
- Suppose char_idx==j,
then we have l1==l2,
which contradicts the assumption that curr_unique_permutations is a list of unique permutations.
Thus the argument hold.
---
See Also:
- https://leetcode.com/problems/permutations-ii/discuss/18602/9-line-python-solution-with-1-line-to-handle-duplication-beat-99-of-others-%3A-)
- [Permutations Involving Repeated Symbols - Example 1](https://www.youtube.com/watch?v=3VBdsNCSBXM)
- [Permutations II - Backtracking - Leetcode 47](https://www.youtube.com/watch?v=qhBVWf0YafA)
- https://leetcode.com/problems/permutations-ii/discuss/189116/summarization-of-permutations-I-and-II-(Python)
"""
class Solution:
def permuteUnique(self, nums: list[int]) -> list[list[int]]:
return permute_unique(nums)
def permute_unique(nums: list[int]) -> list[list[int]]:
"""Compute all the *unique* permutations of the elements in a given input array
Args:
nums: array of possibly non-distinct elements
Returns: all *unique* permutations of elements in `nums`
Examples:
>>> sorted(permute_unique([1,1,2]))
[[1, 1, 2], [1, 2, 1], [2, 1, 1]]
>>> sorted(permute_unique([1,2,1,1]))
[[1, 1, 1, 2], [1, 1, 2, 1], [1, 2, 1, 1], [2, 1, 1, 1]]
>>> sorted(permute_unique([1,2,3]))
[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
"""
"""ALGORITHM"""
def get_last_valid_insertion_idx(perm, item):
"""Restrict insertion past the first occurrence of a duplicate value (if one exists)"""
# equivalent to `(perm + [item]).index(item)`
try:
return perm.index(item)
except ValueError:
return len(perm)
# DS's/res
uniq_perms = [[]]
# Build unique permutations
# increasing the permutation size by 1 at each iteration
for curr_num in nums:
uniq_perms = [
perm[:insertion_idx] + [curr_num] + perm[insertion_idx:]
for perm in uniq_perms
for insertion_idx in range(get_last_valid_insertion_idx(perm, curr_num) + 1)
]
return uniq_perms
def permute_unique_i(nums: list[int]) -> list[list[int]]:
"""Compute all the *unique* permutations of the elements in a given input array
Args:
nums: array of possibly non-distinct elements
Returns: all *unique* permutations of elements in `nums`
Examples:
>>> sorted(permute_unique_i([1,1,2]))
[[1, 1, 2], [1, 2, 1], [2, 1, 1]]
>>> sorted(permute_unique_i([1,2,1,1]))
[[1, 1, 1, 2], [1, 1, 2, 1], [1, 2, 1, 1], [2, 1, 1, 1]]
>>> sorted(permute_unique_i([1,2,3]))
[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
"""
"""ALGORITHM"""
def get_last_valid_insertion_idx(perm, item): # nosemgrep
"""Restrict insertion past the first occurrence of a duplicate value (if one exists)"""
# equivalent to `(perm + [item]).index(item)`
try:
return perm.index(item)
except ValueError:
return len(perm)
# DS's/res
uniq_perms = [[]]
# Build unique permutations
# increasing the permutation size by 1 at each iteration
for curr_num in nums:
np = []
for perm in uniq_perms:
for insertion_idx in range(
get_last_valid_insertion_idx(perm, curr_num) + 1
):
new_perm = perm.copy()
new_perm.insert(insertion_idx, curr_num)
np.append(new_perm)
uniq_perms = np
return uniq_perms
def permute_unique_long(nums: list[int]) -> list[list[int]]:
"""Compute all the *unique* permutations of the elements in a given
input array
Args:
nums: array of possibly non-distinct elements
Returns: all *unique* permutations of elements in `nums`
Examples:
>>> sorted(permute_unique_long([1,1,2]))
[[1, 1, 2], [1, 2, 1], [2, 1, 1]]
>>> sorted(permute_unique_long([1,2,1,1]))
[[1, 1, 1, 2], [1, 1, 2, 1], [1, 2, 1, 1], [2, 1, 1, 1]]
>>> sorted(permute_unique_long([1,2,3]))
[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
"""
"""ALGORITHM"""
uniq_perms = [[]] # Initialized with the empty set
# for each iteration, size of current permutations will increase by 1
# => at the end of the algorithm, size of each permutation will be equal to len(nums)
for curr_num in nums:
new_uniq_perms = []
for perm in uniq_perms:
# Insert element at each position in existing permutation to create new permutation
for insertion_idx in range(len(perm) + 1):
# Bisect-left: Insert `curr_num` to the left of insertion_idx in perm
# increases size of permutation by 1
new_perm = perm[:insertion_idx] + [curr_num] + perm[insertion_idx:]
new_uniq_perms.append(new_perm)
# Prevents duplicates
# equivalent to setting the for loop as:
# `for insertion_idx in range(get_last_valid_insertion_idx(perm,curr_num) + 1):`
if insertion_idx < len(perm) and perm[insertion_idx] == curr_num:
break
uniq_perms = new_uniq_perms
return uniq_perms
def permute_unique_set(nums: list[int]) -> list[list[int]]:
"""Compute all the *unique* permutations of the elements in a given input array
Args:
nums: array of possibly non-distinct elements
Returns: all *unique* permutations of elements in `nums`
Examples:
>>> sorted(permute_unique_set([1,1,2]))
[[1, 1, 2], [1, 2, 1], [2, 1, 1]]
>>> sorted(permute_unique_set([1,2,1,1]))
[[1, 1, 1, 2], [1, 1, 2, 1], [1, 2, 1, 1], [2, 1, 1, 1]]
>>> sorted(permute_unique_set([1,2,3]))
[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
"""
uniq_perms = {tuple()} # Initialized with the empty set
# for each iteration, size of current permutations will increase by 1
# => at the end of the algorithm, size of each permutation will be equal to len(nums)
for curr_num in nums:
# Bisect-left: Insert `curr_num` to the left of insertion_idx in perm
# (increases size of permutation by 1)
uniq_perms = {
# tuples for hashability
(*perm[:insertion_idx], curr_num, *perm[insertion_idx:])
for perm in uniq_perms
for insertion_idx in range(len(perm) + 1)
}
return [list(permutation) for permutation in uniq_perms]
def permute_unique_backtrack(nums: list[int]) -> list[list[int]]:
"""Compute all the *unique* permutations of the elements in a given input array
Args:
nums: array of possibly non-distinct elements
Returns: all *unique* permutations of elements in `nums`
Examples:
>>> sorted(permute_unique_backtrack([1,1,2]))
[[1, 1, 2], [1, 2, 1], [2, 1, 1]]
>>> sorted(permute_unique_backtrack([1,2,1,1]))
[[1, 1, 1, 2], [1, 1, 2, 1], [1, 2, 1, 1], [2, 1, 1, 1]]
>>> sorted(permute_unique_backtrack([1,2,3]))
[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
"""
## INITIALIZE VARS ##
# DS's/res
nums_counts = {}
for num in nums:
nums_counts[num] = nums_counts.get(num, 0) + 1
res = []
# Populate res
def compute_possible_permutations(sub_permutation):
# BASE CASE
if len(sub_permutation) == len(nums):
res.append(sub_permutation.copy())
else:
for curr_num in nums_counts: # iterate over *distinct* elements
# If there are remaining instances of `curr_num` left to choose
# => Select curr_num at this position
# and continue building permutation from remaining elements
if nums_counts[curr_num] > 0:
## BACKTRACK
# Save space by in-place appending/popping
nums_counts[curr_num] -= 1 # Select `curr_num` at current position
sub_permutation.append(curr_num)
compute_possible_permutations(sub_permutation)
sub_permutation.pop()
nums_counts[
curr_num
] += 1 # Deselect `curr_num` at current position
compute_possible_permutations(sub_permutation=[]) # initialize with empty list
return res
def permute_unique_backtrack_stack(nums: list[int]) -> list[list[int]]:
"""Compute all the *unique* permutations of the elements in a given input array
Args:
nums: array of possibly non-distinct elements
Returns: all *unique* permutations of elements in `nums`
Examples:
# >>> sorted(permute_unique_backtrack_stack([1,1,2]))
# [[1, 1, 2], [1, 2, 1], [2, 1, 1]]
>>> sorted(permute_unique_backtrack_stack([1,2,1,1]))
[[1, 1, 1, 2], [1, 1, 2, 1], [1, 2, 1, 1], [2, 1, 1, 1]]
>>> sorted(permute_unique_backtrack_stack([1,2,3]))
[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
"""
# TODO stack-based backtracking
# 2. Your implementation is allowed to use a Stack, a Queue
# Hint: Use the stack to store the elements
# yet to be used to generate the permutations,
# and use the queue to store the (partial) collection of permutations
# generated so far.
## INITIALIZE VARS ##
# DS's/res
nums_counts = {}
for num in nums:
nums_counts[num] = nums_counts.get(num, 0) + 1
res = []
stack = [[]] # empty set on stack
# stack2 = [[[]]] # empty set on stack
while stack:
sub_permutation = stack.pop()
# sub_perms = stack2.pop()
# track state?
# BASE CASE
if len(sub_permutation) == len(nums):
res.append(sub_permutation)
else:
# TODO: find a way to avoid nums_count updates every time
# without passing in a a dict
for used_num in sub_permutation:
nums_counts[used_num] -= 1 # Select `curr_num` at current position
children = [
sub_permutation + [curr_num]
for curr_num in nums_counts
if nums_counts[curr_num] > 0
]
stack.extend(children)
# stack2.append(children)
# cats = 2
# for curr_num in nums_counts:
#
# # If there are remaining instances of `curr_num` left to choose
# # => Select curr_num at this position
# # and continue building permutation from remaining elements
# if nums_counts[curr_num] > 0:
# stack.append(sub_permutation + [curr_num])
for used_num in sub_permutation:
nums_counts[used_num] += 1 # Deselect `curr_num` at current position
return res
def permute_unique_matt(nums: list[int]) -> list[list[int]]:
"""Compute all the *unique* permutations of the elements in a given input array
Args:
nums: array of possibly non-distinct elements
Returns: all *unique* permutations of elements in `nums`
Examples:
>>> sorted(permute_unique_matt([1,1,2]))
[[1, 1, 2], [1, 2, 1], [2, 1, 1]]
>>> sorted(permute_unique_matt([1,2,1,1]))
[[1, 1, 1, 2], [1, 1, 2, 1], [1, 2, 1, 1], [2, 1, 1, 1]]
>>> sorted(permute_unique_matt([1,2,3]))
[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
"""
if len(nums) == 1:
return [nums]
uniq_perms = []
already_used_set_of_elements_at_curr_pos = set()
for curr_num in nums:
# Since we are selecting elements at the current pos,
# skip repeated elements we had already explored once before
if curr_num not in already_used_set_of_elements_at_curr_pos:
nums_tmp = nums.copy()
nums_tmp.remove(curr_num)
uniq_perms.extend(
[
[curr_num] + sub_permutation
for sub_permutation in permute_unique_matt(nums_tmp)
]
)
already_used_set_of_elements_at_curr_pos.add(curr_num)
return uniq_perms
def permute_unique_matt_teo(nums: list[int]) -> list[list[int]]:
"""Compute all the *unique* permutations of the elements in a given input array
Args:
nums: array of possibly non-distinct elements
Returns: all *unique* permutations of elements in `nums`
Examples:
>>> sorted(permute_unique_matt_teo([1,1,2]))
[[1, 1, 2], [1, 2, 1], [2, 1, 1]]
>>> sorted(permute_unique_matt_teo([1,2,1,1]))
[[1, 1, 1, 2], [1, 1, 2, 1], [1, 2, 1, 1], [2, 1, 1, 1]]
>>> sorted(permute_unique_matt_teo([1,2,3]))
[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
"""
if len(nums) == 1:
return [nums]
distinct_nums = {num for num in nums}
uniq_perms = []
for curr_num in distinct_nums:
nums_tmp = nums.copy()
nums_tmp.remove(curr_num)
uniq_perms.extend(
[
[curr_num] + sub_permutation
for sub_permutation in permute_unique_matt_teo(nums_tmp)
]
)
return uniq_perms
|
#coding:utf-8
'''
filename:clsmethod.py
learn class method
'''
class Message:
msg = 'Python is a smart language.'
def get_msg(self):
print('self :',self)
print('attrs of class(Message.msg):',Message.msg)
print('use type(self).msg:',type(self).msg)
cls = type(self)
print('[cls = type(self)] cls:',cls)
print('attrs of class(cls.msg):',cls.msg)
@classmethod
def get_cls_msg(cls):
print('cls :',cls)
print('attrs of class(cls.msg):',cls.msg)
mess = Message()
mess.get_msg()
print('-'*50)
mess.get_cls_msg()
|
class Solution:
def findNumbers(self, nums: List[int]) -> int:
if len(nums) == 0:
return 0
return len(list(filter(lambda x:len(str(x))%2==0,nums))) |
"""
This module contains methods that model the properties of galaxy cluster
populations.
"""
|
# 231 - Power Of Two (Easy)
# https://leetcode.com/problems/power-of-two/submissions/
class Solution:
def isPowerOfTwo(self, n: int) -> bool:
return n and (n & (n-1)) == 0
|
random_test_iterations = 64
def repeat(fn):
"""Decorator for running the function's body multiple times."""
def repeated():
i = 0
while i < random_test_iterations:
fn()
i += 1
# nosetest runs functions that start with 'test_'
repeated.__name__ = fn.__name__
return repeated
|
# Some sites give IR codes in this weird pronto format
# Cut off the preamble and footer and find which value represents a 1 in the spacing
code = "0000 0016 0000 0016 0000 0016 0000 003F 0000 003F 0000 003F 0000 0016 0000 003F 0000 0016 0000 0016 0000 0016 0000 0016 0000 0016 0000 0016 0000 0016 0000 0016 0000 0016 0000 003F 0000 0016 0000 003F 0000 003F 0000 0016 0000 0016 0000 003F 0000 003F 0000 0016 0000 003F 0000 0016 0000 0016 0000 003F 0000 003F 0000 0016 0000"
print(int(''.join(list(map(lambda x: "1" if x == '003F' else "0", code.split(' ')[1::2]))), 2)) |
# ----------------------------------------------------------------------------
# This software is in the public domain, furnished "as is", without technical
# support, and with no warranty, express or implied, as to its usefulness for
# any purpose.
#
# iscSendSampleDef
#
# Author: mathewson
# ----------------------------------------------------------------------------
##
# This is an absolute override file, indicating that a higher priority version
# of the file will completely replace a lower priority version of the file.
##
# The configuration interval file is an optional capability of ifpnetCDF.
# It can be used to select certain grids to be placed in the ifpnetCDF
# output file, rather than all grids in the inventory. For example, you can
# choose to only include 3-hrly temperature grids out to 24 hours, then
# 6-hrly temperature grids out to 72 hours, and then no temperature grids
# past 72 hours. You can control this capability on a per weather element
# basis. The definition determines a set of explicit times. If there
# is a grid that contains that explicit time, then the grid is included in
# the output.
# The configuration interval file is a python file and must reside in the
# ifpServer's TEXT/Utility directory. You can create the file through the
# use of the GFE, with the GFE->Define Text Products menu, or by using
# a conventional text editor and the ifpServerText utility.
# This is the default for ifpnetCDF with regard to its use with ISC traffic.
# The data is sent from -24h to the future in 1 hour intervals.
HR=3600
SampleDef = {}
SampleDef['default'] = (
[0*HR], #first tuple is basetimes
[ #2nd tuple is list of offset from basetime, interval
(-24*HR, 1*HR), #start at basetime, take every hour
])
|
#Write a program (using functions!) that asks the user for a long string containing multiple words.
# Print back to the user the same string, except with the words in backwards order. For example, say I type the string:
# My name is Michele
#Then I would see the string:
# Michele is name My
#shown back to me.
def reverse(strng: str):
list = strng.split(' ')
list.reverse()
return list
print(reverse("My name is Michele")) |
# coding: utf-8
def test_index(admin_client):
"""
Basic test to see if it even works.
"""
url = "/nothing-to-see-here/"
HTTP_OK_200 = 200
respnse = admin_client.get(url)
assert respnse.status_code == HTTP_OK_200
|
def strategy(history, memory):
if memory is None or 1 == memory:
return 0, 0
else:
return 1, 1
|
with open("promote.in") as input_file:
input_lst = [[*map(int, line.split())] for line in input_file]
promotions = [
promotion[1] - promotion[0] for promotion in input_lst
]
output = []
for promotion in promotions[::-1]:
output.append(sum([]))
with open("promote.out", "w") as output_file:
for promotion in promotions:
print(promotion, file=output_file)
# print(input_lst)
|
'''
Está chegando a grande final do Campeonato Nlogonense de Surf Aquático, que este ano ocorrerá na cidade de Bonita Horeleninha (BH)! Antes de viajar para BH, você e seus N-1 amigos decidiram combinar algum dia para ir a uma pizzaria, para relaxar e descontrair (e, naturalmente, comer!).
Neste momento está sendo escolhida a data do evento. Para que todas as pessoas possam participar, foi decidido que o encontro na pizzaria ocorrerá em um data tal que todas as N pessoas podem comparecer à pizzaria nesta data. Portanto, nem toda data pode ser escolhida, pois algumas pessoas podem ter outros compromissos já marcados em alguns dias.
Dada a lista de datas consideradas para o evento e a informações de quais pessoas podem comparecer em quais datas, determine se o evento poderá ocorrer e, em caso positivo, sua data. Caso mais de uma data seja possível, o evento deve ocorrer o mais cedo possível.
Entrada
A entrada contém vários casos de teste. A primeira linha de cada caso contém os inteiros N e D (1 ≤ N, D ≤ 50), o número de pessoas e o número de datas consideradas, respectivamente. As pessoas são numeradas de 1 a N. As próximas D linhas descrevem uma data considerada. Cada linha começa com a data na forma dia∕mes∕ano. A linha é seguida de N inteiros p1,p2,...,pN. O inteiro pi é 1 se a pessoa i pode comparecer na data considerada, ou 0 caso contrário. É garantido que as datas são sempre válidas, e não há zeros à esquerda. Além disso, as datas são dadas em ordem, do dia mais cedo para o dia mais tarde.
A entrada termina com fim-de-arquivo (EOF).
Saída
Para cada caso de teste, imprima uma linha contendo a data que o evento deve ocorrer, na forma dia∕mes∕ano, de maneira idêntica à da entrada. Caso não seja possível realizar o evento, imprima “Pizza antes de FdI” (sem aspas).
'''
while True:
try:
entrada_1 = str(input()).split()
num_p = int(entrada_1[0])
num_datas = int(entrada_1[1])
data_perfeita = []
for i in range(num_datas):
cont = 0
entrada_2 = str(input()).split()
valores = entrada_2[1:]
for i in valores:
if i == '1':
cont += 1
if cont == len(valores):
data_perfeita.append(entrada_2[0])
if data_perfeita != []:
print(''.join(data_perfeita[0]))
else:
print('Pizza antes de FdI')
except EOFError:
break |
sample_text = '''
The textwrap module can be used to format text for output in
situations where pretty-printing is desired. It offers
programmatic functionality similar to the paragraph wrapping
or filling features found in many text editors.
''' |
# Write your solutions for 1.5 here!
class Superheros:
def __init__(self, name, superpower, strength):
self.name = name
self.superpower = superpower
self.strength = strength
def hero (self):
print(self.name)
print(self.strength)
def save_civilian (self, work):
if work > self.strength:
print("Superhero is not strong enough! :(")
else:
self.strength = self.strength - work
superman = Superheros("Super Man", "strong", 8)
hero(superman)
save_civilian(superman, 9)
hero(superman)
|
# Size of program memory (bytes)
MAX_PGM_MEM = 4096
# Size of context memory (bytes)
MAX_DATA_MEM = 2048
# Max stack size (bytes)
MAX_STACK = 512
# Number of registers
MAX_REGS = 11
# Default output indentation for some debug messages
IND = " " * 8
# Maximum values for various unsigned integers
MAX_UINT8 = 0xff
MAX_UINT16 = 0xffff
MAX_UINT32 = 0xffffffff
MAX_UINT64 = 0xffffffffffffffff
# +----------------+--------+--------------------+
# | 4 bits | 1 bit | 3 bits |
# | operation code | source | instruction class |
# +----------------+--------+--------------------+
# (MSB) (LSB)
# OpCode Classes
OPC_LD = 0x00 # load from immediate
OPC_LDX = 0x01 # load from register
OPC_ST = 0x02 # store immediate
OPC_STX = 0x03 # store value from register
OPC_ALU = 0x04 # 32 bits arithmetic operation
OPC_JMP = 0x05 # jump
OPC_RES = 0x06 # unused, reserved for future use
OPC_ALU64 = 0x07 # 64 bits arithmetic operation
# Operation codes (OPC_ALU or OPC_ALU64).
ALU_ADD = 0x00 # addition
ALU_SUB = 0x01 # subtraction
ALU_MUL = 0x02 # multiplication
ALU_DIV = 0x03 # division
ALU_OR = 0x04 # or
ALU_AND = 0x05 # and
ALU_LSH = 0x06 # left shift
ALU_RSH = 0x07 # right shift
ALU_NEG = 0x08 # negation
ALU_MOD = 0x09 # modulus
ALU_XOR = 0x0a # exclusive or
ALU_MOV = 0x0b # move
ALU_ARSH = 0x0c # sign extending right shift
ALU_ENDC = 0x0d # endianess conversion
# +--------+--------+-------------------+
# | 3 bits | 2 bits | 3 bits |
# | mode | size | instruction class |
# +--------+--------+-------------------+
# (MSB) (LSB)
# Load/Store Modes
LDST_IMM = 0x00 # immediate value
LDST_ABS = 0x01 # absolute
LDST_IND = 0x02 # indirect
LDST_MEM = 0x03 # load from / store to memory
# 0x04 # reserved
# 0x05 # reserved
LDST_XADD = 0x06 # exclusive add
# Sizes
LEN_W = 0x00 # word (4 bytes)
LEN_H = 0x01 # half-word (2 bytes)
LEN_B = 0x02 # byte (1 byte)
LEN_DW = 0x03 # double word (8 bytes)
EBPF_SIZE_W = LEN_W << 3 # 0x00
EBPF_SIZE_H = LEN_H << 3 # 0x08
EBPF_SIZE_B = LEN_B << 3 # 0x10
EBPF_SIZE_DW = LEN_DW << 3 # 0x18
# Operation codes (OPC_JMP)
JMP_JA = 0x00 # jump
JMP_JEQ = 0x01 # jump if equal
JMP_JGT = 0x02 # jump if greater than
JMP_JGE = 0x03 # jump if greater or equal
JMP_JSET = 0x04 # jump if `src`& `reg`
JMP_JNE = 0x05 # jump if not equal
JMP_JSGT = 0x06 # jump if greater than (signed)
JMP_JSGE = 0x07 # jump if greater or equal (signed)
JMP_CALL = 0x08 # helper function call
JMP_EXIT = 0x09 # return from program
JMP_JLT = 0x0a # jump if lower than
JMP_JLE = 0x0b # jump if lower ir equal
JMP_JSLT = 0x0c # jump if lower than (signed)
JMP_JSLE = 0x0d # jump if lower or equal (signed)
# Sources
JMP_K = 0x00 # 32-bit immediate value
JMP_X = 0x01 # `src` register
EBPF_SRC_IMM = 0x00
EBPF_SRC_REG = 0x08
EBPF_MODE_IMM = 0x00
EBPF_MODE_MEM = 0x60
EBPF_OP_ADD_IMM = (OPC_ALU|EBPF_SRC_IMM|0x00)
EBPF_OP_ADD_REG = (OPC_ALU|EBPF_SRC_REG|0x00)
EBPF_OP_SUB_IMM = (OPC_ALU|EBPF_SRC_IMM|0x10)
EBPF_OP_SUB_REG = (OPC_ALU|EBPF_SRC_REG|0x10)
EBPF_OP_MUL_IMM = (OPC_ALU|EBPF_SRC_IMM|0x20)
EBPF_OP_MUL_REG = (OPC_ALU|EBPF_SRC_REG|0x20)
EBPF_OP_DIV_IMM = (OPC_ALU|EBPF_SRC_IMM|0x30)
EBPF_OP_DIV_REG = (OPC_ALU|EBPF_SRC_REG|0x30)
EBPF_OP_OR_IMM = (OPC_ALU|EBPF_SRC_IMM|0x40)
EBPF_OP_OR_REG = (OPC_ALU|EBPF_SRC_REG|0x40)
EBPF_OP_AND_IMM = (OPC_ALU|EBPF_SRC_IMM|0x50)
EBPF_OP_AND_REG = (OPC_ALU|EBPF_SRC_REG|0x50)
EBPF_OP_LSH_IMM = (OPC_ALU|EBPF_SRC_IMM|0x60)
EBPF_OP_LSH_REG = (OPC_ALU|EBPF_SRC_REG|0x60)
EBPF_OP_RSH_IMM = (OPC_ALU|EBPF_SRC_IMM|0x70)
EBPF_OP_RSH_REG = (OPC_ALU|EBPF_SRC_REG|0x70)
EBPF_OP_NEG = (OPC_ALU|0x80)
EBPF_OP_MOD_IMM = (OPC_ALU|EBPF_SRC_IMM|0x90)
EBPF_OP_MOD_REG = (OPC_ALU|EBPF_SRC_REG|0x90)
EBPF_OP_XOR_IMM = (OPC_ALU|EBPF_SRC_IMM|0xa0)
EBPF_OP_XOR_REG = (OPC_ALU|EBPF_SRC_REG|0xa0)
EBPF_OP_MOV_IMM = (OPC_ALU|EBPF_SRC_IMM|0xb0)
EBPF_OP_MOV_REG = (OPC_ALU|EBPF_SRC_REG|0xb0)
EBPF_OP_ARSH_IMM = (OPC_ALU|EBPF_SRC_IMM|0xc0)
EBPF_OP_ARSH_REG = (OPC_ALU|EBPF_SRC_REG|0xc0)
EBPF_OP_LE = (OPC_ALU|EBPF_SRC_IMM|0xd0)
EBPF_OP_BE = (OPC_ALU|EBPF_SRC_REG|0xd0)
EBPF_OP_ADD64_IMM = (OPC_ALU64|EBPF_SRC_IMM|0x00)
EBPF_OP_ADD64_REG = (OPC_ALU64|EBPF_SRC_REG|0x00)
EBPF_OP_SUB64_IMM = (OPC_ALU64|EBPF_SRC_IMM|0x10)
EBPF_OP_SUB64_REG = (OPC_ALU64|EBPF_SRC_REG|0x10)
EBPF_OP_MUL64_IMM = (OPC_ALU64|EBPF_SRC_IMM|0x20)
EBPF_OP_MUL64_REG = (OPC_ALU64|EBPF_SRC_REG|0x20)
EBPF_OP_DIV64_IMM = (OPC_ALU64|EBPF_SRC_IMM|0x30)
EBPF_OP_DIV64_REG = (OPC_ALU64|EBPF_SRC_REG|0x30)
EBPF_OP_OR64_IMM = (OPC_ALU64|EBPF_SRC_IMM|0x40)
EBPF_OP_OR64_REG = (OPC_ALU64|EBPF_SRC_REG|0x40)
EBPF_OP_AND64_IMM = (OPC_ALU64|EBPF_SRC_IMM|0x50)
EBPF_OP_AND64_REG = (OPC_ALU64|EBPF_SRC_REG|0x50)
EBPF_OP_LSH64_IMM = (OPC_ALU64|EBPF_SRC_IMM|0x60)
EBPF_OP_LSH64_REG = (OPC_ALU64|EBPF_SRC_REG|0x60)
EBPF_OP_RSH64_IMM = (OPC_ALU64|EBPF_SRC_IMM|0x70)
EBPF_OP_RSH64_REG = (OPC_ALU64|EBPF_SRC_REG|0x70)
EBPF_OP_NEG64 = (OPC_ALU64|0x80)
EBPF_OP_MOD64_IMM = (OPC_ALU64|EBPF_SRC_IMM|0x90)
EBPF_OP_MOD64_REG = (OPC_ALU64|EBPF_SRC_REG|0x90)
EBPF_OP_XOR64_IMM = (OPC_ALU64|EBPF_SRC_IMM|0xa0)
EBPF_OP_XOR64_REG = (OPC_ALU64|EBPF_SRC_REG|0xa0)
EBPF_OP_MOV64_IMM = (OPC_ALU64|EBPF_SRC_IMM|0xb0)
EBPF_OP_MOV64_REG = (OPC_ALU64|EBPF_SRC_REG|0xb0)
EBPF_OP_ARSH64_IMM = (OPC_ALU64|EBPF_SRC_IMM|0xc0)
EBPF_OP_ARSH64_REG = (OPC_ALU64|EBPF_SRC_REG|0xc0)
EBPF_OP_LDXW = (OPC_LDX|EBPF_MODE_MEM|EBPF_SIZE_W)
EBPF_OP_LDXH = (OPC_LDX|EBPF_MODE_MEM|EBPF_SIZE_H)
EBPF_OP_LDXB = (OPC_LDX|EBPF_MODE_MEM|EBPF_SIZE_B)
EBPF_OP_LDXDW = (OPC_LDX|EBPF_MODE_MEM|EBPF_SIZE_DW)
EBPF_OP_STW = (OPC_ST|EBPF_MODE_MEM|EBPF_SIZE_W)
EBPF_OP_STH = (OPC_ST|EBPF_MODE_MEM|EBPF_SIZE_H)
EBPF_OP_STB = (OPC_ST|EBPF_MODE_MEM|EBPF_SIZE_B)
EBPF_OP_STDW = (OPC_ST|EBPF_MODE_MEM|EBPF_SIZE_DW)
EBPF_OP_STXW = (OPC_STX|EBPF_MODE_MEM|EBPF_SIZE_W)
EBPF_OP_STXH = (OPC_STX|EBPF_MODE_MEM|EBPF_SIZE_H)
EBPF_OP_STXB = (OPC_STX|EBPF_MODE_MEM|EBPF_SIZE_B)
EBPF_OP_STXDW = (OPC_STX|EBPF_MODE_MEM|EBPF_SIZE_DW)
EBPF_OP_LDDW = (OPC_LD|EBPF_MODE_IMM|EBPF_SIZE_DW)
EBPF_OP_JA = (OPC_JMP|0x00)
EBPF_OP_JEQ_IMM = (OPC_JMP|EBPF_SRC_IMM|0x10)
EBPF_OP_JEQ_REG = (OPC_JMP|EBPF_SRC_REG|0x10)
EBPF_OP_JGT_IMM = (OPC_JMP|EBPF_SRC_IMM|0x20)
EBPF_OP_JGT_REG = (OPC_JMP|EBPF_SRC_REG|0x20)
EBPF_OP_JGE_IMM = (OPC_JMP|EBPF_SRC_IMM|0x30)
EBPF_OP_JGE_REG = (OPC_JMP|EBPF_SRC_REG|0x30)
EBPF_OP_JSET_IMM = (OPC_JMP|EBPF_SRC_IMM|0x40)
EBPF_OP_JSET_REG = (OPC_JMP|EBPF_SRC_REG|0x40)
EBPF_OP_JNE_IMM = (OPC_JMP|EBPF_SRC_IMM|0x50)
EBPF_OP_JNE_REG = (OPC_JMP|EBPF_SRC_REG|0x50)
EBPF_OP_JSGT_IMM = (OPC_JMP|EBPF_SRC_IMM|0x60)
EBPF_OP_JSGT_REG = (OPC_JMP|EBPF_SRC_REG|0x60)
EBPF_OP_JSGE_IMM = (OPC_JMP|EBPF_SRC_IMM|0x70)
EBPF_OP_JSGE_REG = (OPC_JMP|EBPF_SRC_REG|0x70)
EBPF_OP_CALL = (OPC_JMP|0x80)
EBPF_OP_EXIT = (OPC_JMP|0x90)
EBPF_OP_JLT_IMM = (OPC_JMP|EBPF_SRC_IMM|0xa0)
EBPF_OP_JLT_REG = (OPC_JMP|EBPF_SRC_REG|0xa0)
EBPF_OP_JLE_IMM = (OPC_JMP|EBPF_SRC_IMM|0xb0)
EBPF_OP_JLE_REG = (OPC_JMP|EBPF_SRC_REG|0xb0)
EBPF_OP_JSLT_IMM = (OPC_JMP|EBPF_SRC_IMM|0xc0)
EBPF_OP_JSLT_REG = (OPC_JMP|EBPF_SRC_REG|0xc0)
EBPF_OP_JSLE_IMM = (OPC_JMP|EBPF_SRC_IMM|0xd0)
EBPF_OP_JSLE_REG = (OPC_JMP|EBPF_SRC_REG|0xd0)
|
# Copyright (c) 2011 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'targets': [
{
'target_name': 'prefix_header',
'type': 'static_library',
'sources': [ 'file.c', ],
'xcode_settings': {
'GCC_PREFIX_HEADER': 'header.h',
},
},
{
'target_name': 'precompiled_prefix_header',
'type': 'shared_library',
'mac_bundle': 1,
'sources': [ 'file.c', ],
'xcode_settings': {
'GCC_PREFIX_HEADER': 'header.h',
'GCC_PRECOMPILE_PREFIX_HEADER': 'YES',
},
},
],
}
|
#FACTORIAL OF A NUMBER
a = input("Enter number1")
a=int(a)
factorial=1
if a==1:
print('Factorial is 1')
elif a<1:
print('Please enter a valid number')
else:
for i in range(1, a+1):
factorial *= i
print(f'The factorial is {factorial}') |
# Copyright 2020 Q-CTRL Pty Ltd & Q-CTRL 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.
"""
Defines constants for driven controls module.
"""
# Maximum allowed rabi rate
UPPER_BOUND_RABI_RATE = 1e10
# Maximum allowed detuning rate
UPPER_BOUND_DETUNING_RATE = UPPER_BOUND_RABI_RATE
# Maximum allowed duration of a control
UPPER_BOUND_DURATION = 1e6
# Minimum allowed duration of a control
LOWER_BOUND_DURATION = 1e-12
# Maximum number of segments allowed in a control
UPPER_BOUND_SEGMENTS = 10000
# Primitive control
PRIMITIVE = "primitive"
# First-order Wimperis control, also known as BB1
BB1 = "BB1"
# First-order Solovay-Kitaev control
SK1 = "SK1"
# First-order Walsh sequence control
WAMF1 = "WAMF1"
# Dynamically corrected control - Compensating for Off-Resonance with a Pulse Sequence (COPRSE)
CORPSE = "CORPSE"
# Concatenated dynamically corrected control - BB1 inside COPRSE
CORPSE_IN_BB1 = "CORPSE in BB1"
# Concatenated dynamically corrected control - First order Solovay-Kitaev inside COPRSE
CORPSE_IN_SK1 = "CORPSE in SK1"
# Dynamically corrected control
# Short Composite Rotation For Undoing Length Over and Under Shoot (SCROFULOUS)
SCROFULOUS = "SCROFULOUS"
# Concatenated dynamically corrected control - CORPSE inside SCROFULOUS
CORPSE_IN_SCROFULOUS = "CORPSE in SCROFULOUS"
|
class Node:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
node = Node("root", Node("left", Node("left.left")), Node("right"))
s = ""
def serialize(node, s=""):
if not node:
s += "# "
return s
s += str(node.val) + " "
s = serialize(node.left, s=s)
s = serialize(node.right, s=s)
return s
i = 0
def deserialize(s):
global i
if s[i] == "#":
if i < len(s) - 2:
i += 2
return None
else:
space = s[i:].find(" ")
sp = space + i
node = Node(s[i:sp])
i = sp + 1
node.left = deserialize(s)
node.right = deserialize(s)
return node
if __name__ == "__main__":
"""
from timeit import timeit
print(timeit(lambda: serialize(node), number=10000)) # 0.017630080999879283
print(timeit(lambda: deserialize(serialize(node)), number=10000)) # 0.020570166999732464
"""
|
# 5) Faça um programa que leia um número inteiro e mostre na tela o seu sucessor e antecessor.
# Resolução do Exercício 5:
valor = int(input('Digite um número: '))
print(f'Analisando o valor {valor}, seu antecessor é {valor - 1} e o sucessor é {valor + 1}.') |
# Программа запрашивает у пользователя строку чисел, разделенных пробелом.
# При нажатии Enter должна выводиться сумма чисел.
# Пользователь может продолжить ввод чисел, разделенных пробелом и снова нажать Enter.
# Сумма вновь введенных чисел будет добавляться к уже подсчитанной сумме.
# Но если вместо числа вводится специальный символ, выполнение программы завершается.
# Если специальный символ введен после нескольких чисел,
# то вначале нужно добавить сумму этих чисел к полученной ранее сумме и после этого завершить программу.
def sum_nums(numbers_list):
sum_ = 0
for n in numbers_list:
sum_ += int(n)
return sum_
result = 0
while True:
num_string = input("Введите строку чисел, разделенных пробелом "
"(для завершения работы введите 'q' в конце строки): \n")
nums = num_string.split()
if nums[-1] == 'q':
nums.pop()
result += sum_nums(nums)
print(f"Работа завершена. Сумма чисел: {result}")
break
else:
result += sum_nums(nums)
print(f"Сумма чисел: {result}")
|
# -*- coding: utf-8 -*-
class Job:
def __init__(self, job_id, name, status, start_date, end_date,
source_records, processed_records, price):
self.id = job_id
self.name = name
self.status = status
self.start_date = start_date
self.end_date = end_date
self.source_records = source_records
self.processed_records = processed_records
self.price = price
def __repr__(self):
return str(vars(self))
class JobReport:
def __new__(cls, *args, **kwargs):
if 'code' in kwargs:
return None
return super().__new__(cls)
def __init__(self, quality_issues, quality_names, results):
self.quality_issues = quality_issues
self.quality_names = quality_names
self.results = results
def __repr__(self):
return str(vars(self))
class JobConfig:
def __init__(self, name):
self.name = name
self._input_format = {
"field_separator": ",",
"text_delimiter": "\"",
"code_page": "utf-8"
}
self._input_columns = {}
self._extend = {
"teryt": 0,
"gus": 0,
"geocode": 0,
"building_info": 0,
"diagnostic": 0,
"area_characteristic": 0
}
self._module_std = {
"address": 0,
"names": 0,
"contact": 0,
"id_numbers": 0
}
self._client = {
"name": "",
"mode": ""
}
self._deduplication = {
"on": 0,
"incremental": 0
}
def input_format(self, field_separator=",", text_delimiter="\"",
code_page="utf-8"):
self._input_format["field_separator"] = field_separator
self._input_format["text_delimiter"] = text_delimiter
self._input_format["code_page"] = code_page
def input_column(self, idx, name, function):
self._input_columns[idx] = {"no": idx, "name": name,
"function": function}
def extend(self, teryt=False, gus=False, geocode=False,
building_info=False, diagnostic=False,
area_characteristic=False):
self._extend["teryt"] = self.__boolean_to_num(teryt)
self._extend["gus"] = self.__boolean_to_num(gus)
self._extend["geocode"] = self.__boolean_to_num(geocode)
self._extend["building_info"] = self.__boolean_to_num(building_info)
self._extend["diagnostic"] = self.__boolean_to_num(diagnostic)
self._extend["area_characteristic"] = \
self.__boolean_to_num(area_characteristic)
def module_std(self, address = False, names = False, contact = False, id_numbers = False):
self._module_std["address"] = self.__boolean_to_num(address)
self._module_std["names"] = self.__boolean_to_num(names)
self._module_std["contact"] = self.__boolean_to_num(contact)
self._module_std["id_numbers"] = self.__boolean_to_num(id_numbers)
def deduplication(self, on = False, incremental = False):
self._deduplication["on"] = self.__boolean_to_num(on)
self._deduplication["incremental"] = self.__boolean_to_num(incremental)
def client(self, name, mode):
self._client["name"] = name
self._client["mode"] = mode
@staticmethod
def __boolean_to_num(value):
return 1 if value else 0
def data(self):
return {
"job_name": self.name,
"input_format": self._input_format,
"input_columns": list(self._input_columns.values()),
"extend": self._extend,
"module_std": self._module_std,
"deduplication": self._deduplication,
"client": self._client
}
|
def median(iterable):
items = sorted(iterable)
if len(items) == 0:
raise ValueError("median() arg is an empty series")
median_index = (len(items) - 1) // 2
if len(items) % 2 != 0:
return items[median_index]
return (items[median_index] + items[median_index + 1]) / 2
print(median([5, 2, 1, 4, 3]))
def main():
try:
median([])
except ValueError as e:
print("Payload", e.args)
main()
|
"""
Product Store
Write a class Product that has three attributes:
type
name
price
Then create a class ProductStore, which will have some Products and will operate with
all products in the store. All methods, in case they can’t perform its action, should
raise ValueError with appropriate error information.
Tips: Use aggregation/composition concepts while implementing the ProductStore class.
You can also implement additional classes to operate on a certain type of product, etc.
Also, the ProductStore class must have the following methods:
add(product, amount) - adds a specified quantity of a single product with a predefined price
premium for your store(30 percent)
set_discount(identifier, percent, identifier_type=’name’) - adds a discount for all products
specified by input identifiers (type or name). The discount must be specified in percentage
sell_product(product_name, amount) - removes a particular amount of products from the store
if available, in other case raises an error. It also increments income
if the sell_product method succeeds.
get_income() - returns amount of many earned by ProductStore instance.
get_all_products() - returns information about all available products in the store.
get_product_info(product_name) - returns a tuple with product name and amount of items in the store.
"""
class Product:
def __init__(self, type_, name, price):
self.type = type_
self.name = name
self.price = price
class ProductStore:
def __init__(self):
self.products = []
self.discounts = []
self.income = 0
def add(self, product, amount, discount=None):
self.products.append({
"product": product,
"amount": amount
})
if discount is not None:
self.discounts.append({
"product": product,
"discount": discount
})
def set_discount(self, identifier, percent, identifier_type='name'):
pass
def sell_product(self, product_name, amount):
for p in self.products:
product_in_store = p["product"]
amount_in_store = p["amount"]
if product_in_store.name != product_name:
continue
if amount_in_store < amount:
raise ValueError(f"Can't sell {amount} product(s). Store contains only {amount_in_store}.")
p['amount'] -= amount
self.income += (product_in_store.price * 1.3) * amount
def get_income(self):
return self.income
def get_all_products(self):
for product in self.products:
product_in_store = product["product"]
amount_in_store = product["amount"]
print("{}\t | {}\t | ${}\t | {}".format(
product_in_store.type,
product_in_store.name,
product_in_store.price,
amount_in_store if amount_in_store > 0 else "Not in store"
))
def get_product_info(self, product_name):
for p in self.products:
product_in_store = p["product"]
amount_in_store = p["amount"]
if product_in_store.name != product_name:
continue
return (product_in_store.name, amount_in_store)
raise ValueError("Product not found")
def main():
store = ProductStore()
p1 = Product("Sport", "Football T-Shirt", 100)
p2 = Product("Food", "Ramen", 1.5)
store.add(p1, 10)
store.add(p2, 100)
print("Initial store state:")
store.get_all_products()
print("Selling 10 ramens...")
store.sell_product("Ramen", 10)
print("Store state after selling:")
store.get_all_products()
print(store.get_income())
print(store.discounts)
#
# print("Total income: ${}".format(store.get_income()))
if __name__ == "__main__":
main() |
# Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo
# Copyright (C) 2011-2019 German Aerospace Center (DLR) and others.
# This program and the accompanying materials
# are made available under the terms of the Eclipse Public License v2.0
# which accompanies this distribution, and is available at
# http://www.eclipse.org/legal/epl-v20.html
# SPDX-License-Identifier: EPL-2.0
# @file node.py
# @author Daniel Krajzewicz
# @author Laura Bieker
# @author Karol Stosiek
# @author Michael Behrisch
# @author Jakob Erdmann
# @date 2011-11-28
# @version $Id$
class Node:
""" Nodes from a sumo network """
def __init__(self, id, type, coord, incLanes, intLanes=None):
self._id = id
self._type = type
self._coord = coord
self._incoming = []
self._outgoing = []
self._foes = {}
self._prohibits = {}
self._incLanes = incLanes
self._intLanes = intLanes
self._shape3D = None
self._shape = None
self._params = {}
def getID(self):
return self._id
def setShape(self, shape):
"""Set the shape of the node.
Shape must be a list containing x,y,z coords as numbers
to represent the shape of the node.
"""
for pp in shape:
if len(pp) != 3:
raise ValueError('shape point must consist of x,y,z')
self._shape3D = shape
self._shape = [(x, y) for x, y, z in shape]
def getShape(self):
"""Returns the shape of the node in 2d.
This function returns the shape of the node, as defined in the net.xml
file. The returned shape is a list containing numerical
2-tuples representing the x,y coordinates of the shape points.
If no shape is defined in the xml, an empty list will be returned.
"""
return self._shape
def getShape3D(self):
"""Returns the shape of the node in 3d.
This function returns the shape of the node, as defined in the net.xml
file. The returned shape is a list containing numerical
3-tuples representing the x,y,z coordinates of the shape points.
If no shape is defined in the xml, an empty list will be returned.
"""
return self._shape3D
def addOutgoing(self, edge):
self._outgoing.append(edge)
def getOutgoing(self):
return self._outgoing
def addIncoming(self, edge):
self._incoming.append(edge)
def getIncoming(self):
return self._incoming
def getInternal(self):
return self._intLanes
def setFoes(self, index, foes, prohibits):
self._foes[index] = foes
self._prohibits[index] = prohibits
def areFoes(self, link1, link2):
return self._foes[link1][len(self._foes[link1]) - link2 - 1] == '1'
def getLinkIndex(self, conn):
ret = 0
for lane_id in self._incLanes:
lastUnderscore = lane_id.rfind("_")
if lastUnderscore > 0:
edge_id = lane_id[:lastUnderscore]
index = lane_id[lastUnderscore+1:]
edge = [e for e in self._incoming if e.getID() == edge_id][0]
for candidate_conn in edge.getLane(int(index)).getOutgoing():
if candidate_conn == conn:
return ret
ret += 1
return -1
def forbids(self, possProhibitor, possProhibited):
possProhibitorIndex = self.getLinkIndex(possProhibitor)
possProhibitedIndex = self.getLinkIndex(possProhibited)
if possProhibitorIndex < 0 or possProhibitedIndex < 0:
return False
ps = self._prohibits[possProhibitedIndex]
return ps[-(possProhibitorIndex - 1)] == '1'
def getCoord(self):
return tuple(self._coord[:2])
def getCoord3D(self):
return self._coord
def getType(self):
return self._type
def getConnections(self, source=None, target=None):
if source:
incoming = [source]
else:
incoming = list(self._incoming)
conns = []
for e in incoming:
if (hasattr(e, "getLanes")):
lanes = e.getLanes()
else:
# assuming source is a lane
lanes = [e]
for l in lanes:
all_outgoing = l.getOutgoing()
outgoing = []
if target:
if hasattr(target, "getLanes"):
for o in all_outgoing:
if o.getTo() == target:
outgoing.append(o)
else:
# assuming target is a lane
for o in all_outgoing:
if o.getToLane() == target:
outgoing.append(o)
else:
outgoing = all_outgoing
conns.extend(outgoing)
return conns
def setParam(self, key, value):
self._params[key] = value
def getParam(self, key, default=None):
return self._params.get(key, default)
def getParams(self):
return self._params
def getNeighboringNodes(self, outgoingNodes=True, incomingNodes=True):
neighboring = []
if incomingNodes:
edges = self._incoming
for e in edges:
if not (e.getFromNode() in neighboring) and not(e.getFromNode().getID() == self.getID()):
neighboring.append(e.getFromNode())
if outgoingNodes:
edges = self._outgoing
for e in edges:
if not (e.getToNode() in neighboring)and not(e.getToNode().getID() == self.getID()):
neighboring.append(e.getToNode())
return neighboring
|
cali_cities = ["Adelanto",
"Agoura Hills",
"Alameda",
"Albany",
"Alhambra",
"Aliso Viejo",
"Alturas",
"Amador City",
"American Canyon",
"Anaheim",
"Anderson",
"Angels Camp",
"Antioch",
"Apple Valley",
"Arcadia",
"Arcata",
"Arroyo Grande",
"Artesia",
"Arvin",
"Atascadero",
"Atherton",
"Atwater",
"Auburn",
"Avalon",
"Avenal",
"Azusa",
"Bakersfield",
"Baldwin Park",
"Banning",
"Barstow",
"Beaumont",
"Bell",
"Bell Gardens",
"Bellflower",
"Belmont",
"Belvedere",
"Benicia",
"Berkeley",
"Beverly Hills",
"Big Bear Lake",
"Biggs",
"Bishop",
"Blue Lake",
"Blythe",
"Bradbury",
"Brawley",
"Brea",
"Brentwood",
"Brisbane",
"Buellton",
"Buena Park",
"Burbank",
"Burlingame",
"Calabasas",
"Calexico",
"California City",
"Calimesa",
"Calipatria",
"Calistoga",
"Camarillo",
"Campbell",
"Canyon Lake",
"Capitola",
"Carlsbad",
"Carmel-by-the-Sea",
"Carpinteria",
"Carson",
"Cathedral City",
"Ceres",
"Cerritos",
"Chico",
"Chino",
"Chino Hills",
"Chowchilla",
"Chula Vista",
"Citrus Heights",
"Claremont",
"Clayton",
"Clearlake",
"Cloverdale",
"Clovis",
"Coachella",
"Coalinga",
"Colfax",
"Colma",
"Colton",
"Colusa",
"Commerce",
"Compton",
"Concord",
"Corcoran",
"Corning",
"Corona",
"Coronado",
"Corte Madera",
"Costa Mesa",
"Cotati",
"Covina",
"Crescent City",
"Cudahy",
"Culver City",
"Cupertino",
"Cypress",
"Daly City",
"Dana Point",
"Danville",
"Davis",
"Del Mar",
"Del Rey Oaks",
"Delano",
"Desert Hot Springs",
"Diamond Bar",
"Dinuba",
"Dixon",
"Dorris",
"Dos Palos",
"Downey",
"Duarte",
"Dublin",
"Dunsmuir",
"East Palo Alto",
"Eastvale",
"El Cajon",
"El Centro",
"El Cerrito",
"El Monte",
"El Segundo",
"Elk Grove",
"Emeryville",
"Encinitas",
"Escalon",
"Escondido",
"Etna",
"Eureka",
"Exeter",
"Fairfax",
"Fairfield",
"Farmersville",
"Ferndale",
"Fillmore",
"Firebaugh",
"Folsom",
"Fontana",
"Fort Bragg",
"Fort Jones",
"Fortuna",
"Foster City",
"Fountain Valley",
"Fowler",
"Fremont",
"Fresno",
"Fullerton",
"Galt",
"Garden Grove",
"Gardena",
"Gilroy",
"Glendale",
"Glendora",
"Goleta",
"Gonzales",
"Grand Terrace",
"Grass Valley",
"Greenfield",
"Gridley",
"Grover Beach",
"Guadalupe",
"Gustine",
"Half Moon Bay",
"Hanford",
"Hawaiian Gardens",
"Hawthorne",
"Hayward",
"Healdsburg",
"Hemet",
"Hercules",
"Hermosa Beach",
"Hesperia",
"Hidden Hills",
"Highland",
"Hillsborough",
"Hollister",
"Holtville",
"Hughson",
"Huntington Beach",
"Huntington Park",
"Huron",
"Imperial",
"Imperial Beach",
"Indian Wells",
"Indio",
"Industry",
"Inglewood",
"Ione",
"Irvine",
"Irwindale",
"Isleton",
"Jackson",
"Jurupa Valley",
"Kerman",
"King City",
"Kingsburg",
"La Cañada Flintridge",
"La Habra",
"La Habra Heights",
"La Mesa",
"La Mirada",
"La Palma",
"La Puente",
"La Quinta",
"La Verne",
"Lafayette",
"Laguna Beach",
"Laguna Hills",
"Laguna Niguel",
"Laguna Woods",
"Lake Elsinore",
"Lake Forest",
"Lakeport",
"Lakewood",
"Lancaster",
"Larkspur",
"Lathrop",
"Lawndale",
"Lemon Grove",
"Lemoore",
"Lincoln",
"Lindsay",
"Live Oak",
"Livermore",
"Livingston",
"Lodi",
"Loma Linda",
"Lomita",
"Lompoc",
"Long Beach",
"Loomis",
"Los Alamitos",
"Los Altos",
"Los Altos Hills",
"Los Angeles",
"Los Banos",
"Los Gatos",
"Loyalton",
"Lynwood",
"Madera",
"Malibu",
"Mammoth Lakes",
"Manhattan Beach",
"Manteca",
"Maricopa",
"Marina",
"Martinez",
"Marysville",
"Maywood",
"McFarland",
"Mendota",
"Menifee",
"Menlo Park",
"Merced",
"Mill Valley",
"Millbrae",
"Milpitas",
"Mission Viejo",
"Modesto",
"Monrovia",
"Montague",
"Montclair",
"Monte Sereno",
"Montebello",
"Monterey",
"Monterey Park",
"Moorpark",
"Moraga",
"Moreno Valley",
"Morgan Hill",
"Morro Bay",
"Mount Shasta",
"Mountain View",
"Murrieta",
"Napa",
"National City",
"Needles",
"Nevada City",
"Newark",
"Newman",
"Newport Beach",
"Norco",
"Norwalk",
"Novato",
"Oakdale",
"Oakland",
"Oakley",
"Oceanside",
"Ojai",
"Ontario",
"Orange",
"Orange Cove",
"Orinda",
"Orland",
"Oroville",
"Oxnard",
"Pacific Grove",
"Pacifica",
"Palm Desert",
"Palm Springs",
"Palmdale",
"Palo Alto",
"Palos Verdes Estates",
"Paradise",
"Paramount",
"Parlier",
"Pasadena",
"Paso Robles",
"Patterson",
"Perris",
"Petaluma",
"Pico Rivera",
"Piedmont",
"Pinole",
"Pismo Beach",
"Pittsburg",
"Placentia",
"Placerville",
"Pleasant Hill",
"Pleasanton",
"Plymouth",
"Point Arena",
"Pomona",
"Port Hueneme",
"Porterville",
"Portola",
"Portola Valley",
"Poway",
"Rancho Cordova",
"Rancho Cucamonga",
"Rancho Mirage",
"Rancho Palos Verdes",
"Rancho Santa Margarita",
"Red Bluff",
"Redding",
"Redlands",
"Redondo Beach",
"Redwood City",
"Reedley",
"Rialto",
"Richmond",
"Ridgecrest",
"Rio Dell",
"Rio Vista",
"Ripon",
"Riverbank",
"Riverside",
"Rocklin",
"Rohnert Park",
"Rolling Hills",
"Rolling Hills Estates",
"Rosemead",
"Roseville",
"Ross",
"Sacramento",
"St. Helena",
"Salinas",
"San Anselmo",
"San Bernardino",
"San Bruno",
"San Carlos",
"San Clemente",
"San Diego",
"San Dimas",
"San Fernando",
"San Francisco",
"San Gabriel",
"San Jacinto",
"San Joaquin",
"San Jose",
"San Juan Bautista",
"San Juan Capistrano",
"San Leandro",
"San Luis Obispo",
"San Marcos",
"San Marino",
"San Mateo",
"San Pablo",
"San Rafael",
"San Ramon",
"Sand City",
"Sanger",
"Santa Ana",
"Santa Barbara",
"Santa Clara",
"Santa Clarita",
"Santa Cruz",
"Santa Fe Springs",
"Santa Maria",
"Santa Monica",
"Santa Paula",
"Santa Rosa",
"Santee",
"Saratoga",
"Sausalito",
"Scotts Valley",
"Seal Beach",
"Seaside",
"Sebastopol",
"Selma",
"Shafter",
"Shasta Lake",
"Sierra Madre",
"Signal Hill",
"Simi Valley",
"Solana Beach",
"Soledad",
"Solvang",
"Sonoma",
"Sonora",
"South El Monte",
"South Gate",
"South Lake Tahoe",
"South Pasadena",
"South San Francisco",
"Stanton",
"Stockton",
"Suisun City",
"Sunnyvale",
"Susanville",
"Sutter Creek",
"Taft",
"Tehachapi",
"Tehama",
"Temecula",
"Temple City",
"Thousand Oaks",
"Tiburon",
"Torrance",
"Tracy",
"Trinidad",
"Truckee",
"Tulare",
"Tulelake",
"Turlock",
"Tustin",
"Twentynine Palms",
"Ukiah",
"Union City",
"Upland",
"Vacaville",
"Vallejo",
"Ventura",
"Vernon",
"Victorville",
"Villa Park",
"Visalia",
"Vista",
"Walnut",
"Walnut Creek",
"Wasco",
"Waterford",
"Watsonville",
"Weed",
"West Covina",
"West Hollywood",
"West Sacramento",
"Westlake Village",
"Westminster",
"Westmorland",
"Wheatland",
"Whittier",
"Wildomar",
"Williams",
"Willits",
"Willows",
"Windsor",
"Winters",
"Woodlake",
"Woodland",
"Woodside",
"Yorba Linda",
"Yountville",
"Yreka",
"Yuba City",
"Yucaipa",
"Yucca Valley"]
|
def get():
return int(input())
def get_num():
return get()
def get_line():
return get_num()
print(get_line())
|
# ### Problem 1
# ```
# # Start with this List
# list_of_many_numbers = [12, 24, 1, 34, 10, 2, 7]
# ```
# Example Input/Output if the user enters the number 9:
# ```
# The User entered 9
# 1 2 7 are smaller than 9
# 12 24 34 10 are larger than 9
# ```
# Ask the user to enter a number.
userInput = int(input("Enter a number "))
# Using the provided list of numbers, use a for loop to iterate the array and
# print out all the values that are smaller than the user input and print out
# all the values that are larger than the number entered by the user.
list_of_many_numbers = [12, 24, 1, 34, 10, 2, 7]
for x in list_of_many_numbers:
# print out all the values that are smaller than the user input
if (userInput > x):
print('the value that is smaller than the user input ', x)
# print out all the values that are larger than the number entered by the user
if (userInput < x):
print('the value that is greater than the user input ', x)
|
class Scheduler(object):
def __init__(self, env, cpu_list=[], task_list=[]):
self.env = env
self.cpu_list = cpu_list
self.task_list = []
self._lock = False
self.overhead = 0
def run(self):
pass
def on_activate(self, job):
pass
def on_terminated(self, job):
pass
def schedule(self, cpu):
raise NotImplementedError("You need to everride the schedule method!")
def add_task(self, task):
self.task_list.append(task)
def add_processor(self, cpu):
self.cpu_list.append(cpu) |
"""
This is a sample program to demonstrate string concatenation
"""
if __name__ == "__main__":
alice_name = "Alice"
bob_name = "Bob"
print(alice_name + bob_name) |
# test 0
# correct answer
# [0]
num_topics, num_themes = 1, 1
lst = [0]
with open('input.txt', 'w') as f:
f.write("{} {}\n".format(num_topics, num_themes))
for l in lst:
f.write(str(l) + '\n')
|
def binary_Search(w, q):
if len(w) == 1 or len(q) == 1:
return False
else:
# q의 앞이 ?로 시작하는지
q_next_start = 0
q_next_end = len(q) - 1
if q[0] == '?':
q_next_start = (len(q) // 2)
else:
q_next_end = (len(q) // 2)
print(q[q_next_start:q_next_end])
binary_Search(w[q_next_start:q_next_end], q[q_next_start:q_next_end])
def solution(words, queries):
answer = []
for i in range(len(words)):
for j in range(len(queries)):
if len(words[i]) != len(queries[j]):
continue
else:
binary_Search(words[i], queries[i])
return answer
solution(["frodo", "front", "frost", "frozen", "frame", "kakao"], ["fro??", "????o", "fr???", "fro???", "pro?"])
|
class Stack():
def __init__(self):
self.items = []
def push(self, item):
return self.items.append(item)
def pop(self):
return self.items.pop()
def IsEmpty(self):
return self.items == []
def length(self):
return len(self.items)
def peek(self):
return self.items[len(self.items) - 1]
s = Stack()
s.IsEmpty()
s.push(10)
s.length()
s.push(20)
s.push(30)
s.length()
s.peek()
s.pop()
s.IsEmpty()
s.pop()
s.pop()
s.IsEmpty() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.