content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
class Statistics:
def __init__(
self,
):
self.metrics = {
'success': 0,
'failure': 0,
'retry': 0,
'process': 0,
'heartbeat': 0,
}
self.workers = {}
def process_report(
self,
message,
):
self.process_report_metrics(
message=message,
)
self.process_report_worker_statistics(
message=message,
)
def process_report_metrics(
self,
message,
):
report_type = message['type']
report_value = message['value']
self.metrics[report_type] += report_value
def process_report_worker_statistics(
self,
message,
):
report_hostname = message['hostname']
report_worker_name = message['worker_name']
report_type = message['type']
report_value = message['value']
if report_hostname not in self.workers:
self.workers[report_hostname] = {
report_worker_name: {
'success': 0,
'failure': 0,
'retry': 0,
'process': 0,
'heartbeat': 0,
}
}
elif report_worker_name not in self.workers[report_hostname]:
self.workers[report_hostname][report_worker_name] = {
'success': 0,
'failure': 0,
'retry': 0,
'process': 0,
'heartbeat': 0,
}
self.workers[report_hostname][report_worker_name][report_type] += report_value
| class Statistics:
def __init__(self):
self.metrics = {'success': 0, 'failure': 0, 'retry': 0, 'process': 0, 'heartbeat': 0}
self.workers = {}
def process_report(self, message):
self.process_report_metrics(message=message)
self.process_report_worker_statistics(message=message)
def process_report_metrics(self, message):
report_type = message['type']
report_value = message['value']
self.metrics[report_type] += report_value
def process_report_worker_statistics(self, message):
report_hostname = message['hostname']
report_worker_name = message['worker_name']
report_type = message['type']
report_value = message['value']
if report_hostname not in self.workers:
self.workers[report_hostname] = {report_worker_name: {'success': 0, 'failure': 0, 'retry': 0, 'process': 0, 'heartbeat': 0}}
elif report_worker_name not in self.workers[report_hostname]:
self.workers[report_hostname][report_worker_name] = {'success': 0, 'failure': 0, 'retry': 0, 'process': 0, 'heartbeat': 0}
self.workers[report_hostname][report_worker_name][report_type] += report_value |
def in_the_matrix():
matrix = [[1, 2, 3],[4, 5, 6],[7, 8, 9]]
rows = len(matrix) # count # of rows
for i in range(rows):
col = len(matrix[i]) # count # of columns
for x in range(col):
print(matrix[i][x], end='')
print()
return | def in_the_matrix():
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
rows = len(matrix)
for i in range(rows):
col = len(matrix[i])
for x in range(col):
print(matrix[i][x], end='')
print()
return |
# https://github.com/jeffmer/micropython-upybbot/blob/master/font.py
'''
* This file is part of the Micro Python project, http:#micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2013, 2014 Damien P. George
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
'''
font_8x8 = bytes([
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, # 32=
0x00,0x00,0x00,0x4f,0x4f,0x00,0x00,0x00, # 33=!
0x00,0x07,0x07,0x00,0x00,0x07,0x07,0x00, # 34="
0x14,0x7f,0x7f,0x14,0x14,0x7f,0x7f,0x14, # 35= hash
0x00,0x24,0x2e,0x6b,0x6b,0x3a,0x12,0x00, # 36=$
0x00,0x63,0x33,0x18,0x0c,0x66,0x63,0x00, # 37=%
0x00,0x32,0x7f,0x4d,0x4d,0x77,0x72,0x50, # 38=&
0x00,0x00,0x00,0x04,0x06,0x03,0x01,0x00, # 39='
0x00,0x00,0x1c,0x3e,0x63,0x41,0x00,0x00, # 40=(
0x00,0x00,0x41,0x63,0x3e,0x1c,0x00,0x00, # 41=)
0x08,0x2a,0x3e,0x1c,0x1c,0x3e,0x2a,0x08, # 42=*
0x00,0x08,0x08,0x3e,0x3e,0x08,0x08,0x00, # 43=+
0x00,0x00,0x80,0xe0,0x60,0x00,0x00,0x00, # 44=,
0x00,0x08,0x08,0x08,0x08,0x08,0x08,0x00, # 45=-
0x00,0x00,0x00,0x60,0x60,0x00,0x00,0x00, # 46=.
0x00,0x40,0x60,0x30,0x18,0x0c,0x06,0x02, # 47=/
0x00,0x3e,0x7f,0x49,0x45,0x7f,0x3e,0x00, # 48=0
0x00,0x40,0x44,0x7f,0x7f,0x40,0x40,0x00, # 49=1
0x00,0x62,0x73,0x51,0x49,0x4f,0x46,0x00, # 50=2
0x00,0x22,0x63,0x49,0x49,0x7f,0x36,0x00, # 51=3
0x00,0x18,0x18,0x14,0x16,0x7f,0x7f,0x10, # 52=4
0x00,0x27,0x67,0x45,0x45,0x7d,0x39,0x00, # 53=5
0x00,0x3e,0x7f,0x49,0x49,0x7b,0x32,0x00, # 54=6
0x00,0x03,0x03,0x79,0x7d,0x07,0x03,0x00, # 55=7
0x00,0x36,0x7f,0x49,0x49,0x7f,0x36,0x00, # 56=8
0x00,0x26,0x6f,0x49,0x49,0x7f,0x3e,0x00, # 57=9
0x00,0x00,0x00,0x24,0x24,0x00,0x00,0x00, # 58=:
0x00,0x00,0x80,0xe4,0x64,0x00,0x00,0x00, # 59=;
0x00,0x08,0x1c,0x36,0x63,0x41,0x41,0x00, # 60=<
0x00,0x14,0x14,0x14,0x14,0x14,0x14,0x00, # 61==
0x00,0x41,0x41,0x63,0x36,0x1c,0x08,0x00, # 62=>
0x00,0x02,0x03,0x51,0x59,0x0f,0x06,0x00, # 63=?
0x00,0x3e,0x7f,0x41,0x4d,0x4f,0x2e,0x00, # 64=@
0x00,0x7c,0x7e,0x0b,0x0b,0x7e,0x7c,0x00, # 65=A
0x00,0x7f,0x7f,0x49,0x49,0x7f,0x36,0x00, # 66=B
0x00,0x3e,0x7f,0x41,0x41,0x63,0x22,0x00, # 67=C
0x00,0x7f,0x7f,0x41,0x63,0x3e,0x1c,0x00, # 68=D
0x00,0x7f,0x7f,0x49,0x49,0x41,0x41,0x00, # 69=E
0x00,0x7f,0x7f,0x09,0x09,0x01,0x01,0x00, # 70=F
0x00,0x3e,0x7f,0x41,0x49,0x7b,0x3a,0x00, # 71=G
0x00,0x7f,0x7f,0x08,0x08,0x7f,0x7f,0x00, # 72=H
0x00,0x00,0x41,0x7f,0x7f,0x41,0x00,0x00, # 73=I
0x00,0x20,0x60,0x41,0x7f,0x3f,0x01,0x00, # 74=J
0x00,0x7f,0x7f,0x1c,0x36,0x63,0x41,0x00, # 75=K
0x00,0x7f,0x7f,0x40,0x40,0x40,0x40,0x00, # 76=L
0x00,0x7f,0x7f,0x06,0x0c,0x06,0x7f,0x7f, # 77=M
0x00,0x7f,0x7f,0x0e,0x1c,0x7f,0x7f,0x00, # 78=N
0x00,0x3e,0x7f,0x41,0x41,0x7f,0x3e,0x00, # 79=O
0x00,0x7f,0x7f,0x09,0x09,0x0f,0x06,0x00, # 80=P
0x00,0x1e,0x3f,0x21,0x61,0x7f,0x5e,0x00, # 81=Q
0x00,0x7f,0x7f,0x19,0x39,0x6f,0x46,0x00, # 82=R
0x00,0x26,0x6f,0x49,0x49,0x7b,0x32,0x00, # 83=S
0x00,0x01,0x01,0x7f,0x7f,0x01,0x01,0x00, # 84=T
0x00,0x3f,0x7f,0x40,0x40,0x7f,0x3f,0x00, # 85=U
0x00,0x1f,0x3f,0x60,0x60,0x3f,0x1f,0x00, # 86=V
0x00,0x7f,0x7f,0x30,0x18,0x30,0x7f,0x7f, # 87=W
0x00,0x63,0x77,0x1c,0x1c,0x77,0x63,0x00, # 88=X
0x00,0x07,0x0f,0x78,0x78,0x0f,0x07,0x00, # 89=Y
0x00,0x61,0x71,0x59,0x4d,0x47,0x43,0x00, # 90=Z
0x00,0x00,0x7f,0x7f,0x41,0x41,0x00,0x00, # 91=[
0x00,0x02,0x06,0x0c,0x18,0x30,0x60,0x40, # 92='\'
0x00,0x00,0x41,0x41,0x7f,0x7f,0x00,0x00, # 93=]
0x00,0x08,0x0c,0x06,0x06,0x0c,0x08,0x00, # 94=^
0xc0,0xc0,0xc0,0xc0,0xc0,0xc0,0xc0,0xc0, # 95=_
0x00,0x00,0x01,0x03,0x06,0x04,0x00,0x00, # 96=`
0x00,0x20,0x74,0x54,0x54,0x7c,0x78,0x00, # 97=a
0x00,0x7f,0x7f,0x44,0x44,0x7c,0x38,0x00, # 98=b
0x00,0x38,0x7c,0x44,0x44,0x6c,0x28,0x00, # 99=c
0x00,0x38,0x7c,0x44,0x44,0x7f,0x7f,0x00, # 100=d
0x00,0x38,0x7c,0x54,0x54,0x5c,0x58,0x00, # 101=e
0x00,0x08,0x7e,0x7f,0x09,0x03,0x02,0x00, # 102=f
0x00,0x98,0xbc,0xa4,0xa4,0xfc,0x7c,0x00, # 103=g
0x00,0x7f,0x7f,0x04,0x04,0x7c,0x78,0x00, # 104=h
0x00,0x00,0x00,0x7d,0x7d,0x00,0x00,0x00, # 105=i
0x00,0x40,0xc0,0x80,0x80,0xfd,0x7d,0x00, # 106=j
0x00,0x7f,0x7f,0x30,0x38,0x6c,0x44,0x00, # 107=k
0x00,0x00,0x41,0x7f,0x7f,0x40,0x00,0x00, # 108=l
0x00,0x7c,0x7c,0x18,0x30,0x18,0x7c,0x7c, # 109=m
0x00,0x7c,0x7c,0x04,0x04,0x7c,0x78,0x00, # 110=n
0x00,0x38,0x7c,0x44,0x44,0x7c,0x38,0x00, # 111=o
0x00,0xfc,0xfc,0x24,0x24,0x3c,0x18,0x00, # 112=p
0x00,0x18,0x3c,0x24,0x24,0xfc,0xfc,0x00, # 113=q
0x00,0x7c,0x7c,0x04,0x04,0x0c,0x08,0x00, # 114=r
0x00,0x48,0x5c,0x54,0x54,0x74,0x20,0x00, # 115=s
0x04,0x04,0x3f,0x7f,0x44,0x64,0x20,0x00, # 116=t
0x00,0x3c,0x7c,0x40,0x40,0x7c,0x3c,0x00, # 117=u
0x00,0x1c,0x3c,0x60,0x60,0x3c,0x1c,0x00, # 118=v
0x00,0x1c,0x7c,0x30,0x18,0x30,0x7c,0x1c, # 119=w
0x00,0x44,0x6c,0x38,0x38,0x6c,0x44,0x00, # 120=x
0x00,0x9c,0xbc,0xa0,0xa0,0xfc,0x7c,0x00, # 121=y
0x00,0x44,0x64,0x74,0x5c,0x4c,0x44,0x00, # 122=z
0x00,0x08,0x08,0x3e,0x77,0x41,0x41,0x00, # 123={
0x00,0x00,0x00,0xff,0xff,0x00,0x00,0x00, # 124=|
0x00,0x41,0x41,0x77,0x3e,0x08,0x08,0x00, # 125=}
0x00,0x02,0x03,0x01,0x03,0x02,0x03,0x01, # 126=~
0xaa,0x55,0xaa,0x55,0xaa,0x55,0xaa,0x55]) # 127
def reverse(x):
n = len(x)
b = bytearray(n)
for i in range(n):
b[i] = x[n-1-i]
return b
def chartobit(c,rev=True): # return 8 byte bitmap of character c
i = (ord(c) - ord(' '))*8
if rev:
return reverse(font_8x8[i:i+8])
else:
return font_8x8[i:i+8]
def strtobit(s,rev=False):
b = bytearray(8*len(s))
for i in range(len(s)):
cb =chartobit(s[i],rev)
for j in range(8):
b[i*8+j] = cb[j]
return b
| """
* This file is part of the Micro Python project, http:#micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2013, 2014 Damien P. George
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
"""
font_8x8 = bytes([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 79, 79, 0, 0, 0, 0, 7, 7, 0, 0, 7, 7, 0, 20, 127, 127, 20, 20, 127, 127, 20, 0, 36, 46, 107, 107, 58, 18, 0, 0, 99, 51, 24, 12, 102, 99, 0, 0, 50, 127, 77, 77, 119, 114, 80, 0, 0, 0, 4, 6, 3, 1, 0, 0, 0, 28, 62, 99, 65, 0, 0, 0, 0, 65, 99, 62, 28, 0, 0, 8, 42, 62, 28, 28, 62, 42, 8, 0, 8, 8, 62, 62, 8, 8, 0, 0, 0, 128, 224, 96, 0, 0, 0, 0, 8, 8, 8, 8, 8, 8, 0, 0, 0, 0, 96, 96, 0, 0, 0, 0, 64, 96, 48, 24, 12, 6, 2, 0, 62, 127, 73, 69, 127, 62, 0, 0, 64, 68, 127, 127, 64, 64, 0, 0, 98, 115, 81, 73, 79, 70, 0, 0, 34, 99, 73, 73, 127, 54, 0, 0, 24, 24, 20, 22, 127, 127, 16, 0, 39, 103, 69, 69, 125, 57, 0, 0, 62, 127, 73, 73, 123, 50, 0, 0, 3, 3, 121, 125, 7, 3, 0, 0, 54, 127, 73, 73, 127, 54, 0, 0, 38, 111, 73, 73, 127, 62, 0, 0, 0, 0, 36, 36, 0, 0, 0, 0, 0, 128, 228, 100, 0, 0, 0, 0, 8, 28, 54, 99, 65, 65, 0, 0, 20, 20, 20, 20, 20, 20, 0, 0, 65, 65, 99, 54, 28, 8, 0, 0, 2, 3, 81, 89, 15, 6, 0, 0, 62, 127, 65, 77, 79, 46, 0, 0, 124, 126, 11, 11, 126, 124, 0, 0, 127, 127, 73, 73, 127, 54, 0, 0, 62, 127, 65, 65, 99, 34, 0, 0, 127, 127, 65, 99, 62, 28, 0, 0, 127, 127, 73, 73, 65, 65, 0, 0, 127, 127, 9, 9, 1, 1, 0, 0, 62, 127, 65, 73, 123, 58, 0, 0, 127, 127, 8, 8, 127, 127, 0, 0, 0, 65, 127, 127, 65, 0, 0, 0, 32, 96, 65, 127, 63, 1, 0, 0, 127, 127, 28, 54, 99, 65, 0, 0, 127, 127, 64, 64, 64, 64, 0, 0, 127, 127, 6, 12, 6, 127, 127, 0, 127, 127, 14, 28, 127, 127, 0, 0, 62, 127, 65, 65, 127, 62, 0, 0, 127, 127, 9, 9, 15, 6, 0, 0, 30, 63, 33, 97, 127, 94, 0, 0, 127, 127, 25, 57, 111, 70, 0, 0, 38, 111, 73, 73, 123, 50, 0, 0, 1, 1, 127, 127, 1, 1, 0, 0, 63, 127, 64, 64, 127, 63, 0, 0, 31, 63, 96, 96, 63, 31, 0, 0, 127, 127, 48, 24, 48, 127, 127, 0, 99, 119, 28, 28, 119, 99, 0, 0, 7, 15, 120, 120, 15, 7, 0, 0, 97, 113, 89, 77, 71, 67, 0, 0, 0, 127, 127, 65, 65, 0, 0, 0, 2, 6, 12, 24, 48, 96, 64, 0, 0, 65, 65, 127, 127, 0, 0, 0, 8, 12, 6, 6, 12, 8, 0, 192, 192, 192, 192, 192, 192, 192, 192, 0, 0, 1, 3, 6, 4, 0, 0, 0, 32, 116, 84, 84, 124, 120, 0, 0, 127, 127, 68, 68, 124, 56, 0, 0, 56, 124, 68, 68, 108, 40, 0, 0, 56, 124, 68, 68, 127, 127, 0, 0, 56, 124, 84, 84, 92, 88, 0, 0, 8, 126, 127, 9, 3, 2, 0, 0, 152, 188, 164, 164, 252, 124, 0, 0, 127, 127, 4, 4, 124, 120, 0, 0, 0, 0, 125, 125, 0, 0, 0, 0, 64, 192, 128, 128, 253, 125, 0, 0, 127, 127, 48, 56, 108, 68, 0, 0, 0, 65, 127, 127, 64, 0, 0, 0, 124, 124, 24, 48, 24, 124, 124, 0, 124, 124, 4, 4, 124, 120, 0, 0, 56, 124, 68, 68, 124, 56, 0, 0, 252, 252, 36, 36, 60, 24, 0, 0, 24, 60, 36, 36, 252, 252, 0, 0, 124, 124, 4, 4, 12, 8, 0, 0, 72, 92, 84, 84, 116, 32, 0, 4, 4, 63, 127, 68, 100, 32, 0, 0, 60, 124, 64, 64, 124, 60, 0, 0, 28, 60, 96, 96, 60, 28, 0, 0, 28, 124, 48, 24, 48, 124, 28, 0, 68, 108, 56, 56, 108, 68, 0, 0, 156, 188, 160, 160, 252, 124, 0, 0, 68, 100, 116, 92, 76, 68, 0, 0, 8, 8, 62, 119, 65, 65, 0, 0, 0, 0, 255, 255, 0, 0, 0, 0, 65, 65, 119, 62, 8, 8, 0, 0, 2, 3, 1, 3, 2, 3, 1, 170, 85, 170, 85, 170, 85, 170, 85])
def reverse(x):
n = len(x)
b = bytearray(n)
for i in range(n):
b[i] = x[n - 1 - i]
return b
def chartobit(c, rev=True):
i = (ord(c) - ord(' ')) * 8
if rev:
return reverse(font_8x8[i:i + 8])
else:
return font_8x8[i:i + 8]
def strtobit(s, rev=False):
b = bytearray(8 * len(s))
for i in range(len(s)):
cb = chartobit(s[i], rev)
for j in range(8):
b[i * 8 + j] = cb[j]
return b |
N = int(input())
if N == 1 or N == 103:
print(0)
else:
print(N)
| n = int(input())
if N == 1 or N == 103:
print(0)
else:
print(N) |
# Create a python list containing first 5 positive even numbers. Display the list elements in the desending order.
list1 = [2, 4, 6, 8, 10]
list1.sort(reverse=True)
print(list1)
# hehe be efficient and not just do `print(list1[4])` , `print(list1[3])` etc etc | list1 = [2, 4, 6, 8, 10]
list1.sort(reverse=True)
print(list1) |
# Title : Simple Decorator
# Author : Kiran Raj R.
# Date : 12/11/2020
def my_decorator(function):
def inner_function(name):
print("This is a simple decorator function output")
function(name)
print("Finished....")
return inner_function
def greet_me(name):
print(f"Hello, Mr.{name}")
decor = my_decorator(greet_me)
decor('kiran')
def me_or_you(function1, function2):
def inner_function(name):
if name == 'kiran':
function1(name)
else:
function2(name)
return inner_function
def hello_me(name):
print(f"Hello {name}")
print("You can enter")
def hello_you(name):
print(f"Sorry {name} not allowed here")
decor2 = me_or_you(hello_me, hello_you)
decor2('kiran')
decor2('ram') | def my_decorator(function):
def inner_function(name):
print('This is a simple decorator function output')
function(name)
print('Finished....')
return inner_function
def greet_me(name):
print(f'Hello, Mr.{name}')
decor = my_decorator(greet_me)
decor('kiran')
def me_or_you(function1, function2):
def inner_function(name):
if name == 'kiran':
function1(name)
else:
function2(name)
return inner_function
def hello_me(name):
print(f'Hello {name}')
print('You can enter')
def hello_you(name):
print(f'Sorry {name} not allowed here')
decor2 = me_or_you(hello_me, hello_you)
decor2('kiran')
decor2('ram') |
class MenuItem:
def __init__(self, option: str, name: str):
self.option = option
self.name = name
def __call__(self, action: callable, *args, **kwargs):
self.action = action
def inner_function(*args, **kwargs):
return self.action(*args, **kwargs)
return self
def __str__(self):
return f"{self.option} - {self.name}"
def show(self):
print(self)
def run(self):
return self.action()
| class Menuitem:
def __init__(self, option: str, name: str):
self.option = option
self.name = name
def __call__(self, action: callable, *args, **kwargs):
self.action = action
def inner_function(*args, **kwargs):
return self.action(*args, **kwargs)
return self
def __str__(self):
return f'{self.option} - {self.name}'
def show(self):
print(self)
def run(self):
return self.action() |
__author__ = "Eli Serra"
__copyright__ = "Copyright 2020, Eli Serra"
__deprecated__ = False
__license__ = "MIT"
__status__ = "Production"
# Version of realpython-reader package
__version__ = "2.5.0"
| __author__ = 'Eli Serra'
__copyright__ = 'Copyright 2020, Eli Serra'
__deprecated__ = False
__license__ = 'MIT'
__status__ = 'Production'
__version__ = '2.5.0' |
class WhoisItError(Exception):
'''
Parent Exception for all whoisit raised exceptions.
'''
class BootstrapError(WhoisItError):
'''
Raised when there are any issues with bootstrapping.
'''
class QueryError(WhoisItError):
'''
Raised when there are any issues with queries.
'''
class UnsupportedError(WhoisItError):
'''
Raised when a feature in a query is unsupported.
'''
class ParseError(WhoisItError):
'''
Raised when failing to parse response data.
'''
class ResourceDoesNotExist(WhoisItError):
'''
Raised when querying a resource which doesn't exist.
''' | class Whoisiterror(Exception):
"""
Parent Exception for all whoisit raised exceptions.
"""
class Bootstraperror(WhoisItError):
"""
Raised when there are any issues with bootstrapping.
"""
class Queryerror(WhoisItError):
"""
Raised when there are any issues with queries.
"""
class Unsupportederror(WhoisItError):
"""
Raised when a feature in a query is unsupported.
"""
class Parseerror(WhoisItError):
"""
Raised when failing to parse response data.
"""
class Resourcedoesnotexist(WhoisItError):
"""
Raised when querying a resource which doesn't exist.
""" |
with open("halting.txt") as file:
lines = file.readlines()
lines = [line.rstrip() for line in lines]
insn = [(lines[i][:3], int(lines[i][4:])) for i in range(len(lines))]
jmps = [i for i in range(len(insn)) if insn[i][0] == "jmp"]
curr = 0
acc = 0
switch = 0
while switch < len(jmps):
acc = 0
visited = {}
curr = 0
while curr < len(lines) and curr not in visited and curr < len(lines):
visited[curr] = True
ins, arg = insn[curr]
if ins == "acc":
acc += arg
elif ins == "jmp" and curr != jmps[switch]:
curr += arg
continue
curr += 1
if curr >= len(lines):
break
switch += 1
print(acc) | with open('halting.txt') as file:
lines = file.readlines()
lines = [line.rstrip() for line in lines]
insn = [(lines[i][:3], int(lines[i][4:])) for i in range(len(lines))]
jmps = [i for i in range(len(insn)) if insn[i][0] == 'jmp']
curr = 0
acc = 0
switch = 0
while switch < len(jmps):
acc = 0
visited = {}
curr = 0
while curr < len(lines) and curr not in visited and (curr < len(lines)):
visited[curr] = True
(ins, arg) = insn[curr]
if ins == 'acc':
acc += arg
elif ins == 'jmp' and curr != jmps[switch]:
curr += arg
continue
curr += 1
if curr >= len(lines):
break
switch += 1
print(acc) |
'''
Given two strings str1 and str2, find the length of the smallest string which has both, str1 and str2 as its sub-sequences.
Input:
The first line of input contains an integer T denoting the number of test cases.Each test case contains two space separated strings.
Output:
Output the length of the required string.
Company : Microsoft
'''
def memoized_lcs(memo,a,b,i,j):
if(i==-1 or j==-1):
return 0
if(memo[i][j]!=-1):
return memo[i][j]
if(a[i]==b[j]):
memo[i][j]=memoized_lcs(memo,a,b,i-1,j-1)+1
return memo[i][j]
else:
memo[i][j]=max(memoized_lcs(memo,a,b,i-1,j),memoized_lcs(memo,a,b,i,j-1))
return memo[i][j]
def scs(a,b):
'''shortest common subsequence'''
'''=sum of len of two strings - len of lcs'''
memo=[[-1 for x in range(len(b))] for x in range(len(a))]
lcs_length=memoized_lcs(memo,a,b,len(a)-1,len(b)-1)
return(len(a)+len(b)-lcs_length)
for _ in range(int(input())):
s1,s2=[str(x) for x in input().strip().split()]
print(scs(s1,s2)) | """
Given two strings str1 and str2, find the length of the smallest string which has both, str1 and str2 as its sub-sequences.
Input:
The first line of input contains an integer T denoting the number of test cases.Each test case contains two space separated strings.
Output:
Output the length of the required string.
Company : Microsoft
"""
def memoized_lcs(memo, a, b, i, j):
if i == -1 or j == -1:
return 0
if memo[i][j] != -1:
return memo[i][j]
if a[i] == b[j]:
memo[i][j] = memoized_lcs(memo, a, b, i - 1, j - 1) + 1
return memo[i][j]
else:
memo[i][j] = max(memoized_lcs(memo, a, b, i - 1, j), memoized_lcs(memo, a, b, i, j - 1))
return memo[i][j]
def scs(a, b):
"""shortest common subsequence"""
'=sum of len of two strings - len of lcs'
memo = [[-1 for x in range(len(b))] for x in range(len(a))]
lcs_length = memoized_lcs(memo, a, b, len(a) - 1, len(b) - 1)
return len(a) + len(b) - lcs_length
for _ in range(int(input())):
(s1, s2) = [str(x) for x in input().strip().split()]
print(scs(s1, s2)) |
#cari median
def cariMedian(arr):
totalNum=len(arr)
if totalNum%2 == 0:
index1=int(len(arr)/2)
index2=int(index1-1)
return (arr[index1]+arr[index2])/2
else:
index=int((len(arr)-1)/2)
return arr[index]
#test case
print(cariMedian([1, 2, 3, 4, 5])) # 3
print(cariMedian([1, 3, 4, 10, 12, 13])) # 7
print(cariMedian([3, 4, 7, 7, 10])) # 7
print(cariMedian([1, 3, 3])) # 3
print(cariMedian([7, 7, 8, 8])) # 7.5
| def cari_median(arr):
total_num = len(arr)
if totalNum % 2 == 0:
index1 = int(len(arr) / 2)
index2 = int(index1 - 1)
return (arr[index1] + arr[index2]) / 2
else:
index = int((len(arr) - 1) / 2)
return arr[index]
print(cari_median([1, 2, 3, 4, 5]))
print(cari_median([1, 3, 4, 10, 12, 13]))
print(cari_median([3, 4, 7, 7, 10]))
print(cari_median([1, 3, 3]))
print(cari_median([7, 7, 8, 8])) |
# -*- coding: utf-8 -*-
def main():
s = input()
n = len(s)
if s == s[::-1]:
t = s[:(n - 1) // 2]
u = s[(n + 3) // 2 - 1:]
if t == t[::-1] and u == u[::-1]:
print('Yes')
else:
print('No')
else:
print('No')
if __name__ == '__main__':
main()
| def main():
s = input()
n = len(s)
if s == s[::-1]:
t = s[:(n - 1) // 2]
u = s[(n + 3) // 2 - 1:]
if t == t[::-1] and u == u[::-1]:
print('Yes')
else:
print('No')
else:
print('No')
if __name__ == '__main__':
main() |
ADDRESS = {
'street': 'Elm Street',
'street_2': 'No 185',
'city': 'New York City',
'state': 'NY',
'zipcode': '10006'
}
ADDRESS_2 = {
'street': 'South Park',
'street_2': 'No 1',
'city': 'San Francisco',
'state': 'CA',
'zipcode': '94110'
}
ADMIN_USER = {
'username': 'bobs',
'email': 'bob@gmail.com',
'password': 'pass'
}
PERSON_WITH_ADDRESS = {
'name': 'Elmo',
'insurance_number': 'INS_1',
'form-TOTAL_FORMS': 1,
'form-INITIAL_FORMS': 0,
'form-MIN_NUM_FORMS': 0,
'form-MAX_NUM_FORMS': 1,
'form-0-street': 'Elm Street',
'form-0-street_2': 'No 185',
'form-0-city': 'New York City',
'form-0-state': 'NY',
'form-0-zipcode': '10006',
'phonenumber_set-TOTAL_FORMS': 0,
'phonenumber_set-INITIAL_FORMS': 1
}
PERSON_WITH_ADDRESS_2 = {
'name': 'Elmo',
'form-TOTAL_FORMS': 1,
'form-INITIAL_FORMS': 1,
'form-MIN_NUM_FORMS': 0,
'form-MAX_NUM_FORMS': 1,
'form-0-street': 'South Park',
'form-0-street_2': 'No 1',
'form-0-city': 'San Francisco',
'form-0-state': 'CA',
'form-0-zipcode': '94110',
'phonenumber_set-TOTAL_FORMS': 0,
'phonenumber_set-INITIAL_FORMS': 1
}
PERSON_WITH_NO_ADDRESS = {
'name': 'Elmo',
'insurance_number': 'INS_1',
'form-TOTAL_FORMS': 1,
'form-INITIAL_FORMS': 0,
'phonenumber_set-TOTAL_FORMS': 0,
'phonenumber_set-INITIAL_FORMS': 1
}
PERSON_WITH_NO_ADDRESS_2 = {
'name': 'Elmo (Updated)',
'form-TOTAL_FORMS': 1,
'form-INITIAL_FORMS': 0,
'phonenumber_set-TOTAL_FORMS': 0,
'phonenumber_set-INITIAL_FORMS': 1
}
PERSON_WITH_TWO_ADDRESSES = {
'name': 'Elmo',
'form-TOTAL_FORMS': 1,
'form-INITIAL_FORMS': 0,
'form-MIN_NUM_FORMS': 0,
'form-MAX_NUM_FORMS': 1,
'form-0-street': 'South Park',
'form-0-street_2': 'No 1',
'form-0-city': 'San Francisco',
'form-0-state': 'CA',
'form-0-zipcode': '94110',
'form-2-TOTAL_FORMS': 1,
'form-2-INITIAL_FORMS': 0,
'form-2-MIN_NUM_FORMS': 0,
'form-2-MAX_NUM_FORMS': 1,
'form-2-0-street': 'New Park',
'form-2-0-street_2': 'No 1',
'form-2-0-city': 'New York City',
'form-2-0-state': 'NY',
'form-2-0-zipcode': '10006',
'_save': 'Save'
}
PERSON_WITH_TWO_ADDRESSES_ONE_BLANK = {
'name': 'Elmo',
'form-TOTAL_FORMS': 1,
'form-INITIAL_FORMS': 0,
'form-MIN_NUM_FORMS': 0,
'form-MAX_NUM_FORMS': 1,
'form-0-street': 'South Park',
'form-0-street_2': 'No 1',
'form-0-city': 'San Francisco',
'form-0-state': 'CA',
'form-0-zipcode': '94110',
'form-2-TOTAL_FORMS': 1,
'form-2-INITIAL_FORMS': 0,
'form-2-MIN_NUM_FORMS': 0,
'form-2-MAX_NUM_FORMS': 1,
'form-2-0-street': '',
'form-2-0-street_2': '',
'form-2-0-city': '',
'form-2-0-state': '',
'form-2-0-zipcode': '',
'_save': 'Save'
}
| address = {'street': 'Elm Street', 'street_2': 'No 185', 'city': 'New York City', 'state': 'NY', 'zipcode': '10006'}
address_2 = {'street': 'South Park', 'street_2': 'No 1', 'city': 'San Francisco', 'state': 'CA', 'zipcode': '94110'}
admin_user = {'username': 'bobs', 'email': 'bob@gmail.com', 'password': 'pass'}
person_with_address = {'name': 'Elmo', 'insurance_number': 'INS_1', 'form-TOTAL_FORMS': 1, 'form-INITIAL_FORMS': 0, 'form-MIN_NUM_FORMS': 0, 'form-MAX_NUM_FORMS': 1, 'form-0-street': 'Elm Street', 'form-0-street_2': 'No 185', 'form-0-city': 'New York City', 'form-0-state': 'NY', 'form-0-zipcode': '10006', 'phonenumber_set-TOTAL_FORMS': 0, 'phonenumber_set-INITIAL_FORMS': 1}
person_with_address_2 = {'name': 'Elmo', 'form-TOTAL_FORMS': 1, 'form-INITIAL_FORMS': 1, 'form-MIN_NUM_FORMS': 0, 'form-MAX_NUM_FORMS': 1, 'form-0-street': 'South Park', 'form-0-street_2': 'No 1', 'form-0-city': 'San Francisco', 'form-0-state': 'CA', 'form-0-zipcode': '94110', 'phonenumber_set-TOTAL_FORMS': 0, 'phonenumber_set-INITIAL_FORMS': 1}
person_with_no_address = {'name': 'Elmo', 'insurance_number': 'INS_1', 'form-TOTAL_FORMS': 1, 'form-INITIAL_FORMS': 0, 'phonenumber_set-TOTAL_FORMS': 0, 'phonenumber_set-INITIAL_FORMS': 1}
person_with_no_address_2 = {'name': 'Elmo (Updated)', 'form-TOTAL_FORMS': 1, 'form-INITIAL_FORMS': 0, 'phonenumber_set-TOTAL_FORMS': 0, 'phonenumber_set-INITIAL_FORMS': 1}
person_with_two_addresses = {'name': 'Elmo', 'form-TOTAL_FORMS': 1, 'form-INITIAL_FORMS': 0, 'form-MIN_NUM_FORMS': 0, 'form-MAX_NUM_FORMS': 1, 'form-0-street': 'South Park', 'form-0-street_2': 'No 1', 'form-0-city': 'San Francisco', 'form-0-state': 'CA', 'form-0-zipcode': '94110', 'form-2-TOTAL_FORMS': 1, 'form-2-INITIAL_FORMS': 0, 'form-2-MIN_NUM_FORMS': 0, 'form-2-MAX_NUM_FORMS': 1, 'form-2-0-street': 'New Park', 'form-2-0-street_2': 'No 1', 'form-2-0-city': 'New York City', 'form-2-0-state': 'NY', 'form-2-0-zipcode': '10006', '_save': 'Save'}
person_with_two_addresses_one_blank = {'name': 'Elmo', 'form-TOTAL_FORMS': 1, 'form-INITIAL_FORMS': 0, 'form-MIN_NUM_FORMS': 0, 'form-MAX_NUM_FORMS': 1, 'form-0-street': 'South Park', 'form-0-street_2': 'No 1', 'form-0-city': 'San Francisco', 'form-0-state': 'CA', 'form-0-zipcode': '94110', 'form-2-TOTAL_FORMS': 1, 'form-2-INITIAL_FORMS': 0, 'form-2-MIN_NUM_FORMS': 0, 'form-2-MAX_NUM_FORMS': 1, 'form-2-0-street': '', 'form-2-0-street_2': '', 'form-2-0-city': '', 'form-2-0-state': '', 'form-2-0-zipcode': '', '_save': 'Save'} |
# Package exception model:
# Here we subclass base Python exception overriding its constructor to
# accomodate error message string as its first parameter and an open
# set of keyword arguments that become exception object attributes.
# While exception object is bubbling up the call stack, intermediate
# exception handlers may insert their own attributes into exception
# object.
class PySmiError(Exception):
def __init__(self, *args, **kwargs):
Exception.__init__(self, *args)
self.msg = args and args[0] or ''
for k in kwargs:
setattr(self, k, kwargs[k])
def __repr__(self):
return '%s(%s)' % (self.__class__.__name__, ', '.join(['%s=%r' % (k, getattr(self, k)) for k in dir(self) if k[0] != '_' and k != 'args']))
def __str__(self):
return self.msg
class PySmiLexerError(PySmiError):
lineno = '?'
def __str__(self):
return self.msg + ', line %s' % self.lineno
class PySmiParserError(PySmiLexerError): pass
class PySmiSyntaxError(PySmiParserError): pass
class PySmiSearcherError(PySmiError): pass
class PySmiFileNotModifiedError(PySmiSearcherError): pass
class PySmiFileNotFoundError(PySmiSearcherError): pass
class PySmiReaderError(PySmiError): pass
class PySmiReaderFileNotModifiedError(PySmiReaderError): pass
class PySmiReaderFileNotFoundError(PySmiReaderError): pass
class PySmiCodegenError(PySmiError): pass
class PySmiSemanticError(PySmiCodegenError): pass
class PySmiWriterError(PySmiError): pass
| class Pysmierror(Exception):
def __init__(self, *args, **kwargs):
Exception.__init__(self, *args)
self.msg = args and args[0] or ''
for k in kwargs:
setattr(self, k, kwargs[k])
def __repr__(self):
return '%s(%s)' % (self.__class__.__name__, ', '.join(['%s=%r' % (k, getattr(self, k)) for k in dir(self) if k[0] != '_' and k != 'args']))
def __str__(self):
return self.msg
class Pysmilexererror(PySmiError):
lineno = '?'
def __str__(self):
return self.msg + ', line %s' % self.lineno
class Pysmiparsererror(PySmiLexerError):
pass
class Pysmisyntaxerror(PySmiParserError):
pass
class Pysmisearchererror(PySmiError):
pass
class Pysmifilenotmodifiederror(PySmiSearcherError):
pass
class Pysmifilenotfounderror(PySmiSearcherError):
pass
class Pysmireadererror(PySmiError):
pass
class Pysmireaderfilenotmodifiederror(PySmiReaderError):
pass
class Pysmireaderfilenotfounderror(PySmiReaderError):
pass
class Pysmicodegenerror(PySmiError):
pass
class Pysmisemanticerror(PySmiCodegenError):
pass
class Pysmiwritererror(PySmiError):
pass |
# Python program to demonstrate working of extended
# Euclidean Algorithm
# function for extended Euclidean Algorithm
def gcdExtended(a, b):
# Base Case
if a == 0 :
return b, 0, 1
gcd, x1, y1 = gcdExtended(b%a, a)
# Update x and y using results of recursive
# call
x = y1 - (b//a) * x1
y = x1
return gcd, x, y
# Driver code
a, b = 123439843020,101
g, x, y = gcdExtended(a, b)
print("gcd(", a , "," , b, ") = ", g)
print("x: ", x)
print("y: ", y)
| def gcd_extended(a, b):
if a == 0:
return (b, 0, 1)
(gcd, x1, y1) = gcd_extended(b % a, a)
x = y1 - b // a * x1
y = x1
return (gcd, x, y)
(a, b) = (123439843020, 101)
(g, x, y) = gcd_extended(a, b)
print('gcd(', a, ',', b, ') = ', g)
print('x: ', x)
print('y: ', y) |
class Solution:
@lru_cache(maxsize=None)
def minCostAfter(self, index, lastColor, target):
if target<0 or len(self.houses)-index+1<target:
return -1
if index==self.m-1:
if self.houses[index]!=0:
if (target==0 and lastColor==self.houses[index]) or (target==1 and lastColor!=self.houses[index]):
return 0
else:
return -1
elif target==0:
return self.cost[index][lastColor-1]
elif target==1:
answer=sys.maxsize
return min(self.cost[index][i] for i in range(self.n) if i!=lastColor-1)
else:
return -1
if self.houses[index]!=0:
if index==0 or self.houses[index]!=lastColor:
target-=1
return self.minCostAfter(index+1, self.houses[index], target)
answer=sys.maxsize
for c in range(1, self.n+1):
if index==0 or lastColor!=c:
ca=self.minCostAfter(index+1, c, target-1)
if ca!=-1:
answer=min(answer,ca+self.cost[index][c-1])
else:
ca=self.minCostAfter(index+1,c,target)
if ca!=-1:
answer=min(answer,ca+self.cost[index][c-1])
if answer==sys.maxsize:
return -1
return answer
def minCost(self, houses: List[int], cost: List[List[int]], m: int, n: int, target: int) -> int:
self.cost=cost
self.houses=houses
self.m=m
self.n=n
return self.minCostAfter(0, 0, target)
| class Solution:
@lru_cache(maxsize=None)
def min_cost_after(self, index, lastColor, target):
if target < 0 or len(self.houses) - index + 1 < target:
return -1
if index == self.m - 1:
if self.houses[index] != 0:
if target == 0 and lastColor == self.houses[index] or (target == 1 and lastColor != self.houses[index]):
return 0
else:
return -1
elif target == 0:
return self.cost[index][lastColor - 1]
elif target == 1:
answer = sys.maxsize
return min((self.cost[index][i] for i in range(self.n) if i != lastColor - 1))
else:
return -1
if self.houses[index] != 0:
if index == 0 or self.houses[index] != lastColor:
target -= 1
return self.minCostAfter(index + 1, self.houses[index], target)
answer = sys.maxsize
for c in range(1, self.n + 1):
if index == 0 or lastColor != c:
ca = self.minCostAfter(index + 1, c, target - 1)
if ca != -1:
answer = min(answer, ca + self.cost[index][c - 1])
else:
ca = self.minCostAfter(index + 1, c, target)
if ca != -1:
answer = min(answer, ca + self.cost[index][c - 1])
if answer == sys.maxsize:
return -1
return answer
def min_cost(self, houses: List[int], cost: List[List[int]], m: int, n: int, target: int) -> int:
self.cost = cost
self.houses = houses
self.m = m
self.n = n
return self.minCostAfter(0, 0, target) |
#author SANKALP SAXENA
if __name__ == '__main__':
n = int(input())
arr = map(int, input().split())
arr = list(arr)
arr.sort()
#print(arr)
l = -1
i = 0
e = 0
f = 0
flag = False
while(True) :
e = arr.pop(-1)
if(len(arr) == 1):
flag = True
break
f = arr.pop(-2)
if(e == f) :
continue
else :
break
if flag == True:
print(arr.pop(0))
else:
print(f)
| if __name__ == '__main__':
n = int(input())
arr = map(int, input().split())
arr = list(arr)
arr.sort()
l = -1
i = 0
e = 0
f = 0
flag = False
while True:
e = arr.pop(-1)
if len(arr) == 1:
flag = True
break
f = arr.pop(-2)
if e == f:
continue
else:
break
if flag == True:
print(arr.pop(0))
else:
print(f) |
class CaesarCipher:
def encrypt(self, plain, n):
rst = [None] * len(plain)
for i in range(len(plain)):
rst[i] = chr((ord(plain[i]) - ord('A') + n) % 26 + ord('A'))
return ''.join(rst)
def decrypt(self, encrypted, n):
rst = [None] * len(encrypted)
for i in range(len(encrypted)):
rst[i] = chr((ord(encrypted[i]) - ord('A') - n) % 26 + ord('A'))
return ''.join(rst)
if __name__ == '__main__':
print(CaesarCipher().encrypt('APPLE', 5))
print(CaesarCipher().decrypt('FUUQJ', 5)) | class Caesarcipher:
def encrypt(self, plain, n):
rst = [None] * len(plain)
for i in range(len(plain)):
rst[i] = chr((ord(plain[i]) - ord('A') + n) % 26 + ord('A'))
return ''.join(rst)
def decrypt(self, encrypted, n):
rst = [None] * len(encrypted)
for i in range(len(encrypted)):
rst[i] = chr((ord(encrypted[i]) - ord('A') - n) % 26 + ord('A'))
return ''.join(rst)
if __name__ == '__main__':
print(caesar_cipher().encrypt('APPLE', 5))
print(caesar_cipher().decrypt('FUUQJ', 5)) |
class LotteryPlayer:
def __init__(self, name):
self.name = name
self.number = (1, 34, 56, 90)
def __str__(self):
return f"Person {self.name} year old"
def __repr__(self):
return f"<LotteryPlayer({self.name})>"
def total(self):
return sum(self.number)
player_one = LotteryPlayer('John')
player_one.number = (3, 5, 90)
player_two = LotteryPlayer('Jude')
# print(player_one.name == player_two.name)
# print(player_one.total())
class Student:
def __init__(self, name, school):
self.name = name
self.school = school
self.marks = []
def average(self):
return sum(self.marks) / len(self.marks)
@staticmethod
def go_to_school():
print('I am going to school')
anna = Student('Anna', 'MIT')
anna.marks.append(45)
print(anna.marks)
print(anna.average())
Student.go_to_school()
| class Lotteryplayer:
def __init__(self, name):
self.name = name
self.number = (1, 34, 56, 90)
def __str__(self):
return f'Person {self.name} year old'
def __repr__(self):
return f'<LotteryPlayer({self.name})>'
def total(self):
return sum(self.number)
player_one = lottery_player('John')
player_one.number = (3, 5, 90)
player_two = lottery_player('Jude')
class Student:
def __init__(self, name, school):
self.name = name
self.school = school
self.marks = []
def average(self):
return sum(self.marks) / len(self.marks)
@staticmethod
def go_to_school():
print('I am going to school')
anna = student('Anna', 'MIT')
anna.marks.append(45)
print(anna.marks)
print(anna.average())
Student.go_to_school() |
def vert_mirror(strng):
arr = strng.split("\n")
res = []
for word in arr:
w = word[::-1]
res.append(w)
return '\n'.join(res)
def hor_mirror(strng):
# arr = splint("\n")
arr = strng.split("\n")
# revirse every element in arr
res = arr[::-1]
# return join arr ("\n")
return '\n'.join(res)
def oper(fct, s):
return fct(s)
def vert_mirror2(s):
return "\n".join(line[::-1] for line in s.split("\n"))
def hor_mirror2(s):
return "\n".join(s.split("\n")[::-1])
def oper2(fct, s):
return fct(s)
| def vert_mirror(strng):
arr = strng.split('\n')
res = []
for word in arr:
w = word[::-1]
res.append(w)
return '\n'.join(res)
def hor_mirror(strng):
arr = strng.split('\n')
res = arr[::-1]
return '\n'.join(res)
def oper(fct, s):
return fct(s)
def vert_mirror2(s):
return '\n'.join((line[::-1] for line in s.split('\n')))
def hor_mirror2(s):
return '\n'.join(s.split('\n')[::-1])
def oper2(fct, s):
return fct(s) |
display = [['.' for i in range(50)] for j in range(6)]
instructions = []
while True:
try:
instructions.append(input())
except:
break
for instruction in instructions:
if instruction[:4] == 'rect':
i, j = instruction.find(' '), instruction.find('x')
width = int(instruction[i + 1: j])
height = int(instruction[j+1:])
for a in range(height):
for b in range(width):
display[a][b] = '#'
if instruction[:13] == 'rotate column':
i, j, k = instruction.find('='), instruction.rfind(' '), instruction.find(' by')
column = int(instruction[i+1: k])
step = int(instruction[j+1:])
text = []
for a in range(6):
text.append(display[a][column])
new_column = ['' for i in range(6)]
for i in range(6):
index = (i + step) % 6
new_column[index] = text[i]
for a in range(6):
display[a][column] = new_column[a]
if instruction[:10] == 'rotate row':
i, j, k = instruction.find('='), instruction.rfind(' '), instruction.find(' by')
row = int(instruction[i+1: k])
step = int(instruction[j+1:])
text = display[row]
new_row = ['' for i in range(50)]
for i in range(50):
index = (i + step) % 50
new_row[index] = text[i]
display[row] = new_row[:]
count = 0
for row in display:
for i in row:
if i == '#':
count += 1
print(count)
print()
for row in display:
print(' '.join(row))
| display = [['.' for i in range(50)] for j in range(6)]
instructions = []
while True:
try:
instructions.append(input())
except:
break
for instruction in instructions:
if instruction[:4] == 'rect':
(i, j) = (instruction.find(' '), instruction.find('x'))
width = int(instruction[i + 1:j])
height = int(instruction[j + 1:])
for a in range(height):
for b in range(width):
display[a][b] = '#'
if instruction[:13] == 'rotate column':
(i, j, k) = (instruction.find('='), instruction.rfind(' '), instruction.find(' by'))
column = int(instruction[i + 1:k])
step = int(instruction[j + 1:])
text = []
for a in range(6):
text.append(display[a][column])
new_column = ['' for i in range(6)]
for i in range(6):
index = (i + step) % 6
new_column[index] = text[i]
for a in range(6):
display[a][column] = new_column[a]
if instruction[:10] == 'rotate row':
(i, j, k) = (instruction.find('='), instruction.rfind(' '), instruction.find(' by'))
row = int(instruction[i + 1:k])
step = int(instruction[j + 1:])
text = display[row]
new_row = ['' for i in range(50)]
for i in range(50):
index = (i + step) % 50
new_row[index] = text[i]
display[row] = new_row[:]
count = 0
for row in display:
for i in row:
if i == '#':
count += 1
print(count)
print()
for row in display:
print(' '.join(row)) |
one = int(input("Enter the number no 1: "))
two = int(input("Enter the number no 2: "))
three = int(input("Enter the number no 3: "))
four = int(input("Enter the number no 4: "))
one += two
three += four
dell = one / three
print("Answer %.2f" % dell)
| one = int(input('Enter the number no 1: '))
two = int(input('Enter the number no 2: '))
three = int(input('Enter the number no 3: '))
four = int(input('Enter the number no 4: '))
one += two
three += four
dell = one / three
print('Answer %.2f' % dell) |
# https://www.hackerrank.com/challenges/counting-valleys/problem
def countingValleys(steps, path):
# Write your code here
valley = 0
mountain = 0
state = 0
up = 0
down = 0
before_present_state = 0
for step in range(steps):
if path[step] == 'D':
down += 1
elif path[step] == 'U':
up += 1
before_present_state = state
state = up - down
if(before_present_state > 0 and state == 0):
mountain += 1
elif(before_present_state < 0 and state == 0):
valley += 1
return valley | def counting_valleys(steps, path):
valley = 0
mountain = 0
state = 0
up = 0
down = 0
before_present_state = 0
for step in range(steps):
if path[step] == 'D':
down += 1
elif path[step] == 'U':
up += 1
before_present_state = state
state = up - down
if before_present_state > 0 and state == 0:
mountain += 1
elif before_present_state < 0 and state == 0:
valley += 1
return valley |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Purpose:
connections methods
'''
__author__ = 'Matt Joyce'
__email__ = 'matt@joyce.nyc'
__copyright__ = 'Copyright 2016, Symphony Communication Services LLC'
class Connections(object):
def __init__(self, *args, **kwargs):
super(Connections, self).__init__(*args, **kwargs)
def sessioninfo(self):
''' session info '''
response, status_code = self.__pod__.Session.get_v2_sessioninfo(
sessionToken=self.__session__
).result()
self.logger.debug('%s: %s' % (status_code, response))
return status_code, response
def list_connections(self, status=None):
''' list connections '''
if status is None:
status = 'ALL'
response, status_code = self.__pod__.Connection.get_v1_connection_list(
sessionToken=self.__session__,
status=status
).result()
self.logger.debug('%s: %s' % (status_code, response))
return status_code, response
def connection_status(self, userid):
''' get connection status '''
response, status_code = self.__pod__.Connection.get_v1_connection_user_userId_info(
sessionToken=self.__session__,
userId=userid
).result()
self.logger.debug('%s: %s' % (status_code, response))
return status_code, response
def accept_connection(self, userid):
''' accept connection request '''
req_hook = 'pod/v1/connection/accept'
req_args = '{ "userId": %s }' % userid
status_code, response = self.__rest__.POST_query(req_hook, req_args)
self.logger.debug('%s: %s' % (status_code, response))
return status_code, response
def create_connection(self, userid):
''' create connection '''
req_hook = 'pod/v1/connection/create'
req_args = '{ "userId": %s }' % userid
status_code, response = self.__rest__.POST_query(req_hook, req_args)
self.logger.debug('%s: %s' % (status_code, response))
return status_code, response
| """
Purpose:
connections methods
"""
__author__ = 'Matt Joyce'
__email__ = 'matt@joyce.nyc'
__copyright__ = 'Copyright 2016, Symphony Communication Services LLC'
class Connections(object):
def __init__(self, *args, **kwargs):
super(Connections, self).__init__(*args, **kwargs)
def sessioninfo(self):
""" session info """
(response, status_code) = self.__pod__.Session.get_v2_sessioninfo(sessionToken=self.__session__).result()
self.logger.debug('%s: %s' % (status_code, response))
return (status_code, response)
def list_connections(self, status=None):
""" list connections """
if status is None:
status = 'ALL'
(response, status_code) = self.__pod__.Connection.get_v1_connection_list(sessionToken=self.__session__, status=status).result()
self.logger.debug('%s: %s' % (status_code, response))
return (status_code, response)
def connection_status(self, userid):
""" get connection status """
(response, status_code) = self.__pod__.Connection.get_v1_connection_user_userId_info(sessionToken=self.__session__, userId=userid).result()
self.logger.debug('%s: %s' % (status_code, response))
return (status_code, response)
def accept_connection(self, userid):
""" accept connection request """
req_hook = 'pod/v1/connection/accept'
req_args = '{ "userId": %s }' % userid
(status_code, response) = self.__rest__.POST_query(req_hook, req_args)
self.logger.debug('%s: %s' % (status_code, response))
return (status_code, response)
def create_connection(self, userid):
""" create connection """
req_hook = 'pod/v1/connection/create'
req_args = '{ "userId": %s }' % userid
(status_code, response) = self.__rest__.POST_query(req_hook, req_args)
self.logger.debug('%s: %s' % (status_code, response))
return (status_code, response) |
def findOutlier(integers):
ofound = 0
efound = 0
ocnt = 0
ecnt = 0
for el in integers:
if (el % 2 == 1):
ofound = el
ocnt += 1
else:
efound = el
ecnt += 1
return(efound if ocnt > ecnt else ofound)
print("The outlier is %s" % findOutlier([1, 6, 3, 5, 7]))
print("The outlier is %s" % findOutlier([2, 6, 34, 5, 8]))
| def find_outlier(integers):
ofound = 0
efound = 0
ocnt = 0
ecnt = 0
for el in integers:
if el % 2 == 1:
ofound = el
ocnt += 1
else:
efound = el
ecnt += 1
return efound if ocnt > ecnt else ofound
print('The outlier is %s' % find_outlier([1, 6, 3, 5, 7]))
print('The outlier is %s' % find_outlier([2, 6, 34, 5, 8])) |
testList = [1, -4, 8, -9]
def applyToEach(L, f):
for i in range(len(L)):
L[i] = f(L[i])
def turnToPositive(n):
if(n<0):
n*=-1
return n
applyToEach(testList, turnToPositive)
def sumOne(n):
n+=1
return n
applyToEach(testList, sumOne)
def square(n):
n**=2
return n
applyToEach(testList, square) | test_list = [1, -4, 8, -9]
def apply_to_each(L, f):
for i in range(len(L)):
L[i] = f(L[i])
def turn_to_positive(n):
if n < 0:
n *= -1
return n
apply_to_each(testList, turnToPositive)
def sum_one(n):
n += 1
return n
apply_to_each(testList, sumOne)
def square(n):
n **= 2
return n
apply_to_each(testList, square) |
n=500
primeno=[2,3]
i=5
flag=0
diff=2
while i<=500:
print(i)
flag_p=1
for j in primeno:
if i%j== 0:
flag_p = 0
break
if flag_p==1:
primeno.append(i)
i += diff
if flag == 0:
diff=4
flag=1
continue
if flag == 1:
diff=2
flag=0
print(primeno)
print(len(primeno))
| n = 500
primeno = [2, 3]
i = 5
flag = 0
diff = 2
while i <= 500:
print(i)
flag_p = 1
for j in primeno:
if i % j == 0:
flag_p = 0
break
if flag_p == 1:
primeno.append(i)
i += diff
if flag == 0:
diff = 4
flag = 1
continue
if flag == 1:
diff = 2
flag = 0
print(primeno)
print(len(primeno)) |
#! /usr/bin/env python3
def neighbors(board, x, y) -> int :
minx, maxx = x - 1, x + 1
miny, maxy = y - 1, y + 1
if miny < 0 : miny = 0
if maxy >= len(board[0]) : maxy = len(board[0]) - 1
if minx < 0 : minx = 0
if maxx >= len(board) : maxx = len(board) - 1
count = 0
for i in range(minx, maxx + 1) :
for j in range(miny, maxy + 1) :
if not(x == i and y == j) and board[i][j] == '#' :
count += 1
return count
def nextBoard(board) :
newBoard = [x[:] for x in board]
for i in range(len(board)) :
for j in range(len(board[0])) :
if board[i][j] == 'L' and neighbors(board, i, j) == 0 :
newBoard[i][j] = '#'
elif board[i][j] == '#' and neighbors(board, i, j) >= 4 :
newBoard[i][j] = 'L'
return newBoard
def occupiedSeats(board) -> int :
total = 0
for row in board :
total += row.count('#')
return total
def printBoard(board) -> None :
for row in board :
print(*row)
print("\n")
with open("input", "r") as fd :
board = [[y for y in x] for x in fd.read().strip().split('\n')]
lastBoard = None
while lastBoard != board :
lastBoard = board
board = nextBoard(board)
print(f"Total occupied seats : {occupiedSeats(board)}") | def neighbors(board, x, y) -> int:
(minx, maxx) = (x - 1, x + 1)
(miny, maxy) = (y - 1, y + 1)
if miny < 0:
miny = 0
if maxy >= len(board[0]):
maxy = len(board[0]) - 1
if minx < 0:
minx = 0
if maxx >= len(board):
maxx = len(board) - 1
count = 0
for i in range(minx, maxx + 1):
for j in range(miny, maxy + 1):
if not (x == i and y == j) and board[i][j] == '#':
count += 1
return count
def next_board(board):
new_board = [x[:] for x in board]
for i in range(len(board)):
for j in range(len(board[0])):
if board[i][j] == 'L' and neighbors(board, i, j) == 0:
newBoard[i][j] = '#'
elif board[i][j] == '#' and neighbors(board, i, j) >= 4:
newBoard[i][j] = 'L'
return newBoard
def occupied_seats(board) -> int:
total = 0
for row in board:
total += row.count('#')
return total
def print_board(board) -> None:
for row in board:
print(*row)
print('\n')
with open('input', 'r') as fd:
board = [[y for y in x] for x in fd.read().strip().split('\n')]
last_board = None
while lastBoard != board:
last_board = board
board = next_board(board)
print(f'Total occupied seats : {occupied_seats(board)}') |
class Container:
def __init__(self, processor, processes):
self._processor = processor
self._processes = processes
def run(self):
for process in self._processes:
process.run(self._processor)
| class Container:
def __init__(self, processor, processes):
self._processor = processor
self._processes = processes
def run(self):
for process in self._processes:
process.run(self._processor) |
def test_registering_new_filter_with_no_args(rpc_client, rpc_call_emitter):
filter_id = rpc_client(
method='eth_newFilter',
params=[{}]
)
changes = rpc_client(
method='eth_getFilterChanges',
params=[filter_id],
)
assert not changes
def test_registering_new_filter_with_no_args(rpc_client, rpc_call_emitter):
filter_id = rpc_client(
method='eth_newFilter',
params=[{
'fromBlock': 1,
'toBlock': 10,
'address': '0xd3cda913deb6f67967b99d67acdfa1712c293601',
'topics': ['0x000000000000000000000000a94f5374fce5edbc8e2a8697c15331677e6ebf0b'],
}]
)
changes = rpc_client(
method='eth_getFilterChanges',
params=[filter_id],
)
assert not changes
| def test_registering_new_filter_with_no_args(rpc_client, rpc_call_emitter):
filter_id = rpc_client(method='eth_newFilter', params=[{}])
changes = rpc_client(method='eth_getFilterChanges', params=[filter_id])
assert not changes
def test_registering_new_filter_with_no_args(rpc_client, rpc_call_emitter):
filter_id = rpc_client(method='eth_newFilter', params=[{'fromBlock': 1, 'toBlock': 10, 'address': '0xd3cda913deb6f67967b99d67acdfa1712c293601', 'topics': ['0x000000000000000000000000a94f5374fce5edbc8e2a8697c15331677e6ebf0b']}])
changes = rpc_client(method='eth_getFilterChanges', params=[filter_id])
assert not changes |
data = []
# zbieranie danych z pliku do listy
with open('../dane/sygnaly.txt') as f:
for x in f:
data.append(x[:-1])
# funkcja sprawdzajaca czy string spelnia warunek z zadania
def is_valid(s):
# parowanie kazdej litery z kazda litera zeby sprawdzic
# czy ich kody ASCII sa wystarczajaco blisko siebie
for a in s:
for b in s:
if distance(a, b) > 10:
return False
return True
# funkcja sprawdzajaca dystans miedzy dwoma literami w talblicy unicode
def distance(a, b):
return abs(ord(a) - ord(b))
result = []
for s in data:
if is_valid(s):
result.append(s)
# wyswietlenie odpowiedzi
answer = f'4.3. Te wyrazy byly wystarczajaco blisko siebie na tablicy ASCII:\n' + \
'\n'.join(result)
print(answer)
| data = []
with open('../dane/sygnaly.txt') as f:
for x in f:
data.append(x[:-1])
def is_valid(s):
for a in s:
for b in s:
if distance(a, b) > 10:
return False
return True
def distance(a, b):
return abs(ord(a) - ord(b))
result = []
for s in data:
if is_valid(s):
result.append(s)
answer = f'4.3. Te wyrazy byly wystarczajaco blisko siebie na tablicy ASCII:\n' + '\n'.join(result)
print(answer) |
__author__ = 'Eric SHI'
__author_email__ = 'longwosion@gmail.com'
__url__ = 'https://github.com/Longwosion/parrot'
__license__ = 'BSD'
version = __version__ = '0.1.0'
| __author__ = 'Eric SHI'
__author_email__ = 'longwosion@gmail.com'
__url__ = 'https://github.com/Longwosion/parrot'
__license__ = 'BSD'
version = __version__ = '0.1.0' |
def steam(received):
# substitute spaces for url space character
response = "https://store.steampowered.com/search/?term=" + received.replace(' ', "%20")
return response
| def steam(received):
response = 'https://store.steampowered.com/search/?term=' + received.replace(' ', '%20')
return response |
#encoding:utf-8
subreddit = 'desigentlemanboners'
t_channel = '@r_dgb'
def send_post(submission, r2t):
return r2t.send_simple(submission)
| subreddit = 'desigentlemanboners'
t_channel = '@r_dgb'
def send_post(submission, r2t):
return r2t.send_simple(submission) |
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'includes': [
'app_remoting_webapp_build.gypi',
],
'targets': [
{
'target_name': 'ar_sample_app',
'app_id': 'ljacajndfccfgnfohlgkdphmbnpkjflk',
'app_name': 'App Remoting Client',
'app_description': 'App Remoting client',
},
], # end of targets
}
| {'includes': ['app_remoting_webapp_build.gypi'], 'targets': [{'target_name': 'ar_sample_app', 'app_id': 'ljacajndfccfgnfohlgkdphmbnpkjflk', 'app_name': 'App Remoting Client', 'app_description': 'App Remoting client'}]} |
n , dm = map(int,input().split())
li = list(map(int, input().split()))
x = -1
for i in range(n):
if int(li[i]) <= dm:
x = i
print("It hadn't snowed this early in %d years!"%x)
break
else:
print("It had never snowed this early!") | (n, dm) = map(int, input().split())
li = list(map(int, input().split()))
x = -1
for i in range(n):
if int(li[i]) <= dm:
x = i
print("It hadn't snowed this early in %d years!" % x)
break
else:
print('It had never snowed this early!') |
class BasePSError:
def __init__(self, start_position, end_position, error_type, error_message, context):
self.start_position = start_position
self.end_position = end_position
self.error_type = error_type
self.error_message = error_message
self.context = context
def generate_traceback(self):
result = ""
prev_line = ""
count = 1
pos = self.start_position
context = self.context
while context:
line = f' File {pos.filename}, line {str(pos.line + 1)}, in {context.display_name}'
if line == prev_line:
count += 1
else:
if count == 1:
result = line + "\n" + result
else:
result = line + "\n" + result[:result.index("\n")] + f' (x{count})' + result[result.index("\n"):]
count = 1
pos = context.parent_entry_pos
context = context.parent
prev_line = line
return "Traceback (most recent call last):\n" + result
def __repr__(self):
idx_start = max(self.start_position.ftxt.rfind('\n', 0, self.start_position.index), 0)
idx_end = self.start_position.ftxt.find('\n', idx_start + 1)
if idx_end < 0:
idx_end = len(self.start_position.ftxt)
line = self.start_position.ftxt[idx_start:idx_end]
return (self.generate_traceback()
+ " "
+ line.strip()
+ "\n " + "-" * self.start_position.column
+ "~" * (self.end_position.column - self.start_position.column)
+ "-" * (len(line) - self.end_position.column - 2)
+ f"\npscode > ERROR: {self.error_type}\n"
+ f'{self.error_message}'
)
class IllegalCharError:
def __init__(self, position, char):
self.position = position
self.char = char
def __repr__(self):
idx_start = max(self.position.ftxt.rfind('\n', 0, self.position.index), 0)
idx_end = self.position.ftxt.find('\n', idx_start + 1)
if idx_end < 0:
idx_end = len(self.position.ftxt)
line = self.position.ftxt[idx_start:idx_end]
return (f"pscode > ERROR: Illegal Character '{self.char}'\n"
f' File "{self.position.filename}", line {self.position.line + 1}'
+ "\n "
+ line[1:self.position.column + 1]
+ line[self.position.column + 1]
+ line[self.position.column + 2:]
+ "\n " + "-" * self.position.column + "^" + (len(line) - self.position.column - 1) * "-")
class ExpectedCharError:
def __init__(self, position, details):
self.position = position
self.details = details
def __repr__(self):
idx_start = max(self.position.ftxt.rfind('\n', 0, self.position.index), 0)
idx_end = self.position.ftxt.find('\n', idx_start + 1)
if idx_end < 0:
idx_end = len(self.position.ftxt)
line = self.position.ftxt[idx_start:idx_end]
return (f"pscode > ERROR: {self.details}\n"
f' File "{self.position.filename}", line {self.position.line + 1}'
+ "\n "
+ line[1:self.position.column + 1]
+ line[self.position.column + 1]
+ line[self.position.column + 2:]
+ "\n " + "-" * self.position.column + "^" + (len(line) - self.position.column - 1) * "-")
class UnexpectedEOFError:
def __init__(self, position, details):
self.position = position
self.details = details
def __repr__(self):
idx_start = max(self.position.ftxt.rfind('\n', 0, self.position.index), 0)
idx_end = self.position.ftxt.find('\n', idx_start + 1)
if idx_end < 0:
idx_end = len(self.position.ftxt)
line = self.position.ftxt[idx_start:idx_end][1:]
return (f"pscode > ERROR: Unexpected EOF while parsing string\n"
+ self.details
+ f'\n File "{self.position.filename}", line {self.position.line + 1}'
+ "\n "
+ line + "\n "
+ "-" * (len(line)) + "^")
class InvalidSyntaxError:
def __init__(self, start_position, end_position, error_message):
self.start_position = start_position.copy()
self.end_position = end_position.copy()
self.error_message = error_message
def __repr__(self):
idx_start = max(self.start_position.ftxt.rfind('\n', 0, self.start_position.index), 0)
idx_end = self.start_position.ftxt.find('\n', idx_start + 1)
if idx_end < 0:
idx_end = len(self.start_position.ftxt)
line = self.start_position.ftxt[idx_start:idx_end].strip()
return (f"pscode > ERROR: Invalid Syntax\n"
f'{self.error_message}\n'
f' File "{self.start_position.filename}", line {self.start_position.line + 1}'
+ "\n "
+ line[:self.start_position.column]
+ line[self.start_position.column:self.end_position.column]
+ line[self.end_position.column:]
+ "\n " + "-" * self.start_position.column
+ "~" * (self.end_position.column - self.start_position.column)
+ "-" * (len(line) - self.end_position.column))
class RuntimeError(BasePSError):
def __init__(self, start_position, end_position, error_message, context):
super().__init__(start_position, end_position, "Runtime Error", error_message, context)
class NotImplementedError(BasePSError):
def __init__(self, start_position, end_position, error_message, context):
super().__init__(start_position, end_position, "Not Implemented", error_message, context)
| class Basepserror:
def __init__(self, start_position, end_position, error_type, error_message, context):
self.start_position = start_position
self.end_position = end_position
self.error_type = error_type
self.error_message = error_message
self.context = context
def generate_traceback(self):
result = ''
prev_line = ''
count = 1
pos = self.start_position
context = self.context
while context:
line = f' File {pos.filename}, line {str(pos.line + 1)}, in {context.display_name}'
if line == prev_line:
count += 1
else:
if count == 1:
result = line + '\n' + result
else:
result = line + '\n' + result[:result.index('\n')] + f' (x{count})' + result[result.index('\n'):]
count = 1
pos = context.parent_entry_pos
context = context.parent
prev_line = line
return 'Traceback (most recent call last):\n' + result
def __repr__(self):
idx_start = max(self.start_position.ftxt.rfind('\n', 0, self.start_position.index), 0)
idx_end = self.start_position.ftxt.find('\n', idx_start + 1)
if idx_end < 0:
idx_end = len(self.start_position.ftxt)
line = self.start_position.ftxt[idx_start:idx_end]
return self.generate_traceback() + ' ' + line.strip() + '\n ' + '-' * self.start_position.column + '~' * (self.end_position.column - self.start_position.column) + '-' * (len(line) - self.end_position.column - 2) + f'\npscode > ERROR: {self.error_type}\n' + f'{self.error_message}'
class Illegalcharerror:
def __init__(self, position, char):
self.position = position
self.char = char
def __repr__(self):
idx_start = max(self.position.ftxt.rfind('\n', 0, self.position.index), 0)
idx_end = self.position.ftxt.find('\n', idx_start + 1)
if idx_end < 0:
idx_end = len(self.position.ftxt)
line = self.position.ftxt[idx_start:idx_end]
return f'''pscode > ERROR: Illegal Character '{self.char}'\n File "{self.position.filename}", line {self.position.line + 1}''' + '\n ' + line[1:self.position.column + 1] + line[self.position.column + 1] + line[self.position.column + 2:] + '\n ' + '-' * self.position.column + '^' + (len(line) - self.position.column - 1) * '-'
class Expectedcharerror:
def __init__(self, position, details):
self.position = position
self.details = details
def __repr__(self):
idx_start = max(self.position.ftxt.rfind('\n', 0, self.position.index), 0)
idx_end = self.position.ftxt.find('\n', idx_start + 1)
if idx_end < 0:
idx_end = len(self.position.ftxt)
line = self.position.ftxt[idx_start:idx_end]
return f'pscode > ERROR: {self.details}\n File "{self.position.filename}", line {self.position.line + 1}' + '\n ' + line[1:self.position.column + 1] + line[self.position.column + 1] + line[self.position.column + 2:] + '\n ' + '-' * self.position.column + '^' + (len(line) - self.position.column - 1) * '-'
class Unexpectedeoferror:
def __init__(self, position, details):
self.position = position
self.details = details
def __repr__(self):
idx_start = max(self.position.ftxt.rfind('\n', 0, self.position.index), 0)
idx_end = self.position.ftxt.find('\n', idx_start + 1)
if idx_end < 0:
idx_end = len(self.position.ftxt)
line = self.position.ftxt[idx_start:idx_end][1:]
return f'pscode > ERROR: Unexpected EOF while parsing string\n' + self.details + f'\n File "{self.position.filename}", line {self.position.line + 1}' + '\n ' + line + '\n ' + '-' * len(line) + '^'
class Invalidsyntaxerror:
def __init__(self, start_position, end_position, error_message):
self.start_position = start_position.copy()
self.end_position = end_position.copy()
self.error_message = error_message
def __repr__(self):
idx_start = max(self.start_position.ftxt.rfind('\n', 0, self.start_position.index), 0)
idx_end = self.start_position.ftxt.find('\n', idx_start + 1)
if idx_end < 0:
idx_end = len(self.start_position.ftxt)
line = self.start_position.ftxt[idx_start:idx_end].strip()
return f'pscode > ERROR: Invalid Syntax\n{self.error_message}\n File "{self.start_position.filename}", line {self.start_position.line + 1}' + '\n ' + line[:self.start_position.column] + line[self.start_position.column:self.end_position.column] + line[self.end_position.column:] + '\n ' + '-' * self.start_position.column + '~' * (self.end_position.column - self.start_position.column) + '-' * (len(line) - self.end_position.column)
class Runtimeerror(BasePSError):
def __init__(self, start_position, end_position, error_message, context):
super().__init__(start_position, end_position, 'Runtime Error', error_message, context)
class Notimplementederror(BasePSError):
def __init__(self, start_position, end_position, error_message, context):
super().__init__(start_position, end_position, 'Not Implemented', error_message, context) |
class Solution:
def sequenceReconstruction(self, org: List[int], seqs: List[List[int]]) -> bool:
children = collections.defaultdict(set)
parents = collections.defaultdict(set)
nodes = set()
for s in seqs:
for i in range(len(s)):
nodes.add(s[i])
if i > 0:
parents[s[i]].add(s[i-1])
if i < len(s) - 1:
children[s[i]].add(s[i+1])
potential_parent = [n for n in nodes if not parents[n]]
indegree = len(potential_parent) # Count is the in-degree
ans = [] # ans is the final result
while indegree == 1: # Indegree need to equal one
cur_parent, count = potential_parent.pop(), indegree - 1
ans.append(cur_parent)
nodes.remove(cur_parent)
for n in children[cur_parent]:
parents[n].remove(cur_parent)
if not parents[n]:
potential_parent.append(n)
indegree += 1
return True if not nodes and ans==org else False
| class Solution:
def sequence_reconstruction(self, org: List[int], seqs: List[List[int]]) -> bool:
children = collections.defaultdict(set)
parents = collections.defaultdict(set)
nodes = set()
for s in seqs:
for i in range(len(s)):
nodes.add(s[i])
if i > 0:
parents[s[i]].add(s[i - 1])
if i < len(s) - 1:
children[s[i]].add(s[i + 1])
potential_parent = [n for n in nodes if not parents[n]]
indegree = len(potential_parent)
ans = []
while indegree == 1:
(cur_parent, count) = (potential_parent.pop(), indegree - 1)
ans.append(cur_parent)
nodes.remove(cur_parent)
for n in children[cur_parent]:
parents[n].remove(cur_parent)
if not parents[n]:
potential_parent.append(n)
indegree += 1
return True if not nodes and ans == org else False |
def parse_vars(vars):
res = set()
for var in vars.split(" "):
var = var.split("<")[0]
res.add(chr(int(var[2:], 16)))
return res
| def parse_vars(vars):
res = set()
for var in vars.split(' '):
var = var.split('<')[0]
res.add(chr(int(var[2:], 16)))
return res |
n,m=map(int,input().split())
l=[]
for i in range(n):
new=list(map(int,input().split()))
l.append(new)
ans=[]
for i in range(n):
ans.append([0]*m)
for i in range(n):
for j in range(m):
if (i+j)%2==1:
ans[i][j]=720720 #lcm of first 16 numbers
else:
ans[i][j]=720720+(l[i][j])**4
for k in range(n):
print(*ans[k]) | (n, m) = map(int, input().split())
l = []
for i in range(n):
new = list(map(int, input().split()))
l.append(new)
ans = []
for i in range(n):
ans.append([0] * m)
for i in range(n):
for j in range(m):
if (i + j) % 2 == 1:
ans[i][j] = 720720
else:
ans[i][j] = 720720 + l[i][j] ** 4
for k in range(n):
print(*ans[k]) |
# -*- coding: utf-8 -*-
# @Author: 1uci3n
# @Date: 2021-03-10 16:02:41
# @Last Modified by: 1uci3n
# @Last Modified time: 2021-03-10 16:03:13
class Solution:
def calculate(self, s: str) -> int:
i = 0
kuohao = []
temp_sums = []
temp_sum = 0
temp_str = '0'
while i < len(s):
if s[i] == ' ':
s = s[:i] + s[i + 1:]
continue
else:
if s[i] == '(':
temp_sum += int(temp_str)
temp_str = '0'
temp_sums.append(temp_sum)
temp_sum = 0
if i == 0:
kuohao.append(1)
else:
if s[i - 1] == "-":
kuohao.append(-1)
else:
kuohao.append(1)
elif s[i] == ')':
temp_sum += int(temp_str)
temp_str = '0'
temp_sum = temp_sums.pop(-1) + (temp_sum * kuohao.pop(-1))
elif (s[i] == '+') or (s[i] == '-'):
temp_sum += int(temp_str)
temp_str = '0'
else:
if i == 0:
temp_str = s[i]
else:
if (s[i - 1] == '(') or (s[i - 1] == ")"):
temp_str = s[i]
elif s[i - 1] == '+':
temp_str = s[i]
elif s[i - 1] == '-':
temp_str = s[i-1:i+1]
else:
temp_str += s[i]
i += 1
temp_sum += int(temp_str)
return temp_sum | class Solution:
def calculate(self, s: str) -> int:
i = 0
kuohao = []
temp_sums = []
temp_sum = 0
temp_str = '0'
while i < len(s):
if s[i] == ' ':
s = s[:i] + s[i + 1:]
continue
else:
if s[i] == '(':
temp_sum += int(temp_str)
temp_str = '0'
temp_sums.append(temp_sum)
temp_sum = 0
if i == 0:
kuohao.append(1)
elif s[i - 1] == '-':
kuohao.append(-1)
else:
kuohao.append(1)
elif s[i] == ')':
temp_sum += int(temp_str)
temp_str = '0'
temp_sum = temp_sums.pop(-1) + temp_sum * kuohao.pop(-1)
elif s[i] == '+' or s[i] == '-':
temp_sum += int(temp_str)
temp_str = '0'
elif i == 0:
temp_str = s[i]
elif s[i - 1] == '(' or s[i - 1] == ')':
temp_str = s[i]
elif s[i - 1] == '+':
temp_str = s[i]
elif s[i - 1] == '-':
temp_str = s[i - 1:i + 1]
else:
temp_str += s[i]
i += 1
temp_sum += int(temp_str)
return temp_sum |
print('='*8,'Aumentos Multiplos','='*8)
s = float(input('Qual o valor do salario atual do funcionario? R$'))
if s<=1250.00:
ns = s*1.15
print('O novo salario do funcionario devera ser de R${:.2f}.'.format(ns))
else:
ns = s*1.10
print('O novo salario do funcionario devera ser de R${:.2f}.'.format(ns))
| print('=' * 8, 'Aumentos Multiplos', '=' * 8)
s = float(input('Qual o valor do salario atual do funcionario? R$'))
if s <= 1250.0:
ns = s * 1.15
print('O novo salario do funcionario devera ser de R${:.2f}.'.format(ns))
else:
ns = s * 1.1
print('O novo salario do funcionario devera ser de R${:.2f}.'.format(ns)) |
X = int(input())
azuke = 100
ans = 0
while True:
azuke = int(azuke*1.01)
ans += 1
if azuke >= X:
print(ans)
exit(0)
| x = int(input())
azuke = 100
ans = 0
while True:
azuke = int(azuke * 1.01)
ans += 1
if azuke >= X:
print(ans)
exit(0) |
text = "hello world"
for c in text:
if c ==" ":
break
print(c) #will print every single fro mthe beginning of text but will stop a first space
| text = 'hello world'
for c in text:
if c == ' ':
break
print(c) |
# Write a program that ask the user car speed.If exceed 80km/h, show one message saying that the user has been fined.In this case, show the fine price, charging $5 per km over the limit of 80km/h
speed=int(input("What is your car speed(in km/h): "))
if speed>80:
fine=(speed-80)*5
print(f"You has been fined in ${fine}")
else:
print("You're ok!!!") | speed = int(input('What is your car speed(in km/h): '))
if speed > 80:
fine = (speed - 80) * 5
print(f'You has been fined in ${fine}')
else:
print("You're ok!!!") |
TEAM_DATA = {
"nba": {
"1": [
"atl",
"hawks",
"atlanta hawks",
"<:hawks:935782369212895232>"
],
"2": [
"bos",
"celtics",
"boston celtics",
"<:celtics:935742825377718302>"
],
"3": [
"no",
"pelicans",
"new orleans pelicans",
"<:pelicans:935742824639524906>"
],
"4": [
"chi",
"bulls",
"chicago bulls",
"<:bulls:935781032408530965>"
],
"5": [
"cle",
"cavaliers",
"cleveland cavaliers",
"<:cavs:935780132323467304>"
],
"6": [
"dal",
"mavericks",
"dallas mavericks",
"<:mavs:935779419954495489>"
],
"7": [
"den",
"nuggets",
"denver nuggets",
"<:nuggets:935742824111042641>"
],
"8": [
"det",
"pistons",
"detroit pistons",
"<:pistons:935742822617845781>"
],
"9": [
"gs",
"warriors",
"golden state warriors",
"<:warriors:935778738975686756>"
],
"10": [
"hou",
"rockets",
"houston rockets",
"<:rockets:935777235946864720>"
],
"11": [
"ind",
"pacers",
"indiana pacers",
"<:pacers:935742819816071178>"
],
"12": [
"lac",
"clippers",
"los angeles clippers",
"<:clippers:935777432382894110>"
],
"13": [
"lal",
"lakers",
"los angeles lakers",
"<:lakers:935742822508793916>"
],
"14": [
"mia",
"heat",
"miami heat",
"<:heat:935742822475259924>"
],
"15": [
"mil",
"bucks",
"milwaukee bucks",
"<:bucks:935783302684606574>"
],
"16": [
"min",
"timberwolves",
"minnesota timberwolves",
"<:wolves:935779853196734484>"
],
"17": [
"bkn",
"nets",
"brooklyn nets",
"<:nets:935777990342750230>"
],
"18": [
"ny",
"knicks",
"new york knicks",
"<:knicks:935742823502839868>"
],
"19": [
"orl",
"magic",
"orlando magic",
"<:magic:935742825218310184>"
],
"20": [
"phi",
"76ers",
"philadelphia 76ers",
"<:76ers:935742824803078196>"
],
"21": [
"phx",
"suns",
"phoenix suns",
"<:suns:935742825230905454>"
],
"22": [
"por",
"blazers",
"portland trail blazers",
"<:tblazers:935742823985205358>"
],
"23": [
"sac",
"kings",
"sacramento kings",
"<:kings:935742821275689001>"
],
"24": [
"sa",
"spurs",
"san antonio spurs",
"<:spurs:935777073841201162>"
],
"25": [
"okc",
"thunder",
"oklahoma city thunder",
"<:thunder:935742823603519538>"
],
"26": [
"utah",
"jazz",
"utah jazz",
"<:jazz:935742822190035074>"
],
"27": [
"wsh",
"wizards",
"washington wizards",
"<:wizards:935742825004425287>"
],
"28": [
"tor",
"raptors",
"toronto raptors",
"<:raptors:935779004366061588>"
],
"29": [
"mem",
"grizzlies",
"memphis grizzlies",
"<:grizzlies:935782819500793877>"
],
"30": [
"cha",
"hornets",
"charlotte hornets",
"<:hornets:935742822873727046>"
]
},
"nfl": {
"4": [
"cin",
"bengals",
"cincinnati bengals",
"<:bengals:936134271943442444>"
],
"12": [
"kc",
"chiefs",
"kansas city chiefs",
"<:chiefs:936134176590164019>"
],
"14": [
"lar",
"rams",
"los angeles rams",
"<:rams:936134176619511891>"
],
"25": [
"sf",
"49ers",
"san francisco 49ers",
"<:49ers:936134177038958592>"
]
}
}
| team_data = {'nba': {'1': ['atl', 'hawks', 'atlanta hawks', '<:hawks:935782369212895232>'], '2': ['bos', 'celtics', 'boston celtics', '<:celtics:935742825377718302>'], '3': ['no', 'pelicans', 'new orleans pelicans', '<:pelicans:935742824639524906>'], '4': ['chi', 'bulls', 'chicago bulls', '<:bulls:935781032408530965>'], '5': ['cle', 'cavaliers', 'cleveland cavaliers', '<:cavs:935780132323467304>'], '6': ['dal', 'mavericks', 'dallas mavericks', '<:mavs:935779419954495489>'], '7': ['den', 'nuggets', 'denver nuggets', '<:nuggets:935742824111042641>'], '8': ['det', 'pistons', 'detroit pistons', '<:pistons:935742822617845781>'], '9': ['gs', 'warriors', 'golden state warriors', '<:warriors:935778738975686756>'], '10': ['hou', 'rockets', 'houston rockets', '<:rockets:935777235946864720>'], '11': ['ind', 'pacers', 'indiana pacers', '<:pacers:935742819816071178>'], '12': ['lac', 'clippers', 'los angeles clippers', '<:clippers:935777432382894110>'], '13': ['lal', 'lakers', 'los angeles lakers', '<:lakers:935742822508793916>'], '14': ['mia', 'heat', 'miami heat', '<:heat:935742822475259924>'], '15': ['mil', 'bucks', 'milwaukee bucks', '<:bucks:935783302684606574>'], '16': ['min', 'timberwolves', 'minnesota timberwolves', '<:wolves:935779853196734484>'], '17': ['bkn', 'nets', 'brooklyn nets', '<:nets:935777990342750230>'], '18': ['ny', 'knicks', 'new york knicks', '<:knicks:935742823502839868>'], '19': ['orl', 'magic', 'orlando magic', '<:magic:935742825218310184>'], '20': ['phi', '76ers', 'philadelphia 76ers', '<:76ers:935742824803078196>'], '21': ['phx', 'suns', 'phoenix suns', '<:suns:935742825230905454>'], '22': ['por', 'blazers', 'portland trail blazers', '<:tblazers:935742823985205358>'], '23': ['sac', 'kings', 'sacramento kings', '<:kings:935742821275689001>'], '24': ['sa', 'spurs', 'san antonio spurs', '<:spurs:935777073841201162>'], '25': ['okc', 'thunder', 'oklahoma city thunder', '<:thunder:935742823603519538>'], '26': ['utah', 'jazz', 'utah jazz', '<:jazz:935742822190035074>'], '27': ['wsh', 'wizards', 'washington wizards', '<:wizards:935742825004425287>'], '28': ['tor', 'raptors', 'toronto raptors', '<:raptors:935779004366061588>'], '29': ['mem', 'grizzlies', 'memphis grizzlies', '<:grizzlies:935782819500793877>'], '30': ['cha', 'hornets', 'charlotte hornets', '<:hornets:935742822873727046>']}, 'nfl': {'4': ['cin', 'bengals', 'cincinnati bengals', '<:bengals:936134271943442444>'], '12': ['kc', 'chiefs', 'kansas city chiefs', '<:chiefs:936134176590164019>'], '14': ['lar', 'rams', 'los angeles rams', '<:rams:936134176619511891>'], '25': ['sf', '49ers', 'san francisco 49ers', '<:49ers:936134177038958592>']}} |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# TIOJ 1006.py
# @Author : ()
# @Link :
# @Date : 2019/10/5
a = input()
b = input()
a = int(a)
b = int(b)
print(a//b) | a = input()
b = input()
a = int(a)
b = int(b)
print(a // b) |
days = input().split("|")
energy = 100
coins = 100
bakery_is_closed = False
for current_day in days:
current_day = current_day.split("-")
to_do = current_day[0]
number = int(current_day[1])
if to_do == "rest":
needed_energy = 100 - energy
gained_energy = min(number, needed_energy)
energy += gained_energy
print(f"You gained {gained_energy} energy.")
print(f"Current energy: {energy}.")
elif to_do == "order":
if energy >= 30:
energy -= 30
coins += number
print(f"You earned {number} coins.")
else:
energy += 50
print(f"You had to rest!")
continue
else:
ingredient = to_do
coins -= number
if coins > 0:
print(f"You bought {ingredient}.")
else:
print(f"Closed! Cannot afford {ingredient}.")
bakery_is_closed = True
break
if bakery_is_closed is True:
break
if bakery_is_closed is False:
print("Day completed!")
print(f"Coins: {coins}")
print(f"Energy: {energy}")
| days = input().split('|')
energy = 100
coins = 100
bakery_is_closed = False
for current_day in days:
current_day = current_day.split('-')
to_do = current_day[0]
number = int(current_day[1])
if to_do == 'rest':
needed_energy = 100 - energy
gained_energy = min(number, needed_energy)
energy += gained_energy
print(f'You gained {gained_energy} energy.')
print(f'Current energy: {energy}.')
elif to_do == 'order':
if energy >= 30:
energy -= 30
coins += number
print(f'You earned {number} coins.')
else:
energy += 50
print(f'You had to rest!')
continue
else:
ingredient = to_do
coins -= number
if coins > 0:
print(f'You bought {ingredient}.')
else:
print(f'Closed! Cannot afford {ingredient}.')
bakery_is_closed = True
break
if bakery_is_closed is True:
break
if bakery_is_closed is False:
print('Day completed!')
print(f'Coins: {coins}')
print(f'Energy: {energy}') |
MODULE_NAME = 'Gigamon ThreatINSIGHT ConfTokenTest'
INTEGRATION_NAME = 'Gigamon ThreatINSIGHT'
GIGAMON_URL = 'https://portal.icebrg.io'
CONFIDENCE = SEVERITY = ('High', 'Medium', 'Low')
RELATIONS_TYPES = (
'Connected_To', 'Sent_From', 'Sent_To',
'Resolved_To', 'Hosted_On', 'Queried_For',
'Downloaded_To', 'Downloaded_From',
'Uploaded_From', 'Uploaded_To',
)
TARGETS_OBSERVABLES_TYPES = ('ip', 'hostname', 'mac_address')
RELATED_OBSERVABLES_TYPES = (
'ip', 'domain', 'sha1', 'sha256', 'md5', 'url', 'user_agent'
)
OBSERVABLE_HUMAN_READABLE_NAME = {
'ip': 'IP',
'sha256': 'SHA256',
'md5': 'MD5',
'sha1': 'SHA1',
'domain': 'domain'
}
CTR_ENTITIES_LIMIT = 100
| module_name = 'Gigamon ThreatINSIGHT ConfTokenTest'
integration_name = 'Gigamon ThreatINSIGHT'
gigamon_url = 'https://portal.icebrg.io'
confidence = severity = ('High', 'Medium', 'Low')
relations_types = ('Connected_To', 'Sent_From', 'Sent_To', 'Resolved_To', 'Hosted_On', 'Queried_For', 'Downloaded_To', 'Downloaded_From', 'Uploaded_From', 'Uploaded_To')
targets_observables_types = ('ip', 'hostname', 'mac_address')
related_observables_types = ('ip', 'domain', 'sha1', 'sha256', 'md5', 'url', 'user_agent')
observable_human_readable_name = {'ip': 'IP', 'sha256': 'SHA256', 'md5': 'MD5', 'sha1': 'SHA1', 'domain': 'domain'}
ctr_entities_limit = 100 |
def get_subindicator(metric):
subindicators = metric.indicator.subindicators
idx = metric.subindicator if metric.subindicator is not None else 0
return subindicators[idx]
def get_sum(data, group=None, subindicator=None):
if (group is not None and subindicator is not None):
return sum([float(row["count"]) for row in data if group in row and row[group] == subindicator])
return sum(float(row["count"]) for row in data)
class MetricCalculator:
@staticmethod
def absolute_value(data, metric, geography):
group = metric.indicator.groups[0]
subindicator = get_subindicator(metric)
filtered_data = [row["count"] for row in data if group in row and row[group] == subindicator]
return get_sum(data, group, subindicator)
@staticmethod
def subindicator(data, metric, geography):
group = metric.indicator.groups[0]
subindicator = get_subindicator(metric)
numerator = get_sum(data, group, subindicator)
denominator = get_sum(data)
if denominator > 0 and numerator is not None:
return numerator / denominator
@staticmethod
def sibling(data, metric, geography):
group = metric.indicator.groups[0]
subindicator = get_subindicator(metric)
geography_total = total = 0
geography_has_data = False
for datum in data:
total += get_sum(datum.data, group=group, subindicator=subindicator)
if datum.geography == geography:
geography_total = get_sum(datum.data, group=group, subindicator=subindicator)
geography_has_data = True
if not geography_has_data:
return None
denominator, numerator = total, geography_total
if denominator > 0 and numerator is not None:
return numerator / denominator
@staticmethod
def get_algorithm(algorithm, default="absolute_value"):
return {
"absolute_value": MetricCalculator.absolute_value,
"sibling": MetricCalculator.sibling,
"subindicators": MetricCalculator.subindicator
}.get(algorithm, default)
| def get_subindicator(metric):
subindicators = metric.indicator.subindicators
idx = metric.subindicator if metric.subindicator is not None else 0
return subindicators[idx]
def get_sum(data, group=None, subindicator=None):
if group is not None and subindicator is not None:
return sum([float(row['count']) for row in data if group in row and row[group] == subindicator])
return sum((float(row['count']) for row in data))
class Metriccalculator:
@staticmethod
def absolute_value(data, metric, geography):
group = metric.indicator.groups[0]
subindicator = get_subindicator(metric)
filtered_data = [row['count'] for row in data if group in row and row[group] == subindicator]
return get_sum(data, group, subindicator)
@staticmethod
def subindicator(data, metric, geography):
group = metric.indicator.groups[0]
subindicator = get_subindicator(metric)
numerator = get_sum(data, group, subindicator)
denominator = get_sum(data)
if denominator > 0 and numerator is not None:
return numerator / denominator
@staticmethod
def sibling(data, metric, geography):
group = metric.indicator.groups[0]
subindicator = get_subindicator(metric)
geography_total = total = 0
geography_has_data = False
for datum in data:
total += get_sum(datum.data, group=group, subindicator=subindicator)
if datum.geography == geography:
geography_total = get_sum(datum.data, group=group, subindicator=subindicator)
geography_has_data = True
if not geography_has_data:
return None
(denominator, numerator) = (total, geography_total)
if denominator > 0 and numerator is not None:
return numerator / denominator
@staticmethod
def get_algorithm(algorithm, default='absolute_value'):
return {'absolute_value': MetricCalculator.absolute_value, 'sibling': MetricCalculator.sibling, 'subindicators': MetricCalculator.subindicator}.get(algorithm, default) |
# -*- coding: utf-8 -*-
__all__ = ('__version__',)
__version__ = '0.39.0+dev'
def includeme(config):
config.include('pyramid_services')
# This must be included first so it can set up the model base class if
# need be.
config.include('memex.models')
config.include('memex.links')
| __all__ = ('__version__',)
__version__ = '0.39.0+dev'
def includeme(config):
config.include('pyramid_services')
config.include('memex.models')
config.include('memex.links') |
description = 'setup for the NICOS watchdog'
group = 'special'
# The entries in this list are dictionaries. Possible keys:
#
# 'setup' -- setup that must be loaded (default '' to mean all setups)
# 'condition' -- condition for warning (a Python expression where cache keys
# can be used: t_value stands for t/value etc.
# 'gracetime' -- time in sec allowed for the condition to be true without
# emitting a warning (default 5 sec)
# 'message' -- warning message to display
# 'priority' -- 1 or 2, where 2 is more severe (default 1)
# 'action' -- code to execute if condition is true (default no code is executed)
watch_conditions = [
dict(condition = 'LogSpace_status[0] == WARN',
message = 'Disk space for log files becomes too low.',
type = 'critical',
gracetime = 30,
),
dict(condition = '(sixfold_value == "closed" or nl4a_value == "closed") '
'and reactorpower_value > 19',
message = 'NL4a or sixfold shutter closed',
type = 'critical',
),
dict(condition = 't_in_memograph_value > 20',
message = 'Cooling water inlet temperature exceeds 20 C, check FAK40 and SANS-1 memograph!',
#type = 'critical',
type = None,
gracetime = 30,
),
# dict(condition = 'ReactorPower_value < 19',
# message = 'Reactor power is below 19 MW!',
# #type = 'critical',
# type = None,
# gracetime = 120,
# ),
dict(condition = 'ReactorPower_value < 4.5',
message = 'Reactor power is below 4.5 MW!',
#type = 'critical',
type = None,
gracetime = 120,
),
dict(condition = 'ccm5h_T_topleft_value > 4.5',
message = 'Magnet Topleft > 4.5 K, check for possible quench of magnet!',
#type = 'critical',
type = None,
setup = 'ccm5h',
gracetime = 5,
),
dict(condition = 'coll_tube_value > 1',
message = 'Pressure within collimation tube above 1 mbar! Check if pump is running.',
#type = 'critical',
type = None,
gracetime = 30,
),
dict(condition = 'coll_nose_value > 1',
message = 'Pressure within collimation nose above 1 mbar! Check if pump is running.',
#type = 'critical',
type = None,
gracetime = 30,
),
dict(condition = 'det_nose_value > 0.5',
message = 'Pressure within detector nose above 0.5 mbar! Check if pump is running.',
#type = 'critical',
type = None,
gracetime = 30,
),
dict(condition = 'det_tube_value > 0.5',
message = 'Pressure within detector tube above 0.5 mbar! Check if pump is running.',
#type = 'critical',
type = None,
gracetime = 30,
),
dict(condition = 'p_diff_filter_value > 0.5',
message = 'Differential pressure at filter above 0.5 bar! Clean Filter.',
#type = 'critical',
type = None,
gracetime = 60,
),
dict(condition = 'det1_hv_ax_value < 1000',
message = 'Detector Voltage down for more than 15 min! Check high voltage.',
#type = 'critical',
type = None,
gracetime = 900,
),
# dict(condition = 'chopper_ch2_phase_value < 4.7 or chopper_ch2_phase_value > 4.9',
# message = 'Chopper 2 lost parking phase position!',
# #type = 'critical',
# type = None,
# setup = 'not tisane',
# gracetime = 5,
# action = 'move(chopper_ch2_parkingpos, 4.8)',
# ),
# dict(condition = 'chopper_ch1_phase_value < 16.1 or chopper_ch1_phase_value > 16.3',
# message = 'Chopper 1 lost parking phase position!',
# #type = 'critical',
# type = None,
# setup = 'not tisane',
# gracetime = 5,
# action = 'move(chopper_ch1_parkingpos, 16.2)',
# ),
dict(condition = 'selector_rpm_value > 30000',
message = 'selector rpm above 30000. Please check Selector hardware!!!',
#type = 'critical',
type = None,
gracetime = 30,
),
# dict(condition = 'chopper_waterflow_value < 3',
# message = 'Low Waterflow for chopper!!!\nCheck filter and pressure knob!',
# #type = 'critical',
# type = None,
# gracetime = 30,
# ),
]
# The Watchdog device has two lists of notifiers, one for priority 1 and
# one for priority 2.
includes = ['notifiers']
devices = dict(
Watchdog = device('nicos.services.watchdog.Watchdog',
cache = 'sans1ctrl.sans1.frm2:14869',
# notifiers = {'default': ['info'], 'critical': ['email']},
notifiers = {},
watch = watch_conditions,
# mailreceiverkey = 'email/receivers',
),
)
| description = 'setup for the NICOS watchdog'
group = 'special'
watch_conditions = [dict(condition='LogSpace_status[0] == WARN', message='Disk space for log files becomes too low.', type='critical', gracetime=30), dict(condition='(sixfold_value == "closed" or nl4a_value == "closed") and reactorpower_value > 19', message='NL4a or sixfold shutter closed', type='critical'), dict(condition='t_in_memograph_value > 20', message='Cooling water inlet temperature exceeds 20 C, check FAK40 and SANS-1 memograph!', type=None, gracetime=30), dict(condition='ReactorPower_value < 4.5', message='Reactor power is below 4.5 MW!', type=None, gracetime=120), dict(condition='ccm5h_T_topleft_value > 4.5', message='Magnet Topleft > 4.5 K, check for possible quench of magnet!', type=None, setup='ccm5h', gracetime=5), dict(condition='coll_tube_value > 1', message='Pressure within collimation tube above 1 mbar! Check if pump is running.', type=None, gracetime=30), dict(condition='coll_nose_value > 1', message='Pressure within collimation nose above 1 mbar! Check if pump is running.', type=None, gracetime=30), dict(condition='det_nose_value > 0.5', message='Pressure within detector nose above 0.5 mbar! Check if pump is running.', type=None, gracetime=30), dict(condition='det_tube_value > 0.5', message='Pressure within detector tube above 0.5 mbar! Check if pump is running.', type=None, gracetime=30), dict(condition='p_diff_filter_value > 0.5', message='Differential pressure at filter above 0.5 bar! Clean Filter.', type=None, gracetime=60), dict(condition='det1_hv_ax_value < 1000', message='Detector Voltage down for more than 15 min! Check high voltage.', type=None, gracetime=900), dict(condition='selector_rpm_value > 30000', message='selector rpm above 30000. Please check Selector hardware!!!', type=None, gracetime=30)]
includes = ['notifiers']
devices = dict(Watchdog=device('nicos.services.watchdog.Watchdog', cache='sans1ctrl.sans1.frm2:14869', notifiers={}, watch=watch_conditions)) |
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Point(self.x + other.x, self.y + other.y)
def __sub__(self, other):
return Point(self.x - other.x, self.y - other.y)
def __mul__(self, other):
return Point(self.x * other.x, self.y * other.y)
# +=
def __iadd__(self, other):
self.x += other.x
self.y += other.y
return self
def __str__(self):
return f'({self.x}, {self.y})'
point1 = Point(1,2)
point2 = Point(2,3)
print (point1 + point2)
print (point1 - point2)
print (point1 * point2)
point1 += point2
print (point1)
| class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return point(self.x + other.x, self.y + other.y)
def __sub__(self, other):
return point(self.x - other.x, self.y - other.y)
def __mul__(self, other):
return point(self.x * other.x, self.y * other.y)
def __iadd__(self, other):
self.x += other.x
self.y += other.y
return self
def __str__(self):
return f'({self.x}, {self.y})'
point1 = point(1, 2)
point2 = point(2, 3)
print(point1 + point2)
print(point1 - point2)
print(point1 * point2)
point1 += point2
print(point1) |
def main():
n_gnomes_orig, n_gnomes_remain = [int(x) for x in input().split()]
gnomes_remain = []
for _ in range(n_gnomes_remain):
gnomes_remain.append(int(input()))
gnomes_remain_tmp = set(gnomes_remain)
missing_gnomes = [g for g in range(1, n_gnomes_orig + 1) if g not in gnomes_remain_tmp]
i = 0
for g in missing_gnomes:
while i < len(gnomes_remain) and gnomes_remain[i] < g:
print(gnomes_remain[i])
i += 1
print(g)
if i < len(gnomes_remain):
print("\n".join(str(g) for g in gnomes_remain[i:]))
if __name__ == '__main__':
main()
| def main():
(n_gnomes_orig, n_gnomes_remain) = [int(x) for x in input().split()]
gnomes_remain = []
for _ in range(n_gnomes_remain):
gnomes_remain.append(int(input()))
gnomes_remain_tmp = set(gnomes_remain)
missing_gnomes = [g for g in range(1, n_gnomes_orig + 1) if g not in gnomes_remain_tmp]
i = 0
for g in missing_gnomes:
while i < len(gnomes_remain) and gnomes_remain[i] < g:
print(gnomes_remain[i])
i += 1
print(g)
if i < len(gnomes_remain):
print('\n'.join((str(g) for g in gnomes_remain[i:])))
if __name__ == '__main__':
main() |
print("*****************")
print("Guessing game")
print("*****************")
secret_number = 43
attempts_total = 3
for attempt in range(1, attempts_total + 1):
print("Attempt {} by {}".format(attempt, attempts_total))
user_number_str = input("Fill the number: ")
print("Your number was: " + user_number_str)
user_number = int(user_number_str)
if(user_number < 1 or user_number > 100):
print("Please fill number between 1 and 100!")
continue #Sai do IF e executa o for de novo
right_result = secret_number == user_number
lower_result = user_number < secret_number
bigger_result = user_number > secret_number
if (right_result):
print("You discovery the secret number")
print("WINNER!")
break
elif(lower_result):
print("Wrong number! The Number is Lower than real number")
elif (bigger_result):
print("Wrong number! The Number is bigger than real number")
print("GAME OVER") | print('*****************')
print('Guessing game')
print('*****************')
secret_number = 43
attempts_total = 3
for attempt in range(1, attempts_total + 1):
print('Attempt {} by {}'.format(attempt, attempts_total))
user_number_str = input('Fill the number: ')
print('Your number was: ' + user_number_str)
user_number = int(user_number_str)
if user_number < 1 or user_number > 100:
print('Please fill number between 1 and 100!')
continue
right_result = secret_number == user_number
lower_result = user_number < secret_number
bigger_result = user_number > secret_number
if right_result:
print('You discovery the secret number')
print('WINNER!')
break
elif lower_result:
print('Wrong number! The Number is Lower than real number')
elif bigger_result:
print('Wrong number! The Number is bigger than real number')
print('GAME OVER') |
[
[0.0, 1.3892930788974391, 0.8869425734660505, 1.402945620973322],
[0.0, 0.1903540333363253, 0.30894158244285624, 0.3994739596013725],
[0.0, 0.03761142927757482, 1.2682277741610029, 0.36476016345069556],
[0.0, -1.187392798652706, -1.0206496663686406, -1.35111583891054],
[0.0, -1.742783579889951, -2.425391682127969, -3.0738474093706927],
]
| [[0.0, 1.3892930788974391, 0.8869425734660505, 1.402945620973322], [0.0, 0.1903540333363253, 0.30894158244285624, 0.3994739596013725], [0.0, 0.03761142927757482, 1.2682277741610029, 0.36476016345069556], [0.0, -1.187392798652706, -1.0206496663686406, -1.35111583891054], [0.0, -1.742783579889951, -2.425391682127969, -3.0738474093706927]] |
_ = input() # number of test cases; we can ignore this since it has no significance
temps = map(int, input().split()) # all the temps stored to a list with type int
subercold = 0 # how many temps below 0 we got
for i in temps:
# for every temp we recorded if it's less than 0 add +1 to subercold
if i < 0:
subercold += 1
print(subercold)
| _ = input()
temps = map(int, input().split())
subercold = 0
for i in temps:
if i < 0:
subercold += 1
print(subercold) |
#!/usr/bin/python
# -*- utf-8 -*-
class Solution:
# @param A, a list of integer
# @return an integer
def singleNumber(self, A):
cache = {}
for a in A:
count = cache.get(a, 0) + 1
if count >= 3:
cache.pop(a)
else:
cache[a] = count
return cache.popitem()[0]
if __name__ == '__main__':
print(Solution().singleNumber([1,2,3,2,1,2,3,1])) | class Solution:
def single_number(self, A):
cache = {}
for a in A:
count = cache.get(a, 0) + 1
if count >= 3:
cache.pop(a)
else:
cache[a] = count
return cache.popitem()[0]
if __name__ == '__main__':
print(solution().singleNumber([1, 2, 3, 2, 1, 2, 3, 1])) |
# Criando arquivo 1 com 10 linhas
with open('arquivo1.txt', 'w') as arq1:
for line in range(1, 11):
arq1.write(f'Linha {line} do arquivo 1\n')
# Criando arquivo 2 com 10 linhas
with open('arquivo2.txt', 'w') as arq1:
for line in range(1, 11):
arq1.write(f'Linha {line} do arquivo 2\n')
# Lendo ambos arquivos e intercalando
with open('arquivo1.txt', 'r') as arq1:
with open('arquivo2.txt', 'r') as arq2:
with open('arquivo3.txt', 'w') as arq3:
for line in range(0, 20):
arq3.write(arq1.readline())
arq3.write(arq2.readline())
| with open('arquivo1.txt', 'w') as arq1:
for line in range(1, 11):
arq1.write(f'Linha {line} do arquivo 1\n')
with open('arquivo2.txt', 'w') as arq1:
for line in range(1, 11):
arq1.write(f'Linha {line} do arquivo 2\n')
with open('arquivo1.txt', 'r') as arq1:
with open('arquivo2.txt', 'r') as arq2:
with open('arquivo3.txt', 'w') as arq3:
for line in range(0, 20):
arq3.write(arq1.readline())
arq3.write(arq2.readline()) |
# https://www.codewars.com/kata/5432fd1c913a65b28f000342/train/python
'''
Instructions :
Create a function that accepts dimensions, of Rows x Columns, as parameters in order to create a multiplication table sized according to the given dimensions. **The return value of the function must be an array, and the numbers must be Fixnums, NOT strings.
Example:
multiplication_table(3,3)
1 2 3
2 4 6
3 6 9
-->[[1,2,3],[2,4,6],[3,6,9]]
Each value on the table should be equal to the value of multiplying the number in its first row times the number in its first column.
'''
def multiplication_table(row,col):
return [[j*i for j in range(1, col+1)] for i in range(1, row+1)]
| """
Instructions :
Create a function that accepts dimensions, of Rows x Columns, as parameters in order to create a multiplication table sized according to the given dimensions. **The return value of the function must be an array, and the numbers must be Fixnums, NOT strings.
Example:
multiplication_table(3,3)
1 2 3
2 4 6
3 6 9
-->[[1,2,3],[2,4,6],[3,6,9]]
Each value on the table should be equal to the value of multiplying the number in its first row times the number in its first column.
"""
def multiplication_table(row, col):
return [[j * i for j in range(1, col + 1)] for i in range(1, row + 1)] |
class Solution:
def reorderedPowerOf2(self, N: int) -> bool:
t=1
cands=set()
while t<=1000000000:
tt=sorted([ttt for ttt in str(t)])
cands.add(''.join(tt))
t*=2
print(cands)
tt=sorted([ttt for ttt in str(N)])
print(tt)
return ''.join(tt) in cands | class Solution:
def reordered_power_of2(self, N: int) -> bool:
t = 1
cands = set()
while t <= 1000000000:
tt = sorted([ttt for ttt in str(t)])
cands.add(''.join(tt))
t *= 2
print(cands)
tt = sorted([ttt for ttt in str(N)])
print(tt)
return ''.join(tt) in cands |
#Meaning of Life?
answer = "42"
n = 1
i = 0
while i < 1:
x = input("What is the meaning of life? ")
if x != answer:
print("Incorrect.")
n = n + 1
if x == answer:
print("You got it in " + str(n) + " attempt(s)!")
break
| answer = '42'
n = 1
i = 0
while i < 1:
x = input('What is the meaning of life? ')
if x != answer:
print('Incorrect.')
n = n + 1
if x == answer:
print('You got it in ' + str(n) + ' attempt(s)!')
break |
#Create an empty set
s = set()
# Add elements to set
s.add(1)
s.add(2)
s.add(3)
s.add(4)
s.add(3)
s.remove(2)
print(s)
print(f"The set has {len(s)} elements.")
| s = set()
s.add(1)
s.add(2)
s.add(3)
s.add(4)
s.add(3)
s.remove(2)
print(s)
print(f'The set has {len(s)} elements.') |
# /* Kattis: acm
# *
# * Topic: others
# *
# * Level: easy
# *
# * Brief problem description:
# *
# * branching summation
# *
# * Solution Summary:
# *
# * basic arithmetic
# *
# * Used Resources:
# *
# *
# *
# * I hereby certify that I have produced the following solution myself
# * using only the resources listed above in accordance with the CMPUT
# * 403 collaboration policy.
# *
# *
# * Hung Nguyen
# */
line = input()
point = 0
penalty = 0
problems = dict()
while line != "-1":
try:
line = line.split(" ")
# print(line)
if line[2] == "right":
point += 1
penalty += int(line[0])
penalty += problems[line[1]] * 20
else:
problems[line[1]] += 1
except KeyError:
problems[line[1]] = 1
line = input()
print(str(point) + " " + str(penalty))
| line = input()
point = 0
penalty = 0
problems = dict()
while line != '-1':
try:
line = line.split(' ')
if line[2] == 'right':
point += 1
penalty += int(line[0])
penalty += problems[line[1]] * 20
else:
problems[line[1]] += 1
except KeyError:
problems[line[1]] = 1
line = input()
print(str(point) + ' ' + str(penalty)) |
def jmp_simple(n):
return 3 if n == 0 else 5
def jmp_short(n):
if n == 0:
n += 1
n += 1
n += 1
n += 1
n += 1
n += 1
n += 1
n += 1
n += 1
n += 1
n += 1
n += 1
n += 1
n += 1
n += 1
n += 1
n += 1
n += 1
n += 1
n += 1
n += 1
n += 1
n += 1
n += 1
n += 1
n += 1
n += 1
n += 1
n += 1
n += 1
return n
if __name__ == '__main__':
print("jmp_simple return %s" % jmp_simple(0))
print("jmp_short return %s" % jmp_short(0))
| def jmp_simple(n):
return 3 if n == 0 else 5
def jmp_short(n):
if n == 0:
n += 1
n += 1
n += 1
n += 1
n += 1
n += 1
n += 1
n += 1
n += 1
n += 1
n += 1
n += 1
n += 1
n += 1
n += 1
n += 1
n += 1
n += 1
n += 1
n += 1
n += 1
n += 1
n += 1
n += 1
n += 1
n += 1
n += 1
n += 1
n += 1
n += 1
return n
if __name__ == '__main__':
print('jmp_simple return %s' % jmp_simple(0))
print('jmp_short return %s' % jmp_short(0)) |
class Solution:
def minOperationsMaxProfit(self, customers: List[int], boardingCost: int, runningCost: int) -> int:
run = maxRun = 0
profit = maxProfit = 0
wait = 0
i = 0
while wait > 0 or i < len(customers):
if i < len(customers):
wait += customers[i]
i += 1
board = min(4, wait)
wait -= board
profit += board * boardingCost - runningCost
run += 1
if profit > maxProfit:
maxProfit = profit
maxRun = run
return maxRun if maxProfit > 0 else -1
| class Solution:
def min_operations_max_profit(self, customers: List[int], boardingCost: int, runningCost: int) -> int:
run = max_run = 0
profit = max_profit = 0
wait = 0
i = 0
while wait > 0 or i < len(customers):
if i < len(customers):
wait += customers[i]
i += 1
board = min(4, wait)
wait -= board
profit += board * boardingCost - runningCost
run += 1
if profit > maxProfit:
max_profit = profit
max_run = run
return maxRun if maxProfit > 0 else -1 |
# Method 1
def reverse(str):
return str[::-1]
# Method 2
'''
def reverse(string):
result = ""
for letter in xrange(len(string), 0, -1):
result = result + string[letter-1]
return result
'''
if __name__=="__main__":
print("Enter a String: ",end="")
str = input()
print("Reverse of '",str,"' is '",reverse(str),"'")
| def reverse(str):
return str[::-1]
'\ndef reverse(string):\n result = ""\n for letter in xrange(len(string), 0, -1):\n result = result + string[letter-1]\n return result\n'
if __name__ == '__main__':
print('Enter a String: ', end='')
str = input()
print("Reverse of '", str, "' is '", reverse(str), "'") |
config = {
# coinflex production api server
'rest_url': 'https://v2api.coinflex.com',
'rest_path': 'v2api.coinflex.com',
# local data filename
'coinflex_data_filename': 'coinflex_data.json',
# create an api key on coinflex.com and put it here
'api_key': "<your api key>",
'api_secret': "<your api secret>",
# list the assets and market pairs you used
'assets': [
"flexUSD"
],
'markets': [
"BCH-USD",
"DOGE-USD",
"BTC-USD"
],
# data will be pulled starting from this timestamp
't_account_start': int(1609455600 * 1000), # 2021/01/01 Europe/Berlin (output of "date -d 2021-01-01 +%s")
# list of endpoints to sync (look at endpoints.json for which ones are available)
'endpoints_to_sync': 'mint,redeem,earned,trades,withdrawals,deposits'
}
| config = {'rest_url': 'https://v2api.coinflex.com', 'rest_path': 'v2api.coinflex.com', 'coinflex_data_filename': 'coinflex_data.json', 'api_key': '<your api key>', 'api_secret': '<your api secret>', 'assets': ['flexUSD'], 'markets': ['BCH-USD', 'DOGE-USD', 'BTC-USD'], 't_account_start': int(1609455600 * 1000), 'endpoints_to_sync': 'mint,redeem,earned,trades,withdrawals,deposits'} |
GUILD_ID = 391155528501559296
# ==== rewards ====
REWARDS_CHANNEL = 404753143172431873
DISCUSSION_CHANNEL = 556531902865997834
SCHEDULED_HOUR = 20 # 2000 GMT
ROLES_TO_PING = [
404055199054036993, # dm
631621534233919499, # planar dm
# 405499372592168960 # trial dm
]
# ==== onboarding ====
ROLLING_CHANNEL = 404368543740723200
ROLES_TO_ASSIGN = ["Player"]
ONBOARDING_MESSAGE = "PLACEHOLDER" # todo
# ==== calendar ====
DM_QUEST_CHANNEL = 404050367454773251
PLAYER_QUEST_CHANNEL = 404050326128164884
REQUEST_DISCUSSION = 404497514113531905
| guild_id = 391155528501559296
rewards_channel = 404753143172431873
discussion_channel = 556531902865997834
scheduled_hour = 20
roles_to_ping = [404055199054036993, 631621534233919499]
rolling_channel = 404368543740723200
roles_to_assign = ['Player']
onboarding_message = 'PLACEHOLDER'
dm_quest_channel = 404050367454773251
player_quest_channel = 404050326128164884
request_discussion = 404497514113531905 |
class Movie():
# Initialize instance of class Movie
def __init__(self, movie_title, poster_image, trailer_youtube,
movie_storyline, movie_rating):
self.title = movie_title
self.poster_image_url = poster_image
self.trailer_youtube_url = trailer_youtube
self.storyline = movie_storyline
self.rating_image_url = movie_rating | class Movie:
def __init__(self, movie_title, poster_image, trailer_youtube, movie_storyline, movie_rating):
self.title = movie_title
self.poster_image_url = poster_image
self.trailer_youtube_url = trailer_youtube
self.storyline = movie_storyline
self.rating_image_url = movie_rating |
class Mammal:
mammal_population = 0
def __init__(self, name, age):
self.name = name
self.age = age
Mammal.mammal_population += 1
class Dog(Mammal):
dog_population = 0
def __init__(self, name, age, breed):
super().__init__(name, age)
self.breed = breed
Dog.dog_population += 1
def __str__(self):
return "{} is a dog - {}, {}".format(self.name, self.age, self.breed)
def __repr__(self):
return self.__str__()
def bark(self, times):
for i in range(times):
print("Woof!")
class Cat(Mammal):
cat_population = 0
def __init__(self, name, age, lives):
Mammal.__init__(self, name, age)
self.lives = lives
Cat.cat_population += 1
def __str__(self):
return "{} is a cat - {} {}".format(self.name, self.age, self.lives)
class Horse(Mammal):
pass
# charlie = Dog("charlie", 3, "collie")
# print(charlie)
#
# tom = Cat("tom", 3, 9)
# print(tom) | class Mammal:
mammal_population = 0
def __init__(self, name, age):
self.name = name
self.age = age
Mammal.mammal_population += 1
class Dog(Mammal):
dog_population = 0
def __init__(self, name, age, breed):
super().__init__(name, age)
self.breed = breed
Dog.dog_population += 1
def __str__(self):
return '{} is a dog - {}, {}'.format(self.name, self.age, self.breed)
def __repr__(self):
return self.__str__()
def bark(self, times):
for i in range(times):
print('Woof!')
class Cat(Mammal):
cat_population = 0
def __init__(self, name, age, lives):
Mammal.__init__(self, name, age)
self.lives = lives
Cat.cat_population += 1
def __str__(self):
return '{} is a cat - {} {}'.format(self.name, self.age, self.lives)
class Horse(Mammal):
pass |
def apply_filters(sv_list, rmsk_track=None, segdup_track=None):
for sv in sv_list:
if sv.type == 'INS' or (sv.type == 'BND' and sv.bnd_ins > 0):
sv.filters.add('INSERTION')
def get_filter_string(sv, filter_criteria):
intersection = set(sv.filters).intersection(set(filter_criteria))
if len(intersection) > 0:
return ','.join(sorted(intersection))
else:
return 'PASS'
| def apply_filters(sv_list, rmsk_track=None, segdup_track=None):
for sv in sv_list:
if sv.type == 'INS' or (sv.type == 'BND' and sv.bnd_ins > 0):
sv.filters.add('INSERTION')
def get_filter_string(sv, filter_criteria):
intersection = set(sv.filters).intersection(set(filter_criteria))
if len(intersection) > 0:
return ','.join(sorted(intersection))
else:
return 'PASS' |
huge = 999999999 # nothing but the largest number during calculation, just for convenience
cross_p = 0.8 # chromo cross probability
random_mutate_p = 0.1 # chromo random mutate probability
remove_mutate_p = 0.5 # remove the 'worst' route probability, opposite of it is direct restart probability
inter_change_p = 0.8 # interchange probability, opposite of it is random reverse probability
combine_try_time = 10 # chromo try combination mutate times per step
insert_try_time = 10 # chromo try insert mutate times per step
remove_try_p = 0.7 # temporary not use
restart_p = 0.01 # restart probability (when even introduce more distance cost)
starve_para = 0.25
feasible_generate_p = 0.2
# when random init chromo, 'feasible_generate_p' of total generate number will generate by 'feasible generate' algorithm
# warning, feasible generate' algorithm is really time-consuming, don't set this probability too large
perturb_generate_p = 0.2
# when random init chromo, it is the probability the node swap with the next node in the sorted node sequence
center_id = 0 # center depot idx, may not changeable (so don't change this one!)
custom_number = 1000 # custom number, may not changeable (so don't change this one!)
station_number = 100 # station number, may not changeable (so don't change this one!)
max_volume = 16 # max volume of cargo that vehicle can take
max_weight = 2.5 # max weight of cargo that vehicle can take
unload_time = 0.5 # cargo unload time
driving_range = 120000 # driving range of vehicle
charge_tm = 0.5 # charging time of vehicle
charge_cost = 50 # charge cost of vehicle
wait_cost = 24 # wait cost of vehicle
depot_wait = 1 # the time that vehicle need to spend when it is back to center depot
depot_open_time = 8. # the open time of center depot
unit_trans_cost = 14. / 1000 # the unit transportation cost
vehicle_cost = 300 # the cost of using a vehicle in one day
| huge = 999999999
cross_p = 0.8
random_mutate_p = 0.1
remove_mutate_p = 0.5
inter_change_p = 0.8
combine_try_time = 10
insert_try_time = 10
remove_try_p = 0.7
restart_p = 0.01
starve_para = 0.25
feasible_generate_p = 0.2
perturb_generate_p = 0.2
center_id = 0
custom_number = 1000
station_number = 100
max_volume = 16
max_weight = 2.5
unload_time = 0.5
driving_range = 120000
charge_tm = 0.5
charge_cost = 50
wait_cost = 24
depot_wait = 1
depot_open_time = 8.0
unit_trans_cost = 14.0 / 1000
vehicle_cost = 300 |
brace = None
db = None
announcement = ""
templateLoader = None
templateEnv = None
datadog = None
datadogConfig = {} | brace = None
db = None
announcement = ''
template_loader = None
template_env = None
datadog = None
datadog_config = {} |
def countWays(n):
a = 1
b = 2
c = 4
d = 0
if (n == 0 or n == 1 or n == 2):
return n
if (n == 3):
return c
for i in range(4, n + 1):
d = c + b + a
a = b
b = c
c = d
return d
n = 4
print(countWays(n))
| def count_ways(n):
a = 1
b = 2
c = 4
d = 0
if n == 0 or n == 1 or n == 2:
return n
if n == 3:
return c
for i in range(4, n + 1):
d = c + b + a
a = b
b = c
c = d
return d
n = 4
print(count_ways(n)) |
class Solution:
def addNegabinary(self, arr1: 'List[int]', arr2: 'List[int]') -> 'List[int]':
n = max(len(arr1), len(arr2))
res = []
for i in range(-1, -n - 1, -1):
r = 0
if len(arr1) + i >= 0:
r += arr1[i]
if len(arr2) + i >= 0:
r += arr2[i]
res.append(r)
i = 0
while i < len(res):
if res[i] == 0:
i += 1
continue
n, r = divmod(res[i], 2)
res[i] = r
if n > 0:
if i + 1 >= len(res):
res.append(0)
if res[i + 1] >= n:
res[i + 1] -= n
n = 0
else:
n -= res[i + 1]
res[i + 1] = n
if i + 2 >= len(res):
res.append(0)
res[i + 2] += n
i += 1
for j in range(len(res) - 1, -1, -1):
if res[j] != 0:
return res[j::-1]
return [0]
def main():
s = Solution()
print(s.addNegabinary([1, 1, 0], [0, 1, 0]))
if __name__ == "__main__":
main()
| class Solution:
def add_negabinary(self, arr1: 'List[int]', arr2: 'List[int]') -> 'List[int]':
n = max(len(arr1), len(arr2))
res = []
for i in range(-1, -n - 1, -1):
r = 0
if len(arr1) + i >= 0:
r += arr1[i]
if len(arr2) + i >= 0:
r += arr2[i]
res.append(r)
i = 0
while i < len(res):
if res[i] == 0:
i += 1
continue
(n, r) = divmod(res[i], 2)
res[i] = r
if n > 0:
if i + 1 >= len(res):
res.append(0)
if res[i + 1] >= n:
res[i + 1] -= n
n = 0
else:
n -= res[i + 1]
res[i + 1] = n
if i + 2 >= len(res):
res.append(0)
res[i + 2] += n
i += 1
for j in range(len(res) - 1, -1, -1):
if res[j] != 0:
return res[j::-1]
return [0]
def main():
s = solution()
print(s.addNegabinary([1, 1, 0], [0, 1, 0]))
if __name__ == '__main__':
main() |
def logCommand(Command, Author, Date):
Message = f"[{str(Date)}] {Author}: {Command}\n"
with open('data/logs/commands.easy', 'a') as logFile:
logFile.write(Message)
logFile.close()
| def log_command(Command, Author, Date):
message = f'[{str(Date)}] {Author}: {Command}\n'
with open('data/logs/commands.easy', 'a') as log_file:
logFile.write(Message)
logFile.close() |
# https://atcoder.jp/contests/abc192/tasks/abc192_c
N, K = map(int, input().split())
ans = N
for _ in range(K):
str_N = str(ans)
g1 = int("".join(sorted(str_N, reverse=True)))
g2 = int("".join(sorted(str_N)))
ans = g1 - g2
print(ans)
| (n, k) = map(int, input().split())
ans = N
for _ in range(K):
str_n = str(ans)
g1 = int(''.join(sorted(str_N, reverse=True)))
g2 = int(''.join(sorted(str_N)))
ans = g1 - g2
print(ans) |
# https://atcoder.jp/contests/abc002/tasks/abc002_3
ax, ay, bx, by, cx, cy = map(int, input().split())
ans = (ax * by + ay * cx + bx * cy - ay * bx - ax * cy - by * cx) * 0.5
print(abs(ans))
# ax ay 1 ax ay
# bx by 1 bx by
# cx cy 1 cx cy
# ax * by + ay * cx + bx * cy - ay * bx - ax * cy - by * cx
| (ax, ay, bx, by, cx, cy) = map(int, input().split())
ans = (ax * by + ay * cx + bx * cy - ay * bx - ax * cy - by * cx) * 0.5
print(abs(ans)) |
# separate file for keeping global constants
# right now need for LOGDIR_ROOT because this value is used in backend.py
# but is defined in backend.py descendants
LOGDIR_ROOT = None
| logdir_root = None |
'''
You can verify if a specified item
is exists in a tuple using in keyword:
'''
test=[]
n=int(input('Enter size of tuple: '))
for i in range(n):
data=input(f'Elements of tuple are: ')
test.append(data)
test=tuple(test)
print(f'Elements of the tuple are: {test}')
if "israel" in test:
print('yes')
else:
print('False') | """
You can verify if a specified item
is exists in a tuple using in keyword:
"""
test = []
n = int(input('Enter size of tuple: '))
for i in range(n):
data = input(f'Elements of tuple are: ')
test.append(data)
test = tuple(test)
print(f'Elements of the tuple are: {test}')
if 'israel' in test:
print('yes')
else:
print('False') |
#Q
row=0
while row<8:
col =0
while col<8:
if (col==1 and row==0)or (col==2 and row==0)or (col==3 and row==0)or (col==4 and row==1)or (col==4 and row==2)or (col==4 and row==3)or (col==5 and row==5)or (col==6 and row==6)or (col==1 and row==4)or (col==2 and row==4)or (col==3 and row==4)or (col==4 and row==4)or (col==0 and row==1)or (col==0 and row==2)or (col==0 and row==3)or (col==3 and row==3)or (col==2 and row==2):
print("*",end=" ")
else:
print(" ",end=" ")
col +=1
row +=1
print()
| row = 0
while row < 8:
col = 0
while col < 8:
if col == 1 and row == 0 or (col == 2 and row == 0) or (col == 3 and row == 0) or (col == 4 and row == 1) or (col == 4 and row == 2) or (col == 4 and row == 3) or (col == 5 and row == 5) or (col == 6 and row == 6) or (col == 1 and row == 4) or (col == 2 and row == 4) or (col == 3 and row == 4) or (col == 4 and row == 4) or (col == 0 and row == 1) or (col == 0 and row == 2) or (col == 0 and row == 3) or (col == 3 and row == 3) or (col == 2 and row == 2):
print('*', end=' ')
else:
print(' ', end=' ')
col += 1
row += 1
print() |
# User defined functions
# Example 1
def function_name():
print("my first user-defined function!")
function_name()
function_name()
function_name()
function_name()
# Example 2
def welcome_msg():
print("Welcome to Python 101")
welcome_msg()
# Example 3
def welcome_msg(name):
print(f"Welcome to Python 101, {name}")
welcome_msg("Casey")
welcome_msg("Rico")
welcome_msg("Mia")
welcome_msg("Marilyn")
welcome_msg("Jenny")
# DRY - Don't Repeat Yourself
# Example 4
def welcome_msg(title, name):
print(f"Welcome to {title}, {name}")
welcome_msg("Python 101", "Casey")
# Example 5
def welcome_msg(title, name, isbn='NoISBN'):
print(f"Welcome to {title}, {name}. The ISBN for the book is: {isbn}")
welcome_msg("Python 101", "Rico", isbn="1234567")
welcome_msg("Python 101", "Mia")
welcome_msg("Python 101", "Jenny")
| def function_name():
print('my first user-defined function!')
function_name()
function_name()
function_name()
function_name()
def welcome_msg():
print('Welcome to Python 101')
welcome_msg()
def welcome_msg(name):
print(f'Welcome to Python 101, {name}')
welcome_msg('Casey')
welcome_msg('Rico')
welcome_msg('Mia')
welcome_msg('Marilyn')
welcome_msg('Jenny')
def welcome_msg(title, name):
print(f'Welcome to {title}, {name}')
welcome_msg('Python 101', 'Casey')
def welcome_msg(title, name, isbn='NoISBN'):
print(f'Welcome to {title}, {name}. The ISBN for the book is: {isbn}')
welcome_msg('Python 101', 'Rico', isbn='1234567')
welcome_msg('Python 101', 'Mia')
welcome_msg('Python 101', 'Jenny') |
q=int(input("Enter large prime integer(q):"))
a=int(input("Enter primitive root(a):"))
xa=int(input("Enter Xa:"))
ya=(a**xa)%q
k=int(input("Enter the value of k:"))
m=int(input("Enter Message:"))
print("Public key (Ya):",ya)
S1=(a**k)%q
print("S1:",S1)
i=1
while True:
x=(k*i)%(q-1)
if x==1:
break
else:
i=i+1
S2=i*(m-(xa*S1))%(q-1)
print("S2:",S2)
print("Signature(S1,S2):(",S1,",",S2,")")
V1=(a**m)%q
V2=((ya**S1)*(S1**S2))%q
print("V1:",V1)
print("V2:",V2)
print("\t*** Verifivation ***")
if V1==V2:
print("Signature is valid")
else:
print("Signature is not valid!!!") | q = int(input('Enter large prime integer(q):'))
a = int(input('Enter primitive root(a):'))
xa = int(input('Enter Xa:'))
ya = a ** xa % q
k = int(input('Enter the value of k:'))
m = int(input('Enter Message:'))
print('Public key (Ya):', ya)
s1 = a ** k % q
print('S1:', S1)
i = 1
while True:
x = k * i % (q - 1)
if x == 1:
break
else:
i = i + 1
s2 = i * (m - xa * S1) % (q - 1)
print('S2:', S2)
print('Signature(S1,S2):(', S1, ',', S2, ')')
v1 = a ** m % q
v2 = ya ** S1 * S1 ** S2 % q
print('V1:', V1)
print('V2:', V2)
print('\t*** Verifivation ***')
if V1 == V2:
print('Signature is valid')
else:
print('Signature is not valid!!!') |
s = "I'm a string."
print(type(s))
yes = True #Bool true
print(type(yes))
no = False #Bool false
print(type(no))
#List - ordered and changeable
alpha_list = ["a", "b", "c"] #list init
print(type(alpha_list)) #tuple
print(type(alpha_list[0])) #string
alpha_list.append("d") #will add "d" to list
print(alpha_list) #print list
#Tuple - ordered and unchangeable
alpha_tuple = ("a", "b", "c") #tuple init
print(type(alpha_tuple)) #tuple
try: #attempt the following
alpha_tuple[2] = "d" #wont work
except TypeError: #type error
print("We can't add elements to tuples!") #print this in that case
print(alpha_tuple) #print tuple
| s = "I'm a string."
print(type(s))
yes = True
print(type(yes))
no = False
print(type(no))
alpha_list = ['a', 'b', 'c']
print(type(alpha_list))
print(type(alpha_list[0]))
alpha_list.append('d')
print(alpha_list)
alpha_tuple = ('a', 'b', 'c')
print(type(alpha_tuple))
try:
alpha_tuple[2] = 'd'
except TypeError:
print("We can't add elements to tuples!")
print(alpha_tuple) |
class Grid:
def __init__(self, row, col, gsize):
self.row = row
self.col = col
self.gsize = gsize
self.walls = {} # top, left, bottom, right
def connections(self):
my_list = []
for key, val in self.walls.items():
if val != None:
my_list.append(key)
return (my_list)
class Maze:
def __init__ (self, nrows, ncols, gsize):
self.num_rows = nrows
self.num_cols = ncols
self.grid_size = gsize
self.grid = [[Grid(i, j, self.grid_size) for j in range(self.num_cols)] \
for i in range(self.num_rows)]
def connect_grid_default(self):
for grid in self.iter_grid(): # iter_grid ist ein generator
grid.walls["top"] = self.get_grid(grid.row - 1, grid.col)
grid.walls["left"] = self.get_grid(grid.row, grid.col + 1)
grid.walls["bottom"] = self.get_grid(grid.row + 1, grid.col)
grid.walls["right"] = self.get_grid(grid.row, grid.col - 1)
def get_grid(self, row, col):
if row >= 0 and row < self.num_rows and col >= 0 and col < self.num_cols:
return self.grid[row][col]
else:
return None
def iter_grid(self):
for i in range(self.num_rows):
for j in range(self.num_cols):
yield self.grid[i][j]
def print_me(self):
for grid in self.iter_grid():
print(grid.row, grid.col, grid.connections())
| class Grid:
def __init__(self, row, col, gsize):
self.row = row
self.col = col
self.gsize = gsize
self.walls = {}
def connections(self):
my_list = []
for (key, val) in self.walls.items():
if val != None:
my_list.append(key)
return my_list
class Maze:
def __init__(self, nrows, ncols, gsize):
self.num_rows = nrows
self.num_cols = ncols
self.grid_size = gsize
self.grid = [[grid(i, j, self.grid_size) for j in range(self.num_cols)] for i in range(self.num_rows)]
def connect_grid_default(self):
for grid in self.iter_grid():
grid.walls['top'] = self.get_grid(grid.row - 1, grid.col)
grid.walls['left'] = self.get_grid(grid.row, grid.col + 1)
grid.walls['bottom'] = self.get_grid(grid.row + 1, grid.col)
grid.walls['right'] = self.get_grid(grid.row, grid.col - 1)
def get_grid(self, row, col):
if row >= 0 and row < self.num_rows and (col >= 0) and (col < self.num_cols):
return self.grid[row][col]
else:
return None
def iter_grid(self):
for i in range(self.num_rows):
for j in range(self.num_cols):
yield self.grid[i][j]
def print_me(self):
for grid in self.iter_grid():
print(grid.row, grid.col, grid.connections()) |
# https://www.hackerrank.com/challenges/python-loops/problem
n = int(input())
# 5
for i in range(n):
print(i ** 2)
# 0
# 1
# 4
# 9
# 16 | n = int(input())
for i in range(n):
print(i ** 2) |
TRANSACTIONALSET_ADD = 0x1201
TRANSACTIONALSET_REMOVE = 0x1202
TRANSACTIONALSET_SIZE = 0x1203
| transactionalset_add = 4609
transactionalset_remove = 4610
transactionalset_size = 4611 |
'''https://leetcode.com/problems/climbing-stairs/
70. Climbing Stairs
Easy
8813
261
Add to List
Share
You are climbing a staircase. It takes n steps to reach the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
Example 1:
Input: n = 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps
Example 2:
Input: n = 3
Output: 3
Explanation: There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step
Constraints:
1 <= n <= 45'''
# for given n steps stairs
# Each time you can either climb 1 or 2 steps.
# In how many distinct ways can you climb to the top?
def brute_force(n):
if n == 1 or n == 2:
return n
return brute_force(n-1)+brute_force(n-2)
memo = {}
def recursion_memo(n, memo):
if n == 1 or n == 2:
return n
if n in memo.keys():
return memo[n]
value = recursion_memo(n-1, memo) + recursion_memo(n-2, memo)
memo.update({n: value})
return memo[n]
def dynamic(n):
if n == 1 or n == 2:
return n
result = [0]*(n)
result[0] = 1
result[1] = 2
for i in range(2, n):
result[i] = result[i-1]+result[i-2]
return result[n-1]
if __name__ == '__main__':
print(recursion_memo(10, memo))
| """https://leetcode.com/problems/climbing-stairs/
70. Climbing Stairs
Easy
8813
261
Add to List
Share
You are climbing a staircase. It takes n steps to reach the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
Example 1:
Input: n = 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps
Example 2:
Input: n = 3
Output: 3
Explanation: There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step
Constraints:
1 <= n <= 45"""
def brute_force(n):
if n == 1 or n == 2:
return n
return brute_force(n - 1) + brute_force(n - 2)
memo = {}
def recursion_memo(n, memo):
if n == 1 or n == 2:
return n
if n in memo.keys():
return memo[n]
value = recursion_memo(n - 1, memo) + recursion_memo(n - 2, memo)
memo.update({n: value})
return memo[n]
def dynamic(n):
if n == 1 or n == 2:
return n
result = [0] * n
result[0] = 1
result[1] = 2
for i in range(2, n):
result[i] = result[i - 1] + result[i - 2]
return result[n - 1]
if __name__ == '__main__':
print(recursion_memo(10, memo)) |
# Lec 2.6, slide 2
x = int(raw_input('Enter an integer: '))
if x%2 == 0:
print('Even')
else:
print('Odd') | x = int(raw_input('Enter an integer: '))
if x % 2 == 0:
print('Even')
else:
print('Odd') |
board = [
[7,8,0,4,0,0,1,2,0],
[6,0,0,0,7,5,0,0,9],
[0,0,0,6,0,1,0,7,8],
[0,0,7,0,4,0,2,6,0],
[0,0,1,0,5,0,9,3,0],
[9,0,4,0,6,0,0,0,5],
[0,7,0,3,0,0,0,1,2],
[1,2,0,0,0,7,4,0,0],
[0,4,9,2,0,6,0,0,7]
]
def print_board(board):
for i in range(len(board)):
if i % 3 == 0:
print("-------------------------")
for j in range(len(board[0])):
if j % 3 == 0:
print("|", end=" ")
if j == 8:
print(board[i][j],end=" |")
print("")
else:
print(str(board[i][j]) + " ", end="")
print("-------------------------")
def sovle_board(board):
find = find_empty(board)
if not find:
return True
for i in range(1,10):
if valid_number(board,i,find):
board[find[0]][find[1]] = i
if sovle_board(board):
return True
board[find[0]][find[1]] = 0
return False
#board = board state
#num = the vaild number
#pos = (position x, position y)
def valid_number(board, num, pos):
#valid row wise
for i in range(9):
if board[pos[0]][i] == num and pos[1] != i:
return False
#valid colum wise
for i in range(9):
if board[i][pos[1]] == num and pos[0] != i:
return False
#valid 3x3 wise
box_x = pos[1]//3
box_y = pos[0]//3
for i in range(box_y*3, box_y*3 + 3):
for j in range(box_x*3, box_x*3 + 3):
if board[i][j] == num and [i,j] != pos:
return False
return True
def find_empty(board):
for i in range(len(board)):
for j in range(len(board[0])):
if board[i][j] == 0:
return [i, j]
return None
print("init board:")
print_board(board)
sovle_board(board)
print("Solved:")
print_board(board) | board = [[7, 8, 0, 4, 0, 0, 1, 2, 0], [6, 0, 0, 0, 7, 5, 0, 0, 9], [0, 0, 0, 6, 0, 1, 0, 7, 8], [0, 0, 7, 0, 4, 0, 2, 6, 0], [0, 0, 1, 0, 5, 0, 9, 3, 0], [9, 0, 4, 0, 6, 0, 0, 0, 5], [0, 7, 0, 3, 0, 0, 0, 1, 2], [1, 2, 0, 0, 0, 7, 4, 0, 0], [0, 4, 9, 2, 0, 6, 0, 0, 7]]
def print_board(board):
for i in range(len(board)):
if i % 3 == 0:
print('-------------------------')
for j in range(len(board[0])):
if j % 3 == 0:
print('|', end=' ')
if j == 8:
print(board[i][j], end=' |')
print('')
else:
print(str(board[i][j]) + ' ', end='')
print('-------------------------')
def sovle_board(board):
find = find_empty(board)
if not find:
return True
for i in range(1, 10):
if valid_number(board, i, find):
board[find[0]][find[1]] = i
if sovle_board(board):
return True
board[find[0]][find[1]] = 0
return False
def valid_number(board, num, pos):
for i in range(9):
if board[pos[0]][i] == num and pos[1] != i:
return False
for i in range(9):
if board[i][pos[1]] == num and pos[0] != i:
return False
box_x = pos[1] // 3
box_y = pos[0] // 3
for i in range(box_y * 3, box_y * 3 + 3):
for j in range(box_x * 3, box_x * 3 + 3):
if board[i][j] == num and [i, j] != pos:
return False
return True
def find_empty(board):
for i in range(len(board)):
for j in range(len(board[0])):
if board[i][j] == 0:
return [i, j]
return None
print('init board:')
print_board(board)
sovle_board(board)
print('Solved:')
print_board(board) |
II = lambda : int(input())
a1 = II()
a2 = II()
k1 = II()
k2 = II()
n = II()
if(k1>k2):
k1,k2 = k2,k1
a1,a2 = a2,a1
auxM = min(a1,n//k1)
restM = n-auxM*k1
M = auxM+min(a2,restM//k2)
if((k1-1)*a1+(k2-1)*a2>=n):
m = 0
else:
m = n-((k1-1)*a1+(k2-1)*a2)
print(m,M)
| ii = lambda : int(input())
a1 = ii()
a2 = ii()
k1 = ii()
k2 = ii()
n = ii()
if k1 > k2:
(k1, k2) = (k2, k1)
(a1, a2) = (a2, a1)
aux_m = min(a1, n // k1)
rest_m = n - auxM * k1
m = auxM + min(a2, restM // k2)
if (k1 - 1) * a1 + (k2 - 1) * a2 >= n:
m = 0
else:
m = n - ((k1 - 1) * a1 + (k2 - 1) * a2)
print(m, M) |
def buttons(ceiling):
connections = ((1, 0), (0, 1), (0, -1), (-1, 0))
g = [[int(c) for c in line] for line in ceiling.strip().splitlines()]
sizex, sizey = len(g), len(g[0])
visited = set()
def is_new(x, y):
return (x, y) not in visited and 0 <= x < sizex and 0 <= y < sizey and g[x][y] != 0
def sum_connected(x, y):
nonlocal visited
active = [(x, y)]
visited.add((x, y))
s = 0
while active:
x, y = active.pop()
s += g[x][y]
neighbors = {(x + dx, y + dy) for dx, dy in connections if is_new(x + dx, y + dy)}
active += neighbors
visited |= neighbors
return s
buttons = (sum_connected(x, y) for x in range(sizex) for y in range(sizey) if is_new(x, y))
return sorted(buttons, reverse=True) | def buttons(ceiling):
connections = ((1, 0), (0, 1), (0, -1), (-1, 0))
g = [[int(c) for c in line] for line in ceiling.strip().splitlines()]
(sizex, sizey) = (len(g), len(g[0]))
visited = set()
def is_new(x, y):
return (x, y) not in visited and 0 <= x < sizex and (0 <= y < sizey) and (g[x][y] != 0)
def sum_connected(x, y):
nonlocal visited
active = [(x, y)]
visited.add((x, y))
s = 0
while active:
(x, y) = active.pop()
s += g[x][y]
neighbors = {(x + dx, y + dy) for (dx, dy) in connections if is_new(x + dx, y + dy)}
active += neighbors
visited |= neighbors
return s
buttons = (sum_connected(x, y) for x in range(sizex) for y in range(sizey) if is_new(x, y))
return sorted(buttons, reverse=True) |
pkgname = "python-setuptools"
version = "57.0.0"
revision = 0
build_style = "python_module"
hostmakedepends = ["python-devel"]
depends = ["python"]
short_desc = "Easily build and distribute Python packages"
maintainer = "q66 <q66@chimera-linux.org>"
license = "MIT"
homepage = "https://github.com/pypa/setuptools"
distfiles = [f"$(PYPI_SITE)/s/setuptools/setuptools-{version}.tar.gz"]
checksum = ["401cbf33a7bf817d08014d51560fc003b895c4cdc1a5b521ad2969e928a07535"]
options = ["!check"]
env = {
"SETUPTOOLS_INSTALL_WINDOWS_SPECIFIC_FILES": "0",
"SETUPTOOLS_DISABLE_VERSIONED_EASY_INSTALL_SCRIPT": "1"
}
def post_install(self):
self.install_license("LICENSE")
| pkgname = 'python-setuptools'
version = '57.0.0'
revision = 0
build_style = 'python_module'
hostmakedepends = ['python-devel']
depends = ['python']
short_desc = 'Easily build and distribute Python packages'
maintainer = 'q66 <q66@chimera-linux.org>'
license = 'MIT'
homepage = 'https://github.com/pypa/setuptools'
distfiles = [f'$(PYPI_SITE)/s/setuptools/setuptools-{version}.tar.gz']
checksum = ['401cbf33a7bf817d08014d51560fc003b895c4cdc1a5b521ad2969e928a07535']
options = ['!check']
env = {'SETUPTOOLS_INSTALL_WINDOWS_SPECIFIC_FILES': '0', 'SETUPTOOLS_DISABLE_VERSIONED_EASY_INSTALL_SCRIPT': '1'}
def post_install(self):
self.install_license('LICENSE') |
def main():
count = 0
sum_ = 0
while True:
try:
number = float(input(f"Number {count+1}: "))
count += 1
sum_ += number
except ValueError:
if not count:
count = 1
break
print(sum_)
print(sum_ / count)
if __name__ == '__main__':
main()
| def main():
count = 0
sum_ = 0
while True:
try:
number = float(input(f'Number {count + 1}: '))
count += 1
sum_ += number
except ValueError:
if not count:
count = 1
break
print(sum_)
print(sum_ / count)
if __name__ == '__main__':
main() |
# Released under the MIT License. See LICENSE for details.
#
# This file was automatically generated from "happy_thoughts.ma"
# pylint: disable=all
points = {}
# noinspection PyDictCreation
boxes = {}
boxes['area_of_interest_bounds'] = (-1.045859963, 12.67722855,
-5.401537075) + (0.0, 0.0, 0.0) + (
34.46156851, 20.94044653, 0.6931564611)
points['ffa_spawn1'] = (-9.295167711, 8.010664315,
-5.44451005) + (1.555840357, 1.453808816, 0.1165648888)
points['ffa_spawn2'] = (7.484707127, 8.172681752, -5.614479365) + (
1.553861796, 1.453808816, 0.04419853907)
points['ffa_spawn3'] = (9.55724115, 11.30789446, -5.614479365) + (
1.337925849, 1.453808816, 0.04419853907)
points['ffa_spawn4'] = (-11.55747023, 10.99170684, -5.614479365) + (
1.337925849, 1.453808816, 0.04419853907)
points['ffa_spawn5'] = (-1.878892369, 9.46490571, -5.614479365) + (
1.337925849, 1.453808816, 0.04419853907)
points['ffa_spawn6'] = (-0.4912812943, 5.077006397, -5.521672101) + (
1.878332089, 1.453808816, 0.007578097856)
points['flag1'] = (-11.75152479, 8.057427485, -5.52)
points['flag2'] = (9.840909039, 8.188634282, -5.52)
points['flag3'] = (-0.2195258696, 5.010273907, -5.52)
points['flag4'] = (-0.04605809154, 12.73369108, -5.52)
points['flag_default'] = (-0.04201942896, 12.72374492, -5.52)
boxes['map_bounds'] = (-0.8748348681, 9.212941713, -5.729538885) + (
0.0, 0.0, 0.0) + (36.09666006, 26.19950145, 7.89541168)
points['powerup_spawn1'] = (1.160232442, 6.745963662, -5.469115985)
points['powerup_spawn2'] = (-1.899700206, 10.56447241, -5.505721177)
points['powerup_spawn3'] = (10.56098871, 12.25165669, -5.576232453)
points['powerup_spawn4'] = (-12.33530337, 12.25165669, -5.576232453)
points['spawn1'] = (-9.295167711, 8.010664315,
-5.44451005) + (1.555840357, 1.453808816, 0.1165648888)
points['spawn2'] = (7.484707127, 8.172681752,
-5.614479365) + (1.553861796, 1.453808816, 0.04419853907)
points['spawn_by_flag1'] = (-9.295167711, 8.010664315, -5.44451005) + (
1.555840357, 1.453808816, 0.1165648888)
points['spawn_by_flag2'] = (7.484707127, 8.172681752, -5.614479365) + (
1.553861796, 1.453808816, 0.04419853907)
points['spawn_by_flag3'] = (-1.45994593, 5.038762459, -5.535288724) + (
0.9516389866, 0.6666414677, 0.08607244075)
points['spawn_by_flag4'] = (0.4932087091, 12.74493212, -5.598987003) + (
0.5245740665, 0.5245740665, 0.01941146064)
| points = {}
boxes = {}
boxes['area_of_interest_bounds'] = (-1.045859963, 12.67722855, -5.401537075) + (0.0, 0.0, 0.0) + (34.46156851, 20.94044653, 0.6931564611)
points['ffa_spawn1'] = (-9.295167711, 8.010664315, -5.44451005) + (1.555840357, 1.453808816, 0.1165648888)
points['ffa_spawn2'] = (7.484707127, 8.172681752, -5.614479365) + (1.553861796, 1.453808816, 0.04419853907)
points['ffa_spawn3'] = (9.55724115, 11.30789446, -5.614479365) + (1.337925849, 1.453808816, 0.04419853907)
points['ffa_spawn4'] = (-11.55747023, 10.99170684, -5.614479365) + (1.337925849, 1.453808816, 0.04419853907)
points['ffa_spawn5'] = (-1.878892369, 9.46490571, -5.614479365) + (1.337925849, 1.453808816, 0.04419853907)
points['ffa_spawn6'] = (-0.4912812943, 5.077006397, -5.521672101) + (1.878332089, 1.453808816, 0.007578097856)
points['flag1'] = (-11.75152479, 8.057427485, -5.52)
points['flag2'] = (9.840909039, 8.188634282, -5.52)
points['flag3'] = (-0.2195258696, 5.010273907, -5.52)
points['flag4'] = (-0.04605809154, 12.73369108, -5.52)
points['flag_default'] = (-0.04201942896, 12.72374492, -5.52)
boxes['map_bounds'] = (-0.8748348681, 9.212941713, -5.729538885) + (0.0, 0.0, 0.0) + (36.09666006, 26.19950145, 7.89541168)
points['powerup_spawn1'] = (1.160232442, 6.745963662, -5.469115985)
points['powerup_spawn2'] = (-1.899700206, 10.56447241, -5.505721177)
points['powerup_spawn3'] = (10.56098871, 12.25165669, -5.576232453)
points['powerup_spawn4'] = (-12.33530337, 12.25165669, -5.576232453)
points['spawn1'] = (-9.295167711, 8.010664315, -5.44451005) + (1.555840357, 1.453808816, 0.1165648888)
points['spawn2'] = (7.484707127, 8.172681752, -5.614479365) + (1.553861796, 1.453808816, 0.04419853907)
points['spawn_by_flag1'] = (-9.295167711, 8.010664315, -5.44451005) + (1.555840357, 1.453808816, 0.1165648888)
points['spawn_by_flag2'] = (7.484707127, 8.172681752, -5.614479365) + (1.553861796, 1.453808816, 0.04419853907)
points['spawn_by_flag3'] = (-1.45994593, 5.038762459, -5.535288724) + (0.9516389866, 0.6666414677, 0.08607244075)
points['spawn_by_flag4'] = (0.4932087091, 12.74493212, -5.598987003) + (0.5245740665, 0.5245740665, 0.01941146064) |
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
def __str__(self):
current = self
ret = ''
while current:
ret += str(current.value)
current = current.next
return ret
# Time: O(n)
# Space: O(1)
def rotate_list(list, k):
length = 0
current = list
while current:
length += 1
current = current.next
k = k % length
fast, slow = list, list
for _ in range(k):
fast = fast.next
while fast.next is not None:
fast = fast.next
slow = slow.next
fast.next = list
head = slow.next
slow .next = None
return head
# order is 1, 2 ,3 ,4
llist = Node(1, Node(2, Node(3, Node(4))))
# order should now be 3, 4, 1, 2
print(rotate_list(llist, 2)) | class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
def __str__(self):
current = self
ret = ''
while current:
ret += str(current.value)
current = current.next
return ret
def rotate_list(list, k):
length = 0
current = list
while current:
length += 1
current = current.next
k = k % length
(fast, slow) = (list, list)
for _ in range(k):
fast = fast.next
while fast.next is not None:
fast = fast.next
slow = slow.next
fast.next = list
head = slow.next
slow.next = None
return head
llist = node(1, node(2, node(3, node(4))))
print(rotate_list(llist, 2)) |
class ColorConstants(object):
#QLineEdit colours
QLE_GREEN = '#c4df9b' # green
QLE_YELLOW = '#fff79a' # yellow
QLE_RED = '#f6989d' # red
#see http://cloford.com/resources/colours/500col.htm
| class Colorconstants(object):
qle_green = '#c4df9b'
qle_yellow = '#fff79a'
qle_red = '#f6989d' |
#bmi calculator
print("YOU ARE WELCOME TO BMI CALCULATOR BUILT BY IDRIS")
print("")
print(" PLEASE KINDLY ENTER YOUR VALUE IN KG FOR WEIGHT AND IN METERS FOR HEIGHT ")
print("")
w=float(input("please enter the value for weight in KG = "))
print("")
h=float(input("please enter the value for height in METERS = "))
bmi=w/(h*h)
answer=round(bmi,1)
print("")
if (answer<18.5):
print("UNDERWEIGHT")
elif ((answer>=18.5) and (answer<=25)):
print("NORMAL")
elif ((answer>=25)and(answer<=30)):
print("OVERWEIGHT")
elif (answer>30):
print("obese")
else:
print("RE-TRY")
| print('YOU ARE WELCOME TO BMI CALCULATOR BUILT BY IDRIS')
print('')
print(' PLEASE KINDLY ENTER YOUR VALUE IN KG FOR WEIGHT AND IN METERS FOR HEIGHT ')
print('')
w = float(input('please enter the value for weight in KG = '))
print('')
h = float(input('please enter the value for height in METERS = '))
bmi = w / (h * h)
answer = round(bmi, 1)
print('')
if answer < 18.5:
print('UNDERWEIGHT')
elif answer >= 18.5 and answer <= 25:
print('NORMAL')
elif answer >= 25 and answer <= 30:
print('OVERWEIGHT')
elif answer > 30:
print('obese')
else:
print('RE-TRY') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.