content stringlengths 7 1.05M |
|---|
#!/usr/bin/python
# -*- encoding: utf-8; py-indent-offset: 4 -*-
# +------------------------------------------------------------------+
# | ____ _ _ __ __ _ __ |
# | / ___| |__ ___ ___| | __ | \/ | |/ / |
# | | | | '_ \ / _ \/ __| |/ / | |\/| | ' / |
# | | |___| | | | __/ (__| < | | | | . \ |
# | \____|_| |_|\___|\___|_|\_\___|_| |_|_|\_\ |
# | |
# | Copyright Mathias Kettner 2014 mk@mathias-kettner.de |
# +------------------------------------------------------------------+
#
# This file is part of Check_MK.
# The official homepage is at http://mathias-kettner.de/check_mk.
#
# check_mk is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation in version 2. check_mk is distributed
# in the hope that it will be useful, but WITHOUT ANY WARRANTY; with-
# out even the implied warranty of MERCHANTABILITY or FITNESS FOR A
# PARTICULAR PURPOSE. See the GNU General Public License for more de-
# tails. You should have received a copy of the GNU General Public
# License along with GNU Make; see the file COPYING. If not, write
# to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
# Boston, MA 02110-1301 USA.
# Temporary variable which stores settings during the backup process
backup_perfdata_enabled = True
def performancedata_restore(pre_restore = True):
global backup_perfdata_enabled
site = config.default_site()
html.live.set_only_sites([site])
if pre_restore:
data = html.live.query("GET status\nColumns: process_performance_data")
if data:
backup_perfdata_enabled = data[0][0] == 1
else:
backup_perfdata_enabled = None # Core is offline
# Return if perfdata is not activated - nothing to do..
if not backup_perfdata_enabled: # False or None
return []
command = pre_restore and "DISABLE_PERFORMANCE_DATA" or "ENABLE_PERFORMANCE_DATA"
html.live.command("[%d] %s" % (int(time.time()), command), site)
html.live.set_only_sites()
return []
if not defaults.omd_root:
backup_domains.update( {
"noomd-config": {
"group" : _("Configuration"),
"title" : _("WATO Configuration"),
"prefix" : defaults.default_config_dir,
"paths" : [
("dir", "conf.d/wato"),
("dir", "multisite.d/wato"),
("file", "multisite.d/sites.mk")
],
"default" : True,
},
"noomd-personalsettings": {
"title" : _("Personal User Settings and Custom Views"),
"prefix" : defaults.var_dir,
"paths" : [ ("dir", "web") ],
"default" : True
},
"noomd-authorization": {
"group" : _("Configuration"),
"title" : _("Local Authentication Data"),
"prefix" : os.path.dirname(defaults.htpasswd_file),
"paths" : [
("file", "htpasswd"),
("file", "auth.secret"),
("file", "auth.serials")
],
"cleanup" : False,
"default" : True
}})
else:
backup_domains.update({
"check_mk": {
"group" : _("Configuration"),
"title" : _("Hosts, Services, Groups, Timeperiods, Business Intelligence and Monitoring Configuration"),
"prefix" : defaults.default_config_dir,
"paths" : [
("file", "liveproxyd.mk"),
("file", "main.mk"),
("file", "final.mk"),
("file", "local.mk"),
("file", "mkeventd.mk"),
("dir", "conf.d"),
("dir", "multisite.d"),
("dir", "mkeventd.d"),
("dir", "mknotifyd.d"),
],
"default" : True,
},
"authorization": {
# This domain is obsolete
# It no longer shows up in the backup screen
"deprecated" : True,
"group" : _("Configuration"),
"title" : _("Local Authentication Data"),
"prefix" : os.path.dirname(defaults.htpasswd_file),
"paths" : [
("file", "htpasswd"),
("file", "auth.secret"),
("file", "auth.serials")
],
"cleanup" : False,
"default" : True,
},
"authorization_v1": {
"group" : _("Configuration"),
"title" : _("Local Authentication Data"),
"prefix" : defaults.omd_root,
"paths" : [
("file", "etc/htpasswd"),
("file", "etc/auth.secret"),
("file", "etc/auth.serials"),
("file", "var/check_mk/web/*/serial.mk")
],
"cleanup" : False,
"default" : True
},
"personalsettings": {
"title" : _("Personal User Settings and Custom Views"),
"prefix" : defaults.var_dir,
"paths" : [ ("dir", "web") ],
"exclude" : [ "*/serial.mk" ],
"cleanup" : False,
},
"autochecks": {
"group" : _("Configuration"),
"title" : _("Automatically Detected Services"),
"prefix" : defaults.autochecksdir,
"paths" : [ ("dir", "") ],
},
"snmpwalks": {
"title" : _("Stored SNMP Walks"),
"prefix" : defaults.snmpwalks_dir,
"paths" : [ ("dir", "") ],
},
"logwatch": {
"group" : _("Historic Data"),
"title" : _("Logwatch Data"),
"prefix" : defaults.var_dir,
"paths" : [
("dir", "logwatch"),
],
},
"mkeventstatus": {
"group" : _("Configuration"),
"title" : _("Event Console Configuration"),
"prefix" : defaults.omd_root,
"paths" : [
("dir", "etc/check_mk/mkeventd.d"),
],
"default" : True
},
"mkeventhistory": {
"group" : _("Historic Data"),
"title" : _("Event Console Archive and Current State"),
"prefix" : defaults.omd_root,
"paths" : [
("dir", "var/mkeventd/history"),
("file", "var/mkeventd/status"),
("file", "var/mkeventd/messages"),
("dir", "var/mkeventd/messages-history"),
],
},
"corehistory": {
"group" : _("Historic Data"),
"title" : _("Monitoring History"),
"prefix" : defaults.omd_root,
"paths" : [
("dir", "var/nagios/archive"),
("file", "var/nagios/nagios.log"),
("dir", "var/icinga/archive"),
("file", "var/icinga/icinga.log"),
("dir", "var/check_mk/core/archive"),
("file", "var/check_mk/core/history"),
],
},
"performancedata": {
"group" : _("Historic Data"),
"title" : _("Performance Data"),
"prefix" : defaults.omd_root,
"paths" : [
("dir", "var/pnp4nagios/perfdata"),
("dir", "var/rrdcached"),
("dir", "var/check_mk/rrd"),
],
"pre_restore" : lambda: performancedata_restore(pre_restore = True),
"post_restore" : lambda: performancedata_restore(pre_restore = False),
"checksum" : False,
},
"applicationlogs": {
"group" : _("Historic Data"),
"title" : _("Application Logs"),
"prefix" : defaults.omd_root,
"paths" : [
("dir", "var/log"),
("file", "var/nagios/livestatus.log"),
("dir", "var/pnp4nagios/log"),
],
"checksum" : False,
},
"snmpmibs": {
"group" : _("Configuration"),
"title" : _("SNMP MIBs"),
"prefix" : defaults.omd_root,
"paths" : [
("dir", "local/share/check_mk/mibs"),
],
},
"extensions" : {
"title" : _("Extensions in <tt>~/local/</tt> and MKPs"),
"prefix" : defaults.omd_root,
"paths" : [
("dir", "var/check_mk/packages" ),
("dir", "local" ),
],
"default" : True,
},
"dokuwiki": {
"title" : _("Doku Wiki Pages and Settings"),
"prefix" : defaults.omd_root,
"paths" : [
("dir", "var/dokuwiki"),
],
},
"nagvis": {
"title" : _("NagVis Maps, Configurations and User Files"),
"prefix" : defaults.omd_root,
"exclude" : [
"etc/nagvis/apache.conf",
"etc/nagvis/conf.d/authorisation.ini.php",
"etc/nagvis/conf.d/omd.ini.php",
"etc/nagvis/conf.d/cookie_auth.ini.php",
"etc/nagvis/conf.d/urls.ini.php"
],
"paths" : [
("dir", "local/share/nagvis"),
("dir", "etc/nagvis"),
("dir", "var/nagvis"),
],
},
})
|
class Solution:
"""
@param candidates: A list of integers
@param target: An integer
@return: A list of lists of integers
"""
def combinationSum(self, candidates, target):
# write your code here
if not candidates: return [[]]
nums = sorted(candidates)
res = []
visited = [0] * len(nums)
self.helper(res, [], 0, target, nums, 0, visited)
return res
def helper(self, res, part, sum, target, candidates, pos, visited):
if sum == target:
res.append(list(part))
return
for i in range(pos, len(candidates)):
sum += candidates[i]
part.append(candidates[i])
self.helper(res, part, sum, target, candidates, i, visited)
part.pop() # todo 这个的问题就在于没有 sum -= candidates[i]
def combinationSum(self, candidates, target):
candidates = sorted(list(set(candidates)))
results = []
self.dfs(candidates, target, 0, [], results,0)
return results
def dfs(self, candidates, target, start, combination, results,sum):
if target < sum: #todo 出口 勿忘
return
if target == sum:
return results.append(list(combination))
for i in range(start, len(candidates)):
sum+=candidates[i]
combination.append(candidates[i])
self.dfs(candidates, target, i, combination, results,sum)
combination.pop()
sum -= candidates[i]
s=Solution()
print(s.combinationSum([1, 2, 3], 5)) |
def create_mine_field(n, m, mines):
mine_field = [
[0 for _ in range(m)
] for _ in range(n)
]
for mine in mines:
x, y = mine
mine_field[x-1][y-1] = '*'
return mine_field
def neighbours(i, j, m):
nearest = [m[x][y] for x in [i-1, i, i+1] for y in [j-1, j, j+1]
if x in range(0, len(m)) and y in range(0, len(m[x]))
and (x, y) != (i, j)]
nearest_count = nearest.count('*')
return nearest_count
def check_field(mine_field, n, m):
for x in range(n):
for y in range(m):
if mine_field[x][y] == '*':
continue
else:
mine_field[x][y] = neighbours(i=x, j=y, m=mine_field)
with open('input.txt') as file:
lines = file.readlines()
n, m, k = list(map(int, lines[0].split()))
mines = []
for line in lines[1::]:
mines.append(list(map(int, line.split())))
mine_field = create_mine_field(n, m, mines)
check_field(mine_field, n, m)
with open('output.txt', 'w') as file:
rows = []
for row in mine_field:
line = f"{' '.join([str(item) for item in row])}\n"
rows.append(line)
file.writelines(rows)
|
'''
Что покажет приведенный ниже фрагмент кода?
'''
s = 'i Learn Python language'
print(s.capitalize()) |
line = '-'*39
blank = '|' + ' '*37 + '|'
print(line)
print(blank)
print(blank)
print(blank)
print(blank)
print(blank)
print(line)
|
print('*' * 47)
print('DIGITE 2 NÚMEROS ABAIXO PARA COMPARAR O MAIOR!')
print('*' * 47)
num1 = float(input('1º Número: '))
num2 = float(input('2º Número: '))
if num1 > num2:
print('O 1º valor é MAIOR!')
elif num2 > num1:
print('O 2º valor é MAIOR!')
else:
print('Os 2 valores são EQUIVALENTES!')
|
"""Iteration utilities"""
class Batch:
"""Yields batches (groups) from an iterable
Modified from:
http://codereview.stackexchange.com/questions/118883/split-up-an-iterable-into-batches
Args:
iterable (iterable) any iterable
limit (int) How many items to include per group
"""
def __init__(self, iterable, limit=None):
self.iterator = iter(iterable)
self.limit = limit
try:
self.current = next(self.iterator)
except StopIteration:
self.on_going = False
else:
self.on_going = True
def group(self):
"""Yield a group from the iterable"""
yield self.current
# start enumerate at 1 because we already yielded the last saved item
for num, item in enumerate(self.iterator, 1):
self.current = item
if num == self.limit:
break
yield item
else:
self.on_going = False
def __iter__(self):
"""Implementation of __iter__ to allow a standard interface:
for group in Batch(iterable, 10):
do_stuff(group)
"""
while self.on_going:
yield self.group()
|
"""
Created on February 17 2021
@author: Andreas Spanopoulos
Contains custom Exceptions classes that can be used for debugging purposes.
"""
class GameIsNotOverError(Exception):
""" Custom exception raised when the outcome of a game that has not yet finished is queried """
def __init__(self, *args):
""" constructor """
self.fen = args[0] if args else None
def __str__(self):
""" print when raised outside try block """
message = 'The game has not reached a terminal state.'
if self.fen:
message += f' The current FEN position is: {self.fen}'
return message
class InvalidConfigurationError(Exception):
""" Custom Error raised when a configuration file is invalid """
def __init__(self, **kwargs):
""" constructor """
super(InvalidConfigurationError, self).__init__()
self.message = '' + kwargs.get('msg', '')
def __str__(self):
""" return string representation of the error """
return self.message
class InvalidArchitectureError(Exception):
""" Custom Error raised when the architecture of a Network is invalid """
def __init__(self, **kwargs):
""" constructor """
super(InvalidArchitectureError, self).__init__()
self.message = '' + kwargs.get('msg', '')
def __str__(self):
""" return string representation of the error """
return self.message
|
class Solution:
def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
if len(a:=nums1) > len(b:=nums2):
a, b = b, a
n = len(a)
m = len(b)
median, i, j = 0, 0, 0
min_index = 0
max_index = n
while (min_index <= max_index) :
i = int((min_index + max_index) / 2)
j = int(((n + m + 1) / 2) - i)
if (i < n and j > 0 and b[j - 1] > a[i]) :
min_index = i + 1
elif (i > 0 and j < m and b[j] < a[i - 1]) :
max_index = i - 1
else :
if (i == 0) :
median = b[j - 1]
elif (j == 0) :
median = a[i - 1]
else :
median = maximum(a[i - 1], b[j - 1])
break
if ((n + m) % 2 == 1) :
return median
if (i == n) :
return ((median + b[j]) / 2.0)
if (j == m) :
return ((median + a[i]) / 2.0)
return ((median + minimum(a[i], b[j])) / 2.0)
def maximum(a, b) :
return a if a > b else b
def minimum(a, b) :
return a if a < b else b |
so={'1':'Windows Server','2':'Unix','3':'Linux','4':'Netware','5':'Mac OS','6':'Outro'}
dados={'voto':0,'maiorx':'','maiory':0,'final':''}
contagem={'Windows Server':0,'Unix':0,'Linux':0,'Netware':0,'Mac OS':0,'Outro':0}
ordem={}
print('Qual o melhor Sistema Operacional para uso em servidores?')
print('''
1- Windows Server
2- Unix
3- Linux
4- Netware
5- Mac OS
6- Outro''')
while True:
num = input('opção: ')
if int(num)>6:
print('valor invalido, digite um valor entre 1-6 ou 0 para encerrar')
elif num == '0':
break
else:
contagem[so[str(num)]]+=50
dados['voto']+=50
while True:
dados['maiorx'] = ''
dados['maiory'] = 0
for x,y in contagem.items():
if y > dados['maiory']:
dados['maiorx'] = x
dados['maiory'] = y
else:
if dados['final']=='':
dados['final']=dados['maiorx']
if dados['maiory'] == 0:
break
else:
ordem[dados['maiorx']] = dados['maiory']
contagem.pop('{}'.format(dados['maiorx']))
print('''
Sistema Operacional Votos %
------------------- ----- ---''')
for x,y in ordem.items():
print('{:15} {:5} {:.1f}%'.format(x,y,(y/dados['voto'])*100))
else:
print('''
------------------- -----
Total {}
O Sistema Operacional mais votado foi o {}, com {} votos, correspondendo a {:.1f}% dos votos.'''
.format(dados['voto'],dados['final'],ordem[dados['final']],(ordem[dados['final']]/dados['voto'])*100)) |
'''
Python function to check whether a number is divisible by another number.
Accept two integers values form the user.
'''
def multiple(m, n):
return True if m % n == 0 else False
print(multiple(20, 5))
print(multiple(7, 2))
|
def be_shy(say):
say('そんなこと言われたら照れるぱっちょ:denpaccho_upper_left::denpaccho_upper_right:')
def i_am_not_alexa(say):
say('誰に向かって言ってるぱっちょ:oni_paccho::punch:\n明日からキミの分は打刻しない:paccho:')
def i_am_not_siri(say):
say('誰に向かって言ってるぱっちょ:oni_paccho::punch:\nキミの有給1日減らす:paccho::denpaccho_kakusei:')
def you_know_secret_command(say):
say('君はヒミツのコマンド知ってるぱっちょね:denpacho_face_large:')
def how_to_use(say):
say('"おはー" か "おつー" って言うだけで打刻できるぱっちょ:paccho:\n `/clock-in` `/clock-out` のSlackコマンドでもいいぱっちょ!')
|
def extractSabishiidesu(item):
"""
Sabishii desu!
"""
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol or frag) or 'preview' in item['title'].lower():
return None
if 'tags' in item['tags']:
return None
tagmap = [
('Sono-sha. Nochi ni. . .', 'Sono-sha. Nochi ni. . .', 'translated'),
('Sonomono. Nochi ni.....', 'Sono-sha. Nochi ni. . .', 'translated'),
('Ore Dake Shoki Jobu Ga Maōdatta Ndaga', 'Ore Dake Shoki Jobu Ga Maōdatta Ndaga', 'translated'),
('VRMMO Summoner Hajimemashita', 'VRMMO Summoner Hajimemashita', 'translated'),
("My Room Has Become A Dungeon's Rest Area", "My Room Has Become A Dungeon's Rest Area", 'translated'),
]
for tagname, name, tl_type in tagmap:
if tagname in item['tags']:
return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)
return False |
#
# PySNMP MIB module MISSION-CRITICAL-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/MISSION-CRITICAL-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:12:55 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
Integer, OctetString, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
SingleValueConstraint, ConstraintsUnion, ValueSizeConstraint, ConstraintsIntersection, ValueRangeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ConstraintsUnion", "ValueSizeConstraint", "ConstraintsIntersection", "ValueRangeConstraint")
NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance")
NotificationType, TimeTicks, iso, MibScalar, MibTable, MibTableRow, MibTableColumn, Counter64, MibIdentifier, Bits, NotificationType, enterprises, Gauge32, Counter32, Unsigned32, IpAddress, Integer32, ModuleIdentity, ObjectIdentity = mibBuilder.importSymbols("SNMPv2-SMI", "NotificationType", "TimeTicks", "iso", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Counter64", "MibIdentifier", "Bits", "NotificationType", "enterprises", "Gauge32", "Counter32", "Unsigned32", "IpAddress", "Integer32", "ModuleIdentity", "ObjectIdentity")
TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString")
missionCritical = MibIdentifier((1, 3, 6, 1, 4, 1, 2349))
mcsCompanyInfo = MibIdentifier((1, 3, 6, 1, 4, 1, 2349, 1))
mcsSoftware = MibIdentifier((1, 3, 6, 1, 4, 1, 2349, 2))
eemProductInfo = MibIdentifier((1, 3, 6, 1, 4, 1, 2349, 2, 1))
omProductInfo = MibIdentifier((1, 3, 6, 1, 4, 1, 2349, 2, 2))
ownershipDetails = MibScalar((1, 3, 6, 1, 4, 1, 2349, 1, 1), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: ownershipDetails.setStatus('mandatory')
if mibBuilder.loadTexts: ownershipDetails.setDescription('Details of the company providing this MIB')
contactDetails = MibScalar((1, 3, 6, 1, 4, 1, 2349, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 64))).setMaxAccess("readonly")
if mibBuilder.loadTexts: contactDetails.setStatus('mandatory')
if mibBuilder.loadTexts: contactDetails.setDescription('Contact responsible for maintaining this MIB')
eemService = MibIdentifier((1, 3, 6, 1, 4, 1, 2349, 2, 1, 1))
version = MibScalar((1, 3, 6, 1, 4, 1, 2349, 2, 1, 1, 1), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 16))).setMaxAccess("readonly")
if mibBuilder.loadTexts: version.setStatus('mandatory')
if mibBuilder.loadTexts: version.setDescription('The version of the EEM Agent running')
primaryServer = MibScalar((1, 3, 6, 1, 4, 1, 2349, 2, 1, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 16))).setMaxAccess("readonly")
if mibBuilder.loadTexts: primaryServer.setStatus('mandatory')
if mibBuilder.loadTexts: primaryServer.setDescription('The Primary Server for this EEM Agent')
serviceState = MibScalar((1, 3, 6, 1, 4, 1, 2349, 2, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("up", 1), ("down", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: serviceState.setStatus('mandatory')
if mibBuilder.loadTexts: serviceState.setDescription('State of the service. Running is 1, stopped is 2')
serviceUpTime = MibScalar((1, 3, 6, 1, 4, 1, 2349, 2, 1, 1, 4), TimeTicks()).setMaxAccess("readonly")
if mibBuilder.loadTexts: serviceUpTime.setStatus('mandatory')
if mibBuilder.loadTexts: serviceUpTime.setDescription('No. of milliseconds since the service was started')
redTrapCount = MibScalar((1, 3, 6, 1, 4, 1, 2349, 2, 1, 1, 5), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: redTrapCount.setStatus('deprecated')
if mibBuilder.loadTexts: redTrapCount.setDescription('The number of red alert traps sent since the service was started')
orangeTrapCount = MibScalar((1, 3, 6, 1, 4, 1, 2349, 2, 1, 1, 6), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: orangeTrapCount.setStatus('deprecated')
if mibBuilder.loadTexts: orangeTrapCount.setDescription('The number of orange alert traps sent since the service was started')
amberTrapCount = MibScalar((1, 3, 6, 1, 4, 1, 2349, 2, 1, 1, 7), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: amberTrapCount.setStatus('deprecated')
if mibBuilder.loadTexts: amberTrapCount.setDescription('The number of yellow alert traps sent since the service was started')
blueTrapCount = MibScalar((1, 3, 6, 1, 4, 1, 2349, 2, 1, 1, 8), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: blueTrapCount.setStatus('deprecated')
if mibBuilder.loadTexts: blueTrapCount.setDescription('The number of blue alert traps sent since the service was started')
greenTrapCount = MibScalar((1, 3, 6, 1, 4, 1, 2349, 2, 1, 1, 9), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: greenTrapCount.setStatus('deprecated')
if mibBuilder.loadTexts: greenTrapCount.setDescription('The number of Green Alert Traps since the service was started')
eemLastTrap = MibIdentifier((1, 3, 6, 1, 4, 1, 2349, 2, 1, 2))
trapTime = MibScalar((1, 3, 6, 1, 4, 1, 2349, 2, 1, 2, 1), TimeTicks()).setMaxAccess("readonly")
if mibBuilder.loadTexts: trapTime.setStatus('deprecated')
if mibBuilder.loadTexts: trapTime.setDescription('Time of the last trap sent')
alertLevel = MibScalar((1, 3, 6, 1, 4, 1, 2349, 2, 1, 2, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("red", 1), ("orange", 2), ("yellow", 3), ("blue", 4), ("green", 5)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: alertLevel.setStatus('mandatory')
if mibBuilder.loadTexts: alertLevel.setDescription('Alert level of the last trap sent. red=1, orange=2, yellow=3, blue=4, green=5')
logType = MibScalar((1, 3, 6, 1, 4, 1, 2349, 2, 1, 2, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 99))).clone(namedValues=NamedValues(("ntevent", 1), ("application", 2), ("snmp", 3), ("wbem", 4), ("activemonitoring", 5), ("performancemonitoring", 6), ("timedevent", 7), ("eem", 99)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: logType.setStatus('mandatory')
if mibBuilder.loadTexts: logType.setDescription('Log type generating the last trap sent. system=1,application=2,security=3 (fill in others here) EEM=99')
server = MibScalar((1, 3, 6, 1, 4, 1, 2349, 2, 1, 2, 4), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: server.setStatus('mandatory')
if mibBuilder.loadTexts: server.setDescription('Server generating the last trap sent')
source = MibScalar((1, 3, 6, 1, 4, 1, 2349, 2, 1, 2, 5), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: source.setStatus('mandatory')
if mibBuilder.loadTexts: source.setDescription('Source generating the last trap sent')
user = MibScalar((1, 3, 6, 1, 4, 1, 2349, 2, 1, 2, 6), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: user.setStatus('mandatory')
if mibBuilder.loadTexts: user.setDescription('User generating the last trap sent')
eventID = MibScalar((1, 3, 6, 1, 4, 1, 2349, 2, 1, 2, 7), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: eventID.setStatus('mandatory')
if mibBuilder.loadTexts: eventID.setDescription('Event ID of the last trap sent')
description = MibScalar((1, 3, 6, 1, 4, 1, 2349, 2, 1, 2, 8), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 1024))).setMaxAccess("readonly")
if mibBuilder.loadTexts: description.setStatus('mandatory')
if mibBuilder.loadTexts: description.setDescription('Text description of the last trap sent')
genericTrapNumber = MibScalar((1, 3, 6, 1, 4, 1, 2349, 2, 1, 2, 9), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: genericTrapNumber.setStatus('mandatory')
if mibBuilder.loadTexts: genericTrapNumber.setDescription('The generic trap number of the last trap sent')
specificTrapNumber = MibScalar((1, 3, 6, 1, 4, 1, 2349, 2, 1, 2, 10), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: specificTrapNumber.setStatus('mandatory')
if mibBuilder.loadTexts: specificTrapNumber.setDescription('The user specific trap number of the last trap sent')
serviceGoingDown = NotificationType((1, 3, 6, 1, 4, 1, 2349, 2, 1) + (0,2))
if mibBuilder.loadTexts: serviceGoingDown.setDescription('The SeNTry EEM Sender service is stopping.')
serviceComingUp = NotificationType((1, 3, 6, 1, 4, 1, 2349, 2, 1) + (0,3))
if mibBuilder.loadTexts: serviceComingUp.setDescription('The SeNTry EEM Sender service is starting.')
gathererServiceGoingDown = NotificationType((1, 3, 6, 1, 4, 1, 2349, 2, 1) + (0,4))
if mibBuilder.loadTexts: gathererServiceGoingDown.setDescription('The SeNTry EEM Gatherer service is stopping.')
gathererServiceComingUp = NotificationType((1, 3, 6, 1, 4, 1, 2349, 2, 1) + (0,5))
if mibBuilder.loadTexts: gathererServiceComingUp.setDescription('The SeNTry EEM Gatherer service is starting.')
eemRedAlert = NotificationType((1, 3, 6, 1, 4, 1, 2349, 2, 1) + (0,100)).setObjects(("MISSION-CRITICAL-MIB", "alertLevel"), ("MISSION-CRITICAL-MIB", "logType"), ("MISSION-CRITICAL-MIB", "server"), ("MISSION-CRITICAL-MIB", "source"), ("MISSION-CRITICAL-MIB", "user"), ("MISSION-CRITICAL-MIB", "eventID"), ("MISSION-CRITICAL-MIB", "description"))
if mibBuilder.loadTexts: eemRedAlert.setDescription('A SeNTry EEM red alert has been generated.')
eemOrangeAlert = NotificationType((1, 3, 6, 1, 4, 1, 2349, 2, 1) + (0,200)).setObjects(("MISSION-CRITICAL-MIB", "alertLevel"), ("MISSION-CRITICAL-MIB", "logType"), ("MISSION-CRITICAL-MIB", "server"), ("MISSION-CRITICAL-MIB", "source"), ("MISSION-CRITICAL-MIB", "user"), ("MISSION-CRITICAL-MIB", "eventID"), ("MISSION-CRITICAL-MIB", "description"))
if mibBuilder.loadTexts: eemOrangeAlert.setDescription('A SeNTry EEM orange alert has been generated.')
eemYellowAlert = NotificationType((1, 3, 6, 1, 4, 1, 2349, 2, 1) + (0,300)).setObjects(("MISSION-CRITICAL-MIB", "alertLevel"), ("MISSION-CRITICAL-MIB", "logType"), ("MISSION-CRITICAL-MIB", "server"), ("MISSION-CRITICAL-MIB", "source"), ("MISSION-CRITICAL-MIB", "user"), ("MISSION-CRITICAL-MIB", "eventID"), ("MISSION-CRITICAL-MIB", "description"))
if mibBuilder.loadTexts: eemYellowAlert.setDescription('A SeNTry EEM yellow alert has been generated.')
eemBlueAlert = NotificationType((1, 3, 6, 1, 4, 1, 2349, 2, 1) + (0,400)).setObjects(("MISSION-CRITICAL-MIB", "alertLevel"), ("MISSION-CRITICAL-MIB", "logType"), ("MISSION-CRITICAL-MIB", "server"), ("MISSION-CRITICAL-MIB", "source"), ("MISSION-CRITICAL-MIB", "user"), ("MISSION-CRITICAL-MIB", "eventID"), ("MISSION-CRITICAL-MIB", "description"))
if mibBuilder.loadTexts: eemBlueAlert.setDescription('A SeNTry EEM blue alert has been generated.')
eemGreenAlert = NotificationType((1, 3, 6, 1, 4, 1, 2349, 2, 1) + (0,500)).setObjects(("MISSION-CRITICAL-MIB", "alertLevel"), ("MISSION-CRITICAL-MIB", "logType"), ("MISSION-CRITICAL-MIB", "server"), ("MISSION-CRITICAL-MIB", "source"), ("MISSION-CRITICAL-MIB", "user"), ("MISSION-CRITICAL-MIB", "eventID"), ("MISSION-CRITICAL-MIB", "description"))
if mibBuilder.loadTexts: eemGreenAlert.setDescription('A SeNTry EEM green alert has been generated.')
omService = MibIdentifier((1, 3, 6, 1, 4, 1, 2349, 2, 2, 1))
omLastTrap = MibIdentifier((1, 3, 6, 1, 4, 1, 2349, 2, 2, 2))
omTrapTime = MibScalar((1, 3, 6, 1, 4, 1, 2349, 2, 2, 2, 1), TimeTicks()).setMaxAccess("readonly")
if mibBuilder.loadTexts: omTrapTime.setStatus('deprecated')
if mibBuilder.loadTexts: omTrapTime.setDescription('Time of the last trap sent.')
omAlertLevel = MibScalar((1, 3, 6, 1, 4, 1, 2349, 2, 2, 2, 2), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: omAlertLevel.setStatus('mandatory')
if mibBuilder.loadTexts: omAlertLevel.setDescription('Alert level of the last trap sent.')
omAlertLevelName = MibScalar((1, 3, 6, 1, 4, 1, 2349, 2, 2, 2, 3), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: omAlertLevelName.setStatus('mandatory')
if mibBuilder.loadTexts: omAlertLevelName.setDescription('A textual description of the alert level for the last trap sent.')
omServer = MibScalar((1, 3, 6, 1, 4, 1, 2349, 2, 2, 2, 4), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: omServer.setStatus('mandatory')
if mibBuilder.loadTexts: omServer.setDescription('Server generating the last trap sent.')
omSource = MibScalar((1, 3, 6, 1, 4, 1, 2349, 2, 2, 2, 5), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: omSource.setStatus('mandatory')
if mibBuilder.loadTexts: omSource.setDescription('Source generating the last trap sent.')
omOwner = MibScalar((1, 3, 6, 1, 4, 1, 2349, 2, 2, 2, 6), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: omOwner.setStatus('mandatory')
if mibBuilder.loadTexts: omOwner.setDescription('User generating the last trap sent.')
omDescription = MibScalar((1, 3, 6, 1, 4, 1, 2349, 2, 2, 2, 7), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 1024))).setMaxAccess("readonly")
if mibBuilder.loadTexts: omDescription.setStatus('mandatory')
if mibBuilder.loadTexts: omDescription.setDescription('Text description of the last trap sent.')
omCustomField1 = MibScalar((1, 3, 6, 1, 4, 1, 2349, 2, 2, 2, 8), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 1024))).setMaxAccess("readonly")
if mibBuilder.loadTexts: omCustomField1.setStatus('mandatory')
if mibBuilder.loadTexts: omCustomField1.setDescription('Custom Field 1 defined by user')
omCustomField2 = MibScalar((1, 3, 6, 1, 4, 1, 2349, 2, 2, 2, 9), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 1024))).setMaxAccess("readonly")
if mibBuilder.loadTexts: omCustomField2.setStatus('mandatory')
if mibBuilder.loadTexts: omCustomField2.setDescription('Custom Field 2 defined by user')
omCustomField3 = MibScalar((1, 3, 6, 1, 4, 1, 2349, 2, 2, 2, 10), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 1024))).setMaxAccess("readonly")
if mibBuilder.loadTexts: omCustomField3.setStatus('mandatory')
if mibBuilder.loadTexts: omCustomField3.setDescription('Custom Field 3 defined by user')
omCustomField4 = MibScalar((1, 3, 6, 1, 4, 1, 2349, 2, 2, 2, 11), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 1024))).setMaxAccess("readonly")
if mibBuilder.loadTexts: omCustomField4.setStatus('mandatory')
if mibBuilder.loadTexts: omCustomField4.setDescription('Custom Field 4 defined by user')
omCustomField5 = MibScalar((1, 3, 6, 1, 4, 1, 2349, 2, 2, 2, 12), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 1024))).setMaxAccess("readonly")
if mibBuilder.loadTexts: omCustomField5.setStatus('mandatory')
if mibBuilder.loadTexts: omCustomField5.setDescription('Custom Field 5 defined by user')
omAlertURL = MibScalar((1, 3, 6, 1, 4, 1, 2349, 2, 2, 2, 13), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 2048))).setMaxAccess("readonly")
if mibBuilder.loadTexts: omAlertURL.setStatus('mandatory')
if mibBuilder.loadTexts: omAlertURL.setDescription('URL used to view alert details')
omGenericTrapNumber = MibScalar((1, 3, 6, 1, 4, 1, 2349, 2, 2, 2, 14), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: omGenericTrapNumber.setStatus('mandatory')
if mibBuilder.loadTexts: omGenericTrapNumber.setDescription('The generic trap number of the last trap sent.')
omSpecificTrapNumber = MibScalar((1, 3, 6, 1, 4, 1, 2349, 2, 2, 2, 15), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: omSpecificTrapNumber.setStatus('mandatory')
if mibBuilder.loadTexts: omSpecificTrapNumber.setDescription('The user specific trap number of the last trap sent')
omBlueAlert = NotificationType((1, 3, 6, 1, 4, 1, 2349, 2, 2) + (0,10)).setObjects(("MISSION-CRITICAL-MIB", "omAlertLevel"), ("MISSION-CRITICAL-MIB", "omAlertLevelName"), ("MISSION-CRITICAL-MIB", "omServer"), ("MISSION-CRITICAL-MIB", "omSource"), ("MISSION-CRITICAL-MIB", "omOwner"), ("MISSION-CRITICAL-MIB", "omDescription"), ("MISSION-CRITICAL-MIB", "omCustomField1"), ("MISSION-CRITICAL-MIB", "omCustomField2"), ("MISSION-CRITICAL-MIB", "omCustomField3"), ("MISSION-CRITICAL-MIB", "omCustomField4"), ("MISSION-CRITICAL-MIB", "omCustomField5"), ("MISSION-CRITICAL-MIB", "omAlertURL"))
if mibBuilder.loadTexts: omBlueAlert.setDescription('A OnePoint Operations Manager Blue Alert has been generated.')
omGreenAlert = NotificationType((1, 3, 6, 1, 4, 1, 2349, 2, 2) + (0,20)).setObjects(("MISSION-CRITICAL-MIB", "omAlertLevel"), ("MISSION-CRITICAL-MIB", "omAlertLevelName"), ("MISSION-CRITICAL-MIB", "omServer"), ("MISSION-CRITICAL-MIB", "omSource"), ("MISSION-CRITICAL-MIB", "omOwner"), ("MISSION-CRITICAL-MIB", "omDescription"), ("MISSION-CRITICAL-MIB", "omCustomField1"), ("MISSION-CRITICAL-MIB", "omCustomField2"), ("MISSION-CRITICAL-MIB", "omCustomField3"), ("MISSION-CRITICAL-MIB", "omCustomField4"), ("MISSION-CRITICAL-MIB", "omCustomField5"), ("MISSION-CRITICAL-MIB", "omAlertURL"))
if mibBuilder.loadTexts: omGreenAlert.setDescription('A OnePoint Operations Manager Green Alert has been generated.')
omYellowAlert = NotificationType((1, 3, 6, 1, 4, 1, 2349, 2, 2) + (0,30)).setObjects(("MISSION-CRITICAL-MIB", "omAlertLevel"), ("MISSION-CRITICAL-MIB", "omAlertLevelName"), ("MISSION-CRITICAL-MIB", "omServer"), ("MISSION-CRITICAL-MIB", "omSource"), ("MISSION-CRITICAL-MIB", "omOwner"), ("MISSION-CRITICAL-MIB", "omDescription"), ("MISSION-CRITICAL-MIB", "omCustomField1"), ("MISSION-CRITICAL-MIB", "omCustomField2"), ("MISSION-CRITICAL-MIB", "omCustomField3"), ("MISSION-CRITICAL-MIB", "omCustomField4"), ("MISSION-CRITICAL-MIB", "omCustomField5"), ("MISSION-CRITICAL-MIB", "omAlertURL"))
if mibBuilder.loadTexts: omYellowAlert.setDescription('A OnePoint Operations Manager Yellow Alert has been generated.')
omOrangeAlert = NotificationType((1, 3, 6, 1, 4, 1, 2349, 2, 2) + (0,40)).setObjects(("MISSION-CRITICAL-MIB", "omAlertLevel"), ("MISSION-CRITICAL-MIB", "omAlertLevelName"), ("MISSION-CRITICAL-MIB", "omServer"), ("MISSION-CRITICAL-MIB", "omSource"), ("MISSION-CRITICAL-MIB", "omOwner"), ("MISSION-CRITICAL-MIB", "omDescription"), ("MISSION-CRITICAL-MIB", "omCustomField1"), ("MISSION-CRITICAL-MIB", "omCustomField2"), ("MISSION-CRITICAL-MIB", "omCustomField3"), ("MISSION-CRITICAL-MIB", "omCustomField4"), ("MISSION-CRITICAL-MIB", "omCustomField5"), ("MISSION-CRITICAL-MIB", "omAlertURL"))
if mibBuilder.loadTexts: omOrangeAlert.setDescription('A OnePoint Operations Manager Orange Alert has been generated.')
omRedCriticalErrorAlert = NotificationType((1, 3, 6, 1, 4, 1, 2349, 2, 2) + (0,50)).setObjects(("MISSION-CRITICAL-MIB", "omAlertLevel"), ("MISSION-CRITICAL-MIB", "omAlertLevelName"), ("MISSION-CRITICAL-MIB", "omServer"), ("MISSION-CRITICAL-MIB", "omSource"), ("MISSION-CRITICAL-MIB", "omOwner"), ("MISSION-CRITICAL-MIB", "omDescription"), ("MISSION-CRITICAL-MIB", "omCustomField1"), ("MISSION-CRITICAL-MIB", "omCustomField2"), ("MISSION-CRITICAL-MIB", "omCustomField3"), ("MISSION-CRITICAL-MIB", "omCustomField4"), ("MISSION-CRITICAL-MIB", "omCustomField5"), ("MISSION-CRITICAL-MIB", "omAlertURL"))
if mibBuilder.loadTexts: omRedCriticalErrorAlert.setDescription('A OnePoint Operations Manager Critical Error Alert has been generated.')
omRedSecurityBreachAlert = NotificationType((1, 3, 6, 1, 4, 1, 2349, 2, 2) + (0,60)).setObjects(("MISSION-CRITICAL-MIB", "omAlertLevel"), ("MISSION-CRITICAL-MIB", "omAlertLevelName"), ("MISSION-CRITICAL-MIB", "omServer"), ("MISSION-CRITICAL-MIB", "omSource"), ("MISSION-CRITICAL-MIB", "omOwner"), ("MISSION-CRITICAL-MIB", "omDescription"), ("MISSION-CRITICAL-MIB", "omCustomField1"), ("MISSION-CRITICAL-MIB", "omCustomField2"), ("MISSION-CRITICAL-MIB", "omCustomField3"), ("MISSION-CRITICAL-MIB", "omCustomField4"), ("MISSION-CRITICAL-MIB", "omCustomField5"), ("MISSION-CRITICAL-MIB", "omAlertURL"))
if mibBuilder.loadTexts: omRedSecurityBreachAlert.setDescription('A OnePoint Operations Manager Security Breach Alert has been generated.')
omRedServiceUnavailableAlert = NotificationType((1, 3, 6, 1, 4, 1, 2349, 2, 2) + (0,70)).setObjects(("MISSION-CRITICAL-MIB", "omAlertLevel"), ("MISSION-CRITICAL-MIB", "omAlertLevelName"), ("MISSION-CRITICAL-MIB", "omServer"), ("MISSION-CRITICAL-MIB", "omSource"), ("MISSION-CRITICAL-MIB", "omOwner"), ("MISSION-CRITICAL-MIB", "omDescription"), ("MISSION-CRITICAL-MIB", "omCustomField1"), ("MISSION-CRITICAL-MIB", "omCustomField2"), ("MISSION-CRITICAL-MIB", "omCustomField3"), ("MISSION-CRITICAL-MIB", "omCustomField4"), ("MISSION-CRITICAL-MIB", "omCustomField5"), ("MISSION-CRITICAL-MIB", "omAlertURL"))
if mibBuilder.loadTexts: omRedServiceUnavailableAlert.setDescription('A OnePoint Operations Manager Service Unavailable Alert has been generated.')
mibBuilder.exportSymbols("MISSION-CRITICAL-MIB", serviceUpTime=serviceUpTime, omYellowAlert=omYellowAlert, redTrapCount=redTrapCount, eemOrangeAlert=eemOrangeAlert, mcsCompanyInfo=mcsCompanyInfo, omCustomField4=omCustomField4, gathererServiceComingUp=gathererServiceComingUp, serviceState=serviceState, omCustomField2=omCustomField2, omDescription=omDescription, missionCritical=missionCritical, omService=omService, eventID=eventID, omAlertLevelName=omAlertLevelName, serviceGoingDown=serviceGoingDown, omProductInfo=omProductInfo, trapTime=trapTime, eemService=eemService, eemYellowAlert=eemYellowAlert, omRedCriticalErrorAlert=omRedCriticalErrorAlert, omRedSecurityBreachAlert=omRedSecurityBreachAlert, blueTrapCount=blueTrapCount, greenTrapCount=greenTrapCount, omServer=omServer, mcsSoftware=mcsSoftware, serviceComingUp=serviceComingUp, omCustomField1=omCustomField1, omGreenAlert=omGreenAlert, eemLastTrap=eemLastTrap, omCustomField5=omCustomField5, omAlertURL=omAlertURL, omOrangeAlert=omOrangeAlert, omTrapTime=omTrapTime, logType=logType, amberTrapCount=amberTrapCount, user=user, specificTrapNumber=specificTrapNumber, source=source, omBlueAlert=omBlueAlert, ownershipDetails=ownershipDetails, eemRedAlert=eemRedAlert, omSpecificTrapNumber=omSpecificTrapNumber, omOwner=omOwner, gathererServiceGoingDown=gathererServiceGoingDown, orangeTrapCount=orangeTrapCount, server=server, omLastTrap=omLastTrap, omAlertLevel=omAlertLevel, omCustomField3=omCustomField3, omGenericTrapNumber=omGenericTrapNumber, description=description, genericTrapNumber=genericTrapNumber, eemGreenAlert=eemGreenAlert, primaryServer=primaryServer, alertLevel=alertLevel, version=version, omSource=omSource, eemProductInfo=eemProductInfo, eemBlueAlert=eemBlueAlert, contactDetails=contactDetails, omRedServiceUnavailableAlert=omRedServiceUnavailableAlert)
|
def assert_has_size(output_bytes, value, delta=0):
"""Asserts the specified output has a size of the specified value"""
output_size = len(output_bytes)
assert abs(output_size - int(value)) <= int(delta), "Expected file size was %s, actual file size was %s (difference of %s accepted)" % (value, output_size, delta)
|
'''
Copyright (©) 2019 - Randall Simpson
pi-iot
This base sensor class.
'''
class Sensor:
def __init__(self, source, metric_prefix, output):
self.source = source
self.metric_prefix = metric_prefix
self.output = output
self.metrics = []
def get_info():
return None
def format_metrics():
return None
|
num = 111
num = 222
num = 333333
num = 333
num4 = 44444
|
__author__ = "hoongeun"
__version__ = "0.0.1"
__copyright__ = "Copyright (c) hoongeun"
__license__ = "Beer ware"
|
# Function arguments ...
#
# Class instances can be pass as arguments to functions
class Point:
""" a 2D point """
p = Point()
p.x = 1
p.y = 2
def print_point(point):
print('(%s, %s)' % (point.x, point.y))
print_point(p) # (1, 2) |
def test1():
inp="0 2 7 0"
inp="4 10 4 1 8 4 9 14 5 1 14 15 0 15 3 5"
nums = list(map(lambda x: int(x), inp.split()))
hist = [ nums ]
step = 1
current = nums[:]
while True:
#print('step', step, 'current', current)
#search max
m = max(current)
#max index
idx = current.index(m)
current[idx] = 0
idx += 1
while m > 0:
idx = 0 if idx >= len(current) else idx
current[idx] += 1
m -= 1
idx += 1
if current in hist:
print(step, hist.index(current), step - hist.index(current))
break
step += 1
hist.append(current[:])
#print(hist[0])
|
#!/usr/bin/env python
#
# @Author: Dalmasso Giovanni <gioda>
# @Date: 09-Feb-2018
# @Email: giovanni.dalmasso@embl.es
# @Project: python_utils
# @Filename: colors.py
# @Last modified by: gioda
# @Last modified time: 15-Mar-2018
# @License: MIT
"""Collection of basic colors as RGB for plotting (inspired by "Tableau" www.tableau.com)."""
def colBase10():
"""List of 10 basic colors as RGB."""
col = [(31, 119, 180), (255, 127, 14), (44, 160, 44), (214, 39, 40), (148, 103, 189),
(140, 86, 75), (227, 119, 194), (127, 127, 127), (188, 189, 34), (23, 190, 207)]
# Scale the RGB values to the [0, 1] range, which is the format matplotlib accepts.
for j in range(len(col)):
r, g, b = col[j]
col[j] = (r / 255., g / 255., b / 255.)
col = col * 100000
return col
def colLight():
"""List of 10 light colors as RGB."""
col = [(174, 199, 232), (255, 187, 120), (152, 223, 138), (255, 152, 150), (197, 176, 213),
(196, 156, 148), (247, 182, 210), (199, 199, 199), (219, 219, 141), (158, 218, 229)]
# Scale the RGB values to the [0, 1] range, which is the format matplotlib accepts.
for j in range(len(col)):
r, g, b = col[j]
col[j] = (r / 255., g / 255., b / 255.)
col = col * 100000
return col
def colMedium():
"""List of 10 medium colors as RGB."""
col = [(114, 158, 206), (255, 158, 74), (103, 191, 92), (237, 102, 93), (173, 139, 201),
(168, 120, 110), (237, 151, 202), (162, 162, 162), (205, 204, 93), (109, 204, 218)]
# Scale the RGB values to the [0, 1] range, which is the format matplotlib accepts.
for j in range(len(col)):
r, g, b = col[j]
col[j] = (r / 255., g / 255., b / 255.)
col = col * 100000
return col
def colCblind():
"""List of 10 color blind colors as RGB."""
col = [(0, 107, 164), (255, 128, 14), (171, 171, 171), (89, 89, 89), (95, 158, 209),
(200, 82, 0), (137, 137, 137), (162, 200, 236), (255, 188, 121), (207, 207, 207)]
# Scale the RGB values to the [0, 1] range, which is the format matplotlib accepts.
for j in range(len(col)):
r, g, b = col[j]
col[j] = (r / 255., g / 255., b / 255.)
col = col * 100000
return col
def colGrey():
"""List of 5 grey colors as RGB."""
col = [(207, 207, 207), (165, 172, 175), (143, 135, 130), (96, 99, 106), (65, 68, 81)]
# Scale the RGB values to the [0, 1] range, which is the format matplotlib accepts.
for j in range(len(col)):
r, g, b = col[j]
col[j] = (r / 255., g / 255., b / 255.)
col = col * 100000
return col
def colTrafficLigth():
"""List of 9 traffic-light colors as RGB."""
col = [(255, 193, 86), (219, 161, 58), (216, 37, 38), (177, 3, 24),
(48, 147, 67), (255, 221, 113), (242, 108, 100), (159, 205, 153), (105, 183, 100)]
# Scale the RGB values to the [0, 1] range, which is the format matplotlib accepts.
for j in range(len(col)):
r, g, b = col[j]
col[j] = (r / 255., g / 255., b / 255.)
col = col * 100000
return col
def colPurpleGrey():
"""List of 6 purple-grey colors as RGB."""
col = [(220, 95, 189), (208, 152, 238), (153, 86, 136),
(148, 145, 123), (123, 102, 210), (215, 213, 197)]
# Scale the RGB values to the [0, 1] range, which is the format matplotlib accepts.
for j in range(len(col)):
r, g, b = col[j]
col[j] = (r / 255., g / 255., b / 255.)
col = col * 100000
return col
def colBase20():
"""List of 20 basic colors as RGB."""
col = [(31, 119, 180), (174, 199, 232), (255, 127, 14), (255, 187, 120),
(44, 160, 44), (152, 223, 138), (214, 39, 40), (255, 152, 150),
(148, 103, 189), (197, 176, 213), (140, 86, 75), (196, 156, 148),
(227, 119, 194), (247, 182, 210), (127, 127, 127), (199, 199, 199),
(188, 189, 34), (219, 219, 141), (23, 190, 207), (158, 218, 229)]
# Scale the RGB values to the [0, 1] range, which is the format matplotlib accepts.
for j in range(len(col)):
r, g, b = col[j]
col[j] = (r / 255., g / 255., b / 255.)
col = col * 100000
return col
|
"""
На вход подается число n, верните разность n и 21. При этом если n больше 21, верните удвоенную разность.
diff21(19) → 2
diff21(10) → 11
diff21(21) → 0
diff21(50) → 58
diff21(-2) → 23
diff21(-1) → 22
diff21(2) → 19
diff21(0) → 21
diff21(30) → 18
"""
def diff(num):
return 0
|
##functions-question1
# def ask_questions():
# print("who is the the founder of facebook?")
# print(" - Mark Zuckerberg\n# - Bill Gates\n# - Steve Jobs\n# - Larry Page")
#ask_questions()
# ask_questions()
# ask_questions()
# ask_questions()
# ask_questions()
# ask_questions()
## called function 100 time using loop
# def ask_questions():
# print("who is the the founder of facebook?")
# print(" - Mark Zuckerberg\n# - Bill Gates\n# - Steve Jobs\n# - Larry Page")
#for i in range(101):
# i=0
# while i<=100:
# ask_questions()
# i+=1
###################################################################################
## questions-1
# numbers = [3, 5, 7, 34, 2, 89, 2, 5]
# print("maximum number in list=",max(numbers))
## ques-2
# numbers = [1, 2, 3, 4, 5]
# print("sum of numbers=",sum(numbers))
# ## quesn-3
# unorder_list = [6, 8, 4, 3, 9, 56, 0, 34, 7, 15]
# unorder_list.sort()
# print("ordered list =",unorder_list)
## questions-4
# list = [8, 6, 4, 8, 4, 50, 2, 7]
# print("minimum number in list=",min(numbers))
# ## questions-5
# reverse_list = ["Z", "A", "A", "B", "E", "M", "A", "R", "D"]
# reverse_list.reverse()
# print("reverse of list",reverse_list)
################################################################
## DEBUG
## que-1 " : "colon is missing
## que-2 "def" spelling is wrong like daf
## que-3 "full indentation is missing" in less indentation was there
# isEven()
# def isEven():
# if(12%2==0):
# print("Even Number")
# else:
# print("Old Number")
# isEven()
#############################################################################
## Multiple Function Arguments
# def say_hello_language(name, language):
# if language == "hindi":
# print("Namaste ", name)
# print("Aap kaise ho?")
# elif language == "punjabi":
# print("Sat sri akaal ", name)
# print("Tuhada ki haal hai?")
# else:
# print("Hello ", name)
# print("How are you?")
# say_hello_language("Rishabh", "punjabi")
# say_hello_language("Armaan", "english")
# say_hello_language("Abhishek", "french")
# say_hello_language("Kavay", "hindi")
##################################################################################
# def say_hello_people(name_x, name_y, name_z, name_a):
# print("Namaste ", name_x) # hindi mein
# print("Alah hafiz ", name_y) # urdu mein
# print("Bonjour ", name_z) # french mein
# print("Hello ", name_a) # english mein
# say_hello_people("Imitiyaz", "Rishabh", "Rahul", "Vidya")
# say_hello_people("Steve", "Saswata", "Shakrundin", "Rajeev")
###########################################################################
## Python Arbitrary Arguments
#Arbitrary arguments hum tab use karte hai jab hume pata nahi hota
#hai ki hume kitne no. of arguments function mai dene hai. Hum arbitrary
#arguments ke sath function of define karne ke liye parameter se pehle ( * )
#ka use karte hai jai ki neeche dikhaya gaya hai.
# def icecream(*flavours):
# for flavour in flavours:
# print("i love"+flavour)
# icecream("chocolate", "butterscotch","vanilla","strawberry")
###########################################################################3
##Default parameter value
# Default parameter value se yaha humara ye matlab hai ki hum function ko define karte time kisi
# parameter ko value assign kar dete hai taaki hum function ko bina kisi argument ke call kare to
# vo default value ko le le.
# def attendance(name,status="absent"):
# print(name,"is",status," today")
# attendance("kartik","present")
# attendance("sonu")
# attendance("vishal","present")
# attendance("umesh")
#################################################################################
## code debug
## quen-1
# def greet(*names):
# for name in names:
# print("Welcome", name)
# greet("Rinki", "Vishal", "Kartik", "Bijender")
# ans * is missing in parametre because for unlimited argument we need *
##quen-2 bug- second argument was not in first call i added 12 there
# def info(name, age):
# print(name + " is " + age + " years old")
# info("Sonu",'12')
# info("Sana", "17")
# info("Umesh", "18")
## quen-3 third argument was not in call section so i added there amol
# def studentDetails(name,currentMilestone,mentorName):
# print("Hello " , name, "your" , currentMilestone, "concept " , "is clear with the help of ", mentorName)
# studentDetails("Nilam","loop","amol")
####################################################################################
## functions-question2
# def function_print_lines(name,founder):
# print("mera name "+ name + " hai")
# print("mai "+ founder + " ka co-founder hu")
# function_print_lines("pradeep","pk institute")
############################################################################
# ## Question2
# def student_name(*a):
# print(a)
# student_name("pk","ck","dk","nk","sk")
## Question 2 (Part 2)
# def isGreaterThen20(20,b): *****doubt have to ask this questions
# if b>20:
# print("true")
# else:
# print("false")
# isGreaterThen20(15)
############################################################################
## functions-question3
# #Write add_numbers function here
# def add_numbers(num1,num2):
# z=num1+num2
# print("sum=",z)
# add_numbers(2,6)
## functions-question3(part-2)
#def add_numbers_list(list(num1),list(num2)): # have to find the solution
#################################################################################
## functions-question4
# def check_numbers(a,b):
# if (a and b)%2==0:
# print("dono divisible hai")
# else:
# print("dono divisible nahi hai")
# check_numbers(2,4)
# check_numbers(8,7)
## functions-question4(part-2)
# def check_numbers_list(a,b): ### have to find solution of this questions
# for
#####################################################################################
## functions-return_values
## How to return a value from a function?
## functions-question5
# def calculator(number_x, number_y, operation): ## find solution for this not known
# add=number_x+number_y
# return add
# sub=number_x-number_y
# return sub
# mult=number_x*number_y
# return mult
# divide=number_x/number_y
# return divide
# result=calculator(4,5,"mult")
# print(result)
## Question (Part 2)
## Question (Part 3)
################################################################################
## innerFunction not working have to find error and resolved
# def first_function():
# s = 'I love India'
# def second_function():
# s = "MY NAME IS JACK"
# print(s)
# second_function()
# print(s)
# first_function()
##OUTPUT:-
# MY NAME IS JACK
# I love India
#####################################################################################
## InTRO
## QUESTion-1
# def eligibleforvote(age):
# if age>=18:
# print("you are eligible for vote")
# else:
# print("you will be eligible after ",18-age,"year")
# eligibleforvote(17)
# eligibleforvote(19)
##################################################################################
## Question 2
# def perfect(n):
# s=0
# #n=int(input("Enter number :"))
# for k in range(1,n):
# if n%k==0:
# s=s+k
# if s==n:
# print(n,"is perfect number")
# else:
# print(n,"not perfect number")
# perfect(6)
# perfect(28)
##### 2nd qestion of question-2 ## have to ask all perfect no from 1 to 1000
# def perfect():
# for inp in range(1,1001):
# ls=[]
# for i in range(1,inp):
# if inp%i==0:
# ls.append(i)
# sum=0
# for i in ls:
# sum=sum+i
# if sum==inp:
# print(inp)
# perfect()
# def perfect(n):
# for i in range(1,n):
# s=0
# for k in range(1,n):
# if n%k==0:
# s=s+k
# if s==n:
# print(n,"is perfect number")
# else:
# print(n,"not perfect number")
##########################################################################
## Question 3
# def sumaverage():
# s=0
# for i in a:
# s=s+i
# sum=s
# avg=sum/3
# print("sum of three no=",sum ,"\naverage of no= ",avg)
# for i in range(3):
# a=[]
# v=int(input("enter the number:"))
# a.append(v)
# sumaverage()
#########################################################################
## Question 4
# def shownumbers(limit):
# for i in range(0,(limit+1)):
# if i%2==0:
# print(i,"even")
# else:
# print(i,"odd")
# shownumbers(8)
##########################################################################
## Question 5 some bugs here all multiple number not showing in place of mulftiple are
# def multiple3and5(limit):
# sum=0
# for i in range(0,(limit+1)):
# a=[]
# if i%3==0 or i%5==0:
# sum=sum+i
# a.append(i)
# print("multiple are=",a,"\nsum=",sum)
# multiple3and5(10)
###########################################################################
# questions -6
# def checkKey():
# car ={
# "brand": "ford",
# "model": "mustang",
# "year": 1964
# }
# if "model" in car:
# print("Yes, 'model' is one of the keys in the thisdict dictionary.")
# else:
# print("No, 'model' key dictionary mai nahi hai.")
# checkKey()
##########################################################################3
## question6
# def speed_checker(speed):
# if speed>70:
# if speed>70 and speed<=75:
# print("point1")
# if speed>75 and speed<=80:
# print("point2")
# if speed>80 and speed<=85:
# print("point3")
# if speed>85 and speed<=90:
# print("point4")
# if speed>75 and speed<=80:
# print("point5")
# if speed>75 and speed<=80:
# print("point6")
# if speed>75 and speed<=80:
# print("point7")
# if speed>75 and speed<=80:
# print("point8")
# if speed>75 and speed<=80:
# print("point9")
# if speed>75 and speed<=80:
# print("point10")
# if speed>75 and speed<=80:
# print("point11")
# if speed>75 and speed<=80:
# print("point12, your licenced is suspended")
# else:
# print("okey")
# speed_checker(60)
# speed_checker(90)
########################################################################
## question7
# def stringlengthcheck(a,b):
# if len(a)>len(b):
# print(a)
# elif len(a)<len(b):
# print(b)
# else:
# print(a)
# print(b)
# c=input("enter your word: ")
# d=input("enter your word: ")
# stringlengthcheck(c,d)
###############################################################################
## question8
# def numberindictionary(number):
# # dict={}
# # for i in range (1,number+1):
# c=dict()
# for i in range(1,number+1):
# c.update({i:i*i})
# print(c)
# numberindictionary(5)
# numberindictionary(20)
###############################################################################
## INTRO PART-II
## question1
# def employee(name,salary=20000):
# print(name,"your salary is:-",salary)
# employee("kartik",30000)
# employee("deepak")
###################################################################################
## question-2 have to find error indentation
# def primeorNot(num):
# if num > 1:
# for i in range(2,num):
# if (num % i) == 0:
# print(num,"is not a prime number")
# print(i,"times",num//i,"is",num)
# break
# else:
# print(num,"is a prime number")
# else:
# print(num,"is not a prime number")
# primeorNot(406)
####################################################################################
## Questions-3
# def greet(*names):
# for name in names:
# print("Hello", name)
# greet("sonu", "kartik", "umesh", "bijender")
#######################################################################
## Question 4
# def sumofdigits(number):
# sum = 0
# modulus = 0
# while number!=0 :
# modulus = number%10
# sum+=modulus
# number/=10
# return sum
# print(sumofdigits(123))
#######################################################################
## question5
# def meal(day,time):
# if day=="sunday":
# if time=="breakfast":
# return "dosa"
# elif time=="lunch":
# return "dal rice"
# elif time=="dinner":
# return "paneer and chapati"
# else :
# return "time not found"
# elif day=="monday":
# if time=="breakfast":
# return "fried rice"
# elif time=="lunch":
# return "aloo rice"
# elif time=="dinner":
# return "chhole bhature"
# else :
# return "time not found"
# elif day=="other":
# if time=="breakfast":
# return "aloo"
# elif time=="lunch":
# return "rajma rice"
# elif time=="dinner":
# return "veg-chapati"
# else :
# return "time not found"
# print(meal("sunday","lunch"))
# print(meal("monday","dinner"))
##########################################################
## question6
# def checkKey():
# car ={
# "brand": "ford",
# "model": "mustang",
# "year": 1964
# }
# if "model" in car:
# print("Yes, 'model' is one of the keys in the thisdict dictionary.")
# else:
# print("No, 'model' key dictionary mai nahi hai.")
# checkKey()
######################################################################
## intro 3
## questions-1 i did its debuge only adding calculate in calling function
# def calculate_sum(a,b):
# sum = a+b
# print(sum)
# calculate_sum(4,5)
#######################################################################
## Question 2 debuge-i add def in starting by removing function from there
# def multi(a,b):
# multiply=a*b
# return multiply
# print(multi(3,4))
##############################################################################
## Question 3 debuge-d was capital in place of Def ,in print replace sum by avg/3
# def Avg(number1,number2,number3):
# avg=number1+number2+number3
# print(avg/3)
# Avg(1,3,2)
#######################################################################
## Question 4 debuge-indentation space was not there so gave that
# def voter(age):
# if age >=18:
# print("eligible")
# else:
# print("not eligible")
# voter(20)
####################################################################################
## Question 5
def distance(kms):
if kms < 20:
print("close")
elif kms < 50:
print("median")
else:
Print("far")
distance(20)
|
# test floor-division and modulo operators
@micropython.viper
def div(x:int, y:int) -> int:
return x // y
@micropython.viper
def mod(x:int, y:int) -> int:
return x % y
def dm(x, y):
print(div(x, y), mod(x, y))
for x in (-6, 6):
for y in range(-7, 8):
if y == 0:
continue
dm(x, y)
|
# -*- coding: utf-8 -*-
def func(precess_data, x):
precess_data = list(range(0, 100, 3))
low = 0
high = 34
guess = int((low + high) / 2)
while precess_data[guess] != x:
if precess_data[guess] < x:
low = guess
elif precess_data[guess] > x:
high = guess
else:
break
guess = (low + high) // 2
return guess
print(func(list(range(0, 100, 3)), 99))
|
while True:
n = input('Texto errado, digite tudo em maiúscula: ')
if n.isupper():
print('Texto correto')
break
#https://pt.stackoverflow.com/q/433623/101
|
# setup_function 每个测试函数执行之前被调用
# teardown_function 每个测试函数执行之后被调用
def setup_function():
print('setup function')
def teardown_function():
print('teardown function')
def test_1():
print('test 1')
def test_2():
print('test 2')
def test_3():
print('test 3')
|
velocidade = float(input("Qual a velocidade Atual do carro em km/h-->"))
def result(velocidade):
if velocidade > 80:
print("MULTADO")
print("MULTADO,Por execeder o limite permitido de 80km/h")
multa = 90 +((velocidade - 80)*5)
print("o Valor da multa é de R${:.2f}!".format(multa) )
else:
print("Voce esta dentro do limite de Velocidade \n Tenha um Bom Dia \nDirigia com segurança")
return
x = result(velocidade) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
We have two functions in this class.
one to collect data from the winner and store in a text file,
and one to print this data on a scoreboard.
"""
class Highscore():
"""Highscore class."""
def show_score_board(self, filename):
"""Read textfile, format the data to display the scores."""
with open(filename, "r") as file:
print("{:*^50}".format(" HIGHSCORE TABLE "))
data = file.readlines()
all_scores = []
for line in data:
name, total, streak = line.split(";")
score = (name, int(total), streak.rstrip())
all_scores.append(score)
all_scores.sort(key=lambda y: y[1], reverse=True)
position = 1
print(" Name: Total Score: Longest Streak:")
for score in all_scores:
print(f"{position:>2}: {score[0]:15}" +
f"{score[1]:<15} {score[2]}")
position = position + 1
def collect_score(self, name, score, longeststreak, filename):
"""Write score from winning player to textfile."""
with open(filename, "a") as file:
file.write(name + ";" + str(score) +
";" + str(longeststreak) + "\n")
|
'''
Created on 08.06.2014
@author: ionitadaniel19
'''
map_selenium_objects={
"SUSER":"name=login",
"SPWD":"name=password",
"SREMEMBER":"id=remember_me",
"SSUBMIT":"name=commit",
"SKEYWORD":"id=q1c",
"SSHOWANSER":"name=showanswer",
"SANSWER":"css=#answer > p"
} |
linesize = int(input())
table = [[0 for x in range(4)] for y in range(linesize)]
queue = []
for i in range(linesize):
entry = input().split(' ')
# print(entry, 'pushed')
country = (int(entry[1]),int(entry[2]),int(entry[3]),str(entry[0]))
queue.append(country)
out = sorted(queue, key = lambda x: x[3])
out = sorted(out, key = lambda x: (x[0], x[1], x[2]), reverse=True)
for elemt in out:
print("{0} {1} {2} {3}".format(elemt[3],elemt[0],elemt[1],elemt[2])) |
print('-='*20)
print('Analisador de triângulo')
print('-='*20)
a = float(input('Qual o valor das reta 1: '))
b = float(input('Qual o valor da reta 2: '))
c = float(input('Qual o valor da reta 3: '))
# if a < b + c and b < a + c and c < a + b
if (b-c) <a < (b + c):
if (a- c) <b < (a + c):
if (a - b) <c < (a +b):
print('O triângulo é Verdadeiro!')
else:
print('O triângulo é Falso!') |
#SOMA SIMPLES #1003
#Leia dois valores inteiros, no caso para variáveis A e B. A seguir, calcule a soma entre elas e atribua à variável SOMA. A seguir escrever o valor desta variável.
#Accepted
a = int(input())
b = int(input())
soma = a + b
print("SOMA = {}".format(soma)) |
name = input('Enter your Name: ')
sen = "Hello "+ name +" ,How r u today??"
print(sen)
para = ''' hey , this is a
multiline comment.Lets see how
it works.'''
print(para)
|
x, y = map(float, input().split())
exp = 0.0001
count = 1
while y - x > exp:
x += x * 0.7
count += 1
print(count) |
#!/usr/bin/python
class helloworld:
def __init__(self):
print("Hello World!")
helloworld()
|
def init():
return {
"ingest": {
"outputKafkaTopic": "telemetry.ingest",
"inputPrefix": "ingest",
"dependentSinkSources": [
{
"type": "azure",
"prefix": "raw"
},
{
"type": "azure",
"prefix": "unique"
},
{
"type": "azure",
"prefix": "channel"
},
{
"type": "azure",
"prefix": "telemetry-denormalized/raw"
},
{
"type": "druid",
"prefix": "telemetry-events"
},
{
"type": "druid",
"prefix": "telemetry-log-events"
},
{
"type": "druid",
"prefix": "telemetry-error-events"
},
{
"type": "druid",
"prefix": "telemetry-feedback-events"
}
]
},
"raw": {
"outputKafkaTopic": "telemetry.raw",
"inputPrefix": "raw",
"dependentSinkSources": [
{
"type": "azure",
"prefix": "unique"
},
{
"type": "azure",
"prefix": "channel"
},
{
"type": "azure",
"prefix": "telemetry-denormalized/raw"
},
{
"type": "druid",
"prefix": "telemetry-events"
},
{
"type": "druid",
"prefix": "telemetry-log-events"
},
{
"type": "druid",
"prefix": "telemetry-error-events"
},
{
"type": "druid",
"prefix": "telemetry-feedback-events"
}
]
},
"unique": {
"outputKafkaTopic": "telemetry.unique",
"inputPrefix": "unique",
"dependentSinkSources": [
{
"type": "azure",
"prefix": "channel"
},
{
"type": "azure",
"prefix": "telemetry-denormalized/raw"
},
{
"type": "druid",
"prefix": "telemetry-events"
},
{
"type": "druid",
"prefix": "telemetry-log-events"
},
{
"type": "druid",
"prefix": "telemetry-error-events"
},
{
"type": "druid",
"prefix": "telemetry-feedback-events"
}
]
},
"telemetry-denorm": {
"outputKafkaTopic": "telemetry.denorm",
"inputPrefix": "telemetry-denormalized/raw",
"dependentSinkSources": [
{
"type": "druid",
"prefix": "telemetry-events"
},
{
"type": "druid",
"prefix": "telemetry-feedback-events"
}
]
},
"summary-denorm": {
"outputKafkaTopic": "telemetry.denorm",
"inputPrefix": "telemetry-denormalized/summary",
"dependentSinkSources": [
{
"type": "druid",
"prefix": "summary-events"
}
]
},
"failed": {
"outputKafkaTopic": "telemetry.raw",
"inputPrefix": "failed",
"dependentSinkSources": [
],
"filters": [
{
"key": "flags",
"operator": "Is Null",
"value": ""
}
]
},
"batch-failed": {
"outputKafkaTopic": "telemetry.ingest",
"inputPrefix": "extractor-failed",
"dependentSinkSources": [
],
"filters": [
{
"key": "flags",
"operator": "Is Null",
"value": ""
}
]
},
"wfs": {
"outputKafkaTopic": "telemetry.derived",
"inputPrefix": "derived/wfs",
"dependentSinkSources": [
{
"type": "azure",
"prefix": "channel"
},
{
"type": "azure",
"prefix": "telemetry-denormalized/summary"
},
{
"type": "druid",
"prefix": "summary-events"
}
]
}
} |
#!/usr/bin/python
# -*- coding: utf-8 -*-
RECOVER_ITEM = [
("n 't ", "n't ")
]
def recover_quotewords(text):
for before, after in RECOVER_ITEM:
text = text.replace(before, after)
return text
|
names = [
'Christal',
'Ray',
'Ron'
]
print(names)
|
# * N <= 1e9, A <= N, P <= 6000000
# * 20 คะแนน : N <= 100
# * 10 คะแนน : A = 1
# * 10 คะแนน : P = 2
# * 20 คะแนน : P <= 50000
# * 40 คะแนน : ไม่มีเงื่อนไขเพิ่มเติม
def useGenerator(gen):
gen("s1", "Sample 1", 8, 3, 4)
gen("s2", "Sample 2", 8, 6, 4)
gen(1, "Cocoa", 40, 4, 5)
gen(2, "Chino", 100, 17, 2000)
gen(3, "Rize", 200000, 1, 50000)
gen(4, "Chiya", 10**7, 10**3, 2)
gen(5, "Sharo", 10**7, 112, 49999)
gen(6, "Daydream Cafe", 10**8, 14000, 50000)
gen(7, "No Poi!", 10**8, 10**4, 2*10**6)
gen(8, "Tenkuu Cafeteria", 10**8, 10**4 + 20, 2*10**6)
gen(9, "Sekai ga Cafe ni Natchatta", 10**8, 10**3, 2*10**6)
gen(10, "Nikkori Cafe no Mahou Tsukai", 10**9, 3*10**6, 6*10**6)
|
def solution(numBottles,numExchange):
finalsum = numBottles
emptyBottles = numBottles
numBottles = 0
while (emptyBottles >= numExchange):
numBottles = emptyBottles // numExchange
emptyBottles -= emptyBottles // numExchange * numExchange
finalsum += numBottles
emptyBottles += numBottles
print (finalsum)
numBottles = int(input("numBottles = "))
numExchange = int(input("numExchange = "))
solution(numBottles,numExchange) |
def undistort_image(image, objectpoints, imagepoints):
# Get image size
img_size = (image.shape[1], image.shape[0])
# Calibrate camera based on objectpoints, imagepoints, and image size
ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objectpoints, imagepoints, img_size, None, None)
# Call cv2.undistort
dst = cv2.undistort(image, mtx, dist, None, mtx)
return dst
def get_shresholded_img(image,grad_thresh,s_thresh):
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
#process the x direction gradient
sobelx = cv2.Sobel(gray, cv2.CV_64F, 1, 0) # Take the derivative in x
abs_sobelx = np.absolute(sobelx) # Absolute x derivative to accentuate lines away from horizontal
scaled_sobel = np.uint8(255*abs_sobelx/np.max(abs_sobelx))
sxbinary = np.zeros_like(scaled_sobel)
sxbinary[(scaled_sobel >= grad_thresh[0]) & (scaled_sobel <= grad_thresh[1])] = 1
#process the HIS s channel
hls = cv2.cvtColor(img, cv2.COLOR_RGB2HLS)
s_channel = hls[:,:,2]
s_binary = np.zeros_like(s_channel)
s_binary[(s_channel >= s_thresh[0]) & (s_channel <= s_thresh[1])] = 1
# color_binary = np.dstack(( np.zeros_like(sxbinary), sxbinary, s_binary)) * 255
# one can show it out to see the colored binary
# Combine the two binary thresholds
combined_binary = np.zeros_like(sxbinary)
combined_binary[(s_binary == 1) | (sxbinary == 1)] = 1
return combined_binary
def warp_image_to_birdseye_view(image,corners):
img_size=(image.shape[1], image.shape[0])
#choose an offset to determine the distination for birdseye view area
offset = 150
src = np.float32(
[corners[0],
corners[1],
corners[2],
corners[3]])
#decide a place to place the birdviewed image, get these points by testing an image
dst = np.float32([
[offset, 0],
[offset, img_size[1]],
[img_size[0] - offset, img_size[1]],
[img_size[0] - offset,0]])
# Get perspective transform
perspectiveTransform = cv2.getPerspectiveTransform(src, dst)
# Warp perspective
warped = cv2.warpPerspective(image, perspectiveTransform, img_size, flags=cv2.INTER_LINEAR)
# Get the destination perspective transform
Minv = cv2.getPerspectiveTransform(dst, src)
return warped, Minv
def find_lane_lines(warped_binary_image, testing=False):
if testing == True:
# Create an output image to draw on and visualize the result
output_image = np.dstack((warped_binary_image, warped_binary_image, warped_binary_image))*255
# Create histogram to find the lanes by identifying the peaks in the histogram
histogram = np.sum(warped_binary_image[int(warped_binary_image.shape[0]/2):,:], axis=0)
# Find the peak of the left and right halves of the histogram
midpoint = np.int(histogram.shape[0]/2)
left_x_base = np.argmax(histogram[:midpoint])
right_x_base = np.argmax(histogram[midpoint:]) + midpoint
# Choose the number of sliding windows
number_of_windows = 9
# Set height of windows
window_height = np.int(warped_binary_image.shape[0]/number_of_windows)
# Identify the x and y positions of all nonzero pixels in the image
nonzero_pixels = warped_binary_image.nonzero()
nonzero_y_pixels = np.array(nonzero_pixels[0])
nonzero_x_pixels = np.array(nonzero_pixels[1])
# Current positions to be updated for each window
left_x_current = left_x_base
right_x_current = right_x_base
# Set the width of the windows +/- margin
margin = 100
# Set minimum number of pixels found to recenter window
minpix = 50
# Create empty lists to receive left and right lane pixel indices
left_lane_inds = []
right_lane_inds = []
# Step through the windows one by one
for window in range(number_of_windows):
# Identify window boundaries in x and y (and right and left)
win_y_low = warped_binary_image.shape[0] - (window+1)*window_height
win_y_high = warped_binary_image.shape[0] - window*window_height
win_x_left_low = left_x_current - margin
win_x_left_high = left_x_current + margin
win_x_right_low = right_x_current - margin
win_x_right_high = right_x_current + margin
if testing == True:
# Draw the windows on the visualization image
cv2.rectangle(output_image, (win_x_left_low,win_y_low), (win_x_left_high,win_y_high), (0,255,0), 2)
cv2.rectangle(output_image, (win_x_right_low,win_y_low), (win_x_right_high,win_y_high), (0,255,0), 2)
# Identify the nonzero pixels in x and y within the window
left_inds = ((nonzero_y_pixels >= win_y_low) & (nonzero_y_pixels < win_y_high) & (nonzero_x_pixels >= win_x_left_low) & (nonzero_x_pixels < win_x_left_high)).nonzero()[0]
right_inds = ((nonzero_y_pixels >= win_y_low) & (nonzero_y_pixels < win_y_high) & (nonzero_x_pixels >= win_x_right_low) & (nonzero_x_pixels < win_x_right_high)).nonzero()[0]
# Append these indices to the lists
left_lane_inds.append(left_inds)
right_lane_inds.append(right_inds)
# If you found > minpix pixels, recenter next window on their mean position
if len(left_inds) > minpix:
left_x_current = np.int(np.mean(nonzero_x_pixels[left_inds]))
if len(right_inds) > minpix:
right_x_current = np.int(np.mean(nonzero_x_pixels[right_inds]))
# Concatenate the arrays of indices
left_lane_inds = np.concatenate(left_lane_inds)
right_lane_inds = np.concatenate(right_lane_inds)
# Extract left and right line pixel positions
left_x = nonzero_x_pixels[left_lane_inds]
left_y = nonzero_y_pixels[left_lane_inds]
right_x = nonzero_x_pixels[right_lane_inds]
right_y = nonzero_y_pixels[right_lane_inds]
# Fit a second order polynomial to each
left_fit = np.polyfit(left_y, left_x, 2)
right_fit = np.polyfit(right_y, right_x, 2)
# Generate x and y values for plotting
plot_y = np.linspace(0, warped_binary_image.shape[0]-1, warped_binary_image.shape[0] )
left_fit_x = left_fit[0]*plot_y**2 + left_fit[1]*plot_y + left_fit[2]
right_fit_x = right_fit[0]*plot_y**2 + right_fit[1]*plot_y + right_fit[2]
# Get binary warped image size
image_size = warped_binary_image.shape
# Get max of plot_y
y_eval = np.max(plot_y)
# Define conversions in x and y from pixels space to meters
y_m_per_pix = 30/720
x_m_per_pix = 3.7/700
# Fit new polynomials to x,y in world space
left_fit_cr = np.polyfit(left_y*y_m_per_pix, left_x*x_m_per_pix, 2)
right_fit_cr = np.polyfit(right_y*y_m_per_pix, right_x*x_m_per_pix, 2)
# Calculate radius of curve
left_curve = ((1+(2*left_fit_cr[0]*y_eval*y_m_per_pix+left_fit_cr[1])**2)**1.5)/np.absolute(2*left_fit_cr[0])
right_curve = ((1+(2*right_fit_cr[0]*y_eval*y_m_per_pix+right_fit_cr[1])**2)**1.5)/np.absolute(2*right_fit_cr[0])
# Calculate lane deviation from center of lane
scene_height = image_size[0] * y_m_per_pix
scene_width = image_size[1] * x_m_per_pix
# Calculate the intercept points at the bottom of our image
left_intercept = left_fit_cr[0] * scene_height ** 2 + left_fit_cr[1] * scene_height + left_fit_cr[2]
right_intercept = right_fit_cr[0] * scene_height ** 2 + right_fit_cr[1] * scene_height + right_fit_cr[2]
center = (left_intercept + right_intercept) / 2.0
# Use intercept points to calculate the lane deviation of the vehicle
lane_deviation = (center - scene_width / 2.0)
if testing == True:
output_image[nonzero_y_pixels[left_lane_inds], nonzero_x_pixels[left_lane_inds]] = [255, 0, 0]
output_image[nonzero_y_pixels[right_lane_inds], nonzero_x_pixels[right_lane_inds]] = [0, 0, 255]
return left_fit_x, right_fit_x, plot_y, left_fit, right_fit, left_curve, right_curve, lane_deviation, output_image
else:
return left_fit_x, right_fit_x, plot_y, left_curve, right_curve, lane_deviation
def draw_lane_lines(warped_binary_image, undistorted_image, Minv):
# Create a blank image to draw the lines on
warp_zero = np.zeros_like(warped_binary_image).astype(np.uint8)
color_warp = np.dstack((warp_zero, warp_zero, warp_zero))
left_fit_x, right_fit_x, ploty, left_radius, right_radius, lane_deviation=find_lane_lines(warped_binary_image)
# Recast the x and y points into usable format for cv2.fillPoly()
pts_left = np.array([np.transpose(np.vstack([left_fit_x, ploty]))])
pts_right = np.array([np.flipud(np.transpose(np.vstack([right_fit_x, ploty])))])
pts = np.hstack((pts_left, pts_right))
# Draw the lane onto the warped blank image with green color
cv2.fillPoly(color_warp, np.int_([pts]), (0, 255, 0))
# Warp the blank back to original image space using inverse perspective matrix (Minv)
unwarp = cv2.warpPerspective(color_warp, Minv, (undistorted_image.shape[1], undistorted_image.shape[0]))
# Combine the result with the original image
result = cv2.addWeighted(undistorted_image, 1, unwarp, 0.3, 0)
# Write text on image
curvature_text = "Curvature: Left = " + str(np.round(left_radius, 2)) + ", Right = " + str(np.round(right_radius, 2))
font = cv2.FONT_HERSHEY_TRIPLEX
cv2.putText(result, curvature_text, (30, 60), font, 1, (0,255,0), 2)
deviation_text = "Lane deviation from center = {:.2f} m".format(lane_deviation)
font = cv2.FONT_HERSHEY_TRIPLEX
cv2.putText(result, deviation_text, (30, 90), font, 1, (0,255,0), 2)
return result
#the pipeline function
def process_image(image):
undistorted = undistort_image(image, objpoints, imgpoints)
combined_binary = get_shresholded_img(undistorted,grad_thresh,s_thresh)
binary_warped, Minv = warp_image_to_birdseye_view(combined_binary,corners)
lane_lines_img = draw_lane_lines(binary_warped, undistorted, Minv)
return lane_lines_img
|
"""
The :mod:`fatf.utils.data` module holds data tools and data sets.
"""
# Author: Kacper Sokol <k.sokol@bristol.ac.uk>
# License: new BSD
|
largest=None
smallest=None
while True:
number=input("Enter a number:")
if number == "done":
break
try:
number=int(number)
if largest == None:
largest = number
elif largest < number:
largest = number
if smallest==None:
smallest=number
elif smallest>number:
smallest=number
except ValueError:
print("Invalid input")
print ("Maximum is", largest)
print ("Minimum is", smallest)
|
class UsdValue(float):
def __init__(self, v) -> None:
super().__init__()
class UsdPrice(float):
def __init__(self, v) -> None:
super().__init__() |
def filter(fname,data):
list=[]
for i in range(len(data)):
f=fname(data[i])
if f==True:
list.append(data[i])
return list
def map(fname,newdata):
list=[]
for i in range(len(newdata)):
f=fname(newdata[i])
list.append(f)
return list
def reduce(fname,incrementdata):
list=[]
for i in range(len(incrementdata)):
if (len(incrementdata))>=2:
f=fname(incrementdata[0],incrementdata[1])
del incrementdata[0]
del incrementdata[0]
incrementdata.append(f)
return incrementdata[0]
|
class Vehicule:
annee_production = 0
def demarrer(self):
print("VROOM")
class Voiture(Vehicule): # voiture hérite de véhicule
couleur = ""
clio_de_sophie = Voiture()
clio_de_sophie.annee_production = 2000
clio_de_sophie.demarrer()
clio_de_sophie.couleur = "Bleu"
|
class script(object):
START_MSG = """ഹായ് {}
ഞാൻ Ma Cartoonzz ഗ്രൂപ്പിൽ വർക്ക് ചെയ്യുന്ന ഒരു പാവം ഓട്ടോഫിൽട്ടർ ബോട്ടാണ്. എന്ന് കരുതി എന്നെ മറ്റ് ഗ്രൂപ്പിൽ ആഡ് ആക്കാൻ പറ്റില്ല.
പിന്നെ എന്തായാലും ഇവിടെ വരെ വന്നതല്ലേ ഞങ്ങളുടെ കാർട്ടൂൺ ഗ്രൂപ്പിൽ ഒന്ന് ജോയിൻ ആയേര്😎😎.
"""
HELP_MSG = """hmm...
എനിക്ക് നിൻ്റെ സഹായം ഒന്നും വേണ്ട അവൻ സഹായം ചോയിച്ച് വന്നേക്കണ്🐔🐔..
"""
ABOUT_MSG = """
🛡️<b> Cartoon Channel :</b> <a href='https://t.me/Ma_Cartoonzz'>CLICK TO JOIN</a>
🛡️<b> Cartoon Group :</b> <a href='https://t.me/Ma_Cartoonzz_discuss'>CLICK TO JOIN</a>
❣️JOIN @Ma_Cartoonzz💕❣️
"""
|
#!/usr/bin/env python3
#coding: utf-8
"""
pythonic way
"""
print(input('Введите строку:')[::-1])
|
#
numbers = [str(x) for x in range(32)]
letters = [chr(x) for x in range(97, 123)]
crate = '''
sandbox crate
map {boot: @init}
/*initialize utility vars and register vars*/
service init {
writer = 0
alpha = 0
beta = 0
status = 0'''
for letter in letters:
crate += '\n ' + letter + ' = 0'
crate += '''
}
/*map operator service to exec jump table*/
map {
copy: @copy
add: @add
sub: @sub
not: @not
or: @or
and: @and
eq: @eq
ne: @ne
gt: @gt
lt: @lt
gte: @gte
lte: @lte
unary: @status_alpha
}
service copy { @status_zero alpha = beta @writer}
service add { @status_zero alpha = alpha + beta @writer}
service sub { @status_zero alpha = alpha - beta @writer}
service not { @status_zero alpha = !beta @writer}
service or { @status_zero alpha = alpha | beta @writer}
service and { @status_zero alpha = alpha & beta @writer}
service eq { @status_zero if (alpha == beta) {[true]} else {[false]}}
service ne { @status_zero if (alpha != beta) {[true]} else {[false]}}
service gt { @status_zero if (alpha > beta) {[true]} else {[false]}}
service lt { @status_zero if (alpha < beta) {[true]} else {[false]}}
service gte { @status_zero if (alpha >= beta) {[true]} else {[false]}}
service lte { @status_zero if (alpha <= beta) {[true]} else {[false]}}
service status_zero {
status = 0
}
service status_alpha {
status = 1
}
service status_beta {
status = 2
}
service writer {
jump (writer) {'''
for letter in letters:
crate += '{ ' + letter + ' = alpha } '
crate += '''}
}
map {jump: @jump}
service jump {
jump (z) {'''
for number in numbers:
crate += '{ [ jump' + number + '] } '
crate += '''}
}
map {printme : @printme}
service printme { ['''
for number in numbers:
crate += '''alias jump''' + number + ''' echo ''' + number + ''';'''
crate += '''jump]
}'''
for letter in letters:
crate += '''
map {''' + letter + ' : @' + letter + '''}
service ''' + letter + ''' { jump (status) {
{ alpha = ''' + letter + ''' @status_alpha}
{ beta = ''' + letter + ''' @status_beta}
{ writer = ''' + str(ord(letter) - 97) + ''' }
}
}'''
for number in numbers:
crate += '''
map {delete''' + number + ' : @delete' + number + '''}
service delete''' + number + ''' { jump (status) {
{ alpha = ''' + number + ''' @status_alpha}
{ beta = ''' + number + ''' @status_beta}
{ }
}
}'''
print(crate)
|
# coding: utf-8
# http://www.crummy.com/software/BeautifulSoup/bs4/doc/#installing-a-parser
DEFAULT_PARSER = 'lxml'
ALLOWED_CONTENT_TYPES = [
'text/html',
'image/',
]
FINDER_PIPELINE = (
'haul.finders.pipeline.html.img_src_finder',
'haul.finders.pipeline.html.a_href_finder',
'haul.finders.pipeline.css.background_image_finder',
)
EXTENDER_PIPELINE = (
'haul.extenders.pipeline.google.blogspot_s1600_extender',
'haul.extenders.pipeline.google.ggpht_s1600_extender',
'haul.extenders.pipeline.google.googleusercontent_s1600_extender',
'haul.extenders.pipeline.pinterest.original_image_extender',
'haul.extenders.pipeline.wordpress.original_image_extender',
'haul.extenders.pipeline.tumblr.media_1280_extender',
'haul.extenders.pipeline.tumblr.avatar_128_extender',
)
SHOULD_JOIN_URL = True
|
# pythran export _brief_loop(float64[:,:], uint8[:,:],
# intp[:,:], int[:,:], int[:,:])
def _brief_loop(image, descriptors, keypoints, pos0, pos1):
for k in range(len(keypoints)):
kr, kc = keypoints[k]
for p in range(len(pos0)):
pr0, pc0 = pos0[p]
pr1, pc1 = pos1[p]
descriptors[k, p] = (image[kr + pr0, kc + pc0]
< image[kr + pr1, kc + pc1])
|
factors = {
1:{
1:"I",5:"I",9:"I",13:"I",17:"I",21:"I",25:"I",29:"I",33:"I",37:"I",41:"I",45:"I",49:"I",53:"I",57:"I"
, 2:"S", 6:"S", 10:"S", 14:"S", 18:"S", 22:"S", 26:"S",30:"S" ,34:"S",38:"S",42:"S",46:"S",50:"S",54:"S",58:"S"
, 3:"T", 7:"T" , 11:"T", 15:"T", 19:"T",23:"T" ,27:"T", 31:"T" ,35:"T" ,39:"T",43:"T",47:"T",51:"T" ,55:"T",59:"T"
, 4:"P", 8:"P", 12:"P", 16:"P", 20:"P", 24:"P", 28:"P", 32:"P", 36:"P", 40:"P", 44:"P", 48:"P", 52:"P", 56:"P", 60:"P"
}
,
2 :{
1:"E",5:"E",9:"E",13:"E",17:"E",21:"E",25:"E",29:"E",33:"E",37:"E",41:"E",45:"E",49:"E",53:"E",57:"E"
, 2:"N", 6:"N", 10:"N", 14:"N", 18:"N", 22:"N", 26:"N",30:"N" ,34:"N",38:"N",42:"N",46:"N",50:"N",54:"N",58:"N"
, 3:"F", 7:"F" , 11:"F", 15:"F", 19:"F",23:"F" ,27:"F", 31:"F" ,35:"F" ,39:"F",43:"F",47:"F",51:"F" ,55:"F",59:"F"
, 4:"J", 8:"J", 12:"J", 16:"J", 20:"J", 24:"J", 28:"J", 32:"J", 36:"J", 40:"J", 44:"J", 48:"J", 52:"J", 56:"J", 60:"J"
}
}
factors_names = ('E', 'I', 'S', 'N', 'F', 'T', 'P', 'J', 'report')
factors_group = (('E', 'I'), ('S', 'N'), ('F', 'T'), ('P', 'J')) |
"""
You can modify any option in this file. :-)
您可以修改此檔案中的任何選項 :-)
"""
# 您可以在 lang 資料夾中找到您語言的語系檔案。
# 只需要複製所需的檔案名稱即可。 :-D
#
# You can find the locale file of your language
# in "lang" folder.
# Just copy the filename of the locale file of your language
# to here. :-D
# or directly read "lang/README", but it may not latest.
#
# Default: zh_TW.json
# Chinese (Taiwan): zh_TW.json
# Chinese (China): zh_CN.json
# English (US): en_US.json
langFile = "zh_TW.json" |
wkidInfo = {
'4326':{'type':'gcs', 'path':'World/WGS 1984.prj'},
'102100':{'type':'pcs', 'path':r'World/WGS 1984 Web Mercator (auxiliary sphere).prj'},
'3857' : {'type':'pcs', 'path':r'World/WGS 1984 Web Mercator (auxiliary sphere).prj'}
} |
#import ctypes
#import GdaImport
#import matplotlib.pyplot as plt
# getting example
# gjden
def GDA_MAIN(gda_obj):
per='the apk permission:\n'
# per+=gda_obj.GetAppString()
# per+=gda_obj.GetCert()
# per+=gda_obj.GetUrlString()
#
per+=gda_obj.GetPermission()
gda_obj.log(per)
tofile = open('out.txt','w')
tofile.write(per)
tofile.close()
return 0
|
# Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'targets': [
{
'target_name': 'control_bar',
'dependencies': [
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr',
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:i18n_behavior',
'profile_browser_proxy',
],
'includes': ['../../../../third_party/closure_compiler/compile_js2.gypi'],
},
{
'target_name': 'create_profile',
'dependencies': [
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:i18n_behavior',
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:util',
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:web_ui_listener_behavior',
'profile_browser_proxy',
],
'includes': ['../../../../third_party/closure_compiler/compile_js2.gypi'],
},
{
'target_name': 'error_dialog',
'includes': ['../../../../third_party/closure_compiler/compile_js2.gypi'],
},
{
'target_name': 'import_supervised_user',
'dependencies': [
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:i18n_behavior',
'profile_browser_proxy',
],
'includes': ['../../../../third_party/closure_compiler/compile_js2.gypi'],
},
{
'target_name': 'profile_browser_proxy',
'dependencies': [
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:assert',
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr',
],
'includes': ['../../../../third_party/closure_compiler/compile_js2.gypi'],
},
{
'target_name': 'supervised_user_create_confirm',
'dependencies': [
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:i18n_behavior',
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:util',
'profile_browser_proxy',
],
'includes': ['../../../../third_party/closure_compiler/compile_js2.gypi'],
},
{
'target_name': 'supervised_user_learn_more',
'dependencies': [
'profile_browser_proxy',
],
'includes': ['../../../../third_party/closure_compiler/compile_js2.gypi'],
},
{
'target_name': 'user_manager_pages',
'includes': ['../../../../third_party/closure_compiler/compile_js2.gypi'],
},
{
'target_name': 'user_manager_tutorial',
'dependencies': [
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:i18n_behavior',
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:util',
],
'includes': ['../../../../third_party/closure_compiler/compile_js2.gypi'],
},
],
}
|
# -*- coding: utf-8 -*-
# @Project: fluentpython
# @Author: xuzhiyi
# @File name: example
# @Create time: 2021/8/1 20:21
"""有一个记录学生分数的类,要求分数不能负数"""
class Score(object):
def __init__(self, math):
if math < 0:
raise ValueError("分数不能为负数")
self.math = math
"""此处在初始化后重新给math属性赋值为-10后并没有抛出ValueError,
这违反了我们设计的初衷,所以仍需改进,改进可以使用@property"""
if __name__ == "__main__":
score_instance = Score(50)
score_instance.math = -10
print(score_instance.math) |
# Part 1 of the Python Review lab.
def hello_world():
print("hello world")
pass
def greet_by_name(name):
print("please enter your name")
name = input
print
pass
def encode(x):
pass
def decode(coded_message):
pass |
# coding:utf-8
# example 02: single_linked_list.py
class Node(object):
def __init__(self, val=None):
self.val = val
self.next = None
class SingleLinkedList(object):
def __init__(self, maxsize=None):
self.maxsize = maxsize # None 表示不限大小;数字表示上限大小
self.root = Node()
self.tailnode = None
self.length = 0
def __len__(self):
return self.length
def iter_node(self):
cur = self.root
for _ in range(self.length):
cur = cur.next
yield cur
def __iter__(self):
for node in self.iter_node():
yield node.val
def empty(self):
return self.length == 0
def append(self, val): # O(1)
if self.maxsize is not None and self.length == self.maxsize:
raise Exception("Full")
node = Node(val)
if self.tailnode is None:
self.root.next = node
else:
self.tailnode.next = node
self.tailnode = node
self.length += 1
def appendleft(self, val): # O(1)
node = Node(val)
node.next = self.root.next
self.root.next = node
self.length += 1
if self.length == 1:
self.tailnode = node
def pop(self): # O(n)
if self.root.next is None:
raise Exception("pop from empty Single Linked List")
val = self.tailnode.val
tailnode = self.root
for _ in range(self.length - 1):
tailnode = tailnode.next
tailnode.next = None
del self.tailnode
self.length -= 1
self.tailnode = None if tailnode is self.root else tailnode
return val
def popleft(self): # O(1)
if self.root.next is None:
raise Exception("pop from empty Single Linked List")
headnode = self.root.next
val = headnode.val
self.root.next = headnode.next
if headnode is self.tailnode:
self.tailnode = None
del headnode
self.length -= 1
return val
def find(self, val): # O(n)
for idx, node in enumerate(self.iter_node()):
if node.val == val:
return idx
return -1
def insert(self, pos, val): # O(n)
if pos <= 0:
self.appendleft(val)
elif self.length - 1 < pos:
self.append(val)
else:
node = Node(val)
pre = self.root
for _ in range(pos):
pre = pre.next
node.next = pre.next
pre.next = node
self.length += 1
def remove(self, val): # O(n)
"""
return 1: 删除成功
return -1: 删除失败
"""
if self.length == 0:
return -1
pre = self.root
for cur in self.iter_node():
if cur.val == val:
pre.next = cur.next
if cur is self.tailnode:
self.tailnode = None if self.length == 1 else pre
del cur
self.length -= 1
return 1
pre = pre.next
return -1
def clear(self):
for node in self.iter_node():
del node
self.root.next = None
self.tailnode = None
self.length = 0
# use pytest
sll = SingleLinkedList()
class TestSingleLinkedList(object):
@classmethod
def setup_class(cls):
pass
@classmethod
def teardown_class(cls):
pass
def setup_method(self):
pass
def teardown_method(self):
pass
def test_append(self):
sll.append(1)
sll.append(2)
sll.append(3)
assert list(sll) == [1, 2, 3]
def test_appendleft(self):
sll.appendleft(0)
assert list(sll) == [0, 1, 2, 3]
def test_len(self):
assert len(sll) == 4
def test_pop(self):
tail_val = sll.pop()
assert tail_val == 3
def test_popleft(self):
head_val = sll.popleft()
assert head_val == 0
def test_find(self):
assert sll.find(2) == 1
assert sll.find(4) == -1
def test_insert(self):
sll.insert(1, 5)
assert list(sll) == [1, 5, 2]
def test_remove(self):
sll.remove(5)
assert list(sll) == [1, 2]
def test_clear_and_empty(self):
sll.clear()
assert sll.empty() is True
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: ai ts=4 sts=4 et sw=4
"""
django-fhir
FILE: __init__.py
Created: 1/6/16 5:07 PM
"""
__author__ = 'Mark Scrimshire:@ekivemark'
# Hello World is here to test the loading of the module from fhir.settings
# from .settings import *
#from fhir_io_hapi.views.get import hello_world
#from fhir_io_hapi.views.delete import delete
#from fhir_io_hapi.views.get import (read, vread, history)
#from fhir_io_hapi.views.search import find
# Used to load post_save signal for write to backend fhir server
default_app_config = 'fhir_io_hapi.apps.fhir_io_hapi_config'
|
# -*- coding: utf-8 -*-
class Personaje:
"""
Clase donde se guarda la informacion sobre personajes
Args:
"""
def __init__(self):
self.__nombres= dict()
self.__pospers = dict()
self.lennombres = dict()
self.__numapar = 0
def getPersonaje(self):
"""
Metodo que devuelve un diccionario con todos los nombres del personaje y sus apariciones
Args:
Return:
diccionario con los nombres y posiciones del personaje por cada nombre
"""
return self.__nombres
def getPosicionPers(self):
"""
Metodo que devuelve un diccionario de todas las posiciones en las que sale el personaje
por cada capitulo
Args:
Return:
diccionario de posiciones del personaje por capitulo
"""
return self.__pospers
def setPosicionPers(self,pospers):
"""
Metodo para establecer un diccionario de todas las posiciones en las que sale el personaje
por cada capitulo
Args:
las posiciones del personaje por capitulo
"""
self.__pospers = pospers
def getNumApariciones(self):
"""
Metodo que devuelve el numero de apariciones de un pesonaje y si todos los personajes de este
tienen las posiciones encontradas
Args:
Return:
numero de apariciones
todos los nombes con las posiciones encontradas
"""
for k in self.__nombres.keys():
if k not in self.lennombres:
return self.__numapar,False
return self.__numapar,True
def sumNumApariciones(self,apar):
"""
Metodo que añade un numero de apariciones a un pesonaje
Args:
apar: numero de apariciones a añadir
"""
self.__numapar += apar
def resNumApariciones(self,apar):
"""
Metodo que elimina un numero de apariciones a un pesonaje
Args:
apar: numero de apariciones a eliminar
"""
self.__numapar -= apar |
pizzas = ["triple carne", "extra queso", "suprema"]
friend_pizzas = ["triple carne", "extra queso", "suprema"]
pizzas.append("baggel")
friend_pizzas.append("hawaiana")
print("Mis pizzas favoritas son:")
for i in range(0,len(pizzas)):
print(pizzas[i])
print()
print("Las pizzas favoritas de mi amigo son:")
for i in range(0,len(friend_pizzas)):
print(friend_pizzas[i])
|
"""Crie um programa que vai ler vários números e colocar em uma lista.
Depois disso,
crie duas listas extras que vão conter apenas os valores pares e os valores ímpares digitados, respectivamente.
Ao final, mostre o conteúdo das três listas geradas."""
lista1 = []
lista2 = []
lista3 = []
v = 1
sair = 'S'
while sair == 'S':
valor = int(input(f'Digite o {v}° valor: '))
v += 1
lista1.append(valor)
sair = str(input('Adicionar mais valores?? [S/N]: ')).upper()[0]
if sair == 'N':
print('Saindo do loop...')
break
for posicao, item in enumerate(lista1):
if item % 2 == 0:
lista2.append(item)
else:
lista3.append(item)
print('Lista completa: ', lista1)
print('Lista com pares: ', lista2)
print('Lista com impares: ', lista3)
|
# -*- coding: utf-8 -*-
GITHUB_STRING = 'https://github.com/earaujoassis/watchman/archive/v{0}.zip'
NAME = "agents"
VERSION = "0.2.4"
|
def first(arr, low , high):
if high >= low:
mid = low + (high - low)//2
if (mid ==0 or arr[mid-1] == 0) and arr[mid] == 1:
return mid
elif arr[mid] == 0:
return first(arr, mid+1, high)
else:
return first(arr, low, mid-1)
return -1
def row_with_max_ones(mat):
r = len(mat)
c = len(mat[0])
max_row_index = 0
max_ = -1
for i in range(r):
index = first(mat[i], 0, c-1)
if index != -1 and c - index > max_:
max_ = c - index
max_row_index = i
return max_row_index
|
class Solution:
def plusOne(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
if not digits:
return [1]
carry = (digits[-1] + 1) // 10
digits[-1] = (digits[-1] + 1) % 10
for i in reversed(range(len(digits) - 1)):
number = digits[i]
digits[i] = (number + carry) % 10
carry = (number + carry) // 10
if carry > 0:
return [carry] + digits
else:
return digits
print(Solution().plusOne([]))
|
def infer_mask_from_batch_data(batch_data):
"""
Create binary mask for all non-empty timesteps
:param batch_data: BatchSize x SequenceLen x Features
:return: BatchSize x SequenceLen
"""
return batch_data.abs().sum(-1) > 0
def infer_lengths_from_mask(mask):
"""
Get array of lengths from binary mask
:param mask: BatchSize x SequenceLen
:return: BatchSize
"""
return mask.long().sum(1)
|
def get_path_components(path):
path = path.strip("/").split("/")
path = [c for c in path if c]
normalized = []
for comp in path:
if comp == ".":
continue
elif comp == "..":
if normalized:
normalized.pop()
else:
raise ValueError("URL tried to traverse above root")
else:
normalized.append(comp)
return normalized
|
#Belajar String Method
#https://docs.python.org/3/library/stdtypes.html#string-methods
nama = "muhammad aris septanugroho"
print(nama)
print(nama.upper()) #Huruf besar semua
print(nama.capitalize()) #Huruf besar kata pertama
print(nama.title()) #Huruf besar tiap kata
print(nama.split(" ")) #Memisah data menjadi list dengan ketentuan "spasi"
|
rm = input("Insira seu RM")
idade = input("Insira sua idade")
if int(idade) >= 18:
print("Sua participação foi autorizada, aluno de RM {}!".format(rm))
print("Mais informações serão enviadas para seu e-mail cadastrado!")
else:
print("Sua participação não foi autorizada por causa da sua idade") |
# Code adapted from Corey Shafer
"""Note: generators are more performat because they don't hold
all the values at the same time! Way better in memory, altho execution
will be a bit slower"""
def square_numbers(nums):
for i in nums:
# yield makes this a generator
# Returns one result at a time
yield(i * i)
my_nums = square_numbers([1, 2, 3, 4, 5])
# Alternative list comprehension my_nums = [x*x for x in [1, 2, 3, 4, 5]]
# and my_nums = (x*x for x in [1, 2, 3, 4, 5]) with circular brackets we are using a generator
for num in my_nums:
print(next(my_nums)) |
class Solution:
# def maxProduct(self, nums):
# """
# :type nums: List[int]
# :rtype: int
# """
# for i in range(1, len(nums)):
# nums[i] = max(nums[i], nums[i] * nums[i - 1])
# return max(nums)
def maxProduct3(self, nums):
if not nums:
return 0
# locMin = nums[0]
# locMax = nums[0]
locMinPrev = nums[0]
locMaxPrev = nums[0]
gloMax = nums[0]
for i in range(1, len(nums)):
locMin = min(locMinPrev * nums[i], locMaxPrev * nums[i], nums[i])
locMax = max(locMaxPrev * nums[i], locMinPrev * nums[i], nums[i])
locMinPrev = locMin
locMaxPrev = locMax
gloMax = max(locMax, gloMax)
return gloMax
def maxProduct2(self, nums):
ans = nums[0]
# locMin, locMax stores the max/min product of subarray that ends with the current number
locMin = locMax = ans
for i in range(1, len(nums)):
# multiplying with a negative number makes a negative number positive, a positive number negative
if nums[i] < 0:
locMax, locMin = locMin, locMax
locMin = min(nums[i], locMin * nums[i])
locMax = max(nums[i], locMax * nums[i])
ans = max(ans, locMax)
return ans
def maxProduct(self, nums):
ans = nums[0]
# locMin, locMax stores the max/min product of subarray that ends with the current number
locMin = locMax = ans
for i in range(1, len(nums)):
candidates = (nums[i], locMax * nums[i], locMin * nums[i])
locMin = min(candidates)
locMax = max(candidates)
# warning: cannot do the following
# locMin is updated before calculating locMax
# locMin = min(nums[i], locMax * nums[i], locMin * nums[i])
# locMax = max(nums[i], locMax * nums[i], locMin * nums[i])
ans = max(ans, locMax)
return ans
solver = Solution()
ans = solver.maxProduct3([-4,-3,-2])
print(ans) |
def product_left_recursive(alist, result=None):
if alist == []:
return result
g = result[-1] * alist[0]
result.append(g)
return product_left_recursive(alist[1:], result)
def product_left(alist):
new_list = [1]
for index in range(1, len(alist)):
value = new_list[-1] * alist[index-1]
new_list.append(value)
return new_list
def product_right(alist):
new_list = [1]
for index in range(len(alist)-2, -1, -1):
value = new_list[-1] * alist[index-1]
new_list.append(value)
return new_list
def product_of_array_of_array(alist):
left_list = product_left(alist)
right_list = product_right(alist)
new_list = []
for index, item in enumerate(alist):
value = left_list[index] * right_list[index]
new_list.append(value)
return new_list
def product_recursive(alist):
if alist == []:
return 1
return alist[0] * product_recursive(alist[1:])
def paa(alist):
new_list = []
for index, item in enumerate(alist):
current_list = alist[:index] + alist[index+1:]
value = product_recursive(current_list)
new_list.append(value)
return new_list
alist = [1, 2, 3, 4, 5, 6]
rlist = alist[::-1]
print(alist)
print(product_left(alist))
print(product_left_recursive(alist[1:], [1]))
print(product_left_recursive(rlist[1:], [1]))
print(product_right(alist))
#print(product_right_recursive(alist, [1]))
#print(product_of_array_of_array(alist))
#print(paa(alist))
|
# coding: utf-8
# pragma: no cover
class Transformator:
"""Rule to transform values"""
def __init__(self, *args, **kwargs):
pass
class TransformatorList(list):
"""Wrapper for all registered Transformators"""
def __init__(self, settings, *args, **kwargs):
super(TransformatorList, self).__init__(*args, **kwargs)
self.settings = settings
def register(self, *args):
self.extend(args)
|
fileName = ["nohup_2", "nohup_1", "nohup_4", "nohup"]
Fo = open("new nohup", "w")
for fil in fileName:
lineNum = 0
with open(fil) as F:
for line in F:
if lineNum % 10 == 0:
Fo.write(",\t".join(line.split()))
Fo.write("\n")
lineNum += 1
Fo.write("e\n") |
#DICIONÁRIOS
#Há duas maneiras de declarar um dicionário:
variavel = dict()
variavel = {}
#Dentro do dicionário, eu posso adicionar elementos. Esses elementos são conhecidos como chaves (keys) e valores (values):
variavel = {'nome':'Pedro', 'idade':25}
print(variavel['nome'])
#Vale lembrar que para declarar uma key (o nome de um índice), eu preciso colocar os dois pontos. 'Pedro' e 25 são os meus valores. Se eu der um print na tela, terei como retorno: Pedro.
#E se eu quiser adicionar mais um item no meu dicionário? Simples. Basta eu inserir:
variavel['sexo']='M'
#O que está dentro do colchetes é a minha key/índice, já o que está pra fora é o meu valor.
# Eu também posso deletar um item do meu dicionário, por exemplo:
del variavel['idade']
#Vamos imaginar que eu tenha um dicionário de um filme:
filme = {'titulo': 'Star Wars', 'ano': 1977, 'diretor': 'George Lucas'}
print(filme.values()) #vai imprimir os valores ('Star Wars', 1977, 'George Lucas')
print(filme.keys()) #vai imprimir as chaves ('titulo', 'ano', 'diretor')
print(filme.items()) #vai imprimir o dicionário todo.
#ESTRUTURA DE REPETIÇÃO
#Com o meu dicionário criado, eu posso usar o laço para representar os meus dados.
for k, v in filme.items():
print(f'O {k} é {v}')
#k = representa os índices. Então sempre o primeiro do for estará relacionado ao índice. Dessa forma, o nome do primeiro índice é 'titulo', o nome do segundo índice é 'ano' e o nome do terceiro índice é 'diretor' e assim sucessivamente. Isso serve para qualquer estrutura. Guarde que o índice nos dicionários são conhecidos como keys.
#v = representa os valores (values). O segundo do for (após a vírgula) estará relacionado aos valores. Nesse exemplo, o primeiro valor é 'Star Wars', o segundo valor é 1977 e o terceiro valor é 'George Lucas'.
#COLOCANDO DICIONÁRIOS DENTRO DE LISTAS
#É possível colocar dicionários dentro de listas! Vamos ver como isso funciona na prática.
locadora = []
locadora.append(filme)
print(locadora)
#Se eu quiser exibir um determinado item da minha lista, farei dessa forma:
print(locadora[0]['ano']) #1977
pessoas = {'nome': 'Renaisa', 'sexo': 'F', 'idade': 23}
print(f'A {pessoas["nome"]} tem {pessoas["idade"]} anos.')
print(pessoas.values())
print(pessoas.keys())
print(pessoas.items())
for k in pessoas.values():
print(k)
del pessoas['sexo']
#pessoas['nome':] = ['Katerine']
#pessoas['peso':] = [60]
for k, v in pessoas.items():
print(f'{k} = {v}')
estado = dict()
brasil = list()
for c in range(0, 3):
estado['uf'] = str(input('Unidade Federativa: '))
estado['sigla'] = str(input('Sigla do Estado: ')).upper()
brasil.append(estado.copy())
for e in brasil:
for v in e.values():
print(v, end='')
print()
|
title('Counting words')
count = dict()
text = '''Ex servente de ladrilheiro que largou o canteiro de obras para realizar um sonho de infância, a tal sonhada
sonhada formação acadêmica. Formado em engenharia de controle e automação em 2019, com um dos melhores rendimentos da turma
agregei valores e informações preciosas.
Durante a graduação em 2017 abri minha própria microempresa de redes de internet onde durante três anos realizei trabalhos
de instalação, manutenção e análises de internet, alcançando mais de 60 clientes na vizinhaça.
Mas nem tudo é um mar de rosas... a crise veio, e é onde surge o professor de inglês e professor de música, com projetos
alcançados em diversas igrejas da zona Oeste, aulas de bateria, violão, baixo e teclado, além de ministrar aulas de inglês básico para diversas faixas etárias.
Me especializando em análise de dados, com auxílio do Python como principal linguagem, SQLs na aquisição de
dados, Jupyter no tratamento e análise gráfica e apliando conhecimentos em bibliotecas como pandas, numpy e TensorFlow.
Atualmente em busca de uma oportunidade de crescimento profissional em equipe, desenvolvendo soluções e gerando valores
como programador. A caminhada sempre foi difícil, mas desistir nunca foi uma opção.'''
words = text.split()
for word in words:
count[word] = count.get(word, 0) + 1
print(count) |
"""
There's an algorithms tournament taking place in which teams of programmers compete against each other to solve algorithmic problems as fast as possible. Teams compete in a round robin, where each team faces off against all other teams. Only two teams compete against each other at a time, and for each competition, one team is designated the home team, while the other team is the away team. In each competition there's always one winner and one loser; there are no ties. A team receives 3 points if it wins and 0 points if it loses. The winner of the tournament is the team that receives the most amount of points.
Given an array of pairs representing the teams that have competed against each other and an array containing the results of each competition, write a function that returns the winner of the tournament. The input arrays are named competitions and results, respectively. The copetitions array has elements in the form of [homeTeam, awayTeam], where each team is a string of at most 30 characters representing the name of the team. The results array contains information about the winner of each corresponding competition in the competitions array. Specifically, results[i] denotes the winner of competitions[i], where a 1 in the results array means that the home team in the corresponding competition won and a 0 means that the away team won.
It’s guaranteed that exactly one team will win the tournament and that each team will compete against all other teams exactly once. It’s also guaranteed that the tournament will always have at least two teams.
example input
[ home , away ]
competitions = [
["HTML", "C#"],
["C#", "Python"],
["Python", "HTML"],
]
results = [0, 0, 1]
output
"Python"
// C# beats HTML, Python beats C#, and Python beats HTML.
// HTML - 0 pts
// C# - 3 pts
// Python - 6 pts
algorithm:
pay attention to who wins and track that in your hash table
then look through your hashtable and return the name of the team with the highest score
{
'HTML': 6,
'C#': 3
}
"""
def tournament_winner(competitions, results):
# [ home , away ]
hash_map_of_winners = {}
for i in range(len(results)):
if results[i] == 0:
index_of_winner = 1
else:
index_of_winner = 0
winner = competitions[i][index_of_winner]
if hash_map_of_winners.get(winner, False) != False:
hash_map_of_winners[winner] += 3
else:
# this has not been instatiated
hash_map_of_winners[winner] = 3
list_of_keys = hash_map_of_winners.keys()
winner = {
'score': 0,
'name': '',
}
for key in list_of_keys:
if hash_map_of_winners[key] > winner['score']:
winner['score'] = hash_map_of_winners[key]
winner['name'] = key
return winner['name']
|
'''
Laçoes de repetição:
laço variável no intervalo(0,x) --> for variavel in range(0,x)
'''
'''
for a in range(0, 5):
print('Oi')
print('Fim')
for b in range(1, 6): #Conta de 1 a 5, se colocar (0,6) conta de 0 a 6
print(b)
print('Fim')
for c in range(5, 0, -1): #Para contar ao contrário.
print(c)
print('Fim')
for d in range(0, 7, 2): #Para contar de 2 em 2.
print(d)
print('Fim')
'''
n = int(input('Digite um número: '))
for mostre in range(0, n+1):
print(mostre)
print('Fim')
i = int(input('Inicio: '))
f = int(input('Fim: '))
p = int(input('Passo: '))
for conta in range(i, f+1, p):
print(conta)
print('Fim')
'''
for c in range(0, 3):
n = int(input('Digite um número: '))
print('Fim') --> Vai receber um número 3 vezes.
'''
s = 0
for soma in range(0, 4):
n = int(input('Digite um número: '))
s += n # --> s = s + n
print('A soma dos números digitados é igual a {}'.format(s))
|
# Python - 3.6.0
test.assert_equals(last([1, 2, 3, 4, 5]), 5)
test.assert_equals(last('abcde'), 'e')
test.assert_equals(last(1, 'b', 3, 'd', 5), 5)
|
class Student:
def __init__(self,m1,m2):
self.m1 = m1
self.m2 = m2
def sum(self, a = None, b = None, c = None):
addition = 0
if a!=None and b!=None and c!=None:
addition = a + b + c
elif a!=None and b!= None:
addition = a + b
else:
addition = a
return addition
s1 = Student(10,20)
print(s1.sum(2,4)) |
a = int(input("Enter number of elements in set A "))
A = set(map(int,input("# Spaced Separated list of elements of A ").split())) # Spaced Separated list of elements of A
n = int(input("Number of sets ")) # Number of sets
for i in range(n):
p = input("Enter the operation and number of elements in set"+i).split()
s2 = set(map(int,input("Enter space separated list of elements for operation #"+p[1]+" ").split()))
if p[0] == "intersection_update":
A.intersection_update(s2)
elif p[0]=="update":
A.update(s2)
elif p[0]=="symmetric_difference_update":
A.symmetric_difference_update(s2)
elif p[0]=="difference_update":
A.difference_update(s2)
print(sum(A)) |
class Solution:
def sqrt(self, x):
low = 0
high = 65536
best = 0
while high > low:
mid = (high + low) / 2
sqr = mid ** 2
if sqr > x:
high = mid
elif sqr == x:
return mid
else:
best = mid
low = mid + 1
return best
|
def palindrome(word, ind):
if word == word[::-1]:
return f"{word} is a palindrome"
if word[ind] != word[len(word) - 1 - ind]:
return f"{word} is not a palindrome"
return palindrome(word, ind + 1)
print(palindrome("abcba", 0))
print(palindrome("peter", 0))
|
#NETWORK
LOCALHOST = "127.0.0.1"
PI_ADDRESS = "192.168.0.1"
PORT = 5000
#STATE
MOVEMENT_MARGIN = 2
KICK_TIMEOUT = 1
LAST_POSITION = -1
PLAYER_LENGTH = 2
NOISE_THRESHOLD = 3
MIN_VELOCITY_THRESHOLD = 300
OPEN_PREP_RANGE = -30
BLOCK_PREP_RANGE = 100
OPEN_KICK_RANGE = -20
BLOCK_KICK_RANGE = 60
KICK_ANGLE = 55
PREP_ANGLE = -30
BLOCK_ANGLE = 0
OPEN_ANGLE = -90
SPEED_THRESHOLD = 3000
MIN_PLAYER_OFFSET = 40
MAX_PLAYER_OFFSET = 640
IDLE_RANGE = 600
RECOVERY_LINEAR = 80
RECOVERY_ANGLE = -57
#PHYSICAL DIMENSIONS
GOAL_ROD = {"maxActuation":228, "playerSpacing":182, "rodX":1125, "numPlayers":3}
TWO_ROD = {"maxActuation":356, "playerSpacing":237, "rodX":975, "numPlayers":2}
FIVE_ROD = {"maxActuation":115, "playerSpacing":120, "rodX":675, "numPlayers":5}
THREE_ROD = {"maxActuation":181, "playerSpacing":207, "rodX":375, "numPlayers":3}
TABLE = {"robot_goalX":1200, "robot_goalY":350, "player_goalX":0, "player_goalY":350, "goalWidth":200, "width":685, "length":1200}
|
#! /usr/bin/env python3.6
#a = 'str'
a = '32'
print(f'float(a) = {float(a)}')
print(f'int(a) = {int(a)}')
if(isinstance(a, str)):
print("Yes, it is string.")
else:
print("No, it is not string.")
|
class TreeNode:
def __init__(self, val):
self.left = None
self.right = None
self.val = val
def is_valid_BST(node, min, max):
if node == None:
return True
if (min is not None and node.val <= min) or (max is not None and max <= node.val):
return False
return is_valid_BST(node.left, min, node.val) and is_valid_BST(node.right, node.val, max)
|
# 由两个栈组成的队列【题目】编写一个类,用两个栈实现队列,
# 支持队列的基本操作(add、poll、peek)。
# 【难度】尉 ★★☆☆
class TwoStacksQueue:
def __init__(self):
self.stackPush = []
self.stackPop = []
def pushToPop(self):
if not self.stackPop:
while self.stackPush:
self.stackPop.append(self.stackPush.pop())
def add(self,num):
self.stackPush.append(num)
def poll(self):
if not self.stackPop and not self.stackPush:
return
self.pushToPop()
return self.stackPop.pop()
def peek(self):
if not self.stackPop and not self.stackPush:
return
return self.stackPop[0]
if __name__ == "__main__":
queue = TwoStacksQueue( )
queue.add(1)
queue.add(2)
queue.add(3)
queue.add(4)
queue.add(5)
queue.poll()
queue.poll()
queue.add(6)
queue.add(7)
queue.add(8)
queue.add(9)
queue.add(10)
queue.poll()
queue.peek() |
"""Heisenbridge
An alternative to https://github.com/matrix-org/matrix-appservice-irc/issues
"""
|
class lagrange(object):
def __init__(self, eval_x = 0):
self._eval_x = eval_x
self._extrapolations = []
def add_point(self, x, y):
new_extraps = [(y, x)]
for past_extrap, x_old in self._extrapolations:
new_val = ((self._eval_x - x) * past_extrap \
+ (x_old - self._eval_x) * new_extraps[-1][0])\
/ (x_old - x)
new_extraps.append((new_val, x_old))
self._extrapolations = new_extraps
return self.estimate
@property
def estimate(self):
return self._extrapolations[-1][0]
if __name__ == "__main__":
interpolator = lagrange(eval_x = 0)
print(interpolator.add_point(1,2))
print(interpolator.add_point(0.5,3))
print(interpolator.add_point(0.25,3.75))
print(interpolator.add_point(0.125,4.25))
print(interpolator.add_point(0.0625,4.5))
|
# -*- coding: utf-8 -*-
__version__ = '1.0.0'
default_app_config = 'webmap.apps.WebmapConfig'
|
#Get a string which is n (non-negative integer) copies of a given string
#
#function to display the string
def dispfunc(iteration):
output=str("")
for i in range(iteration):
output=output+entry
print(output)
#
entry=str(input("\nenter a string : "))
displaynumber=int(input("how many times must it be displayed? : "))
dispfunc(displaynumber)
#experimental
feedback=str(input("\nwould you try it for the stringlength? : "))
if feedback == "yes" or "Yes" or "YES" or "yeah":
dispfunc(len(entry))
#program ends here |
spaces = int(input())
steps =0
while(spaces > 0):
if(spaces >= 5):
spaces -= 5
steps += 1
elif(spaces >= 4):
spaces -= 4
steps += 1
elif(spaces >= 3):
spaces -= 3
steps += 1
elif(spaces >= 2):
spaces -= 2
steps += 1
elif(spaces >= 1):
spaces -= 1
steps += 1
print(str(steps))
|
# Straightforward implementation of the Singleton Pattern
class Logger(object):
_instance = None
def __new__(cls):
if cls._instance is None:
print('Creating the object')
cls._instance = super(Logger, cls).__new__(cls)
# Put any initialization here.
return cls._instance
log1 = Logger()
print(log1)
log2 = Logger()
print(log2)
print('Are they the same object?', log1 is log2)
|
load("@rules_pkg//:providers.bzl", "PackageFilesInfo", "PackageSymlinkInfo", "PackageFilegroupInfo")
def _runfile_path(ctx, file, runfiles_dir):
path = file.short_path
if path.startswith(".."):
return path.replace("..", runfiles_dir)
if not file.owner.workspace_name:
return "/".join([runfiles_dir, ctx.workspace_name, path])
return path
def _runfiles_impl(ctx):
default = ctx.attr.binary[DefaultInfo]
executable = default.files_to_run.executable
manifest = default.files_to_run.runfiles_manifest
runfiles_dir = manifest.short_path.replace(manifest.basename, "")[:-1]
files = depset(transitive = [default.files, default.default_runfiles.files])
fileMap = {
executable.short_path: executable
}
for file in files.to_list():
fileMap[_runfile_path(ctx, file, runfiles_dir)] = file
files = depset([executable], transitive = [files])
symlinks = []
for symlink in default.data_runfiles.root_symlinks.to_list():
info = PackageSymlinkInfo(
source = "/%s" % _runfile_path(ctx, symlink.target_file, runfiles_dir),
destination = "/%s" % "/".join([runfiles_dir, symlink.path]),
attributes = { "mode": "0777" }
)
symlinks.append([info, ctx.label])
return [
PackageFilegroupInfo(
pkg_dirs = [],
pkg_files = [
[PackageFilesInfo(
dest_src_map = fileMap,
attributes = {},
), ctx.label]
],
pkg_symlinks = symlinks,
),
DefaultInfo(files = files),
]
expand_runfiles = rule(
implementation = _runfiles_impl,
attrs = {
"binary": attr.label()
}
) |
# You can also nest for loops with
# while loops. Check it out!
for i in range(4):
print("For loop: " + str(i))
x = i
while x >= 0:
print(" While loop: " + str(x))
x = x - 1
|
##list of integers
student_score= [99, 88, 60]
##printing out that list
print(student_score)
##printing all the integers in a range
print(list(range(1,10)))
##printing out all the integers in a range skipping one every time
print(list(range(1,10,2)))
## manipulating a string and printting all the modifications
x = "hello"
y = x.upper()
z = x.title()
print(x, y, z) |
def harmonic(a, b):
return (2*a*b)/(a + b);
a, b = map(int, input().split())
print(harmonic(a, b))
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Created by PyCharm
# @author : mystic
# @date : 2017/11/11 21:01
"""
Override Configuration
"""
configs = {
'db': {
'host': '127.0.0.1'
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.