content stringlengths 7 1.05M |
|---|
"""
Objective
Today we will expand our knowledge of strings, combining it with what we have already learned about loops. Check out the Tutorial tab for learning materials and an instructional video.
Task
Given a string, , of length that is indexed from to , print its even-indexed and odd-indexed characters as space-separated strings on a single line (see the Sample below for more detail).
Note: is considered to be an even index.
Example
Print abc def
Input Format
The first line contains an integer, (the number of test cases).
Each line of the subsequent lines contain a string, .
Constraints
Output Format
For each String (where ), print 's even-indexed characters, followed by a space, followed by 's odd-indexed characters.
Sample Input
2
Hacker
Rank
Sample Output
Hce akr
Rn ak
"""
T=int(input())
i=0
if(T>=1 and T<=10):
for i in range (0,T):
s=str(input())
print(s[0::2], s[1::2])
|
# 打印输出从文件读取的所有行的字符串(遍历的对象是文件对象)
f = open('hello.txt') # 打开(文本+读取模式)
for line in f:
print(line, end='')
f.close() # 关闭
|
# The sum of the squares of the first ten natural numbers is,
#
# 12 + 22 + ... + 102 = 385
# The square of the sum of the first ten natural numbers is,
#
# (1 + 2 + ... + 10)2 = 552 = 3025
# Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640.
#
# Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
#
# Answer: 25164150
def run():
print(square_of_sums(100) - sum_of_squares(100))
def sum_of_squares(num):
sum = 0
for idx in range(1, num + 1):
sum += idx ** 2
return sum
def square_of_sums(num):
sum = 0
for idx in range(1, num + 1):
sum += idx
return sum ** 2
|
#!/usr/bin/python
""" use in format: "{RED_FG}{0}{RESET}".format(variable, **printformats.print_formats)
from https://stackoverflow.com/questions/287871/print-in-terminal-with-colors
"""
formatting = {
'RESET' : '\033[0m',
'END' : '\033[0m',
'BOLD' : '\033[01m',
'UNDERLINE' : '\033[04m',
'REVERSE' : '\033[07m',
'STRIKETHROUGH' : '\033[09m',
'ITALIC' : '\33[3m',
'LINE' : '=',
'BLANK' : ' ',
'SPACER' : ' ',
'DEFAULT' : '',
'MARK' : 'X',
'BLACK_FG' : '\033[30m',
'RED_FG' : '\033[31m',
'GREEN_FG' : '\033[32m',
'ORANGE_FG' : '\033[33m',
'BLUE_FG' : '\033[34m',
'PURPLE_FG' : '\033[35m',
'CYAN_FG' : '\033[36m',
'LIGHTGREY_FG' : '\033[37m',
'DARKGREY_FG' : '\033[90m',
'LIGHTRED_FG' : '\033[91m',
'LIGHTGREEN_FG' : '\033[92m',
'YELLOW_FG' : '\033[93m',
'LIGHTBLUE_FG' : '\033[94m',
'PINK_FG' : '\033[95m',
'LIGHTCYAN_FG' : '\033[96m',
'BLACK_BG' : '\033[40m',
'RED_BG' : '\033[41m',
'GREEN_BG' : '\033[42m',
'ORANGE_BG' : '\033[43m',
'BLUE_BG' : '\033[44m',
'PURPLE_BG' : '\033[45m',
'CYAN_BG' : '\033[46m',
'LIGHTGREY_BG' : '\033[47m'
} |
#!/usr/bin/python
# -*- coding: utf-8 -*-
OCT_SUCCESS = 0
NOT_ENOUGH_PARAS = 1
TOO_MANY_PARAS = 2
UNACCP_PARAS = 3
XML_ERR = 4
EXEC_CMD_ERR = 5
COMMON_ERR = 6
SEGMENT_NOT_EXIST = 7
SEGMENT_ALREADY_EXIST = 8
FILE_NOT_EXIST = 9
ADDED_TO_TASK = 10
ADDED_TO_SERVER = 11
TIME_OUT = 12
CHECK_ENV_ERR = 13
SEND_MSG_FAILED = 14
INCOMPATIBLE_CONFIG = 17
DROPPED_INTERFACE = 18
UNMATCHED_TEMPLATE_FORMAT = 19
PERMISSION_NOT_ENOUGH = 20
CONFIG_NOT_EXIST = 256
LAZY_PROGRAMMER = 257
NO_CMD = 258
OPE_FORBID = 259
INVALID_CONFIG_FILE = 260
CONFIG_ALREADY_EXIST = 261
SYSCALL_ERR = 262
OCT_SYSTEM_ERR = 263
NO_AUTH_SKEY = 264
WRONG_AUTH_SKEY = 265
WRONG_AUTH_TIMESTAMP = 266
BAD_NSIS_ENV = 267
MAKE_NSIS_ERR = 268
USER_INVALID_NAME = 518
DB_ERR = 519
USER_PASSWD_ERR = 520
USER_NOT_EXIST = 521
USER_ALREADY_EXIST = 522
err_desc_ch = {
OCT_SUCCESS: "执行成功",
NOT_ENOUGH_PARAS: "参数不够",
TOO_MANY_PARAS: "参数太多",
UNACCP_PARAS: "参数错误",
XML_ERR: "XML解析错误",
EXEC_CMD_ERR: "命令执行错误",
COMMON_ERR: "通用错误",
SEGMENT_NOT_EXIST: "字段不存在",
SEGMENT_ALREADY_EXIST: "字段已经存在",
FILE_NOT_EXIST: "文件不存在",
ADDED_TO_TASK: "已添加到任务队列中",
ADDED_TO_SERVER: "服务器端运行中",
TIME_OUT: "等待超时",
CHECK_ENV_ERR: "环境检测失败",
SEND_MSG_FAILED: "发送消息失败",
INCOMPATIBLE_CONFIG: "不兼容的配置",
DROPPED_INTERFACE: "该接口已废弃",
UNMATCHED_TEMPLATE_FORMAT: "模板格式不匹配",
PERMISSION_NOT_ENOUGH: "权限不足",
CONFIG_NOT_EXIST: "配置文件不存在",
LAZY_PROGRAMMER: "此功能未实现",
NO_CMD: "没有此命令",
OPE_FORBID: "禁止此操作",
INVALID_CONFIG_FILE: "配置文件不合法",
CONFIG_ALREADY_EXIST: "配置文件已经存在",
SYSCALL_ERR: "系统调用错误",
OCT_SYSTEM_ERR: "系统错误",
NO_AUTH_SKEY: "没有URL认证密码",
WRONG_AUTH_SKEY: "错误的URL认证密码",
WRONG_AUTH_TIMESTAMP: "错误的URL认证时间戳,请同步你的客户机时间",
BAD_NSIS_ENV: "没有安装JRE或者NSIS工具包",
MAKE_NSIS_ERR: "制作NSIS安装包失败",
USER_INVALID_NAME: "用户错误",
DB_ERR: "数据库错误",
USER_PASSWD_ERR: "用户名密码不匹配",
USER_NOT_EXIST: "用户不存在",
USER_ALREADY_EXIST: "用户已存在"
}
err_desc_en = {
OCT_SUCCESS: "Command success",
NOT_ENOUGH_PARAS: "Not enough parameters",
TOO_MANY_PARAS: "Too many parameters",
UNACCP_PARAS: "Invalid parameters",
XML_ERR: "XML Error",
EXEC_CMD_ERR: "Execute Command Error",
COMMON_ERR: "Common error",
SEGMENT_NOT_EXIST: "Segment not exist",
SEGMENT_ALREADY_EXIST: "Segment already exist",
FILE_NOT_EXIST: "File not exist",
ADDED_TO_TASK: "Added to task",
ADDED_TO_SERVER: "Added to server",
TIME_OUT: "Time out",
CHECK_ENV_ERR: "check env err",
SEND_MSG_FAILED: "send msg failed",
INCOMPATIBLE_CONFIG: "incompatible config",
DROPPED_INTERFACE: "dropped interface",
UNMATCHED_TEMPLATE_FORMAT: "unmatched template_format",
PERMISSION_NOT_ENOUGH: "Permissions Not Enough",
CONFIG_NOT_EXIST: "Config file not exist",
LAZY_PROGRAMMER: "Not Complete This Function",
NO_CMD: "No This Commond",
OPE_FORBID: "Forbid this peration",
INVALID_CONFIG_FILE: "Invalid config file",
CONFIG_ALREADY_EXIST: "Config file already exists",
SYSCALL_ERR: "System call error",
OCT_SYSTEM_ERR: "System error",
NO_AUTH_SKEY: "No skey specified",
WRONG_AUTH_SKEY: "Wrong auth skey",
WRONG_AUTH_TIMESTAMP: "Wrong auth timestamp,please sync your system time",
BAD_NSIS_ENV: "no jre or makensis installed",
MAKE_NSIS_ERR: "make nsis package error",
USER_INVALID_NAME: "Invalid user name",
DB_ERR: "Database Error",
USER_PASSWD_ERR: "User and Password not match",
USER_NOT_EXIST: "User Not Exist",
USER_ALREADY_EXIST: "User Already Exist",
}
def print_retmsg(buff):
print('\n%% %s\n' % buff) |
n = int(input('Digite qualquer numero:'))
resultado = n % 2
if resultado == 0:
print('O numero {} e´ PAR'.format(n))
else:
print('O numero {} e´ IMPAR'.format(n))
|
# https://www.hackerrank.com/challenges/30-nested-logic/problem
# Enter your code here. Read input from STDIN. Print output to STDOUT
Da, Ma, Ya = map(int, input().split())
De, Me, Ye = map(int, input().split())
fine = 0
if Ya-Ye<0:
fine = 0
elif Ya-Ye == 0:
if Ma-Me < 0:
fine = 0
elif Ma-Me == 0:
if Da-De<=0:
fine = 0
else:
fine = 15 * (Da-De)
else:
fine = 500 * (Ma - Me)
else:
fine = 10000
print(fine); |
class Piece:
def __init__(self, s):
split = s.replace("\n", "").split(' ')
self.number = int(split[0][1:])
offset = split[2][:-1].split(',')
self._left_offset = int(offset[0])
self._top_offset = int(offset[1])
size = split[3].split('x')
self._width = int(size[0])
self._height = int(size[1])
self.Corners = [
(self.left_offset, self.top_offset),
(self.left_offset + self.width - 1, self.top_offset),
(self.left_offset + self.width - 1, self.top_offset + self.height - 1),
(self.left_offset, self.top_offset + self.height - 1)
]
@property
def top_offset(self):
return self._top_offset
@property
def left_offset(self):
return self._left_offset
@property
def width(self):
return self._width
@property
def height(self):
return self._height
def overlaps(self, piece):
for corner in piece.Corners:
if self.contains(corner):
return True
for corner in self.Corners:
if piece.contains(corner):
return True
if ((self.Corners[0][0] <= piece.Corners[0][0] < self.Corners[1][0]) or
(self.Corners[0][0] <= piece.Corners[1][0] < self.Corners[1][0])) and \
((piece.Corners[0][1] <= self.Corners[0][1] < piece.Corners[3][1]) or
(piece.Corners[0][1] <= self.Corners[3][1] < piece.Corners[3][1])):
return True
if ((piece.Corners[0][0] <= self.Corners[0][0] < piece.Corners[1][0]) or
(piece.Corners[0][0] <= self.Corners[1][0] < piece.Corners[1][0])) and \
((self.Corners[0][1] <= piece.Corners[0][1] < self.Corners[3][1]) or
(self.Corners[0][1] <= piece.Corners[3][1] < self.Corners[3][1])):
return True
return False
def contains(self, point):
return self.left_offset <= point[0] < self.left_offset + self.width and \
self.top_offset <= point[1] < self.top_offset + self.height
|
nums1 = {1, 2, 3, 4, 5}
nums2 = {4, 5, 6, 7, 8, 9}
nums3 = nums2.difference(nums1)
print("nums2 – nums1: ", nums3)
|
dev_packages = [
"karbon",
"librsvg2-bin",
]
|
# -*- coding: utf-8 -*-
"""
pygsheets.exceptions
~~~~~~~~~~~~~~~~~~~~
Exceptions used in pygsheets.
"""
class PyGsheetsException(Exception):
"""A base class for pygsheets's exceptions."""
class AuthenticationError(PyGsheetsException):
"""An error during authentication process."""
class SpreadsheetNotFound(PyGsheetsException):
"""Trying to open non-existent or inaccessible spreadsheet."""
class WorksheetNotFound(PyGsheetsException):
"""Trying to open non-existent or inaccessible worksheet."""
class CellNotFound(PyGsheetsException):
"""Cell lookup exception."""
class RangeNotFound(PyGsheetsException):
"""Range lookup exception."""
class TeamDriveNotFound(PyGsheetsException):
"""TeamDrive Lookup Exception"""
class FolderNotFound(PyGsheetsException):
"""Folder lookup exception."""
class NoValidUrlKeyFound(PyGsheetsException):
"""No valid key found in URL."""
class IncorrectCellLabel(PyGsheetsException):
"""The cell label is incorrect."""
class RequestError(PyGsheetsException):
"""Error while sending API request."""
class InvalidArgumentValue(PyGsheetsException):
"""Invalid value for argument"""
class InvalidUser(PyGsheetsException):
"""Invalid user/domain"""
class CannotRemoveOwnerError(PyGsheetsException):
"""A owner permission cannot be removed if is the last one."""
|
s = input()
c = 0
for _ in range(int(input())):
if s in input() * 2:
c += 1
print(c)
|
# encoding: utf-8
# module System.Windows.Markup calls itself Markup
# from System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
# by generator 1.145
""" NamespaceTracker represent a CLS namespace. """
# no imports
# no functions
# classes
class ValueSerializerAttribute(Attribute, _Attribute):
"""
ValueSerializerAttribute(valueSerializerType: Type)
ValueSerializerAttribute(valueSerializerTypeName: str)
"""
def __init__(self, *args): # cannot find CLR method
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
@staticmethod # known case of __new__
def __new__(self, *__args):
"""
__new__(cls: type, valueSerializerType: Type)
__new__(cls: type, valueSerializerTypeName: str)
"""
pass
ValueSerializerType = property(
lambda self: object(), lambda self, v: None, lambda self: None
) # default
"""Get: ValueSerializerType(self: ValueSerializerAttribute) -> Type
"""
ValueSerializerTypeName = property(
lambda self: object(), lambda self, v: None, lambda self: None
) # default
"""Get: ValueSerializerTypeName(self: ValueSerializerAttribute) -> str
"""
|
#
# PySNMP MIB module NETBOTZ-SNMP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/NETBOTZ-SNMP-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:18:38 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
Integer, ObjectIdentifier, OctetString = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueRangeConstraint, ConstraintsUnion, ValueSizeConstraint, ConstraintsIntersection, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "ConstraintsUnion", "ValueSizeConstraint", "ConstraintsIntersection", "SingleValueConstraint")
netBotz_snmp, = mibBuilder.importSymbols("NETBOTZ-MIB", "netBotz-snmp")
ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup")
IpAddress, iso, NotificationType, ObjectIdentity, TimeTicks, Gauge32, Counter32, Unsigned32, MibScalar, MibTable, MibTableRow, MibTableColumn, ModuleIdentity, Bits, Integer32, MibIdentifier, Counter64 = mibBuilder.importSymbols("SNMPv2-SMI", "IpAddress", "iso", "NotificationType", "ObjectIdentity", "TimeTicks", "Gauge32", "Counter32", "Unsigned32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "ModuleIdentity", "Bits", "Integer32", "MibIdentifier", "Counter64")
TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString")
netBotz_snmp_traptarget = MibScalar((1, 3, 6, 1, 4, 1, 5528, 40, 1), IpAddress()).setLabel("netBotz-snmp-traptarget").setMaxAccess("readwrite")
if mibBuilder.loadTexts: netBotz_snmp_traptarget.setReference('Netbotz Trap Target')
if mibBuilder.loadTexts: netBotz_snmp_traptarget.setStatus('mandatory')
if mibBuilder.loadTexts: netBotz_snmp_traptarget.setDescription('Target of traps from the Netbotz device. This field contains the IP address where Netbotz traps are to be sent.')
netBotz_snmp_community = MibScalar((1, 3, 6, 1, 4, 1, 5528, 40, 2), DisplayString()).setLabel("netBotz-snmp-community").setMaxAccess("readwrite")
if mibBuilder.loadTexts: netBotz_snmp_community.setReference('Read/Write Community')
if mibBuilder.loadTexts: netBotz_snmp_community.setStatus('mandatory')
if mibBuilder.loadTexts: netBotz_snmp_community.setDescription('The read/write community of the Netbotz device.')
netBotz_snmp_timeout = MibScalar((1, 3, 6, 1, 4, 1, 5528, 40, 3), Integer32()).setLabel("netBotz-snmp-timeout").setMaxAccess("readwrite")
if mibBuilder.loadTexts: netBotz_snmp_timeout.setReference('SNMP Timeout')
if mibBuilder.loadTexts: netBotz_snmp_timeout.setStatus('mandatory')
if mibBuilder.loadTexts: netBotz_snmp_timeout.setDescription('SNMP Timeout period.')
netBotz_snmp_retries = MibScalar((1, 3, 6, 1, 4, 1, 5528, 40, 4), Integer32()).setLabel("netBotz-snmp-retries").setMaxAccess("readwrite")
if mibBuilder.loadTexts: netBotz_snmp_retries.setReference('SNMP Retries')
if mibBuilder.loadTexts: netBotz_snmp_retries.setStatus('mandatory')
if mibBuilder.loadTexts: netBotz_snmp_retries.setDescription('SNMP Retry count.')
netBotz_userid_1 = MibScalar((1, 3, 6, 1, 4, 1, 5528, 40, 5), DisplayString()).setLabel("netBotz-userid-1").setMaxAccess("readwrite")
if mibBuilder.loadTexts: netBotz_userid_1.setReference('UserID 1')
if mibBuilder.loadTexts: netBotz_userid_1.setStatus('mandatory')
if mibBuilder.loadTexts: netBotz_userid_1.setDescription('The userID of the supervisor account (write-only).')
netBotz_password_1 = MibScalar((1, 3, 6, 1, 4, 1, 5528, 40, 6), DisplayString()).setLabel("netBotz-password-1").setMaxAccess("readwrite")
if mibBuilder.loadTexts: netBotz_password_1.setReference('Password 1')
if mibBuilder.loadTexts: netBotz_password_1.setStatus('mandatory')
if mibBuilder.loadTexts: netBotz_password_1.setDescription('The password of the supervisor account (write-only).')
netBotz_userid_2 = MibScalar((1, 3, 6, 1, 4, 1, 5528, 40, 7), DisplayString()).setLabel("netBotz-userid-2").setMaxAccess("readwrite")
if mibBuilder.loadTexts: netBotz_userid_2.setReference('UserID 2')
if mibBuilder.loadTexts: netBotz_userid_2.setStatus('mandatory')
if mibBuilder.loadTexts: netBotz_userid_2.setDescription('The userID of the full read access account (write-only).')
netBotz_password_2 = MibScalar((1, 3, 6, 1, 4, 1, 5528, 40, 8), DisplayString()).setLabel("netBotz-password-2").setMaxAccess("readwrite")
if mibBuilder.loadTexts: netBotz_password_2.setReference('Password 2')
if mibBuilder.loadTexts: netBotz_password_2.setStatus('mandatory')
if mibBuilder.loadTexts: netBotz_password_2.setDescription('The password of the full read access account (write-only).')
netBotz_userid_3 = MibScalar((1, 3, 6, 1, 4, 1, 5528, 40, 9), DisplayString()).setLabel("netBotz-userid-3").setMaxAccess("readwrite")
if mibBuilder.loadTexts: netBotz_userid_3.setReference('UserID 3')
if mibBuilder.loadTexts: netBotz_userid_3.setStatus('mandatory')
if mibBuilder.loadTexts: netBotz_userid_3.setDescription('The userID of the minimum read access account (write-only).')
netBotz_password_3 = MibScalar((1, 3, 6, 1, 4, 1, 5528, 40, 10), DisplayString()).setLabel("netBotz-password-3").setMaxAccess("readwrite")
if mibBuilder.loadTexts: netBotz_password_3.setReference('Password 3')
if mibBuilder.loadTexts: netBotz_password_3.setStatus('mandatory')
if mibBuilder.loadTexts: netBotz_password_3.setDescription('The password of the minimum read access account (write-only).')
netBotz_snmp_traptarget2 = MibScalar((1, 3, 6, 1, 4, 1, 5528, 40, 11), IpAddress()).setLabel("netBotz-snmp-traptarget2").setMaxAccess("readwrite")
if mibBuilder.loadTexts: netBotz_snmp_traptarget2.setReference('Netbotz Trap Target 2')
if mibBuilder.loadTexts: netBotz_snmp_traptarget2.setStatus('mandatory')
if mibBuilder.loadTexts: netBotz_snmp_traptarget2.setDescription('Second target of traps from the Netbotz device. This field contains an additional IP address where Netbotz traps are to be sent.')
mibBuilder.exportSymbols("NETBOTZ-SNMP-MIB", netBotz_snmp_retries=netBotz_snmp_retries, netBotz_userid_1=netBotz_userid_1, netBotz_password_2=netBotz_password_2, netBotz_snmp_traptarget=netBotz_snmp_traptarget, netBotz_snmp_traptarget2=netBotz_snmp_traptarget2, netBotz_password_3=netBotz_password_3, netBotz_snmp_timeout=netBotz_snmp_timeout, netBotz_snmp_community=netBotz_snmp_community, netBotz_password_1=netBotz_password_1, netBotz_userid_2=netBotz_userid_2, netBotz_userid_3=netBotz_userid_3)
|
class Solution(object):
def findDuplicate(self, paths):
"""
:type paths: List[str]
:rtype: List[List[str]]
"""
d = collections.defaultdict(list)
for path in paths:
l = path.split()
directory = l[0]
for file in l[1:]:
name, content = file.split('(')
content = content[:-1]
d[content].append(directory+'/'+name)
# print d
res = []
for key in d:
if len(d[key])>1:
res.append(d[key])
return res |
setA = {"John", "Bob", "Mary", "Serena"}
setB = {"Jim", "Mary", "John", "Bob"}
setA ^ setB # symmetric difference of A and B
{'Jim', 'Serena'}
setA - setB # elements in A that are not in B
{'Serena'}
setB - setA # elements in B that are not in A
{'Jim'}
setA | setB # elements in A or B (union)
{'John', 'Bob', 'Jim', 'Serena', 'Mary'}
setA & setB # elements in both A and B (intersection)
{'Bob', 'John', 'Mary'}
|
def main():
size_of_tlb = input('Input size of TLB\n')
tlb(size_of_tlb, 'execution_large.txt')
def tlb(size, file):
f = open(file, 'r')
f1 = f.readlines()
page = ''
page_list = []
#reads in pages from file
for line in f1:
for bit in xrange(0,54):
page += str(line[bit])
page_list.append(page)
page = ''
#puts into dictionary and will replace key value pair with lowest value/count with new one.
tlb_dict = {}
tlb_miss = 0
for page in page_list:
if len(tlb_dict) < size:
if page not in tlb_dict:
tlb_dict[page] = 1
tlb_miss += 1
elif page in tlb_dict:
tlb_dict[page] += 1
elif len(tlb_dict) == size:
if page not in tlb_dict:
min_page_key = min(tlb_dict, key = tlb_dict.get)
del tlb_dict[min_page_key]
tlb_dict[page] = 1
tlb_miss += 1
elif page in tlb_dict:
tlb_dict[page] += 1
print('\n')
print('Amount of TLB Misses: {}'.format(tlb_miss))
if __name__ == '__main__':
main()
|
'''
Queue - FIFO
Implementtaion of a queue using python List class
the end of the list = rear of the queue
the begining of the list = front of the queue
enqueue = O(n)
dequeue = O(1)
'''
class Queue:
def __init__(self):
self.items=[]
def isEmpty(self):
return self.items == []
def dequeue(self):
if self.isEmpty():
return float('-inf')
else:
return self.items.pop()
def enqueue(self,item):
self.items.insert(0,item)
def size(self):
return len(self.items)
def __repr__(self):
print('called')
return str(self.items)
if __name__ == '__main__':
s=Queue()
type(s)
s.enqueue(10)
s.enqueue(11)
s.dequeue()
print(s) # 11
|
S = input()
result = 0
for c in S:
if c in '0123456789':
result += int(c)
print(result)
|
if __name__ == '__main__':
n = 0
p = input('input a octal number:\n')
for i in range(len(p)):
n = n * 8 + ord(p[i]) - ord('0')
print(n)
# 8 ---> 10
|
def max_number(number1,number2,number3):
max1= max(number1,number2)
max2= max(max1,number3)
print(max2)
max_number(5,4,3)
def min_number(number1,number2,number3):
min1= min(number1,number2)
min2= min(min1,number3)
print(min2)
min_number(5,4,3)
|
sql_vals = {'host' : 'localhost',
'port' : 3306,
'db' : 'gaime',
'user' : 'gaimeAdmin',
'password' : 'BBEgaime3'}
|
# https://www.hackerrank.com/challenges/staircase/problem
def staircase(size):
spaces = size - 1
for i in range(size):
print('{spaces}{hashes}'.format(spaces=' ' * spaces, hashes='#' * (size - spaces)))
spaces -= 1
staircase(4)
|
# see: https://leetcode.com/problems/two-sum/
class Solution:
def twoSum(self, nums: [int], target: int) -> [int]:
nums_size = len(nums)
complements = []
for i in range(nums_size):
complement = target - nums[i]
if complement in complements:
return [nums.index(complement), i]
complements.append(nums[i])
return []
if __name__ == '__main__':
solution = Solution()
print(solution.twoSum([2, 7, 11, 15], 9)) # [0, 1]
|
class ComCompatibleVersionAttribute(Attribute,_Attribute):
"""
Indicates to a COM client that all classes in the current version of an assembly are compatible with classes in an earlier version of the assembly.
ComCompatibleVersionAttribute(major: int,minor: int,build: int,revision: int)
"""
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
@staticmethod
def __new__(self,major,minor,build,revision):
""" __new__(cls: type,major: int,minor: int,build: int,revision: int) """
pass
BuildNumber=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the build number of the assembly.
Get: BuildNumber(self: ComCompatibleVersionAttribute) -> int
"""
MajorVersion=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the major version number of the assembly.
Get: MajorVersion(self: ComCompatibleVersionAttribute) -> int
"""
MinorVersion=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the minor version number of the assembly.
Get: MinorVersion(self: ComCompatibleVersionAttribute) -> int
"""
RevisionNumber=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the revision number of the assembly.
Get: RevisionNumber(self: ComCompatibleVersionAttribute) -> int
"""
|
self.description = "Install a package from a sync db, with a filesystem conflict"
sp = pmpkg("dummy")
sp.files = ["bin/dummy",
"usr/man/man1/dummy.1"]
self.addpkg2db("sync", sp)
self.filesystem = ["bin/dummy"]
self.args = "-S %s" % sp.name
self.addrule("PACMAN_RETCODE=1")
self.addrule("!PKG_EXIST=dummy")
|
# to do: pytz support
class Timer(object):
def __init__(self, start_time: int, end_time: int, ticker_size: int):
self._start_time = start_time
self._end_time = end_time
self._step = ticker_size
self._current_time = start_time
@property
def time(self):
return self._current_time
def next(self) -> bool:
self._current_time += self._step
if self._current_time > self._end_time:
return True
else:
return False
|
print("""
080) Crie um programa onde o usuário possa digitar cinco valores numéricos
e cadastre-os em uma lista, já na posição correta de inserção (sem usar o
sort()). No final, mostre a lista ordenada na tela.
""")
### A solução final foi baseada no código postado no seguinte comentário do
### usuário João Pedro Calixto, no vídeo de resolução do Exercício 080 do
### Curso de Python do Curso em Vídeo: https://bit.ly/2D78pyX (Ver
### comentário em destaque)
### TODO: Documentar melhor a lógica usando comentários
listaComCincoNumeros = []
posicaoDeInsercao = 0
for valor in range(5):
entrada = int(input(f'Informe o {valor+1}º número: '))
for indice, valor in enumerate(listaComCincoNumeros):
if entrada > valor:
posicaoDeInsercao = indice + 1
listaComCincoNumeros.insert(posicaoDeInsercao, entrada)
posicaoDeInsercao = 0
print(f'A lista, ordenada é: {listaComCincoNumeros}')
### TODO: Melhorar a visualização do passo a passo abaixo
#
# Exemplo de entrada: 9, 0, 2, 1, 6
# Observação: pdi = posição de inserção
#
# - programa principal
# iteracao | entrada | for interno | pdi | saida
# 0 | 9 | n/a | 0 | [9]
# 1 | 0 | * | 0 | [0, 9]
# 2 | 2 | + | 1 | [0, 2, 9]
# 3 | 1 | - | 1 | [0, 1, 2, 9]
# 4 | 6 | \ | 3 | [0, 1, 2, 6, 9]
#
# - for's internos
#
#+-------------------------------------------------------+
#| | indice | valor | entrada | entrada > valor | pdi |
#+-------------------------------------------------------+
#| * | 0 | 9 | 0 | não | 0 |
#+-------------------------------------------------------+
#| + | 0 | 0 | 2 | sim | 1 |
#| | 1 | 9 | 2 | nao | 1 |
#+-------------------------------------------------------+
#| - | 0 | 0 | 1 | sim | 1 |
#| | 1 | 2 | 1 | não | 1 |
#| | 2 | 9 | 1 | não | 1 |
#+-------------------------------------------------------+
#| \ | 0 | 0 | 6 | sim | 1 |
#| | 1 | 1 | 6 | sim | 2 |
#| | 2 | 2 | 6 | sim | 3 |
#| | 3 | 9 | 6 | não | 3 |
#+-------------------------------------------------------+
|
def sanitise(item):
"""
Works through a given object and removes collections attributes which have None Type or empty string values
:param item: Object to sanitise
:return: Sanitised object
"""
item_to_sanitise = item.copy()
if isinstance(item_to_sanitise, dict):
item_to_sanitise = _sanitise_dictionary(item_to_sanitise)
elif isinstance(item_to_sanitise, (list, str)):
if len(item_to_sanitise) == 0:
return None
elif isinstance(item_to_sanitise, list):
return _sanitise_list(item_to_sanitise)
return item_to_sanitise
def _sanitise_dictionary(item):
# We must copy this object as we will iterate through it but may remove nodes from it
item_to_sanitise = item.copy()
for key, value in item.items():
# If the key is a collections then pass the value back into this method again
if isinstance(value, dict):
if len(item_to_sanitise[key]) == 0:
del item_to_sanitise[key]
else:
sanitised_key = sanitise(value)
if sanitised_key is None:
del item_to_sanitise[key]
else:
item_to_sanitise[key] = sanitised_key
elif value is None or value == "":
del item_to_sanitise[key]
else:
sanitised_key = sanitise(value)
if sanitised_key is None:
del item_to_sanitise[key]
else:
item_to_sanitise[key] = sanitised_key
return item_to_sanitise
def _sanitise_list(item):
item_to_sanitise = item.copy()
sanitised_index = 0
for list_item in item:
sanitised_index = sanitised_index + 1
if list_item is None:
item_to_sanitise.remove(list_item)
sanitised_index = sanitised_index - 1
elif isinstance(list_item, (str, list, dict)):
if len(list_item) == 0:
item_to_sanitise.remove(list_item)
sanitised_index = sanitised_index - 1
elif isinstance(list_item, dict):
sanitised_item = _sanitise_dictionary(list_item)
if sanitised_item is None:
item_to_sanitise.remove(list_item)
sanitised_index = sanitised_index - 1
else:
item_to_sanitise.remove(list_item)
item_to_sanitise.insert(sanitised_index, sanitised_item)
elif isinstance(list_item, list):
sanitised_item = _sanitise_list(list_item)
if sanitised_item is None:
item_to_sanitise.remove(list_item)
sanitised_index = sanitised_index - 1
else:
item_to_sanitise.remove(list_item)
item_to_sanitise.insert(sanitised_index, sanitised_item)
return item_to_sanitise
|
'''
Decode via autokey cipher
Status: Accepted
'''
###############################################################################
def main():
"""Read input and print output cipher decoded with autokey"""
ord_a = ord('A')
ord_aa = ord_a << 1
cipher = input()
key = input()
length = len(key)
for index, glyph in enumerate(cipher):
key += chr(ord_a + ((ord(glyph) - ord(key[index]) - ord_aa + 26) % 26))
print(key[length:])
###############################################################################
if __name__ == '__main__':
main()
|
_base_config_ = ["../cse.py","../defaults.py"]
dummy_anonymizer = True
generator = dict(
type="PixelationGenerator",
pixelation_size=16
)
|
dict = {
"AD" : "a",
"ABBÁTYA" : ["abaïe", "abaie"],
# " " : "adhuc", #Mot latin
"ADÍDA" : "ahie",
"HÁBYA" : [["aie"], 'verbe_subj'], #verbe
"ADILLE" : "al",
"ALÁCROS" : "alegres",
"ALLMỌNAS" : "almones",
"ADMÁSSAS" : ["amassez", "amassets"],
"AMĘN" : "amen",
"AMÍCU" : "ami",
"AMÍCOS" : "amis",
"AMÍCU" : "amiu",
"ADNÚNTYÁTYO" : ["anunciacïon", "anunciacion"],
"ANOS" : ["anz", "ans"],
"ALMAS" : "armes", #J'ai le résultat almes, est-ce juste ?
"ADTÁNTU" : "atant",
"ALSÍ" : ["ausi", "aussi"], #??
# "ALÍU" : "aussi", #??
"ALTRẸSSÍ" : "autresi",
"ADVẸNÍT" : [["avenit"], 'verbe_parfait'], #verbe
"HABẸTS" : [["avez", "avets"], 'verbe_present'],#verbe
"HABẸANT" : [["avoient"], 'verbe_imparfait'], #verbe
"BÁSYANT" : [["baisent"], 'verbe_present'], #verbe
"BASSU" : "bas",
"BĘNE" : "bien",
"BONU" : "bon",
"BONTÁ" : ["bonté", "bonte"],
"CE" : "ce",
"CELLA" : "cele",
"CELẸBBRAWIT" : [["celebroit"], 'verbe_imparfait'], #verbe
"CELĘSTA" : "celeste",
"CERTÁNAMẸNTE" : "certainement",
"CESTOS" : ["ceuz", "ceuts"],
"CANTẸANT" : [["chantoient"], 'verbe_imparfait'],
"CAPĘLLA" : "chapelle",
# " " : "chas ", #???
"CAUSA" : "chose",
"CÍLLE" : "cil", #??
"CLĘRCU" : "clerc",
"CLÁRA" : "clere",
"QWỌMMO" : "com",
"COMẸNTYATA" : "comencie",
"COMTÁTU" : ["conté", "conte"],
"CORA" : "core",
"CỌRRT" : "cort",
"COSTÚDME" : "cotume",
"CRÍSTO" : ["crist", "crisz"], #Nom propre
# "CRÍSTO" : "crisz", #Nom propre
"CỌGYTỌANT" : [["cuidoient"], 'verbe_imparfait'], #verbe
# "DE" : "d ",
"DE" : "de",
"DE DẸNTUS" : ["dedanz", "dedants", "dedenz", "dedents"], #??
# "DEINTUS" : "dedenz ",
"DELLO" : ["del", "deu", "dé", "de"],
"DĘOS" : "deus",
# "DĘU" : "dieu ",
"DÍRE" : "dire",
"DÍCT" : [["dit"], 'verbe_present'],
# " " : "doint ", #???
"DONATU" : ["done", "doné"],
# "DONATU" : "doné ",
"DỌLCA" : "douce",
# "DEU" : "dé",
"ÁWWĪ" : "ei", #verbe
"EN" : "en",
"ẸNGLATĘRRA" : "engleterre", #Nom propre
"ENSAPẸLLĪ" : "enseveli", #verbe
"ENTRÁTU" : ["entrë", "entré", "entre"],
# "ÍNTRÁTU" : "entrë ",
"ENVÍRỌNBANT" : [["environoient"], 'verbe_imparfait'], #verbe
"ERAT" : "ere",
"ERANT" : "eront", #verbe
"SCǪLTATU" : ["escouté", "escoute"],
"ESTĘT" : [["estoie"], 'verbe_imparfait'], #verbe
# "ESSET" : "estoit", #verbe
"ET" : "et",
"EWÚS" : ["euz", "euts"],
"FACYA" : "face",
"FACTA" : "faite",
"FẸNNĪ" : "fenie",
"FẸNNÍS" : "fenis",
"FESTA" : "fest",
"FILYU" : "fil",
"FÍRUNT" : [["firont"], 'verbe_present'], #verbe
"FONDÁTA" : "fondee",
"FORMANT" : "forment",
"FORS" : "fors",
"FUĪ" : "fu", #??
"FURANT" : "furent",
"FUSSANT" : "fussent",
"WARDA" : ["gardé", "garde"], #vient du germain
"GLORÍỌS" : ["glorïos", "glorios"],
"GLORÍOSA" : ["glorïose", "gloriose"],
"GRÁTTYA" : "grace",
"GRÁTTYAS" : "graces",
"GRANDU" : "grant",
"HHALTU" : "haut",
"ǪMO" : "hom",
"OMĘN" : "homen",
"HHONǪR" : "honor",
"HHONǪRRANT" : [["honoront"], 'verbe_present'],
"HÍC" : "i",
"ILLE" : "il",
"ÍNTRỌYTO" : ["introïte", "introite"], #Évolution étrange
# "INTRODUCTIO" : ["introïtum", "introitum"], #??
"ISSÍ" : "iqui", #??
"IRA" : "ire",
# " " : "it", #???
# " " : "jhesu ", #Nom propre
"GAUDYÁNS" : ["joiants", "joianz"],
"GAUDYA" : ["joie", "joië"],
# "GAUDÍA" : "joië",
"DYǪRNU" : "jor",
"LA" : "la",
"LARMAS" : "larmes",
"LO" : "le",
"LOS" : "les",
"LEVANT" : "levent",
"LI" : "li",
"LǪCU" : "liu",
"LO" : "lo",
"LONGU" : "lonc",
"LORU" : "lor",
"LOROS" : "lors",
"MÁNS" : "mains",
"MÁNIT" : "maint", #Probablement du germain
"MALU" : "mal",
"MERCẸYDE" : "marci", #?
"MARÍA" : "marie ", #Nom propre
"MERÁBÍLYANT" : "meravillont",
"MERCẸYDE" : "merci",
"MÁTRA" : ["mere", "merë"],
# "MÁTER" : "merë",
"MẸSSA" : "messe",
"METTẸRS" : "meters", #à MODIFIER
"MIRÁCCLU" : "miracle",
"MONASTĘRYU" : "monestei", #Évolution scientifique
"MỌSTĘRYU" : "monestei", #Évolution scientifique
"MỌSTĘRYU" : "motier",
# "MOVÍT" : "movit",
"NOME" : "nom",
"NOS" : "nos",
"NOVĘLLA" : "novelle",
"NOVĘLLAMẸNTE" : "novellemant",
"NUUS" : "nus",
"AUNT" : "ont",
"HAUR" : "or",
"ORÁTYỌNES" : "oraisons",
"AURUNT" : [["orent"], 'verbe_present'],
"PRẸYMUS" : "prions",
"ÁWTU" : "ot",
"AUÚT" : "ou",
"AUDÍRE" : ["oïr", "oir"],
"PASSÁTS" : ["passets", "passez"],
"PAGẸYSE" : ["païs", "pais"],
"PITTÁ" : ["pité", "pite"],
"PLORÁNT" : "plorant",
"PLORS" : "plors",
"PǪPLOS" : "pobles",
"POTẸTS" : ["poez", "poets"],
"POR" : "por",
"POTRÁT" : [["porroit"], 'verbe_cond'],
# " " : "pou ", #??
"PRETYǪSU" : ["precïo", "precio"],
"PRETYǪSA" : ["precïose", "preciose"],
"PRESSE" : "pres",
"PRĘRYA" : "priere",
"PRẸSU" : "pris",
"QWANDO" : "quant",
"QWE" : ["quë", "que"],
"QWI" : "qui",
# "QUE" : "quë",
"RELÍGÍO" : ["religïon", "religion"],
"REMANSÍRUNT" : [["remansiront"], 'verbe_parfait'],
"RENDUNT" : [["rendont"], 'verbe_present'],
"RESÚRAXĪ" : [["resurexi"], 'verbe_parfait'],
"SWA" : "sa",
"SAYLÍRE" : "saillir",
"SÁNCTUS" : "sains",
"SÁNCTA" : "sainte",
"SÁNCTUS" : ["sainz", "saints"],
"SINE" : "san",
"SANGU" : "sanc",
"SAPỌNS" : "savons",
# "SECCǪRS" : "secors",
"SECCǪRS" : "socors",
"SENYǪR" : "seignor",
"SENTĪ" : [["senti"], 'verbe_parfait'],
"SI" : "si",
# "SECORRE" : "socors",
"SỌY" : "soi",
"SỌN" : "son",
"SOBẸNDE" : "sovent",
"SỌBTRÁCTA" : "soztraite",
# "" : "sum ", #Latin dans le texte
# " " : "tecum ", #Latin dans le texte
# "TẸ" : "tei",
"TÁLI" : "tel",
"TENIT" : [["tenit"], 'verbe_parfait'],
"TENÚ" : "tenu",
"TERRA" : "terra",
"TERRA" : "terre",
# "TERRA" : "terre ",
"TOTTUS" : ["toz", "tots"],
"TRANSGLÚTTĪ" : [["transgluti"], 'verbe_parfait'],
"TREMLÁT" : [["trembla"], 'verbe_parfait'],
"TRETỌTTU" : "tretuit",
"TROPÁRUNT" : [["troverent"], 'verbe_parfait'],
"TROPÁTU" : ["trové", "trove"],
"TỌTTU" : "tuit",
"UNU" : "un",
"UNA" : "une",
"UMQWAS" : "unques",
"VESTÍMẸNTS" : ["vestimenz", "vestiments"],
"VẸDRE" : ["veïr", "veir"],
"VITA" : "via",
"VẸNRUNT" : [["vindrent"], 'verbe_parfait'],
"VIDRUNT" : "vire",
"VIRGA" : "virge",
"VOCES" : ["voiz", "voits"],
"VOOS" : "vos",
}
|
# Kaibara Yuzan's wise saying.
def kuruma(kuruma="車"):
return f"馬鹿どもに{kuruma}を与えるなっ!"
def arai(arai="あらい"):
return f"この{arai}を作ったのは誰だあっ!"
def kubi():
return f"きさまか!きさまはクビだ、出て行けっ!"
def hiyashi_chuka(hiyashi="冷やし中華"):
return f"{hiyashi}だとっ!?ふざけるなあっ!"
def okami(okami="女将"):
return f"{okami}を呼べっ!" |
class UnionFind:
def __init__(self, n):
# Every element is a different component.
self.data = [i for i in range(n)]
def find(self, i):
if i != self.data[i]:
self.data[i] = self.find(self.data[i])
return self.data[i]
def union(self, i, j):
pi, pj = self.find(i), self.find(j)
if pi != pj:
self.data[pi] = pj
u = UnionFind(10)
connections = [(0, 1), (1, 2), (0, 9), (5, 6), (6, 4), (5, 9)]
# union
for i, j in connections:
u.union(i, j)
# find
for i in range(10):
print('item', i, '-> component', u.find(i)) |
# Evaludate various kinds of diffs in files
class FileDiff:
def __init__(self):
'''
initialize for diffing files
'''
|
# Copyright Contributors to the Amundsen project.
# SPDX-License-Identifier: Apache-2.0
# String for partition column badge
PARTITION_BADGE = 'partition column'
|
# encoding: utf-8
def composed(*decs):
"""
Compose multiple decorators
Example :
>>> @composed(dec1, dec2)
... def some(f):
... pass
"""
def deco(f):
for dec in reversed(decs):
f = dec(f)
return f
return deco
def order_fields(*field_list):
def decorator(form):
original_init = form.__init__
def init(self, *args, **kwargs):
original_init(self, *args, **kwargs)
for field in field_list[::-1]:
self.fields.insert(0, field, self.fields.pop(field))
form.__init__ = init
return form
return decorator
def memoize(func):
"""
Memoization decorator for a function taking one or more arguments.
"""
class memodict(dict):
def __getitem__(self, *key):
return dict.__getitem__(self, key)
def __missing__(self, key):
ret = self[key] = func(*key)
return ret
return memodict().__getitem__
|
#Crie um programa que leia o nome completo de uma pessoa e mostre:
# - O nome com todas as letras maiúsculas e minúsculas.
# - Quantas letras ao todo (sem considerar espaços).
# - Quantas letras tem o primeiro nome.
nome = str(input('Digite o seu nome completo: ')).strip()
print(f'Seu nome completo em Maiusculas é {nome.upper()}.')
print(f'Seu nome completo em minusculas é {nome.lower()}.')
print('O seu nome tem no total {} letras.'.format(len(nome)- nome.count(' ')))
print('O seu primeiro nome tem {} letras.'.format(nome.find(' '))) |
n = int(input())
sum = 0
for i in range(0,n):
num = int(input())
sum+=num
print(sum)
|
class Group(object):
def __init__(self, groupId, ownerJid, subject, subjectOwnerJid, subjectTime, creationTime):
self._groupId = groupId
self._ownerJid = ownerJid
self._subject = subject
self._subjectOwnerJid = subjectOwnerJid
self._subjectTime = int(subjectTime)
self._creationTime = int(creationTime)
def getId(self):
return self._groupId
def getOwner(self):
return self._ownerJid
def getSubject(self):
return self._subject
def getSubjectOwner(self):
return self._subjectOwnerJid
def getSubjectTime(self):
return self._subjectTime
def getCreationTime(self):
return self._creationTime
def __str__(self):
return "ID: %s, Subject: %s, Creation: %s, Owner: %s, Subject Owner: %s, Subject Time: %s" %\
(self.getId(), self.getSubject(), self.getCreationTime(), self.getOwner(), self.getSubjectOwner(), self.getSubjectTime())
|
# StompMessageBroker is a proxy class of StompDaemonConnection with only a sendMessage method
# This exposes a simple interface for a StompMessageController method to communicate via the broker
class StompMessageBroker():
def __init__(self, stomp_daemon_connection):
self.stomp_daemon_connection = stomp_daemon_connection
def sendMessage(self, message, queue):
print("stomp_message_broker.sendMessage() - {0} - {1}".format(queue, message))
#print(self.stomp_daemon_connection)
self.stomp_daemon_connection.stompConn.send(queue, message)
def brokerId():
return self.stomp_daemon_connection.msgSrvrClientId |
######################################
# CHECK AGAIN. NOT WORKING ACCORDINGLY
######################################
class Node(object):
def __init__(self, val, parent=None):
self.val = val
self.leftChild = None
self.rightChild = None
self.parent = parent
def getLeftChild(self):
return self.leftChild
def getRightChild(self):
return self.rightChild
def getParent(self):
return self.parent
def isRoot(self):
return self.parent != None
def hasLeftChild(self):
return self.leftChild != None
def hasRightChild(self):
return self.rightChild != None
def hasBothChildren(self):
return self.hasLeftChild() and self.hasRightChild()
def hasOneChild(self):
return self.hasLeftChild() or self.hasRightChild()
class BinarySearchTree(object):
def __init__(self):
self.size = 0
self.root = None
def insert(self, val):
if not self.root:
self.root = Node(val)
else:
temp = self.root
done = False
while not done:
if val < temp.val:
if temp.hasLeftChild():
temp = temp.getLeftChild()
else:
temp.leftChild = Node(val, temp)
done = True
else:
if temp.hasRightChild():
temp = temp.getRightChild()
else:
temp.rightChild = Node(val, temp)
done = True
self.size += 1
def inorder(self, root):
if root:
self.inorder(root.leftChild)
print(root.val, end=" ")
self.inorder(root.rightChild)
def trimBST(self, tree, minVal, maxVal):
if not tree:
return
tree.leftChild = self.trimBST(tree.leftChild, minVal, maxVal)
tree.rightChild = self.trimBST(tree.rightChild, minVal, maxVal)
if minVal <= tree.val <= maxVal:
return tree
if tree.val < minVal:
return tree.rightChild
if tree.val > maxVal:
return tree.leftChild
if __name__ == "__main__":
b = BinarySearchTree()
b.insert(25)
b.insert(15)
b.insert(8)
b.insert(20)
b.insert(17)
b.insert(16)
b.insert(18)
b.insert(40)
b.insert(35)
b.insert(46)
b.insert(42)
b.insert(50)
b.inorder(b.root)
print("Root:", b.root.val)
print("After trimming:")
b.trimBST(b.root, 20, 46)
b.inorder(b.root)
|
name = 'Amadikwa Joy N'
age = '25'
address = 'Owerri Imo State'
print(name)
print(age)
print(address)
|
all_min = int(input())
hours = all_min // 60
minuts = all_min - hours*60
print(hours)
print(minuts) |
# optimizer
optimizer = dict(type='Adam', lr=0.0002, weight_decay=0)
optimizer_config = dict(grad_clip=None)
# learning policy
lr_config = dict(policy='step', step=[])
runner = dict(type='EpochBasedRunner', max_epochs=50)
|
n=int(input())
r=""
while n>1:
r+=str(n)+" "
if n%2==0:
n=n//2
else:
n=3*n+1
r+=str(n)
print(r)
|
#this program makes a simple calculator which can aad,subtract,multiply,divide using functions
#this function adds two number
def add(a,b):
return a+b
#this function subtracts two numbers
def subtract(a,b):
return a-b
#this function multiplies two numbers
def multiply(a,b):
return a*b
#this function divides two numbers
def divide(a,b):
return a/b
print("select operation.")
print("1.add")
print("2.subtract")
print("3.multiply")
print("4.divide")
#take input from the user
choice=input("enter choice(1/2/3/4):")
num1=int(input("enter first number:"))
num2=int(input("enter second number:"))
if choice =='1':
print(num1,"+",num2,"=",add(num1,num2))
elif choice=='2':
print(num1,"-",num2,"=",subtract(num1,num2))
elif choice=='3':
print(num1,"*",num2,"=",multiply(num1,num2))
elif choice == '4':
print(num1,"/",num2,"=",divide(num1,num2))
else:
print("invalid input")
|
"""Basic HTML."""
def _basic_html(body_str: str):
output = (
f'<!DOCTYPE html><html lang="en-GB">'
f'<head>'
f'<script src="https://cdn.rawgit.com/inexorabletash/polyfill/v0.1.42/polyfill.js"></script>'
f'<script src="https://cdn.rawgit.com/inexorabletash/polyfill/v0.1.42/typedarray.js"></script>'
f'<script src="https://cdn.plot.ly/plotly-cartesian-latest.min.js"></script>'
f'</head>'
f' <div class="container">'
f' <div class="row">'
f' <div class="col-12">'
f' {body_str}'
f' </div>'
f' </div>'
f' </div>'
)
return output
def _plotly_html(body_str: str):
output = (
f'<div id="divPlotly"></div>'
f'<script>'
f' var plotly_data = {body_str};'
f' Plotly.react("divPlotly", plotly_data.data, plotly_data.layout);'
f'</script>'
)
return output
|
"""
Contains exceptions for the trainers package.
"""
class TrainerError(Exception):
"""
Any error related to the trainers in the ML-Agents Toolkit.
"""
pass
class TrainerConfigError(Exception):
"""
Any error related to the configuration of trainers in the ML-Agents Toolkit.
"""
pass
class CurriculumError(TrainerError):
"""
Any error related to training with a curriculum.
"""
pass
class CurriculumLoadingError(CurriculumError):
"""
Any error related to loading the Curriculum config file.
"""
pass
class CurriculumConfigError(CurriculumError):
"""
Any error related to processing the Curriculum config file.
"""
pass
class MetaCurriculumError(TrainerError):
"""
Any error related to the configuration of a metacurriculum.
"""
pass
class SamplerException(TrainerError):
"""
Related to errors with the sampler actions.
"""
pass
class UnityTrainerException(TrainerError):
"""
Related to errors with the Trainer.
"""
pass
|
class Config:
tmp_save_dir='../../models_python'
train_num_workers=6
test_num_workers=3
# train_num_workers=0
# test_num_workers=0
# data_path='../../CT_rotation_data_npy_128'
# model_name='Aug3D'
# lvl1_size=4
# is3d=True
# train_batch_size = 8
# test_batch_size = 4
# max_epochs = 14
# step_size=6
# gamma=0.1
# init_lr=0.001
data_path='../../CT_rotation_data_2D'
model_name='NoAug2D'
is3d=False
train_batch_size = 32
test_batch_size = 32
max_epochs = 12
step_size=5
gamma=0.1
init_lr=0.001
pretrained=True
|
"""
Given an array of ints, return True if the array is length 1 or more, and the first element and the last element are equal.
same_first_last([1, 2, 3]) → False
same_first_last([1, 2, 3, 1]) → True
same_first_last([1, 2, 1]) → True
@author unobatbayar
"""
def same_first_last(nums):
if len(nums) >= 1 and nums[0] == nums[len(nums)-1]:
return True
return False
|
# Num = numero digita
# ========================================================================
# titulo e coleta de dados
print("\033[35m============[ EX 006 ]============")
print(34 * "=", "\033[m")
Num = int(input("Digite um \033[35mnumero\033[m: "))
print(34 * "\033[35m=", "\033[m")
# ========================================================================
# mostra o dobro,triplo e raiz quadrado do numero digitado
print(f"dobro de \033[35m{Num}\033[m = \033[35m{Num * 2}\033[m")
print(f"triplo de \033[35m{Num}\033[m = \033[35m{Num * 3}\033[m")
print(f"raiz quadrada de \033[35m{Num}\033[m = \033[35m{Num * Num}\033[m")
print(34 * "\033[35m=", "\033[m")
# ========================================================================
|
def adicao(n1, n2):
soma = n1 + n2
print('A soma dos {:.2f} + {:.2f} = {:.2f}'.format(n1, n2, soma))
def subtracao(n1, n2):
subtracao = n1 - n2
print('A subtração dos {:.2f} - {:.2f} = {:.2f}'.format(n1, n2, subtracao))
def divisao(n1, n2):
try:
divisao = n1 / n2
print('A divisão dos {:.2f} / {:.2f} = {:.2f}'.format(n1, n2, divisao))
except ZeroDivisionError:
print('n2 = 0, não é possivél fazer a conta')
def multiplicacao(n1, n2):
multiplicacao = n1 * n2
print('A multiplicação dos {:.2f} * {:.2f} = {:.2f}'.format(n1, n2, multiplicacao))
n1 = int(input('Digite N1: '))
n2 = int(input('Digite N2: '))
adicao(n1, n2)
subtracao(n1, n2)
divisao(n1, n2)
multiplicacao(n1, n2)
|
#!/usr/bin/env python3
inputs = list()
DEBUG = False
with open('input', 'r') as f:
inputs = f.read().splitlines()
balls = [int(ball) for ball in inputs.pop(0).split(',')]
if DEBUG:
print(balls)
inputs.pop(0)
card = 0
cards = list()
cards.append(list())
while(len(inputs) > 0):
line = inputs.pop(0)
if len(line) == 0:
if DEBUG:
print(cards[card])
card += 1
cards.append(list())
continue
cards[card].extend([int(n) for n in line.split()])
def winner(card):
for i in range(5):
# row all stamped
if card[(i*5):((i+1)*5)].count(-1) == 5:
return True
# column all stamped
if [card[i+r] for r in range(0,25,5)].count(-1) == 5:
return True
return False
stamp_idx = 0
for ball in balls:
for c in range(len(cards)):
try:
stamp_idx = cards[c].index(ball)
except:
continue
cards[c].pop(stamp_idx)
cards[c].insert(stamp_idx,-1)
if winner(cards[c]):
card_total = sum(filter(lambda x: x != -1, cards[c]))
if DEBUG:
print(f"c {c} card_total {card_total} ball {ball}")
print(f"called balls {balls[:balls.index(ball)]}")
print(f"card {cards[c]}")
print(card_total * ball)
exit()
|
PANEL_DASHBOARD = 'project'
PANEL_GROUP = 'default'
PANEL = 'api_access'
DEFAULT_PANEL = 'api_access'
ADD_PANEL = \
('openstack_dashboard.dashboards.project.api_access.panel.ApiAccess')
|
n, a, b = map(int, input().split())
total = 0
def sum_digits(digits):
return sum(int(digit) for digit in str(digits))
for i in range(1, n + 1):
if sum_digits(i) >= a and sum_digits(i) <= b:
total += i
print(total)
|
"""
Write a Python program to get all strobogrammatic numbers that are of length n
"""
def gen_stroboggrammatic(n):
result = helper(n,n)
return result
def helper(n, length):
if n == 0:
return[""]
if n == 1:
return["1", "0", "8"]
middles = helper(n-2, length)
result = []
for middle in middles:
if n != length:
result.append("0" + middle + "0")
result.append("8" + middle + "8")
result.append("1" + middle + "1")
result.append("9" + middle + "6")
result.append("6" + middle + "9")
return result
print("n = 2: \n", gen_stroboggrammatic(2))
print("n = 3: \n", gen_stroboggrammatic(3))
print("n = 4: \n", gen_stroboggrammatic(4))
# Reference : w3resource |
def Justify(string: str, maxWidth: int) -> str:
"""Returns justified string.
Keyword args:
string -- string largo para que se note
maxWidth -- ancho del texto final
Use:
print(Justify(string, maxWidth))
"""
words = string.split()
res, cur, num_of_letters = [], [], 0
for w in words:
# El condicional revisa que cada palabra entre en las columnas permitidas
assert ( # No me gusta el formato de este assert, pero black me lo bloquea
len(w) < maxWidth
), "Error: La palabra mas larga no entra en las columnas asignadas"
# El condicional revisa que haya espacio en el renglon
if num_of_letters + len(w) + len(cur) > maxWidth:
for i in range(maxWidth - num_of_letters):
cur[i % (len(cur) - 1 or 1)] += " "
res.append("".join(cur))
cur, num_of_letters = [], 0
cur += [w]
num_of_letters += len(w)
return "\n".join(res + [" ".join(cur).ljust(maxWidth)])
|
'''
Created on Apr 8, 2010
@author: jose
'''
|
class Solution:
def findDisappearedNumbers(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
nums = [0] + nums
for i in range(len(nums)):
index = abs(nums[i])
nums[index] = -abs(nums[index])
return [i for i in range(len(nums)) if nums[i] > 0]
|
"""CODE FOR DB STATS"""
"""
on guild join
@client.event
async def on_guild_join(guild):
connect = sqlite3.connect("files/stats.db")
cursor = connect.cursor()
cursor.execute(f"INSERT into stats VALUES ({guild.id}, 0, 0, 0, 0)")
connect.commit()
connect.close()
""" # enable stats
"""
on guild remove
c = sqlite3.connect("files/stats.db")
cursor = c.cursor()
cursor.execute(f"SELECT * FROM stats WHERE guild_id={guild.id}")
if not cursor.fetchone():
...
else:
cursor.execute(f"DELETE from stats WHERE guild_id='{guild.id}'")
c.commit()
c.close()
"""
"""
on message edit
c = sqlite3.connect("files/stats.db")
cursor = c.cursor()
cursor.execute(f"SELECT editmsg FROM stats WHERE guild_id={before.guild.id}")
cursor.execute(f"UPDATE stats SET editmsg = {cursor.fetchone()[0] + 1} WHERE guild_id={before.guild.id}")
c.commit()
c.close()
"""
"""
on message delete
c = sqlite3.connect("files/stats.db")
cursor = c.cursor()
cursor.execute(f"SELECT delmsg FROM stats WHERE guild_id={message.guild.id}")
cursor.execute(f"UPDATE stats SET delmsg = {cursor.fetchone()[0] + 1} WHERE guild_id={message.guild.id}")
c.commit()
c.close()
"""
"""
local stats
cursor.execute(f"SELECT snipe FROM stats WHERE guild_id={ctx.guild.id}")
embed.add_field(name=f"Messages Sniped: {cursor.fetchone()[0]}", value=f"Total amount of messages sniped", inline=False)
cursor.execute(f"SELECT esnipe FROM stats WHERE guild_id={ctx.guild.id}")
embed.add_field(name=f"Messages Editsniped: {cursor.fetchone()[0]}", value=f"Total amount of edited messages sniped", inline=False)
cursor.execute(f"SELECT delmsg FROM stats WHERE guild_id={ctx.guild.id}")
embed.add_field(name=f"Deleted Messages Logged: {cursor.fetchone()[0]}", value=f"Total amount of deleted messages logged", inline=False)
cursor.execute(f"SELECT editmsg FROM stats WHERE guild_id={ctx.guild.id}")
embed.add_field(name=f"Edited Messages Logged: {cursor.fetchone()[0]}", value=f"Total amount of edited messages logged", inline=False)
embed.set_footer(text=f"Server ID: {ctx.guild.id}", icon_url=ctx.guild.icon_url)
"""
"""
global stats
cursor.execute(f"SELECT snipe FROM stats WHERE guild_id={int(-1)}")
embed.add_field(name="Messages Sniped", value=f"`{cursor.fetchone()[0]}`")
cursor.execute(f"SELECT esnipe FROM stats WHERE guild_id={int(-1)}")
embed.add_field(name="Messages Editsniped", value=f"`{cursor.fetchone()[0]}`")
cursor.execute(f"SELECT delmsg FROM stats WHERE guild_id={int(-1)}")
embed.add_field(name="Deleted Messages Logged", value=f"`{cursor.fetchone()[0]}`")
cursor.execute(f"SELECT editmsg FROM stats WHERE guild_id={int(-1)}")
embed.add_field(name="Edited Messages Logged", value=f"`{cursor.fetchone()[0]}`")
"""
"""
multisnipe
c = sqlite3.connect("files/stats.db")
cursor = c.cursor()
cursor.execute(f"SELECT snipe FROM stats WHERE guild_id={ctx.guild.id}")
cursor.execute(f"UPDATE stats SET snipe={cursor.fetchone()[0] + 1} WHERE guild_id={ctx.guild.id}")
c.commit()
c.close()
"""
"""
usersnipe
c = sqlite3.connect("files/stats.db")
cursor = c.cursor()
cursor.execute(f"SELECT snipe FROM stats WHERE guild_id={ctx.guild.id}")
cursor.execute(f"UPDATE stats SET snipe={cursor.fetchone()[0] + 1} WHERE guild_id={ctx.guild.id}")
c.commit()
c.close()
"""
"""
snipe
c = sqlite3.connect("files/stats.db")
cursor = c.cursor()
cursor.execute(f"SELECT snipe FROM stats WHERE guild_id={ctx.guild.id}")
cursor.execute(f"UPDATE stats SET snipe = {cursor.fetchone()[0] + 1} WHERE guild_id={ctx.guild.id}")
c.commit()
c.close()
"""
"""
editsnipe
c = sqlite3.connect("files/stats.db")
cursor = c.cursor()
cursor.execute(f"SELECT esnipe FROM stats WHERE guild_id={int(-1)}")
cursor.execute(f"UPDATE stats SET esnipe = {cursor.fetchone()[0] + 1} WHERE guild_id={int(-1)}")
c.commit()
c.close()
"""
"""
guild remove
@client.event
async def on_guild_remove(guild):
# Clear out all options for the server
c = sqlite3.connect("files/edit_log.db")
cursor = c.cursor()
cursor.execute(f"SELECT * FROM servers WHERE guild_id={guild.id}")
if not cursor.fetchone():
...
else:
cursor.execute(f"DELETE from servers WHERE guild_id='{guild.id}'")
c.commit()
c.close()
c = sqlite3.connect("files/message_log.db")
cursor = c.cursor()
cursor.execute(f"SELECT * FROM servers WHERE guild_id={guild.id}")
if not cursor.fetchone():
...
else:
cursor.execute(f"DELETE from servers WHERE guild_id='{guild.id}'")
c.commit()
c.close()
"""
""" @commands.command()
@commands.cooldown(rate=1, per=1)
async def links(self, ctx):
embed=discord.Embed(description="Links for Sniper", color=0xfdfdfd)
embed.set_author(name="Links")
embed.add_field(name="Invite Links", value="[Manage Messages](https://discord.com/api/oauth2/authorize?client_id=742784763206828032&permissions=8192&scope=bot)\n[Administrator](https://discord.com/api/oauth2/authorize?client_id=742784763206828032&permissions=8&scope=bot)")
embed.add_field(name="Notice", value="You need the permission `Manage Server` to invite bots to your server!")
embed.add_field(name="Misc.", value="[Top.gg](https://top.gg/bot/742784763206828032)", inline=False)
await ctx.send(embed=embed)
@commands.command()
@commands.cooldown(rate=1, per=1)
async def vote(self, ctx):
embed=discord.Embed(description="Thanks for voting! Your vote helps Sniper get better recognized by the community!", color=0xfdfdfd)
embed.set_author(name="Vote")
embed.add_field(name="Direct Link", value="https://top.gg/bot/742784763206828032/vote")
await ctx.send(embed=embed)
@commands.command()
@commands.cooldown(rate=1, per=1)
async def stats(self, ctx):
c = sqlite3.connect("files/stats.db")
cursor = c.cursor()
embed=discord.Embed(description=f"Current Stats for Sniper", color=0xfdfdfd)
embed.set_author(name=f"Stats")
embed.add_field(name=f"Total Server Count: `{len(self.bot.guilds)}`", value=f"Current server count for Sniper")
embed.add_field(name=f"Total Users: `{sum([len(guild.members) for guild in self.bot.guilds])}`", value=f"Current user count for Sniper", inline=False) # Fix Total Users
embed.add_field(name=f"Uptime: `{convert(getUptime())}`", value=f"Current uptime for Sniper (hh:mm:ss)", inline=False)
embed.add_field(name=f"Library: `Discord.py (DPY)`", value=f"Library used for Sniper", inline=False)
embed.add_field(name=f"Developer: `xIntensity#4818`", value=f"Developer",)
await ctx.send(embed=embed)"""
"""
@commands.has_permissions(manage_guild=True)
@client.command()
async def editchannel(ctx, arg=None, channel_id=None):
connect = sqlite3.connect("files/edit_log.db")
cursor = connect.cursor()
if not arg:
await ctx.send(embed=error_embed("`<argument>` not specified.", "Please specify what you wish to do with `$editchannel`\nTyping `$help editchannel` will give you a list of `$editchannel` usages."))
else:
if arg == "-u":
cursor.execute(f"SELECT EXISTS(SELECT 1 FROM servers WHERE guild_id='{ctx.guild.id}')")
if cursor.fetchone()[0] == 0:
await ctx.send(embed=error_embed("This action could not be completed.", "Your server does not have a specified channel to log edited messages!"))
else:
try:
c = client.get_channel(int(channel_id))
if c == None:
await ctx.send(embed=error_embed("Invalid channel ID", "The `<channel_id>` you have entered is not valid."))
else:
cursor.execute(f"SELECT channel_id FROM servers WHERE guild_id={ctx.guild.id}")
if cursor.fetchone()[0] == int(channel_id):
await ctx.send(embed=error_embed("Channel already logging.", "The channel ID you have enter is already being used as a edited-message logger."))
else:
if str(client.get_channel(int(channel_id)).guild) != str((client.get_guild(ctx.guild.id)).name):
await ctx.send(embed=error_embed(f"Invalid channel ID `({channel_id})`", "Please enter a channel ID __within__ the server.\nChannels from other servers cannot be used."))
else:
cursor.execute(f"UPDATE servers SET channel_id={channel_id} WHERE guild_id={ctx.guild.id}")
await ctx.send(embed=success_embed("Action has been completed successfully!", f"All edited messages in `{ctx.guild.name}` are logged in {client.get_channel(int(channel_id)).mention}"))
connect.commit()
except ValueError:
await ctx.send(embed=error_embed("Incorrect data type","`<channel_id>` only accepts number data types! (You can't enter words)"))
elif arg == "-s":
cursor.execute(f"SELECT EXISTS(SELECT 1 FROM servers WHERE guild_id='{ctx.guild.id}')")
if cursor.fetchone()[0] == 0:
await ctx.send(embed=error_embed("This action could not be completed.", "Your server does not have a specified channel to log edited messages!"))
else:
cursor.execute(f"SELECT channel_id FROM servers WHERE guild_id={ctx.guild.id}")
channel = client.get_channel(cursor.fetchone()[0])
cursor.execute(f"DELETE from servers WHERE guild_id='{ctx.guild.id}'")
connect.commit()
server = client.get_guild(ctx.guild.id)
await ctx.send(embed=success_embed("Action has been completed successfully!", f"Edited messages no longer logged for `{server}`\nEdited messages no longer yielded in {channel.mention}"))
elif arg == "-a":
cursor.execute(f"SELECT * FROM servers WHERE guild_id={ctx.guild.id}")
if not cursor.fetchone():
try:
c = client.get_channel(int(channel_id))
if c == None:
await ctx.send(embed=error_embed("Invalid channel ID","The `<channel_id>` you have entered is not valid."))
else:
if str(client.get_channel(int(channel_id)).guild) != str((client.get_guild(ctx.guild.id)).name):
await ctx.send(embed=error_embed(f"Invalid channel ID `({channel_id})`","Please enter a channel ID __within__ the server.\nChannels from other servers cannot be used."))
else:
cursor.execute(f"INSERT INTO servers VALUES ({ctx.guild.id}, {channel_id})")
await ctx.send(embed=success_embed("Action has been completed successfully!",f"All edited messages in `{ctx.guild.name}` are logged in {client.get_channel(int(channel_id)).mention}"))
connect.commit()
except ValueError:
await ctx.send(embed=error_embed("Incorrect data type.","`<channel_id>` only accepts number data types! (You can't enter words)"))
else:
cursor.execute(f"SELECT channel_id FROM servers WHERE guild_id={ctx.guild.id}")
channel = client.get_channel(cursor.fetchone()[0])
await ctx.send(embed=error_embed("Existing Logging Channel",f"{channel.mention} has already been set for the edited-message logger.\nYou can update it with `$editchannel -u <channel_id>`"))
connect.close()
@commands.has_permissions(manage_guild=True)
@client.command()
async def delchannel(ctx, arg=None, channel_id=None):
connect = sqlite3.connect("files/message_log.db")
cursor = connect.cursor()
if not arg:
await ctx.send(embed=error_embed("`<argument>` not specified.","Please specify what you wish to do with `$delchannel`\nTyping `$help delchannel` will give you a list of `$delchannel` usages."))
else:
if arg == "-u":
cursor.execute(f"SELECT EXISTS(SELECT 1 FROM servers WHERE guild_id='{ctx.guild.id}')")
if cursor.fetchone()[0] == 0:
await ctx.send(embed=error_embed("No specified channel!","Your server does not have a specified channel to log deleted messages!"))
else:
try:
c = client.get_channel(int(channel_id))
if c == None:
await ctx.send(embed=error_embed("Invalid channel ID","The `<channel_id>` you have entered is not valid"))
else:
cursor.execute(f"SELECT channel_id FROM servers WHERE guild_id={ctx.guild.id}")
if cursor.fetchone()[0] == int(channel_id):
await ctx.send(embed=error_embed("Channel already logging.","The channel ID you have enter is already being used as a deleted-message logger."))
else:
if str(client.get_channel(int(channel_id)).guild) != str((client.get_guild(ctx.guild.id)).name):
await ctx.send(embed=error_embed(f"Invalid channel ID `({channel_id})`", "Please enter a channel ID __within__ the server.\nChannels from other servers cannot be used."))
else:
cursor.execute(f"UPDATE servers SET channel_id={channel_id} WHERE guild_id={ctx.guild.id}")
await ctx.send(embed=success_embed("Action has been completed successfully!",f"All deleted messages in `{ctx.guild.name}` are logged in {client.get_channel(int(channel_id)).mention}"))
connect.commit()
except ValueError:
await ctx.send(embed=error_embed("Incorrect data type.","`<channel_id>` only accepts number data types! (You can't enter words)"))
elif arg == "-s":
cursor.execute(f"SELECT EXISTS(SELECT 1 FROM servers WHERE guild_id='{ctx.guild.id}')")
if cursor.fetchone()[0] == 0:
await ctx.send(embed=error_embed("No specified channel!","Your server does not have a specified channel to log deleted messages!"))
else:
cursor.execute(f"SELECT channel_id FROM servers WHERE guild_id={ctx.guild.id}")
channel = client.get_channel(cursor.fetchone()[0])
cursor.execute(f"DELETE from servers WHERE guild_id='{ctx.guild.id}'")
connect.commit()
server = client.get_guild(ctx.guild.id)
await ctx.send(embed=success_embed("Action has been completed successfully!",f"Deleted messages no longer logged for `{server}`\nDeleted messages no longer yielded in {channel.mention}"))
elif arg == "-a":
cursor.execute(f"SELECT * FROM servers WHERE guild_id={ctx.guild.id}")
if not cursor.fetchone():
try:
c = client.get_channel(int(channel_id))
if c == None:
await ctx.send(embed=error_embed("Invalid channel ID","The `<channel_id>` you have entered is not valid."))
else:
if str(client.get_channel(int(channel_id)).guild) != str((client.get_guild(ctx.guild.id)).name):
await ctx.send(embed=error_embed(f"Invalid channel ID `({channel_id})`","Please enter a channel ID __within__ the server.\nChannels from other servers cannot be used."))
else:
cursor.execute(f"INSERT INTO servers VALUES ({ctx.guild.id}, {channel_id})")
await ctx.send(embed=success_embed("Action has been completed successfully!",f"All deleted messages in `{ctx.guild.name}` are logged in {client.get_channel(int(channel_id)).mention}"))
connect.commit()
except ValueError:
await ctx.send(embed=error_embed("Incorrect data type.","`<channel_id>` only accepts number data types! (You can't enter words)"))
else:
cursor.execute(f"SELECT channel_id FROM servers WHERE guild_id={ctx.guild.id}")
channel = client.get_channel(cursor.fetchone()[0])
await ctx.send(embed=error_embed("Existing Logging Channel",f"{channel.mention} has already been set for the deleted-message logger.\nYou can update it with `$delchannel -u <channel_id>`"))
connect.close()
else:
...
"""
"""
SLASH
slash = SlashCommand(client, sync_commands=True)
"""
"""
try:
for i in checklist:
for x in range(len(beforemsg[ctx.guild.id][i])):
textchannel = self.bot.get_channel(i)
w.write(f"\n\nBefore: {beforemsg[ctx.guild.id][i][x].content}\nAfter: {aftermsg[ctx.guild.id][i][x].content}\nEdited by {beforemsg[ctx.guild.id][i][x].author} in #{textchannel}")
"""
"""
@commands.command()
@commands.cooldown(rate=1,per=60)
async def permissions(self, ctx, arg=None, value=None):
if not arg:
embed=discord.Embed(color=0xfdfdfd) # work on the embed
elif arg in ["snipe","log","prefix"]:
if not value:
error_embed("Enter a role",f"No permission was provided for {arg}")
elif value in ["@n","@ms","@mm"]:
else:
error_embed("Invalid choice",f"`{value}` is not part of the valid permissions, `None (@n)`, `Manage Messages (@mm)`, and `Manage Server(@ms)`")
else:
error_embed("Invalid choice",f"`{arg}` is not part of the valid choices, `snipe`, `log`, and `prefix`")
"""
# all dict() directiories for beforemsg/aftermsg
#[ctx.guild.id] returns [{channel:[msg,msg1]},{channel2:[msg,msg1]}]
#[ctx.guild.id][x] assuming x = range(len()) of [ctx.guild.id] ]returns selected channel, reroutes to exception if there is no channel id
#[ctx.guild.id][x][i] assuming i = channelid list returns a list of stored messages for the channel
#[ctx.guild.id][x][i][z] returns a certain message
#exceptions cannot be toggled |
"""
Given an array of positive integers nums and a positive integer target, return the minimal length of a contiguous subarray [numsl, numsl+1, ..., numsr-1, numsr] of which the sum is greater than or equal to target. If there is no such subarray, return 0 instead.
Example 1:
Input: target = 7, nums = [2,3,1,2,4,3]
Output: 2
Explanation: The subarray [4,3] has the minimal length under the problem constraint.
Example 2:
Input: target = 4, nums = [1,4,4]
Output: 1
Example 3:
Input: target = 11, nums = [1,1,1,1,1,1,1,1]
Output: 0
Constraints:
1 <= target <= 10^9
1 <= nums.length <= 10^5
1 <= nums[i] <= 10^5
Follow up: If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log(n)).
"""
class Solution:
def minSubArrayLen(self, target: int, nums: List[int]) -> int:
min_length = float("inf")
left = 0
right = 0
current = nums[0]
while left < len(nums) and right < len(nums):
if current >= target:
min_length = min(min_length, right - left + 1)
current -= nums[left]
left += 1
else:
right += 1
if right < len(nums):
current += nums[right]
if min_length == float("inf"):
return 0
else:
return min_length
|
# calculations
print('plus:', 1 + 2, 'minus:', 1 - 2, 'multiple:', 4 * 5, 'division:', 7 / 5)
print('share:', 7 // 5, 'rest:', 7 % 5, 'square:', 3 ** 2)
# data types
print('types:', type(10), type(1.0), type('a'))
# variables
x = 10 # initialization and substisution
print('x:', x)
x = 100 # substisution
print('x:', x)
# list
arr = [1, 2, 3, 4, 5]
print('list:', arr, 'len of list:', len(arr))
arr[4] = 99 # substitution
print('list:', arr)
print('accessing:', arr[0])
print('slicing:', arr[0:2], arr[1:], arr[:3], arr[:-1])
# dictionary
dic = {'a': 1, 'b': 2}
print('accessing:', dic['a'])
dic['c'] = 3 # initialization and substisution
print('dict:', dic)
# booleans
a, b = True, False
print('booleans:', type(a))
print('compares:', a and b, a or b, not b)
# if
if a:
print('check: a is True.')
if not b:
print('check: b is False.')
# for
for i in [1, 2, 3, 4, 5]:
print(i, end=' ')
print()
# function
def greeting():
print('Hello, python!')
greeting()
|
# Practice Quiz: Object-oriented programming
# 1. Let's test your knowledge of using dot notation to access methods
# and attributes in an object. Let's say we have a class called Birds.
# Birds has two attributes: color and number. Birds also has a
# method called count() that counts the number of birds (adds a
# value to number). Which of the following lines of code will correctly
# print the number of birds? Keep in mind, the number of birds is 0
# until they are counted!
# 2. Creating new instances of class objects can be a great way to keep
# track of values using attributes associated with the object. The
# values of these attributes can be easily changed at the object level.
# The following code illustrates a famous quote by George Bernard
# Shaw, using objects to represent people. Fill in the blanks to make
# the code satisfy the behavior described in the quote.
# "If you have an apple and I have an apple and we exchanged these apples then
# you and I will still each have one apple. But if you have an idea and I have
# an idea and we exchanged these ideas, then each of us will have two ideas."
# Geo Bernard Shaw
class Person:
apples = 0
ideas = 0
johanna = Person()
johanna.apples = 1
johanna.ideas = 1
martin = Person()
martin.apples = 2
martin.ideas = 1
def exchanges_apples(you, me):
# Here, despite G.B Shaw's quote, our characters have started with # different amount of apples so we can better observe the results.
# We're going to have Martin and Johanna exchange All their apples with # one another.
# Hint: how would you switch values of variables.
# so that "you" and "me" will exchange ALL their apples with one another?
# Do you need a temporary variable to store one of the values?
# You may need more than one line of code to do that, which is OK.
temp = you.apples
you.apples = me.apples
me.apples = temp
return you.apples, me.apples
def exchange_ideas(you, me):
# "you" and "me" will share our ideas with one another.
# What operations need to be performed, so that each object receives
# the shared number of ideas?
# Hint: how would you assign the total number of of ideas to
# each idea attribute? Do you need a temporary variable to store
# the sum of ideas, or can you find another way?
# Use as many lines of code as you need here.
temp = you.ideas
you.ideas = me.ideas
me.ideas = temp
return you.ideas, me.ideas
johanna.apples, martin.apples = exchanges_apples(johanna, martin)
print("Johanna has {} apples and Martin has {} apples".format(johanna.apples, martin.apples))
ohanna.ideas, martin.ideas = exchange_ideas(johanna, martin)
print("Johanna has {} ideas and Martin has {} ideas".format(johanna.ideas, martin.ideas))
# 3. The City class has the following attributes: name, country (where the city is located)
# elevation (measured in meters) and population (approximate, according to recent statistics).
# Fill in the blanks of the max_elevation_city function to return the name of the city and its
# country (separated by a comma). When comparing the 3 defined instances for a specified
# minimal population. For example, calling the function of a minimum population of 1 million:
# max_elevation_city(1000000) should return "Sofia, Bulgaria".
# define a basic city class
class City:
name = ""
country = ""
elevation = 0
population = 0
# create a new instance of the City class and
# define each attribute
City1 = City()
City1.name = "Cusco"
City1.country = "Peru"
City1.elevation = 3399
City1.population = 358052
# create a new instance of the City class adnd
# define each attribute
City2 = City()
City2.name = "Sofia"
City2.country = "Bulgaria"
City2.elevation = 2290
City2.population = 1241675
# create a new instance of the City class and
# define each attribute
City3 = City()
City3.name = "Seoul"
City3.country = "South Korea"
City3.elevation = 38
City3.population = 9733509
def max_elevation_city(min_population):
# Initialize the variable that will hold
# the information of the city with
# the highest elevation
return_city = City()
# Evaluate the 1st instance to meet the requirements:
# does city #1 have at least min_population and
# is its elevation the highest so far?
if min_population < City1.population and City1.elevation > return_city.elevation:
return_city = City1
# Evaluate the 1st instance to meet the requirements:
# does city #1 have at least min_population and
# is its elevation the highest so far?
if min_population < City2.population and City2.elevation > return_city.elevation:
return_city = City2
# Evaluate the 1st instance to meet the requirements:
# does city #1 have at least min_population and
# is its elevation the highest so far?
if min_population < City3.population and City3.elevation > return_city.elevation:
return_city = City3
# Format the return string
if return_city.name:
return f"{return_city.name}, {return_city.country}"
else:
return ""
print(max_elevation_city(100000)) # Should print "Cusco, Peru"
print(max_elevation_city(1000000)) # Should print "Sofia, Bulgaria"
print(max_elevation_city(10000000)) # Should print ""
# 5. We have two pieces of furniture: a brown wood table and red leather couch. Fill in the
# blanks creation of each Furniture class instance, so that describe_furniture function can
# format a sentence that describes these pieces as follows: "This piece of furniture is made
# of {color} {material}
class Furniture:
color = ""
material = ""
table = Furniture()
table.color = "brown"
table.material = "wood"
couch = Furniture()
couch.color = "red"
couch.material = "leather"
def describe_furniture(piece):
return ("This piece of furniture is made of {} {}".format(piece.color, piece.material))
print(describe_furniture(table))
# Should be "This piece of furniture is made of brown wood"
print(describe_furniture(couch))
# Should be "This piece of furniture is made of red leather"
|
# Given a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original
# BST is changed to the original key plus sum of all keys greater than the original key in BST.
# ex
# Input: The root of a Binary Search Tree like this:
# 5
# / \
# 2 13
#
# Output: The root of a Greater Tree like this:
# 18
# / \
# 20 13
# High Level Idea:
# Use a depth first search to the very right node, and traverse the tree in descending order
# Keep a running total global variable called running sum that is accessable by each recursive call,
# and increase the current root's value by running sum at each function call.
# NOTE. Since variables in Python are immutable, we are declaring runningSum as a list instead--
# lists are mutable so this solves the issue.
class Solution:
def convertBST(self, root):
# lists are mutable
runningSum = [0]
return self.helper(root, runningSum)
#recursive function
def helper(self, root, runningSum):
if root == None:
return
#traverse all the way down to the right (greatest element)
self.helper(root.right, runningSum)
curVal = root.val
root.val += runningSum[0]
runningSum[0] += curVal
self.helper(root.left, runningSum)
#return value is just for the convertBST function
return root
|
#: Regular expression for a valid GitHub username or organization name. As of
#: 2017-07-23, trying to sign up to GitHub with an invalid username or create
#: an organization with an invalid name gives the message "Username may only
#: contain alphanumeric characters or single hyphens, and cannot begin or end
#: with a hyphen". Additionally, trying to create a user named "none" (case
#: insensitive) gives the message "Username name 'none' is a reserved word."
#:
#: Unfortunately, there are a number of users who made accounts before the
#: current name restrictions were put in place, and so this regex also needs to
#: accept names that contain underscores, contain multiple consecutive hyphens,
#: begin with a hyphen, and/or end with a hyphen.
GH_USER_RGX = r'(?![Nn][Oo][Nn][Ee]($|[^-A-Za-z0-9]))[-_A-Za-z0-9]+'
#GH_USER_RGX_DE_JURE = r'(?![Nn][Oo][Nn][Ee]($|[^-A-Za-z0-9]))'\
# r'[A-Za-z0-9](?:-?[A-Za-z0-9])*'
#: Regular expression for a valid GitHub repository name. Testing as of
#: 2017-05-21 indicates that repository names can be composed of alphanumeric
#: ASCII characters, hyphens, periods, and/or underscores, with the names ``.``
#: and ``..`` being reserved and names ending with ``.git`` forbidden.
GH_REPO_RGX = r'(?:\.?[-A-Za-z0-9_][-A-Za-z0-9_.]*|\.\.[-A-Za-z0-9_.]+)'\
r'(?<!\.git)'
_REF_COMPONENT = r'(?!\.)[^\x00-\x20/~^:?*[\\\x7F]+(?<!\.lock)'
#: Regular expression for a (possibly one-level) valid normalized Git refname
#: (e.g., a branch or tag name) as specified in
#: :manpage:`git-check-ref-format(1)`
#: <https://git-scm.com/docs/git-check-ref-format> as of 2017-07-23 (Git
#: 2.13.1)
GIT_REFNAME_RGX = r'(?!@/?$)(?!.*(?:\.\.|@\{{)){0}(?:/{0})*(?<!\.)'\
.format(_REF_COMPONENT)
#: Convenience regular expression for ``<owner>/<repo>``, including named
#: capturing groups
OWNER_REPO_RGX = fr'(?P<owner>{GH_USER_RGX})/(?P<repo>{GH_REPO_RGX})'
API_REPO_RGX = r'(?:https?://)?api\.github\.com/repos/' + OWNER_REPO_RGX
WEB_REPO_RGX = r'(?:https?://)?(?:www\.)?github\.com/' + OWNER_REPO_RGX
|
# test builtin abs
print(abs(False))
print(abs(True))
print(abs(1))
print(abs(-1))
print("PASS") |
# 1. Создать произвольный словарь
# 2. Добавить новый элемент с ключом типа str и значением типа int
# 3. Добавить новый элемент с ключом типа кортеж(tuple) и значением типа список(list)
# 4. Получить элемент по ключу
# 5. Удалить элемент по ключу
# 6. Получить список ключей словаря
dict_one = {'key1': 'value1', 'key2': 'value2'}
print(dict_one)
dict_one['key3'] = 22
print(dict_one)
dict_one[('one', 'two', 'three')] = [1, 'four', "five"]
print(dict_one)
get_el_by_key = dict_one.get('key2')
print(get_el_by_key)
del_el_by_key = dict_one.pop('key3')
print(dict_one)
keys = dict_one.keys()
print(keys)
#Do some changes for another branch
|
class Solution:
def simplifyPath(self, path: str) -> str:
"""
Given an absolute path for a file (Unix-style), simplify it. Or in other
words, convert it to the canonical path.
In a UNIX-style file system, a period . refers to the current directory.
Furthermore, a double period .. moves the directory up a level. For more
information, see: Absolute path vs relative path in Linux/Unix
Note that the returned canonical path must always begin with a slash /,
and there must be only a single slash / between two directory names. The
last directory name (if it exists) must not end with a trailing /. Also,
the canonical path must be the shortest string representing the absolute path.
"""
#side case
if path=="/":
return "/"
#init
result_str_compents=[]
i=0
#code
source_str_compents=path.split('/')
source_str_compents=source_str_compents[1:]
for i in range(len(source_str_compents)):
if source_str_compents[i]=="" or source_str_compents[i]==".":
continue
if source_str_compents[i]=="..":
if len(result_str_compents)>0:
result_str_compents=result_str_compents[:-1]
continue
result_str_compents.append(source_str_compents[i])
return '/'+'/'.join(result_str_compents)
if __name__=="__main__":
solu=Solution()
assert(solu.simplifyPath("/home/")=="/home")
assert(solu.simplifyPath("/home/..")=="/")
assert(solu.simplifyPath("/home/../..")=="/")
assert(solu.simplifyPath("/home/../../sss")=="/sss") |
# full run list
# shape: {number: type} (all string)
# select the run numbers or types to be opened with nRunToOpen...
nRun0 = {}
|
# https://adventofcode.com/2020/day/5
#part 1
with open("./input_day5.txt", encoding="utf-8") as input:
seat_codes = input.readlines()
def half(direction, low, high, lower_half):
if high-low == 1:
return low if direction[0] == lower_half else high
if direction[0] == lower_half:
high = low + (high-low)//2
else:
low = low + (high-low)//2 +1
return half(direction[1:],low, high, lower_half)
seats=[]
for code in seat_codes:
code = code.strip() # remove newline
row, col = half(code[:7],0,127,"F"), half(code[7:],0,7,"L")
seats.append(row*8+col)
print(f"Highest seat: {max(seats)}")
#part 2
seats = sorted(seats)
#zipped seats: (513,514) (514,516) << my_seat is the gap: 514+1
my_seat = [seat[0]+1 for seat in zip(seats[:-1], seats[1:]) if seat[0]+1 != seat[1]][0]
print(f"My seat is {my_seat}")
#print([seat[0]+1 for seat in zip(seats[:-1], seats[1:]) if seat[0]+1 != seat[1]])
|
# 1-T ismlar degan ro'yxat yarating va kamida 3 ta yaqin do'stingizning ismini kiriting
ismlar = ["Anvar","Ulug'bek","Umid"]
# 2- T Ro'yxatdagi har bir do'stingizga qisqa xabar yozib konsolga chiqaring:
print(f"Salom {ismlar[0]},bugun choyxona bormi.\n{ismlar[1]} bugun choyxonaga boramizmi?.\n{ismlar[2]} ishingdan chiqib menga tel qilgin.")
# 3-T sonlar deb nomlangan ro'yxat yarating va ichiga turli sonlarni yuklang (musbat, manfiy, butun, o'nlik).
sonlar = [3,5,546,-563,33.3,1]
# tuplamning 3-index ga 777 soni yuklandi
sonlar[3]=777
print(sonlar)
# tuplamning 2-indexiga 571 element yuklandi.
sonlar.insert(2,571)
# tuplamdan 33.3 elementi uchirib tashlandi.
sonlar.remove(33.3)
print(sonlar)
# tuplmaga 234324 elementi qushildi.
sonlar.append(234324)
# tuplamdan 4 -indexdagi eement uchirib tashlandi.
del sonlar[4]
print(sonlar)
# tuplamdan 3 elementi ug'irib olindi
son1=sonlar.pop(3)
print(son1)
# 7-T Yuqoridagi ro'yxatdan mehmonga kela olmaydigan odamlarni .remove() metodi yordamida o'chrib tashlang.
mehmonlar =["kursdoshlar","qarindoshlar","Do'stlar"]
mehmonlar.remove("kursdoshlar")
print(mehmonlar)
friends=[]
kk=mehmonlar.pop(0)
friends.append(kk)
print(friends) |
error_codes = {
'address_incorrect':
'Enter proxy address in correct format.',
'port_incorrect':
'Proxy port should be an integer between 0 and 65535.',
'credentials_incorrect':
'Only username or only password cannot be null.'
}
class Credentials:
"""
Class to hold the proxy credentials. Local variables http, https, and ftp
holds dictionaries whose keys are 'user', 'password', 'proxy', and 'port'.
Typical dictionary format of self.data:
{
'noproxy': False,
'sameproxy': True, # Implies that same proxy credentials for http,
# ftp and https
'http': {
'proxy': '192.168.0.4',
'port': '3128',
'user': 'rushi',
'password': 'rushi_pass'
}
}
"""
def __init__(self, data):
self.data = data
if self.data['noproxy'] is False:
if self.data['sameproxy'] is True:
self.data['https'] = self.data['http']
self.data['ftp'] = self.data['http']
def validate(self):
"""
Checks if the credentials are in proper format.
Returns (possibly empty) list of errors.
"""
errors = []
# If we're not using proxy, validation not required
if self.data['noproxy'] is True:
return errors
proxies = ['http', 'https', 'ftp']
# Error checking for: proxy address
for proxy in proxies:
# Break loop if the error we're trying to find is already found
if error_codes['address_incorrect'] in errors:
break
split_address = self.data[proxy]['proxy'].split('.')
if len(split_address) is not 4:
errors.append(error_codes['address_incorrect'])
break
else:
for part in split_address:
if not part.isdigit():
errors.append(error_codes['address_incorrect'])
break
if int(part) > 255 or int(part) < 0:
errors.append(error_codes['address_incorrect'])
break
# Error checking for: proxy port
for proxy in proxies:
port = self.data[proxy]['port']
if not port.isdigit() or int(port) > 65535 or int(port) < 0:
errors.append(error_codes['port_incorrect'])
break
# Error checking for: proxy username and password
for proxy in proxies:
user = self.data[proxy]['user']
password = self.data[proxy]['password']
if (len(user) is 0 and len(password) is not 0) or \
(len(user) is not 0 and len(password) is 0):
errors.append(error_codes['credentials_incorrect'])
break
return errors
|
# STUB: do NOT upload to the ESP, it's used to run the tests
def alloc_emergency_exception_buf():
"""stub method."""
def const(self):
return 20000
def heap_lock():
"""stub method."""
def heap_unlock():
"""stub method."""
def kbd_intr():
"""stub method."""
def mem_info():
"""stub method."""
def opt_level():
"""stub method."""
def qstr_info():
"""stub method."""
def schedule():
"""stub method."""
def stack_use():
"""stub method."""
|
snake = "Python!"
langth = 42
sckary = True
if sckary:
print("Ahhh!!!")
else:
print("Phew!!!")
for letter in snake:
print(letter)
def grow(size):
global langth
langth = langth + size
print("The python is now {}m long!".format(langth))
grow(3)
class Employee:
# Common base count for all employees!
empCount = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def displayEmployee(self):
print("Name: {}, Salary: ${}".format(self.name, self.salary))
emp1 = Employee("Zara", 2000)
emp2 = Employee("Manni", 5000)
emp1.displayEmployee()
emp2.displayEmployee()
print("Employee Total: {}".format(Employee.empCount))
|
class Solution:
def reconstructMatrix(self, upper: int, lower: int, colsum: 'List[int]') -> 'List[List[int]]':
if sum(colsum) != upper + lower:
return []
n = len(colsum)
res = [[0] * n for _ in range(2)]
def solve(k, u, l):
if u < 0 or l < 0:
return False
if k == n:
return u == 0 and l == 0
if colsum[k] == 0:
res[0][k] = 0
res[1][k] = 0
return solve(k + 1, u, l)
if colsum[k] == 2:
res[0][k] = 1
res[1][k] = 1
return solve(k + 1, u - 1, l - 1)
res[0][k] = 1
res[1][k] = 0
if solve(k + 1, u - 1, l):
return True
res[0][k] = 0
res[1][k] = 1
return solve(k + 1, u, l - 1)
if solve(0, upper, lower):
return res
return []
s = Solution()
print(s.reconstructMatrix(99,
102,
[2,1,1,1,1,2,0,2,2,2,0,1,0,0,2,1,1,1,2,2,1,2,1,1,1,1,2,0,1,2,1,1,2,2,1,0,2,0,1,0,0,1,0,1,0,1,2,1,0,1,1,0,2,1,1,0,1,0,1,0,1,0,1,1,2,1,1,2,2,1,1,2,2,2,0,1,1,0,0,1,1,1,1,0,0,2,1,1,1,2,1,1,2,1,0,1,2,0,1,1,2,2,2,1,1,2,2,2,0,2,1,2,2,1,0,1,1,1,1,0,1,1,1,2,0,1,0,2,1,2,1,1,2,1,1,2,1,1,1,1,0,2,0,1,0,0,1,1,1,0,1,1,0,0,2,0,0,1,1,1,0,0,2,2,1,1,1,1,1,1,0,2,1,1,0,1,2,1,2,0,1,0,1,1,1,0,1,1,0,0,0,0,1,2,2,2,1,1,0,2]))
|
class Solution:
def climbStairs(self, n: int) -> int:
f0 = f1 = 1
for _ in range(n):
f0, f1 = f1, f0 + f1
return f0
if __name__ == "__main__":
solver = Solution()
print(solver.climbStairs(2))
print(solver.climbStairs(3))
|
class dotRebarGroup_t(object):
# no doc
aSpacingMultipliers = None
aSpacings = None
aX = None
aY = None
aZ = None
EndHook = None
EndPoint = None
ExcludeType = None
nPointsInPolygon = None
nPolygons = None
nSpacingValues = None
Reinforcement = None
SpacingType = None
StartHook = None
StartPoint = None
StirrupType = None
SubType = None
|
"""
Project Euler - Problem Solution 007
Copyright (c) Justin McGettigan. All rights reserved.
https://github.com/jwmcgettigan/project-euler-solutions
"""
def get_nth_prime(nth):
limit = nth
primes, composites = set(), set()
num_primes = 0
while(num_primes < nth):
limit *= 2 # increase the limit if there are less than nth primes
for i in range(2, limit+1):
if i not in composites:
if i not in primes:
primes.add(i)
if(len(primes) == nth):
return i
for j in range(i*i, limit+1, i):
composites.add(j)
num_primes = len(primes)
if __name__ == "__main__":
print(get_nth_prime(10001)) |
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
mapping = {
"2": "abc",
"3": "def",
"4": "ghi",
"5": "jkl",
"6": "mno",
"7": "pqrs",
"8": "tuv",
"9": "wxyz"
}
length = len(digits)
res = []
if (length == 0):
return res
def backtrack(index, candidate, digits, res):
if index == len(digits):
res.append(candidate)
return
for next_char in mapping[digits[index]]:
candidate += next_char
backtrack(index + 1, candidate, digits, res)
candidate = candidate[0:-1]
backtrack(0, "", digits, res)
return res |
def get_sub_expression(expression):
opening_bracket_indices = []
sub_expressons = []
for i in range(len(expression)):
ch = expression[i]
if ch == "(":
opening_bracket_indices.append(i)
elif ch == ")":
start_index = opening_bracket_indices.pop()
end_index = i
sub_expressons.append(
expression[start_index:end_index + 1]
)
return sub_expressons
expression = input()
sub_expressions = get_sub_expression(expression)
[print(exp) for exp in sub_expressions]
|
# https://leetcode.com/problems/largest-odd-number-in-string/
class Solution:
def largestOddNumber(self, num: str) -> str:
flag = True
for i in range(len(num)-1, -1, -1):
if int(num[i]) % 2 != 0:
return num[:i+1]
else:
continue
if flag:
return ""
|
train_data_dir = "trainingData"
test_data_dir = "testData"
original_data_dir = "data/HAM10000_images_part_1"
original_test_data_dir = "data/HAM10000_images_part_2"
##### HYPERPARAMETERS
# NN_IMAGE_COUNT = sample_count_in_folder(train_data_dir)
NN_BATCH_SIZE = 2
NN_CLASSIFIER_WIDTH = 256
NN_EPOCH_COUNT = 200
NN_FINETUNE_EPOCHS = 200
NN_VALIDATION_PROPORTION = 0.2
NN_TARGET_WIDTH = 224
NN_TARGET_HEIGHT = 224
NN_LEARNING_RATE = 1e-6
|
def threeNumberSum(array, targetSum):
array.sort()
results = []
init = array.pop(0)
queue = [([init], init)]
while array:
new = array.pop(0)
arr = [(q[0] + [new], q[1] + new) for q in queue]
queue.append(([new], new))
for tp in arr:
if len(tp[0]) < 3:
queue.append(tp)
elif tp[1] == targetSum:
results.append(tp[0])
results.sort()
return results
|
# Copyright 2020 Ecosoft Co., Ltd. (http://ecosoft.co.th)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "NxPO - Employee Division",
"version": "14.0.1.0.0",
"license": "AGPL-3",
"category": "NxPO",
"author": "Ecosoft",
"depends": ["hr"],
"data": [
"security/ir.model.access.csv",
"views/hr_division_views.xml",
"views/hr_department_views.xml",
],
"installable": True,
"maintainers": ["Saran440"],
}
|
"""Helper function which holds data from unicodedata library."""
#
# (C) Pywikibot team, 2018-2020
#
# Distributed under the terms of the MIT license.
#
# A mapping of characters to their MediaWiki title-cased forms. Python,
# depending on version, handles these characters differently, which causes
# errors in normalizing titles. (T200357) This dict was created using
# Python 3.7 (Unicode version 11.0.0) and should be updated at least with every
# new release of Python with an updated unicodedata.unidata_version.
_first_upper_exception_dict = {
'\xdf': '\xdf', '\u0149': '\u0149', '\u0180': '\u0180', '\u019a': '\u019a',
'\u01c5': '\u01c5', '\u01c6': '\u01c5', '\u01c8': '\u01c8', '\u01c9':
'\u01c8', '\u01cb': '\u01cb', '\u01cc': '\u01cb', '\u01f0': '\u01f0',
'\u01f2': '\u01f2', '\u01f3': '\u01f2', '\u023c': '\u023c', '\u023f':
'\u023f', '\u0240': '\u0240', '\u0242': '\u0242', '\u0247': '\u0247',
'\u0249': '\u0249', '\u024b': '\u024b', '\u024d': '\u024d', '\u024f':
'\u024f', '\u0250': '\u0250', '\u0251': '\u0251', '\u0252': '\u0252',
'\u025c': '\u025c', '\u0261': '\u0261', '\u0265': '\u0265', '\u0266':
'\u0266', '\u026a': '\u026a', '\u026b': '\u026b', '\u026c': '\u026c',
'\u0271': '\u0271', '\u027d': '\u027d', '\u0287': '\u0287', '\u0289':
'\u0289', '\u028c': '\u028c', '\u029d': '\u029d', '\u029e': '\u029e',
'\u0345': '\u0345', '\u0371': '\u0371', '\u0373': '\u0373', '\u0377':
'\u0377', '\u037b': '\u037b', '\u037c': '\u037c', '\u037d': '\u037d',
'\u0390': '\u0390', '\u03b0': '\u03b0', '\u03d7': '\u03d7', '\u03f2':
'\u03a3', '\u03f3': '\u03f3', '\u03f8': '\u03f8', '\u03fb': '\u03fb',
'\u04cf': '\u04cf', '\u04f7': '\u04f7', '\u04fb': '\u04fb', '\u04fd':
'\u04fd', '\u04ff': '\u04ff', '\u0511': '\u0511', '\u0513': '\u0513',
'\u0515': '\u0515', '\u0517': '\u0517', '\u0519': '\u0519', '\u051b':
'\u051b', '\u051d': '\u051d', '\u051f': '\u051f', '\u0521': '\u0521',
'\u0523': '\u0523', '\u0525': '\u0525', '\u0527': '\u0527', '\u0529':
'\u0529', '\u052b': '\u052b', '\u052d': '\u052d', '\u052f': '\u052f',
'\u0587': '\u0587', '\u10d0': '\u10d0', '\u10d1': '\u10d1', '\u10d2':
'\u10d2', '\u10d3': '\u10d3', '\u10d4': '\u10d4', '\u10d5': '\u10d5',
'\u10d6': '\u10d6', '\u10d7': '\u10d7', '\u10d8': '\u10d8', '\u10d9':
'\u10d9', '\u10da': '\u10da', '\u10db': '\u10db', '\u10dc': '\u10dc',
'\u10dd': '\u10dd', '\u10de': '\u10de', '\u10df': '\u10df', '\u10e0':
'\u10e0', '\u10e1': '\u10e1', '\u10e2': '\u10e2', '\u10e3': '\u10e3',
'\u10e4': '\u10e4', '\u10e5': '\u10e5', '\u10e6': '\u10e6', '\u10e7':
'\u10e7', '\u10e8': '\u10e8', '\u10e9': '\u10e9', '\u10ea': '\u10ea',
'\u10eb': '\u10eb', '\u10ec': '\u10ec', '\u10ed': '\u10ed', '\u10ee':
'\u10ee', '\u10ef': '\u10ef', '\u10f0': '\u10f0', '\u10f1': '\u10f1',
'\u10f2': '\u10f2', '\u10f3': '\u10f3', '\u10f4': '\u10f4', '\u10f5':
'\u10f5', '\u10f6': '\u10f6', '\u10f7': '\u10f7', '\u10f8': '\u10f8',
'\u10f9': '\u10f9', '\u10fa': '\u10fa', '\u10fd': '\u10fd', '\u10fe':
'\u10fe', '\u10ff': '\u10ff', '\u13f8': '\u13f8', '\u13f9': '\u13f9',
'\u13fa': '\u13fa', '\u13fb': '\u13fb', '\u13fc': '\u13fc', '\u13fd':
'\u13fd', '\u1c80': '\u1c80', '\u1c81': '\u1c81', '\u1c82': '\u1c82',
'\u1c83': '\u1c83', '\u1c84': '\u1c84', '\u1c85': '\u1c85', '\u1c86':
'\u1c86', '\u1c87': '\u1c87', '\u1c88': '\u1c88', '\u1d79': '\u1d79',
'\u1d7d': '\u1d7d', '\u1e96': '\u1e96', '\u1e97': '\u1e97', '\u1e98':
'\u1e98', '\u1e99': '\u1e99', '\u1e9a': '\u1e9a', '\u1efb': '\u1efb',
'\u1efd': '\u1efd', '\u1eff': '\u1eff', '\u1f50': '\u1f50', '\u1f52':
'\u1f52', '\u1f54': '\u1f54', '\u1f56': '\u1f56', '\u1f71': '\u0386',
'\u1f73': '\u0388', '\u1f75': '\u0389', '\u1f77': '\u038a', '\u1f79':
'\u038c', '\u1f7b': '\u038e', '\u1f7d': '\u038f', '\u1f80': '\u1f88',
'\u1f81': '\u1f89', '\u1f82': '\u1f8a', '\u1f83': '\u1f8b', '\u1f84':
'\u1f8c', '\u1f85': '\u1f8d', '\u1f86': '\u1f8e', '\u1f87': '\u1f8f',
'\u1f88': '\u1f88', '\u1f89': '\u1f89', '\u1f8a': '\u1f8a', '\u1f8b':
'\u1f8b', '\u1f8c': '\u1f8c', '\u1f8d': '\u1f8d', '\u1f8e': '\u1f8e',
'\u1f8f': '\u1f8f', '\u1f90': '\u1f98', '\u1f91': '\u1f99', '\u1f92':
'\u1f9a', '\u1f93': '\u1f9b', '\u1f94': '\u1f9c', '\u1f95': '\u1f9d',
'\u1f96': '\u1f9e', '\u1f97': '\u1f9f', '\u1f98': '\u1f98', '\u1f99':
'\u1f99', '\u1f9a': '\u1f9a', '\u1f9b': '\u1f9b', '\u1f9c': '\u1f9c',
'\u1f9d': '\u1f9d', '\u1f9e': '\u1f9e', '\u1f9f': '\u1f9f', '\u1fa0':
'\u1fa8', '\u1fa1': '\u1fa9', '\u1fa2': '\u1faa', '\u1fa3': '\u1fab',
'\u1fa4': '\u1fac', '\u1fa5': '\u1fad', '\u1fa6': '\u1fae', '\u1fa7':
'\u1faf', '\u1fa8': '\u1fa8', '\u1fa9': '\u1fa9', '\u1faa': '\u1faa',
'\u1fab': '\u1fab', '\u1fac': '\u1fac', '\u1fad': '\u1fad', '\u1fae':
'\u1fae', '\u1faf': '\u1faf', '\u1fb2': '\u1fb2', '\u1fb3': '\u1fbc',
'\u1fb4': '\u1fb4', '\u1fb6': '\u1fb6', '\u1fb7': '\u1fb7', '\u1fbc':
'\u1fbc', '\u1fc2': '\u1fc2', '\u1fc3': '\u1fcc', '\u1fc4': '\u1fc4',
'\u1fc6': '\u1fc6', '\u1fc7': '\u1fc7', '\u1fcc': '\u1fcc', '\u1fd2':
'\u1fd2', '\u1fd3': '\u0390', '\u1fd6': '\u1fd6', '\u1fd7': '\u1fd7',
'\u1fe2': '\u1fe2', '\u1fe3': '\u03b0', '\u1fe4': '\u1fe4', '\u1fe6':
'\u1fe6', '\u1fe7': '\u1fe7', '\u1ff2': '\u1ff2', '\u1ff3': '\u1ffc',
'\u1ff4': '\u1ff4', '\u1ff6': '\u1ff6', '\u1ff7': '\u1ff7', '\u1ffc':
'\u1ffc', '\u214e': '\u214e', '\u2170': '\u2170', '\u2171': '\u2171',
'\u2172': '\u2172', '\u2173': '\u2173', '\u2174': '\u2174', '\u2175':
'\u2175', '\u2176': '\u2176', '\u2177': '\u2177', '\u2178': '\u2178',
'\u2179': '\u2179', '\u217a': '\u217a', '\u217b': '\u217b', '\u217c':
'\u217c', '\u217d': '\u217d', '\u217e': '\u217e', '\u217f': '\u217f',
'\u2184': '\u2184', '\u24d0': '\u24d0', '\u24d1': '\u24d1', '\u24d2':
'\u24d2', '\u24d3': '\u24d3', '\u24d4': '\u24d4', '\u24d5': '\u24d5',
'\u24d6': '\u24d6', '\u24d7': '\u24d7', '\u24d8': '\u24d8', '\u24d9':
'\u24d9', '\u24da': '\u24da', '\u24db': '\u24db', '\u24dc': '\u24dc',
'\u24dd': '\u24dd', '\u24de': '\u24de', '\u24df': '\u24df', '\u24e0':
'\u24e0', '\u24e1': '\u24e1', '\u24e2': '\u24e2', '\u24e3': '\u24e3',
'\u24e4': '\u24e4', '\u24e5': '\u24e5', '\u24e6': '\u24e6', '\u24e7':
'\u24e7', '\u24e8': '\u24e8', '\u24e9': '\u24e9', '\u2c30': '\u2c30',
'\u2c31': '\u2c31', '\u2c32': '\u2c32', '\u2c33': '\u2c33', '\u2c34':
'\u2c34', '\u2c35': '\u2c35', '\u2c36': '\u2c36', '\u2c37': '\u2c37',
'\u2c38': '\u2c38', '\u2c39': '\u2c39', '\u2c3a': '\u2c3a', '\u2c3b':
'\u2c3b', '\u2c3c': '\u2c3c', '\u2c3d': '\u2c3d', '\u2c3e': '\u2c3e',
'\u2c3f': '\u2c3f', '\u2c40': '\u2c40', '\u2c41': '\u2c41', '\u2c42':
'\u2c42', '\u2c43': '\u2c43', '\u2c44': '\u2c44', '\u2c45': '\u2c45',
'\u2c46': '\u2c46', '\u2c47': '\u2c47', '\u2c48': '\u2c48', '\u2c49':
'\u2c49', '\u2c4a': '\u2c4a', '\u2c4b': '\u2c4b', '\u2c4c': '\u2c4c',
'\u2c4d': '\u2c4d', '\u2c4e': '\u2c4e', '\u2c4f': '\u2c4f', '\u2c50':
'\u2c50', '\u2c51': '\u2c51', '\u2c52': '\u2c52', '\u2c53': '\u2c53',
'\u2c54': '\u2c54', '\u2c55': '\u2c55', '\u2c56': '\u2c56', '\u2c57':
'\u2c57', '\u2c58': '\u2c58', '\u2c59': '\u2c59', '\u2c5a': '\u2c5a',
'\u2c5b': '\u2c5b', '\u2c5c': '\u2c5c', '\u2c5d': '\u2c5d', '\u2c5e':
'\u2c5e', '\u2c61': '\u2c61', '\u2c65': '\u2c65', '\u2c66': '\u2c66',
'\u2c68': '\u2c68', '\u2c6a': '\u2c6a', '\u2c6c': '\u2c6c', '\u2c73':
'\u2c73', '\u2c76': '\u2c76', '\u2c81': '\u2c81', '\u2c83': '\u2c83',
'\u2c85': '\u2c85', '\u2c87': '\u2c87', '\u2c89': '\u2c89', '\u2c8b':
'\u2c8b', '\u2c8d': '\u2c8d', '\u2c8f': '\u2c8f', '\u2c91': '\u2c91',
'\u2c93': '\u2c93', '\u2c95': '\u2c95', '\u2c97': '\u2c97', '\u2c99':
'\u2c99', '\u2c9b': '\u2c9b', '\u2c9d': '\u2c9d', '\u2c9f': '\u2c9f',
'\u2ca1': '\u2ca1', '\u2ca3': '\u2ca3', '\u2ca5': '\u2ca5', '\u2ca7':
'\u2ca7', '\u2ca9': '\u2ca9', '\u2cab': '\u2cab', '\u2cad': '\u2cad',
'\u2caf': '\u2caf', '\u2cb1': '\u2cb1', '\u2cb3': '\u2cb3', '\u2cb5':
'\u2cb5', '\u2cb7': '\u2cb7', '\u2cb9': '\u2cb9', '\u2cbb': '\u2cbb',
'\u2cbd': '\u2cbd', '\u2cbf': '\u2cbf', '\u2cc1': '\u2cc1', '\u2cc3':
'\u2cc3', '\u2cc5': '\u2cc5', '\u2cc7': '\u2cc7', '\u2cc9': '\u2cc9',
'\u2ccb': '\u2ccb', '\u2ccd': '\u2ccd', '\u2ccf': '\u2ccf', '\u2cd1':
'\u2cd1', '\u2cd3': '\u2cd3', '\u2cd5': '\u2cd5', '\u2cd7': '\u2cd7',
'\u2cd9': '\u2cd9', '\u2cdb': '\u2cdb', '\u2cdd': '\u2cdd', '\u2cdf':
'\u2cdf', '\u2ce1': '\u2ce1', '\u2ce3': '\u2ce3', '\u2cec': '\u2cec',
'\u2cee': '\u2cee', '\u2cf3': '\u2cf3', '\u2d00': '\u2d00', '\u2d01':
'\u2d01', '\u2d02': '\u2d02', '\u2d03': '\u2d03', '\u2d04': '\u2d04',
'\u2d05': '\u2d05', '\u2d06': '\u2d06', '\u2d07': '\u2d07', '\u2d08':
'\u2d08', '\u2d09': '\u2d09', '\u2d0a': '\u2d0a', '\u2d0b': '\u2d0b',
'\u2d0c': '\u2d0c', '\u2d0d': '\u2d0d', '\u2d0e': '\u2d0e', '\u2d0f':
'\u2d0f', '\u2d10': '\u2d10', '\u2d11': '\u2d11', '\u2d12': '\u2d12',
'\u2d13': '\u2d13', '\u2d14': '\u2d14', '\u2d15': '\u2d15', '\u2d16':
'\u2d16', '\u2d17': '\u2d17', '\u2d18': '\u2d18', '\u2d19': '\u2d19',
'\u2d1a': '\u2d1a', '\u2d1b': '\u2d1b', '\u2d1c': '\u2d1c', '\u2d1d':
'\u2d1d', '\u2d1e': '\u2d1e', '\u2d1f': '\u2d1f', '\u2d20': '\u2d20',
'\u2d21': '\u2d21', '\u2d22': '\u2d22', '\u2d23': '\u2d23', '\u2d24':
'\u2d24', '\u2d25': '\u2d25', '\u2d27': '\u2d27', '\u2d2d': '\u2d2d',
'\ua641': '\ua641', '\ua643': '\ua643', '\ua645': '\ua645', '\ua647':
'\ua647', '\ua649': '\ua649', '\ua64b': '\ua64b', '\ua64d': '\ua64d',
'\ua64f': '\ua64f', '\ua651': '\ua651', '\ua653': '\ua653', '\ua655':
'\ua655', '\ua657': '\ua657', '\ua659': '\ua659', '\ua65b': '\ua65b',
'\ua65d': '\ua65d', '\ua65f': '\ua65f', '\ua661': '\ua661', '\ua663':
'\ua663', '\ua665': '\ua665', '\ua667': '\ua667', '\ua669': '\ua669',
'\ua66b': '\ua66b', '\ua66d': '\ua66d', '\ua681': '\ua681', '\ua683':
'\ua683', '\ua685': '\ua685', '\ua687': '\ua687', '\ua689': '\ua689',
'\ua68b': '\ua68b', '\ua68d': '\ua68d', '\ua68f': '\ua68f', '\ua691':
'\ua691', '\ua693': '\ua693', '\ua695': '\ua695', '\ua697': '\ua697',
'\ua699': '\ua699', '\ua69b': '\ua69b', '\ua723': '\ua723', '\ua725':
'\ua725', '\ua727': '\ua727', '\ua729': '\ua729', '\ua72b': '\ua72b',
'\ua72d': '\ua72d', '\ua72f': '\ua72f', '\ua733': '\ua733', '\ua735':
'\ua735', '\ua737': '\ua737', '\ua739': '\ua739', '\ua73b': '\ua73b',
'\ua73d': '\ua73d', '\ua73f': '\ua73f', '\ua741': '\ua741', '\ua743':
'\ua743', '\ua745': '\ua745', '\ua747': '\ua747', '\ua749': '\ua749',
'\ua74b': '\ua74b', '\ua74d': '\ua74d', '\ua74f': '\ua74f', '\ua751':
'\ua751', '\ua753': '\ua753', '\ua755': '\ua755', '\ua757': '\ua757',
'\ua759': '\ua759', '\ua75b': '\ua75b', '\ua75d': '\ua75d', '\ua75f':
'\ua75f', '\ua761': '\ua761', '\ua763': '\ua763', '\ua765': '\ua765',
'\ua767': '\ua767', '\ua769': '\ua769', '\ua76b': '\ua76b', '\ua76d':
'\ua76d', '\ua76f': '\ua76f', '\ua77a': '\ua77a', '\ua77c': '\ua77c',
'\ua77f': '\ua77f', '\ua781': '\ua781', '\ua783': '\ua783', '\ua785':
'\ua785', '\ua787': '\ua787', '\ua78c': '\ua78c', '\ua791': '\ua791',
'\ua793': '\ua793', '\ua797': '\ua797', '\ua799': '\ua799', '\ua79b':
'\ua79b', '\ua79d': '\ua79d', '\ua79f': '\ua79f', '\ua7a1': '\ua7a1',
'\ua7a3': '\ua7a3', '\ua7a5': '\ua7a5', '\ua7a7': '\ua7a7', '\ua7a9':
'\ua7a9', '\ua7b5': '\ua7b5', '\ua7b7': '\ua7b7', '\ua7b9': '\ua7b9',
'\uab53': '\uab53', '\uab70': '\uab70', '\uab71': '\uab71', '\uab72':
'\uab72', '\uab73': '\uab73', '\uab74': '\uab74', '\uab75': '\uab75',
'\uab76': '\uab76', '\uab77': '\uab77', '\uab78': '\uab78', '\uab79':
'\uab79', '\uab7a': '\uab7a', '\uab7b': '\uab7b', '\uab7c': '\uab7c',
'\uab7d': '\uab7d', '\uab7e': '\uab7e', '\uab7f': '\uab7f', '\uab80':
'\uab80', '\uab81': '\uab81', '\uab82': '\uab82', '\uab83': '\uab83',
'\uab84': '\uab84', '\uab85': '\uab85', '\uab86': '\uab86', '\uab87':
'\uab87', '\uab88': '\uab88', '\uab89': '\uab89', '\uab8a': '\uab8a',
'\uab8b': '\uab8b', '\uab8c': '\uab8c', '\uab8d': '\uab8d', '\uab8e':
'\uab8e', '\uab8f': '\uab8f', '\uab90': '\uab90', '\uab91': '\uab91',
'\uab92': '\uab92', '\uab93': '\uab93', '\uab94': '\uab94', '\uab95':
'\uab95', '\uab96': '\uab96', '\uab97': '\uab97', '\uab98': '\uab98',
'\uab99': '\uab99', '\uab9a': '\uab9a', '\uab9b': '\uab9b', '\uab9c':
'\uab9c', '\uab9d': '\uab9d', '\uab9e': '\uab9e', '\uab9f': '\uab9f',
'\uaba0': '\uaba0', '\uaba1': '\uaba1', '\uaba2': '\uaba2', '\uaba3':
'\uaba3', '\uaba4': '\uaba4', '\uaba5': '\uaba5', '\uaba6': '\uaba6',
'\uaba7': '\uaba7', '\uaba8': '\uaba8', '\uaba9': '\uaba9', '\uabaa':
'\uabaa', '\uabab': '\uabab', '\uabac': '\uabac', '\uabad': '\uabad',
'\uabae': '\uabae', '\uabaf': '\uabaf', '\uabb0': '\uabb0', '\uabb1':
'\uabb1', '\uabb2': '\uabb2', '\uabb3': '\uabb3', '\uabb4': '\uabb4',
'\uabb5': '\uabb5', '\uabb6': '\uabb6', '\uabb7': '\uabb7', '\uabb8':
'\uabb8', '\uabb9': '\uabb9', '\uabba': '\uabba', '\uabbb': '\uabbb',
'\uabbc': '\uabbc', '\uabbd': '\uabbd', '\uabbe': '\uabbe', '\uabbf':
'\uabbf', '\ufb00': '\ufb00', '\ufb01': '\ufb01', '\ufb02': '\ufb02',
'\ufb03': '\ufb03', '\ufb04': '\ufb04', '\ufb05': '\ufb05', '\ufb06':
'\ufb06', '\ufb13': '\ufb13', '\ufb14': '\ufb14', '\ufb15': '\ufb15',
'\ufb16': '\ufb16', '\ufb17': '\ufb17', '\U0001044e': '\U0001044e',
'\U0001044f': '\U0001044f', '\U000104d8': '\U000104d8', '\U000104d9':
'\U000104d9', '\U000104da': '\U000104da', '\U000104db': '\U000104db',
'\U000104dc': '\U000104dc', '\U000104dd': '\U000104dd', '\U000104de':
'\U000104de', '\U000104df': '\U000104df', '\U000104e0': '\U000104e0',
'\U000104e1': '\U000104e1', '\U000104e2': '\U000104e2', '\U000104e3':
'\U000104e3', '\U000104e4': '\U000104e4', '\U000104e5': '\U000104e5',
'\U000104e6': '\U000104e6', '\U000104e7': '\U000104e7', '\U000104e8':
'\U000104e8', '\U000104e9': '\U000104e9', '\U000104ea': '\U000104ea',
'\U000104eb': '\U000104eb', '\U000104ec': '\U000104ec', '\U000104ed':
'\U000104ed', '\U000104ee': '\U000104ee', '\U000104ef': '\U000104ef',
'\U000104f0': '\U000104f0', '\U000104f1': '\U000104f1', '\U000104f2':
'\U000104f2', '\U000104f3': '\U000104f3', '\U000104f4': '\U000104f4',
'\U000104f5': '\U000104f5', '\U000104f6': '\U000104f6', '\U000104f7':
'\U000104f7', '\U000104f8': '\U000104f8', '\U000104f9': '\U000104f9',
'\U000104fa': '\U000104fa', '\U000104fb': '\U000104fb', '\U00010cc0':
'\U00010cc0', '\U00010cc1': '\U00010cc1', '\U00010cc2': '\U00010cc2',
'\U00010cc3': '\U00010cc3', '\U00010cc4': '\U00010cc4', '\U00010cc5':
'\U00010cc5', '\U00010cc6': '\U00010cc6', '\U00010cc7': '\U00010cc7',
'\U00010cc8': '\U00010cc8', '\U00010cc9': '\U00010cc9', '\U00010cca':
'\U00010cca', '\U00010ccb': '\U00010ccb', '\U00010ccc': '\U00010ccc',
'\U00010ccd': '\U00010ccd', '\U00010cce': '\U00010cce', '\U00010ccf':
'\U00010ccf', '\U00010cd0': '\U00010cd0', '\U00010cd1': '\U00010cd1',
'\U00010cd2': '\U00010cd2', '\U00010cd3': '\U00010cd3', '\U00010cd4':
'\U00010cd4', '\U00010cd5': '\U00010cd5', '\U00010cd6': '\U00010cd6',
'\U00010cd7': '\U00010cd7', '\U00010cd8': '\U00010cd8', '\U00010cd9':
'\U00010cd9', '\U00010cda': '\U00010cda', '\U00010cdb': '\U00010cdb',
'\U00010cdc': '\U00010cdc', '\U00010cdd': '\U00010cdd', '\U00010cde':
'\U00010cde', '\U00010cdf': '\U00010cdf', '\U00010ce0': '\U00010ce0',
'\U00010ce1': '\U00010ce1', '\U00010ce2': '\U00010ce2', '\U00010ce3':
'\U00010ce3', '\U00010ce4': '\U00010ce4', '\U00010ce5': '\U00010ce5',
'\U00010ce6': '\U00010ce6', '\U00010ce7': '\U00010ce7', '\U00010ce8':
'\U00010ce8', '\U00010ce9': '\U00010ce9', '\U00010cea': '\U00010cea',
'\U00010ceb': '\U00010ceb', '\U00010cec': '\U00010cec', '\U00010ced':
'\U00010ced', '\U00010cee': '\U00010cee', '\U00010cef': '\U00010cef',
'\U00010cf0': '\U00010cf0', '\U00010cf1': '\U00010cf1', '\U00010cf2':
'\U00010cf2', '\U000118c0': '\U000118c0', '\U000118c1': '\U000118c1',
'\U000118c2': '\U000118c2', '\U000118c3': '\U000118c3', '\U000118c4':
'\U000118c4', '\U000118c5': '\U000118c5', '\U000118c6': '\U000118c6',
'\U000118c7': '\U000118c7', '\U000118c8': '\U000118c8', '\U000118c9':
'\U000118c9', '\U000118ca': '\U000118ca', '\U000118cb': '\U000118cb',
'\U000118cc': '\U000118cc', '\U000118cd': '\U000118cd', '\U000118ce':
'\U000118ce', '\U000118cf': '\U000118cf', '\U000118d0': '\U000118d0',
'\U000118d1': '\U000118d1', '\U000118d2': '\U000118d2', '\U000118d3':
'\U000118d3', '\U000118d4': '\U000118d4', '\U000118d5': '\U000118d5',
'\U000118d6': '\U000118d6', '\U000118d7': '\U000118d7', '\U000118d8':
'\U000118d8', '\U000118d9': '\U000118d9', '\U000118da': '\U000118da',
'\U000118db': '\U000118db', '\U000118dc': '\U000118dc', '\U000118dd':
'\U000118dd', '\U000118de': '\U000118de', '\U000118df': '\U000118df',
'\U00016e60': '\U00016e60', '\U00016e61': '\U00016e61', '\U00016e62':
'\U00016e62', '\U00016e63': '\U00016e63', '\U00016e64': '\U00016e64',
'\U00016e65': '\U00016e65', '\U00016e66': '\U00016e66', '\U00016e67':
'\U00016e67', '\U00016e68': '\U00016e68', '\U00016e69': '\U00016e69',
'\U00016e6a': '\U00016e6a', '\U00016e6b': '\U00016e6b', '\U00016e6c':
'\U00016e6c', '\U00016e6d': '\U00016e6d', '\U00016e6e': '\U00016e6e',
'\U00016e6f': '\U00016e6f', '\U00016e70': '\U00016e70', '\U00016e71':
'\U00016e71', '\U00016e72': '\U00016e72', '\U00016e73': '\U00016e73',
'\U00016e74': '\U00016e74', '\U00016e75': '\U00016e75', '\U00016e76':
'\U00016e76', '\U00016e77': '\U00016e77', '\U00016e78': '\U00016e78',
'\U00016e79': '\U00016e79', '\U00016e7a': '\U00016e7a', '\U00016e7b':
'\U00016e7b', '\U00016e7c': '\U00016e7c', '\U00016e7d': '\U00016e7d',
'\U00016e7e': '\U00016e7e', '\U00016e7f': '\U00016e7f', '\U0001e922':
'\U0001e922', '\U0001e923': '\U0001e923', '\U0001e924': '\U0001e924',
'\U0001e925': '\U0001e925', '\U0001e926': '\U0001e926', '\U0001e927':
'\U0001e927', '\U0001e928': '\U0001e928', '\U0001e929': '\U0001e929',
'\U0001e92a': '\U0001e92a', '\U0001e92b': '\U0001e92b', '\U0001e92c':
'\U0001e92c', '\U0001e92d': '\U0001e92d', '\U0001e92e': '\U0001e92e',
'\U0001e92f': '\U0001e92f', '\U0001e930': '\U0001e930', '\U0001e931':
'\U0001e931', '\U0001e932': '\U0001e932', '\U0001e933': '\U0001e933',
'\U0001e934': '\U0001e934', '\U0001e935': '\U0001e935', '\U0001e936':
'\U0001e936', '\U0001e937': '\U0001e937', '\U0001e938': '\U0001e938',
'\U0001e939': '\U0001e939', '\U0001e93a': '\U0001e93a', '\U0001e93b':
'\U0001e93b', '\U0001e93c': '\U0001e93c', '\U0001e93d': '\U0001e93d',
'\U0001e93e': '\U0001e93e', '\U0001e93f': '\U0001e93f', '\U0001e940':
'\U0001e940', '\U0001e941': '\U0001e941', '\U0001e942': '\U0001e942',
}
_first_upper_exception = _first_upper_exception_dict.get
# All characters in the Cf category in a static list. When testing each Unicode
# codepoint it takes longer especially when working with UCS2. The lists also
# differ between Python versions which can be avoided by this static list.
#
# This frozenset was created using Python 3.9 (Unicode version 13.0.0):
# list(c for c in (chr(i) for i in range(sys.maxunicode))
# if unicodedata.category(c) == 'Cf')
_category_cf = frozenset([
'\xad',
'\u0600', '\u0601', '\u0602', '\u0603', '\u0604', '\u0605', '\u061c',
'\u06dd', '\u070f', '\u08e2', '\u180e', '\u200b', '\u200c', '\u200d',
'\u200e', '\u200f', '\u202a', '\u202b', '\u202c', '\u202d', '\u202e',
'\u2060', '\u2061', '\u2062', '\u2063', '\u2064', '\u2066', '\u2067',
'\u2068', '\u2069', '\u206a', '\u206b', '\u206c', '\u206d', '\u206e',
'\u206f', '\ufeff', '\ufff9', '\ufffa', '\ufffb',
'\U000110bd', '\U000110cd', '\U00013430', '\U00013431', '\U00013432',
'\U00013433', '\U00013434', '\U00013435', '\U00013436', '\U00013437',
'\U00013438', '\U0001bca0', '\U0001bca1', '\U0001bca2', '\U0001bca3',
'\U0001d173', '\U0001d174', '\U0001d175', '\U0001d176', '\U0001d177',
'\U0001d178', '\U0001d179', '\U0001d17a', '\U000e0001', '\U000e0020',
'\U000e0021', '\U000e0022', '\U000e0023', '\U000e0024', '\U000e0025',
'\U000e0026', '\U000e0027', '\U000e0028', '\U000e0029', '\U000e002a',
'\U000e002b', '\U000e002c', '\U000e002d', '\U000e002e', '\U000e002f',
'\U000e0030', '\U000e0031', '\U000e0032', '\U000e0033', '\U000e0034',
'\U000e0035', '\U000e0036', '\U000e0037', '\U000e0038', '\U000e0039',
'\U000e003a', '\U000e003b', '\U000e003c', '\U000e003d', '\U000e003e',
'\U000e003f', '\U000e0040', '\U000e0041', '\U000e0042', '\U000e0043',
'\U000e0044', '\U000e0045', '\U000e0046', '\U000e0047', '\U000e0048',
'\U000e0049', '\U000e004a', '\U000e004b', '\U000e004c', '\U000e004d',
'\U000e004e', '\U000e004f', '\U000e0050', '\U000e0051', '\U000e0052',
'\U000e0053', '\U000e0054', '\U000e0055', '\U000e0056', '\U000e0057',
'\U000e0058', '\U000e0059', '\U000e005a', '\U000e005b', '\U000e005c',
'\U000e005d', '\U000e005e', '\U000e005f', '\U000e0060', '\U000e0061',
'\U000e0062', '\U000e0063', '\U000e0064', '\U000e0065', '\U000e0066',
'\U000e0067', '\U000e0068', '\U000e0069', '\U000e006a', '\U000e006b',
'\U000e006c', '\U000e006d', '\U000e006e', '\U000e006f', '\U000e0070',
'\U000e0071', '\U000e0072', '\U000e0073', '\U000e0074', '\U000e0075',
'\U000e0076', '\U000e0077', '\U000e0078', '\U000e0079', '\U000e007a',
'\U000e007b', '\U000e007c', '\U000e007d', '\U000e007e', '\U000e007f',
])
|
def advance(memory, memory_pointer):
memory_pointer += 1
if memory_pointer > len(memory) - 1:
memory.append(0)
return memory, memory_pointer
def retreat(memory, memory_pointer):
memory_pointer -= 1
return memory, memory_pointer
def increment(memory, memory_pointer):
memory[memory_pointer] += 1
if memory[memory_pointer] > 255:
memory[memory_pointer] = 0
return memory, memory_pointer
def decrement(memory, memory_pointer):
memory[memory_pointer] -= 1
if memory[memory_pointer] < 0:
memory[memory_pointer] = 255
return memory, memory_pointer
def output(memory, memory_pointer):
print(chr(memory[memory_pointer]), end = '')
# print(memory[memory_pointer])
return memory, memory_pointer
def inpt(memory, memory_pointer):
# memory[memory_pointer] = input("")
memory[memory_pointer] = ord(input(""))
return memory, memory_pointer
def nothing(memory, memory_pointer):
return memory, memory_pointer
lookup = {"<": retreat, ">": advance, "+": increment, "-": decrement, ".": output, ",": inpt, "[": nothing, "]": nothing}
def find_end_of_loop(code, i):
ignore = 0
for j in range(i, len(code)):
if code[j] == "[":
ignore += 1
if code[j] == "]":
ignore -= 1
if code[j] == "]" and ignore == 0:
return j
def find_start_of_loop(code, i):
ignore = 0
for j in range(i, -1, -1):
if code[j] == "]":
ignore += 1
if code[j] == "[":
ignore -= 1
if code[j] == "[" and ignore == 0:
return j
|
# 24. In calculus, the derivative of x^4 is 4x^3. The derivative of x^5 is 5x^4. The derivative of x^6 is
# 6x^5. This pattern continues. Write a program that asks the user for input like x^3 or x^25
# and prints the derivative. For example, if the user enters x^3, the program should print out
# 3x^2.
# input: factor * variable ** exponent
# assume: factor and exponent are integers
expression = input('Enter an expression like x^3 or x^25: ')
factor, idx = 0, 0
if expression[0].isalpha():
factor = 1
else:
for i in range(len(expression)):
idx = i
if expression[i].isalpha():
factor = int(expression[0:i])
break
# input: factor
if idx == len(expression) - 1 and expression[idx].isdigit():
print('The derivative of', expression, 'is 0.')
exit()
variable = ''
for i in range(idx, len(expression)):
idx = i
if expression[i] == '^':
variable = expression[idx:i]
break
if idx == len(expression) - 1: # input: factor * variable
exponent = 0
else: # input: factor * variable ** exponent
exponent = int(expression[idx+1:])
if exponent == 0:
print('The derivative of', expression, f'is {factor}.')
else:
print(f'The derivative of {expression} is {factor*exponent}*{variable}^{exponent-1}')
|
# -*- python -*-
# Copyright 2018-2019 Josh Pieper, jjp@pobox.com.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
load("@build_bazel_rules_nodejs//:defs.bzl", "node_repositories", "yarn_install")
# Because bazel's starlark as of 0.28.1 doesn't allow a WORKSPACE
# evaluated function to have load calls anywhere but at the top, we
# have to split our npm initialization into multiple stages. :( Anyone
# who calls us will just have to invoke all of them in order to get
# the proper initialization.
def setup_npm_stage1():
node_repositories(
node_version = "10.16.0",
yarn_version = "1.13.0",
)
yarn_install(
name = "npm",
package_json = "//:package.json",
yarn_lock = "//:yarn.lock",
)
|
# Copyright 2013 10gen Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# flask.config settings.
DEBUG = True
SECRET_KEY = 'foo'
# Misc settings.
HOST = '0.0.0.0'
PORT = 8081
DATA_DIR = '/tmp'
# Rate limit settings
RATELIMIT_COLLECTION = 'ivs_ratelimit'
RATELIMIT_QUOTA = 3 # requests per expiry
RATELIMIT_EXPIRY = 10 # expiry in seconds
# DB Settings
DB_HOSTS = ['localhost']
DB_PORT = 27017
DB_NAME = 'mongows'
# edX integration
EDX_SHARED_KEY = 'wanderlust'
GRADING_SERVER_URL = 'http://localhost'
GRADING_API_KEY = 'i4mm3'
GRADING_API_SECRET = 's0s3cr3t'
|
class Solution:
def maxCount(self, m, n, ops):
"""
:type m: int
:type n: int
:type ops: List[List[int]]
:rtype: int
"""
if len(ops) == 0: return m * n
minX = minY = float('inf')
for op in ops:
minX = min(minX, op[0])
minY = min(minY, op[1])
return minX * minY
|
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def isCousins(self, root, x, y):
"""
:type root: TreeNode
:type x: int
:type y: int
:rtype: bool
"""
a = [root]
b = []
c = []
while a:
v = {}
for n in a:
if n.left:
b.append(n.left)
v[n.left.val] = n.val
if n.right:
b.append(n.right)
v[n.right.val] = n.val
if v:
c.append(v)
a = b
b = []
for d in c:
if x in d and y in d and d[x] != d[y]:
return True
return False
def test_is_cousins():
a = TreeNode(1)
b = TreeNode(2)
c = TreeNode(3)
d = TreeNode(4)
a.left = b
a.right = c
b.left = d
assert Solution().isCousins(a, 3, 4) is False
a = TreeNode(1)
b = TreeNode(2)
c = TreeNode(3)
d = TreeNode(4)
e = TreeNode(5)
a.left = b
a.right = c
b.right = d
c.right = e
assert Solution().isCousins(a, 5, 4)
a = TreeNode(1)
b = TreeNode(2)
c = TreeNode(3)
d = TreeNode(4)
a.left = b
a.right = c
b.right = d
assert Solution().isCousins(a, 2, 3) is False
|
def chunk(list, size):
n = max(1, size)
return (list[i:i + n] for i in range(0, len(list), n))
def valids(sides):
return sum((1 for x, y, z in sides if x + y > z and y + z > x and x + z > y))
def triangles(input):
return (map(int, t.split()) for t in input)
def day3(input):
transposed = (chunk(x, 3) for x in map(list, zip(*triangles(input))))
return valids(triangles(input)), sum(map(valids, transposed))
input = open("../input.txt").read()
print(day3([x.strip() for x in input.strip().split("\n")])) |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Script: solution.py
# @Author: Pradip Patil
# @Contact: @pradip__patil
# @Created: 2018-02-10 21:18:08
# @Last Modified By: Pradip Patil
# @Last Modified: 2018-02-10 21:21:21
# @Description: https://www.hackerrank.com/challenges/python-arithmetic-operators/problem
if __name__ == '__main__':
a = int(input())
b = int(input())
print("{}\n{}\n{}".format(a + b, a - b, a * b))
|
#
# PySNMP MIB module RFC1315-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RFC1315-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 16:59:09 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
ObjectIdentifier, Integer, OctetString = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "Integer", "OctetString")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
SingleValueConstraint, ValueRangeConstraint, ConstraintsUnion, ConstraintsIntersection, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ValueRangeConstraint", "ConstraintsUnion", "ConstraintsIntersection", "ValueSizeConstraint")
ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup")
MibScalar, MibTable, MibTableRow, MibTableColumn, Bits, Gauge32, Integer32, Counter64, IpAddress, ModuleIdentity, ObjectIdentity, transmission, iso, Unsigned32, Counter32, MibIdentifier, NotificationType, NotificationType, TimeTicks = mibBuilder.importSymbols("SNMPv2-SMI", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Bits", "Gauge32", "Integer32", "Counter64", "IpAddress", "ModuleIdentity", "ObjectIdentity", "transmission", "iso", "Unsigned32", "Counter32", "MibIdentifier", "NotificationType", "NotificationType", "TimeTicks")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
frame_relay = MibIdentifier((1, 3, 6, 1, 2, 1, 10, 32)).setLabel("frame-relay")
class Index(Integer32):
pass
class DLCI(Integer32):
pass
frDlcmiTable = MibTable((1, 3, 6, 1, 2, 1, 10, 32, 1), )
if mibBuilder.loadTexts: frDlcmiTable.setStatus('mandatory')
frDlcmiEntry = MibTableRow((1, 3, 6, 1, 2, 1, 10, 32, 1, 1), ).setIndexNames((0, "RFC1315-MIB", "frDlcmiIfIndex"))
if mibBuilder.loadTexts: frDlcmiEntry.setStatus('mandatory')
frDlcmiIfIndex = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 32, 1, 1, 1), Index()).setMaxAccess("readonly")
if mibBuilder.loadTexts: frDlcmiIfIndex.setStatus('mandatory')
frDlcmiState = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 32, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("noLmiConfigured", 1), ("lmiRev1", 2), ("ansiT1-617-D", 3), ("ansiT1-617-B", 4)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: frDlcmiState.setStatus('mandatory')
frDlcmiAddress = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 32, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("q921", 1), ("q922March90", 2), ("q922November90", 3), ("q922", 4)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: frDlcmiAddress.setStatus('mandatory')
frDlcmiAddressLen = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 32, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(2, 3, 4))).clone(namedValues=NamedValues(("two-octets", 2), ("three-octets", 3), ("four-octets", 4)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: frDlcmiAddressLen.setStatus('mandatory')
frDlcmiPollingInterval = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 32, 1, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(5, 30)).clone(10)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: frDlcmiPollingInterval.setStatus('mandatory')
frDlcmiFullEnquiryInterval = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 32, 1, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 255)).clone(6)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: frDlcmiFullEnquiryInterval.setStatus('mandatory')
frDlcmiErrorThreshold = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 32, 1, 1, 7), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 10)).clone(3)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: frDlcmiErrorThreshold.setStatus('mandatory')
frDlcmiMonitoredEvents = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 32, 1, 1, 8), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 10)).clone(4)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: frDlcmiMonitoredEvents.setStatus('mandatory')
frDlcmiMaxSupportedVCs = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 32, 1, 1, 9), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: frDlcmiMaxSupportedVCs.setStatus('mandatory')
frDlcmiMulticast = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 32, 1, 1, 10), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("nonBroadcast", 1), ("broadcast", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: frDlcmiMulticast.setStatus('mandatory')
frCircuitTable = MibTable((1, 3, 6, 1, 2, 1, 10, 32, 2), )
if mibBuilder.loadTexts: frCircuitTable.setStatus('mandatory')
frCircuitEntry = MibTableRow((1, 3, 6, 1, 2, 1, 10, 32, 2, 1), ).setIndexNames((0, "RFC1315-MIB", "frCircuitIfIndex"), (0, "RFC1315-MIB", "frCircuitDlci"))
if mibBuilder.loadTexts: frCircuitEntry.setStatus('mandatory')
frCircuitIfIndex = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 32, 2, 1, 1), Index()).setMaxAccess("readonly")
if mibBuilder.loadTexts: frCircuitIfIndex.setStatus('mandatory')
frCircuitDlci = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 32, 2, 1, 2), DLCI()).setMaxAccess("readonly")
if mibBuilder.loadTexts: frCircuitDlci.setStatus('mandatory')
frCircuitState = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 32, 2, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("invalid", 1), ("active", 2), ("inactive", 3))).clone('active')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: frCircuitState.setStatus('mandatory')
frCircuitReceivedFECNs = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 32, 2, 1, 4), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: frCircuitReceivedFECNs.setStatus('mandatory')
frCircuitReceivedBECNs = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 32, 2, 1, 5), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: frCircuitReceivedBECNs.setStatus('mandatory')
frCircuitSentFrames = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 32, 2, 1, 6), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: frCircuitSentFrames.setStatus('mandatory')
frCircuitSentOctets = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 32, 2, 1, 7), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: frCircuitSentOctets.setStatus('mandatory')
frCircuitReceivedFrames = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 32, 2, 1, 8), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: frCircuitReceivedFrames.setStatus('mandatory')
frCircuitReceivedOctets = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 32, 2, 1, 9), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: frCircuitReceivedOctets.setStatus('mandatory')
frCircuitCreationTime = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 32, 2, 1, 10), TimeTicks()).setMaxAccess("readonly")
if mibBuilder.loadTexts: frCircuitCreationTime.setStatus('mandatory')
frCircuitLastTimeChange = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 32, 2, 1, 11), TimeTicks()).setMaxAccess("readonly")
if mibBuilder.loadTexts: frCircuitLastTimeChange.setStatus('mandatory')
frCircuitCommittedBurst = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 32, 2, 1, 12), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: frCircuitCommittedBurst.setStatus('mandatory')
frCircuitExcessBurst = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 32, 2, 1, 13), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: frCircuitExcessBurst.setStatus('mandatory')
frCircuitThroughput = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 32, 2, 1, 14), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: frCircuitThroughput.setStatus('mandatory')
frErrTable = MibTable((1, 3, 6, 1, 2, 1, 10, 32, 3), )
if mibBuilder.loadTexts: frErrTable.setStatus('mandatory')
frErrEntry = MibTableRow((1, 3, 6, 1, 2, 1, 10, 32, 3, 1), ).setIndexNames((0, "RFC1315-MIB", "frErrIfIndex"))
if mibBuilder.loadTexts: frErrEntry.setStatus('mandatory')
frErrIfIndex = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 32, 3, 1, 1), Index()).setMaxAccess("readonly")
if mibBuilder.loadTexts: frErrIfIndex.setStatus('mandatory')
frErrType = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 32, 3, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))).clone(namedValues=NamedValues(("unknownError", 1), ("receiveShort", 2), ("receiveLong", 3), ("illegalDLCI", 4), ("unknownDLCI", 5), ("dlcmiProtoErr", 6), ("dlcmiUnknownIE", 7), ("dlcmiSequenceErr", 8), ("dlcmiUnknownRpt", 9), ("noErrorSinceReset", 10)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: frErrType.setStatus('mandatory')
frErrData = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 32, 3, 1, 3), OctetString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: frErrData.setStatus('mandatory')
frErrTime = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 32, 3, 1, 4), TimeTicks()).setMaxAccess("readonly")
if mibBuilder.loadTexts: frErrTime.setStatus('mandatory')
frame_relay_globals = MibIdentifier((1, 3, 6, 1, 2, 1, 10, 32, 4)).setLabel("frame-relay-globals")
frTrapState = MibScalar((1, 3, 6, 1, 2, 1, 10, 32, 4, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone('disabled')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: frTrapState.setStatus('mandatory')
frDLCIStatusChange = NotificationType((1, 3, 6, 1, 2, 1, 10, 32) + (0,1)).setObjects(("RFC1315-MIB", "frCircuitIfIndex"), ("RFC1315-MIB", "frCircuitDlci"), ("RFC1315-MIB", "frCircuitState"))
mibBuilder.exportSymbols("RFC1315-MIB", frCircuitReceivedFrames=frCircuitReceivedFrames, frCircuitLastTimeChange=frCircuitLastTimeChange, frCircuitSentOctets=frCircuitSentOctets, frDlcmiMonitoredEvents=frDlcmiMonitoredEvents, frErrTime=frErrTime, frDlcmiEntry=frDlcmiEntry, frDLCIStatusChange=frDLCIStatusChange, frCircuitExcessBurst=frCircuitExcessBurst, frErrIfIndex=frErrIfIndex, frDlcmiState=frDlcmiState, frDlcmiErrorThreshold=frDlcmiErrorThreshold, frCircuitReceivedFECNs=frCircuitReceivedFECNs, frCircuitSentFrames=frCircuitSentFrames, frCircuitCommittedBurst=frCircuitCommittedBurst, frCircuitEntry=frCircuitEntry, frDlcmiIfIndex=frDlcmiIfIndex, frErrTable=frErrTable, frDlcmiMulticast=frDlcmiMulticast, frCircuitThroughput=frCircuitThroughput, frErrData=frErrData, frDlcmiAddress=frDlcmiAddress, frCircuitState=frCircuitState, frDlcmiAddressLen=frDlcmiAddressLen, frDlcmiMaxSupportedVCs=frDlcmiMaxSupportedVCs, frDlcmiFullEnquiryInterval=frDlcmiFullEnquiryInterval, frCircuitTable=frCircuitTable, frCircuitIfIndex=frCircuitIfIndex, frCircuitReceivedBECNs=frCircuitReceivedBECNs, frErrType=frErrType, frame_relay=frame_relay, frDlcmiPollingInterval=frDlcmiPollingInterval, frCircuitReceivedOctets=frCircuitReceivedOctets, frCircuitCreationTime=frCircuitCreationTime, frDlcmiTable=frDlcmiTable, Index=Index, frame_relay_globals=frame_relay_globals, frCircuitDlci=frCircuitDlci, DLCI=DLCI, frTrapState=frTrapState, frErrEntry=frErrEntry)
|
"""
Provides utility functions.
"""
def merge_dicts(source, destination):
"""
Recursively merges two dictionaries source and destination.
The source dictionary will only be read, but the destination dictionary will be overwritten.
"""
for key, value in source.items():
if isinstance(value, dict):
# get node or create one
node = destination.setdefault(key, {})
merge_dicts(value, node)
else:
destination[key] = value
return destination
def align_ellipsis(s, width):
"""
Shrinks the given string to width (including an ellipsis character),
and additionally pads the string with spaces to match the given with.
"""
if len(s) > width:
s = s[:width - 1] + "…"
return f"{s:<{width}}"
def ellipsis(s, width):
"""
Shrinks the given string to width (including an ellipsis character).
"""
if len(s) > width:
s = s[:width - 1] + "…"
return s
def print_transaction_title(transaction, title_color, status_char):
"""
Prints the transaction title and name
"""
title = align_ellipsis(transaction.title, 10)
name_align_at = 30 * (1 + (len(transaction.name) // 30))
name = f"{transaction.name:<{name_align_at}}"
print(f"[{status_char}] {title_color}{title}[m {name}", end="", flush=True)
def print_transaction_early(transaction):
"""
Prints the transaction summary early (i.e. without changes)
"""
title_color = "[1;33m"
status_char = "[33m?[m"
# Print title and name
print_transaction_title(transaction, title_color, status_char)
def print_transaction(context, transaction):
"""
Prints the transaction summary
"""
if transaction.success:
if transaction.changed:
title_color = "[1;34m"
status_char = "[32m+[m"
else:
title_color = "[1m"
status_char = "[37m.[m"
else:
title_color = "[1;31m"
status_char = "[1;31m![m"
# Print title and name, overwriting the transitive status
print("\r", end="")
print_transaction_title(transaction, title_color, status_char)
# Print key: value pairs with changes
state_infos = []
for k,final_v in transaction.final_state.items():
initial_v = transaction.initial_state[k]
# Add ellipsis on long strings
str_k = ellipsis(k, 12)
str_initial_v = ellipsis(str(initial_v), 9)
str_final_v = ellipsis(str(final_v), 9+3+9 if initial_v is None else 9)
if initial_v == final_v:
if context.verbose >= 1:
entry_str = f"[37m{str_k}: {str_initial_v}[m"
state_infos.append(entry_str)
else:
if initial_v is None:
entry_str = f"[33m{str_k}: [32m{str_final_v}[m"
else:
entry_str = f"[33m{str_k}: [31m{str_initial_v}[33m → [32m{str_final_v}[m"
state_infos.append(entry_str)
print("[37m,[m ".join(state_infos))
if context.verbose >= 1 and transaction.extra_info is not None:
extra_infos = []
for k,v in transaction.extra_info.items():
extra_infos.append(f"[37m{str(k)}: {str(v)}[m")
print(" " * 15 + "[37m,[m ".join(extra_infos))
def choice_yes(msg: str) -> bool:
"""
Awaits user choice (Y/n).
"""
while True:
print(f"{msg} (Y/n) ", end="", flush=True)
choice = input().lower()
if choice in ["", "y", "yes"]:
return True
if choice in ["n", "no"]:
return False
print(f"Response '{choice}' not understood.")
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
try:
f = open('D:\\PycharmProjects\\learn_python\\README.md','r', encoding='utf-8')
print(f.read())
finally:
if f:
f.close()
with open('D:\\PycharmProjects\\learn_python\\README.md','r', encoding='utf-8') as f:
for line in f.readlines():
print(line.strip()) # 把末尾的'\n'删掉
# 如果文件很小,read()一次性读取最方便;
# 如果不能确定文件大小,反复调用read(size)比较保险;
# 如果是配置文件,调用readlines()最方便
with open('D:\\PycharmProjects\\20160825144524.png','rb') as f:
print(f.read())
with open('D:\\PycharmProjects\\123.txt', 'w') as f:
f.write('hello, world') |
#Colors
BLACK = 0x0
WHITE = 0xFFFFFF
GRAY = 0x888888
BLUE = 0x0000FF
GREEN = 0x006400
ICE_BLUE = 0x99FFFF
RED = 0xB11A27
ORANGE = 0xFF793B
YELLOW = 0xFFF325
INDIGO = 0x6F00EE
VIOLET = 0x9700DE
def draw_plot():
pass
|
# print(4>3)
# print(4==4)
# print(4<3)
# print(4>=3)
# print(3>=3)
age = int(input("Age of students: "))
age_ate_school = int(input("Age of students: "))
print(age== age_ate_school) |
#############
### NODES ###
#############
class NumberNode:
def __init__(self, num_node_token):
self.num_node_token = num_node_token
def __repr__(self):
return f'{self.num_node_token}'
class BinaryOperationNode:
def __init__(self, left_node, binary_operation_token, right_node):
self.left_node = left_node
self.binary_operation_token = binary_operation_token
self.right_node = right_node
def __repr__(self):
return f'({self.left_node}, {self.binary_operation_token}, {self.right_node})'
class UnaryOperationNode:
def __init__(self, unary_operation_token, node):
self.unary_operation_token = unary_operation_token
self.node = node
def __repr__(self):
return f'({self.unary_operation_token}, {self.node})' |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.