content stringlengths 7 1.05M |
|---|
print("Look at the assinment statements")
#1. Set a variable called playerlives equal to 3
playerlives = 3
#Write assignment statements for 2 to 6 below
#2. set a variable called chocolate equal to 2
#3. set a variable called scorevalue equal to 4
#4. set a variable called totalscore equal to scorevalue * 3
#5. set a variable called robotname equal to "Botty"
#6 Write print statements to ouput all of the variables above |
palavra = input('Informe uma palavra: ')
print('palavra invertida: ', palavra[::-1])
for letra in palavra:
print(letra) |
"""Non-public internal utilities used across the library.
The classes and functions under this module are not meant to be touched by users.
"""
__all__ = ()
|
dy_import_module_symbols("testchunk_helper")
SERVER_IP = getmyip()
SERVER_PORT = 60606
DATA_RECV = 1024
CHUNK_SIZE_SEND = 2**9 # 512KB chunk size
CHUNK_SIZE_RECV = 2**9
DATA_TO_SEND = "Hello" # 5Bytes of data
launch_test()
|
'''
pretrained model for StarGAN
details adding soon !
'''
|
#
# Copyright 2021 Abir Haque
# Subject to MIT License in LICENSE file
#
#
#
# Perfect Square Roots:
#
# Find the square root of any given perfect square without multiplication or division.
#
# This is possible as all perfect squares are the sum of odd integers [1].
# This arithmetic sequence can be seen below:
#
# 1 = 1
# 4 = 1 + 3
# 9 = 1 + 3 + 5
# 16 = 1 + 3 + 5 + 7
# 25 = 1 + 3 + 5 + 7 + 9
#
# We can find a square root of a perfect square by counting the times we add odd increasing numbers to equal a perfect square.
#
# Below is a program I wrote when introduced to this very problem in a weekly challenge at Replit.com [2].
# Given how I am extremely into recreational mathematics, I couldn't help by give a go at this challenge!
# I also decided that I might learn a few more Python hacks, such as writing multiple statements on one line [3][4].
#
# Links:
# [1] https://en.wikipedia.org/wiki/Square_number
# [2] https://replit.com/talk/announcements/Weekly-Challenge-1/142232
# [3] https://tutorialspoint.com/How-to-provide-multiple-statements-on-a-single-line-in-Python
# [4] https://note.nkmk.me/en/python-multi-variables-values/
def sqrt(n):
i, j, k = 0, -1, 0
while(k < n):
j+=2; k+=j; i+=1
if (k==n):
return(i)
return("not possible")
n = int(input("Please enter a number: "))
print("Square root of " + str(n) + " is " + str(sqrt(n)) +".")
|
"""
A module that displays a poor-man's bar chart.
"""
def render_chart(word_list):
"""
Renders a bar chart to the console. Each row of the chart contains the frequency
of each letter in the word list.
Returns:
A dictionary whose keys are the letters and values are the freqency (N) of the
letter. The value is a string containing the key repeated N times.
For example in the string 'apple' the result would be like this:
{"A": "a"},
{"E": "e"},
{"L": "l"},
{"P": "pp"}
Although not shown above all keys are returned even if the frequency is zero.
"""
chart = {chr(n): "" for n in range(ord('A'), ord('Z') + 1)}
for word in word_list:
for letter in word:
try:
chart[letter.upper()] += letter.upper()
except KeyError:
continue
return chart
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""unshurl
- Author: Daniel J. Umpierrez
- Created: 26-05-2019
- License: UNLICENSE
- Github: https://github.com/havocesp/unshurl
"""
__version__ = '0.1.0'
__site__ = 'https://github.com/havocesp/unshurl'
__license__ = 'UNLICENSE'
__author__ = 'Daniel J. Umpierrez'
__email__ = 'umpierrez@pm.me'
__keywords__ = 'url short long internet html http address converter tiny'
__description__ = 'Short to long URL converter.'
|
# For Keystone Engine. AUTO-GENERATED FILE, DO NOT EDIT [keystone_const.py]
KS_API_MAJOR = 0
KS_API_MINOR = 9
KS_VERSION_MAJOR = 0
KS_VERSION_MINOR = 9
KS_VERSION_EXTRA = 1
KS_ARCH_ARM = 1
KS_ARCH_ARM64 = 2
KS_ARCH_MIPS = 3
KS_ARCH_X86 = 4
KS_ARCH_PPC = 5
KS_ARCH_SPARC = 6
KS_ARCH_SYSTEMZ = 7
KS_ARCH_HEXAGON = 8
KS_ARCH_EVM = 9
KS_ARCH_MAX = 10
KS_MODE_LITTLE_ENDIAN = 0
KS_MODE_BIG_ENDIAN = 1073741824
KS_MODE_ARM = 1
KS_MODE_THUMB = 16
KS_MODE_V8 = 64
KS_MODE_MICRO = 16
KS_MODE_MIPS3 = 32
KS_MODE_MIPS32R6 = 64
KS_MODE_MIPS32 = 4
KS_MODE_MIPS64 = 8
KS_MODE_16 = 2
KS_MODE_32 = 4
KS_MODE_64 = 8
KS_MODE_PPC32 = 4
KS_MODE_PPC64 = 8
KS_MODE_QPX = 16
KS_MODE_SPARC32 = 4
KS_MODE_SPARC64 = 8
KS_MODE_V9 = 16
KS_ERR_ASM = 128
KS_ERR_ASM_ARCH = 512
KS_ERR_OK = 0
KS_ERR_NOMEM = 1
KS_ERR_ARCH = 2
KS_ERR_HANDLE = 3
KS_ERR_MODE = 4
KS_ERR_VERSION = 5
KS_ERR_OPT_INVALID = 6
KS_ERR_ASM_EXPR_TOKEN = 128
KS_ERR_ASM_DIRECTIVE_VALUE_RANGE = 129
KS_ERR_ASM_DIRECTIVE_ID = 130
KS_ERR_ASM_DIRECTIVE_TOKEN = 131
KS_ERR_ASM_DIRECTIVE_STR = 132
KS_ERR_ASM_DIRECTIVE_COMMA = 133
KS_ERR_ASM_DIRECTIVE_RELOC_NAME = 134
KS_ERR_ASM_DIRECTIVE_RELOC_TOKEN = 135
KS_ERR_ASM_DIRECTIVE_FPOINT = 136
KS_ERR_ASM_DIRECTIVE_UNKNOWN = 137
KS_ERR_ASM_DIRECTIVE_EQU = 138
KS_ERR_ASM_DIRECTIVE_INVALID = 139
KS_ERR_ASM_VARIANT_INVALID = 140
KS_ERR_ASM_EXPR_BRACKET = 141
KS_ERR_ASM_SYMBOL_MODIFIER = 142
KS_ERR_ASM_SYMBOL_REDEFINED = 143
KS_ERR_ASM_SYMBOL_MISSING = 144
KS_ERR_ASM_RPAREN = 145
KS_ERR_ASM_STAT_TOKEN = 146
KS_ERR_ASM_UNSUPPORTED = 147
KS_ERR_ASM_MACRO_TOKEN = 148
KS_ERR_ASM_MACRO_PAREN = 149
KS_ERR_ASM_MACRO_EQU = 150
KS_ERR_ASM_MACRO_ARGS = 151
KS_ERR_ASM_MACRO_LEVELS_EXCEED = 152
KS_ERR_ASM_MACRO_STR = 153
KS_ERR_ASM_MACRO_INVALID = 154
KS_ERR_ASM_ESC_BACKSLASH = 155
KS_ERR_ASM_ESC_OCTAL = 156
KS_ERR_ASM_ESC_SEQUENCE = 157
KS_ERR_ASM_ESC_STR = 158
KS_ERR_ASM_TOKEN_INVALID = 159
KS_ERR_ASM_INSN_UNSUPPORTED = 160
KS_ERR_ASM_FIXUP_INVALID = 161
KS_ERR_ASM_LABEL_INVALID = 162
KS_ERR_ASM_FRAGMENT_INVALID = 163
KS_ERR_ASM_INVALIDOPERAND = 512
KS_ERR_ASM_MISSINGFEATURE = 513
KS_ERR_ASM_MNEMONICFAIL = 514
KS_OPT_SYNTAX = 1
KS_OPT_SYM_RESOLVER = 2
KS_OPT_SYNTAX_INTEL = 1
KS_OPT_SYNTAX_ATT = 2
KS_OPT_SYNTAX_NASM = 4
KS_OPT_SYNTAX_MASM = 8
KS_OPT_SYNTAX_GAS = 16
KS_OPT_SYNTAX_RADIX16 = 32
|
class TestDataError(Exception):
pass
class MissingElementAmountValue(TestDataError):
pass
class FactoryStartedAlready(TestDataError):
pass
class NoSuchDatatype(TestDataError):
pass
class InvalidFieldType(TestDataError):
pass
class MissingRequiredFields(TestDataError):
pass
class UnmetDependentFields(TestDataError):
pass
class NoFactoriesProvided(TestDataError):
pass
class InvalidDistribution(TestDataError):
pass
|
# -*- coding: utf-8 -*-
def test_help_message(testdir):
result = testdir.runpytest(
'--help',
)
# fnmatch_lines does an assertion internally
result.stdout.fnmatch_lines([
'helm:',
'*--helm-path=HELM_PATH*',
])
def test_helm_path_ini_setting(testdir):
testdir.makeini("""
[pytest]
HELM_PATH=/path/to/helm
""")
testdir.makepyfile("""
import pytest
@pytest.fixture
def helm_path_ini(request):
return request.config.getini('HELM_PATH')
def test_helm_path_ini(helm_path_ini):
assert helm_path_ini == '/path/to/helm'
""")
result = testdir.runpytest('-v')
# fnmatch_lines does an assertion internally
result.stdout.fnmatch_lines([
'*::test_helm_path_ini PASSED*',
])
# make sure that that we get a '0' exit code for the testsuite
assert result.ret == 0
|
# ******Numbers with The Highest Amount of Divisors******
# codewars
# An array of different positive integers is given. We should create a code that gives us the number (or the numbers) that has (or have) the highest number of divisors among other data.
# The function proc_arrInt(), (Javascript: procArrInt()) will receive an array of unsorted integers and should output a list with the following results:
# [(1), (2), (3)]
# (1) - Total amount of numbers received (2) - Total prime numbers received (3) - a list [(a), (b)] (a)- The highest amount of divisors that a certain number (or numbers) of the given
# array have (b)- A sorted list with the numbers that have the largest amount of divisors. The list may have only one number.
# Example:
# arr1 = [66, 36, 49, 40, 73, 12, 77, 78, 76, 8, 50, 20, 85, 22, 24, 68, 26, 59, 92, 93, 30]
# proc_arrInt(arr1) ------> [21, 2, [9, [36]]
# 21 integers in the array
# 2 primes: 73 and 97
# 36 is the number that has the highest amount of divisors:
# 1, 2, 3, 4, 6, 9, 12, 18, 36 (9 divisors, including 1 and 36)
# ANSWER
def proc_arrInt(listNum):
primes = []
output = [0,[0]]
maxi = 0
for i in listNum:
count = 1
for j in range(1,(i//2)+1):
if i % j == 0:
count += 1
if count == 2:
primes.append(i)
if count > maxi:
output[0] = count
output[1] = [i]
maxi = count
elif count == maxi:
output[1].append(i)
output[1].sort()
return [len(listNum),len(primes),output]
|
#
# PySNMP MIB module EDB-snmp (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/EDB-snmp
# Produced by pysmi-0.3.4 at Wed May 1 12:59:23 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
ObjectIdentifier, OctetString, Integer = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "OctetString", "Integer")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueSizeConstraint, ConstraintsIntersection, ConstraintsUnion, SingleValueConstraint, ValueRangeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "ConstraintsIntersection", "ConstraintsUnion", "SingleValueConstraint", "ValueRangeConstraint")
ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup")
iso, Gauge32, Bits, Counter64, MibIdentifier, MibScalar, MibTable, MibTableRow, MibTableColumn, ModuleIdentity, Unsigned32, NotificationType, ObjectIdentity, Counter32, NotificationType, TimeTicks, Integer32, IpAddress, mgmt, internet = mibBuilder.importSymbols("SNMPv2-SMI", "iso", "Gauge32", "Bits", "Counter64", "MibIdentifier", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "ModuleIdentity", "Unsigned32", "NotificationType", "ObjectIdentity", "Counter32", "NotificationType", "TimeTicks", "Integer32", "IpAddress", "mgmt", "internet")
TextualConvention, DisplayString, PhysAddress = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString", "PhysAddress")
private = MibIdentifier((1, 3, 6, 1, 4))
enterprises = MibIdentifier((1, 3, 6, 1, 4, 1))
fibronics = MibIdentifier((1, 3, 6, 1, 4, 1, 22))
trap = MibIdentifier((1, 3, 6, 1, 4, 1, 22, 3))
traprun = MibIdentifier((1, 3, 6, 1, 4, 1, 22, 3, 1))
traperm = MibIdentifier((1, 3, 6, 1, 4, 1, 22, 3, 2))
trapvar = MibIdentifier((1, 3, 6, 1, 4, 1, 22, 3, 3))
fm800 = MibIdentifier((1, 3, 6, 1, 4, 1, 22, 51))
fmsystem = MibIdentifier((1, 3, 6, 1, 4, 1, 22, 51, 1))
fmslot = MibIdentifier((1, 3, 6, 1, 4, 1, 22, 51, 2))
fmlu = MibIdentifier((1, 3, 6, 1, 4, 1, 22, 51, 3))
fmdiag = MibIdentifier((1, 3, 6, 1, 4, 1, 22, 51, 5))
fmsystemrun = MibIdentifier((1, 3, 6, 1, 4, 1, 22, 51, 1, 1))
fmsystemperm = MibIdentifier((1, 3, 6, 1, 4, 1, 22, 51, 1, 2))
rTrapAddrTbl = MibTable((1, 3, 6, 1, 4, 1, 22, 3, 1, 1), )
if mibBuilder.loadTexts: rTrapAddrTbl.setStatus('mandatory')
if mibBuilder.loadTexts: rTrapAddrTbl.setDescription('Table of managers to which traps must be sent. Up to 10 entries in table')
rTrapAddrEntry = MibTableRow((1, 3, 6, 1, 4, 1, 22, 3, 1, 1, 1), ).setIndexNames((0, "EDB-snmp", "rTrapAddrAddr"))
if mibBuilder.loadTexts: rTrapAddrEntry.setStatus('mandatory')
rTrapAddrAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 22, 3, 1, 1, 1, 1), IpAddress()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rTrapAddrAddr.setStatus('mandatory')
if mibBuilder.loadTexts: rTrapAddrAddr.setDescription('IP address of entity requesting event notification')
rTrapAddrComm = MibTableColumn((1, 3, 6, 1, 4, 1, 22, 3, 1, 1, 1, 2), OctetString()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rTrapAddrComm.setStatus('mandatory')
if mibBuilder.loadTexts: rTrapAddrComm.setDescription('Community name the receiving entity will expect. When reading the instance of this object the value has no meaning.')
rTrapAddrVer = MibTableColumn((1, 3, 6, 1, 4, 1, 22, 3, 1, 1, 1, 3), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rTrapAddrVer.setStatus('mandatory')
if mibBuilder.loadTexts: rTrapAddrVer.setDescription('Version number supported by destination node')
rTrapAddrType = MibTableColumn((1, 3, 6, 1, 4, 1, 22, 3, 1, 1, 1, 4), OctetString()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rTrapAddrType.setStatus('mandatory')
if mibBuilder.loadTexts: rTrapAddrType.setDescription('Type of event that should be reported to this address, bit 0 - authentication trap bit 1 - other SNMP traps bit 2 - Error Traps bit 3 - Diagnostic Traps bit 4 - Debug Traps bit 5 - Enterprise Traps other than fmDiagGenericTrap')
rTrapAddrState = MibTableColumn((1, 3, 6, 1, 4, 1, 22, 3, 1, 1, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("active", 1), ("inactive", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rTrapAddrState.setStatus('mandatory')
if mibBuilder.loadTexts: rTrapAddrState.setDescription('Determines status of this entry')
rTrapAddrFlag = MibTableColumn((1, 3, 6, 1, 4, 1, 22, 3, 1, 1, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("fixed", 0), ("removable", 1)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rTrapAddrFlag.setStatus('mandatory')
if mibBuilder.loadTexts: rTrapAddrFlag.setDescription('If the entry is fixed, it can not be deleted because of aging')
rTrapAddrAge = MibTableColumn((1, 3, 6, 1, 4, 1, 22, 3, 1, 1, 1, 7), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rTrapAddrAge.setStatus('mandatory')
if mibBuilder.loadTexts: rTrapAddrAge.setDescription('Aging time of the entry (in sec)')
rTrapLearning = MibScalar((1, 3, 6, 1, 4, 1, 22, 3, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disable", 0), ("enable", 1)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: rTrapLearning.setStatus('mandatory')
if mibBuilder.loadTexts: rTrapLearning.setDescription('Learn the addresses of the managers automatically.')
rTrapAging = MibScalar((1, 3, 6, 1, 4, 1, 22, 3, 1, 3), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rTrapAging.setStatus('mandatory')
if mibBuilder.loadTexts: rTrapAging.setDescription('Time in sec. until we erase a trap entry')
pTrapAddrTbl = MibTable((1, 3, 6, 1, 4, 1, 22, 3, 2, 1), )
if mibBuilder.loadTexts: pTrapAddrTbl.setStatus('mandatory')
if mibBuilder.loadTexts: pTrapAddrTbl.setDescription('Table of managers to which traps must be sent. Up to 10 entries in table')
pTrapAddrEntry = MibTableRow((1, 3, 6, 1, 4, 1, 22, 3, 2, 1, 1), ).setIndexNames((0, "EDB-snmp", "pTrapAddrAddr"))
if mibBuilder.loadTexts: pTrapAddrEntry.setStatus('mandatory')
pTrapAddrAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 22, 3, 2, 1, 1, 1), IpAddress()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: pTrapAddrAddr.setStatus('mandatory')
if mibBuilder.loadTexts: pTrapAddrAddr.setDescription('IP address of entity requesting event notification')
pTrapAddrComm = MibTableColumn((1, 3, 6, 1, 4, 1, 22, 3, 2, 1, 1, 2), OctetString()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: pTrapAddrComm.setStatus('mandatory')
if mibBuilder.loadTexts: pTrapAddrComm.setDescription('Community name the receiving entity will expect. When reading the instance of this object the value has no meaning.')
pTrapAddrVer = MibTableColumn((1, 3, 6, 1, 4, 1, 22, 3, 2, 1, 1, 3), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: pTrapAddrVer.setStatus('mandatory')
if mibBuilder.loadTexts: pTrapAddrVer.setDescription('Version number supported by destination node')
pTrapAddrType = MibTableColumn((1, 3, 6, 1, 4, 1, 22, 3, 2, 1, 1, 4), OctetString()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: pTrapAddrType.setStatus('mandatory')
if mibBuilder.loadTexts: pTrapAddrType.setDescription('Type of event that should be reported to this address, bit 0 - authentication trap bit 1 - other SNMP traps bit 2 - Error Traps bit 3 - Diagnostic Traps bit 4 - Debug Traps bit 5 - all Enterprise Traps other than fmDiagGenericTrap')
pTrapAddrState = MibTableColumn((1, 3, 6, 1, 4, 1, 22, 3, 2, 1, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("active", 1), ("inactive", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: pTrapAddrState.setStatus('mandatory')
if mibBuilder.loadTexts: pTrapAddrState.setDescription('Determines status of this entry')
pTrapLearning = MibScalar((1, 3, 6, 1, 4, 1, 22, 3, 2, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disable", 0), ("enable", 1)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: pTrapLearning.setStatus('mandatory')
if mibBuilder.loadTexts: pTrapLearning.setDescription('Learn the addresses of the managers automatically.')
pTrapAging = MibScalar((1, 3, 6, 1, 4, 1, 22, 3, 2, 3), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: pTrapAging.setStatus('mandatory')
if mibBuilder.loadTexts: pTrapAging.setDescription('Time in sec. until we erase a trap entry')
fmSystemPSAdmin = MibScalar((1, 3, 6, 1, 4, 1, 22, 51, 1, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("primary-power", 1), ("secondary-power", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: fmSystemPSAdmin.setStatus('mandatory')
if mibBuilder.loadTexts: fmSystemPSAdmin.setDescription('Changes power supply to primary or secondary. When reading the instance of this object the value has no meaning.')
fmSystemPSOper = MibScalar((1, 3, 6, 1, 4, 1, 22, 51, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("primary-power", 1), ("secondary-power", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: fmSystemPSOper.setStatus('mandatory')
if mibBuilder.loadTexts: fmSystemPSOper.setDescription('Which power supply active')
fmSystemPSCfg = MibScalar((1, 3, 6, 1, 4, 1, 22, 51, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("primary-power", 1), ("secondary-power", 2), ("primary-and-secondary-power", 3)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: fmSystemPSCfg.setStatus('mandatory')
if mibBuilder.loadTexts: fmSystemPSCfg.setDescription('Configuration of power supply')
fmSystemReset = MibScalar((1, 3, 6, 1, 4, 1, 22, 51, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 127))).clone(namedValues=NamedValues(("cold-reset", 0), ("warm-reset", 1), ("power-up", 2), ("meaning-less-value", 127)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: fmSystemReset.setStatus('mandatory')
if mibBuilder.loadTexts: fmSystemReset.setDescription('Resetting the CARD. When reading the instance of this object the value has no meaning. cold reset is performed with selftest , while warm start is performed without selftest')
fmSystemSelfTestLevel = MibScalar((1, 3, 6, 1, 4, 1, 22, 51, 1, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("none", 0), ("partial", 1), ("full", 2), ("extended", 3)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: fmSystemSelfTestLevel.setStatus('mandatory')
if mibBuilder.loadTexts: fmSystemSelfTestLevel.setDescription('Type of self test to be executed upon cold-reset')
fmSystemVersion = MibScalar((1, 3, 6, 1, 4, 1, 22, 51, 1, 1, 6), OctetString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fmSystemVersion.setStatus('mandatory')
if mibBuilder.loadTexts: fmSystemVersion.setDescription('Version of the station. The version includes station type, hardware version and software version. The string can include CR and LF')
fmSystemIpAddr = MibScalar((1, 3, 6, 1, 4, 1, 22, 51, 1, 1, 7), IpAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fmSystemIpAddr.setStatus('mandatory')
if mibBuilder.loadTexts: fmSystemIpAddr.setDescription('IP address of the agent')
fmSystemIPNetMask = MibScalar((1, 3, 6, 1, 4, 1, 22, 51, 1, 1, 8), IpAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fmSystemIPNetMask.setStatus('mandatory')
if mibBuilder.loadTexts: fmSystemIPNetMask.setDescription('IP Network Mask')
fmSystemIPDefGway = MibScalar((1, 3, 6, 1, 4, 1, 22, 51, 1, 1, 9), IpAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fmSystemIPDefGway.setStatus('mandatory')
if mibBuilder.loadTexts: fmSystemIPDefGway.setDescription('Default Gateway Address')
fmSystemFileServer = MibScalar((1, 3, 6, 1, 4, 1, 22, 51, 1, 1, 10), IpAddress()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: fmSystemFileServer.setStatus('mandatory')
if mibBuilder.loadTexts: fmSystemFileServer.setDescription('IP address to which a TFTP for boot is sent.')
fmSystemBootFile = MibScalar((1, 3, 6, 1, 4, 1, 22, 51, 1, 1, 11), OctetString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fmSystemBootFile.setStatus('mandatory')
if mibBuilder.loadTexts: fmSystemBootFile.setDescription('Path and file name that is sent as a TFTP request')
fmSystemBootMode = MibScalar((1, 3, 6, 1, 4, 1, 22, 51, 1, 1, 12), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("internal-memory", 1), ("bootp", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: fmSystemBootMode.setStatus('deprecated')
if mibBuilder.loadTexts: fmSystemBootMode.setDescription('Method for booting')
fmSystemDownLoad = MibScalar((1, 3, 6, 1, 4, 1, 22, 51, 1, 1, 13), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 127))).clone(namedValues=NamedValues(("download", 1), ("meaning-less-value", 127)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: fmSystemDownLoad.setStatus('mandatory')
if mibBuilder.loadTexts: fmSystemDownLoad.setDescription('Downloading the EDB. When reading the instance of this object the value has no meaning.')
fmSystemSlipIpAddr = MibScalar((1, 3, 6, 1, 4, 1, 22, 51, 1, 1, 14), IpAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fmSystemSlipIpAddr.setStatus('mandatory')
if mibBuilder.loadTexts: fmSystemSlipIpAddr.setDescription('SLIP IP address. This is object is available only when slip interface exist ')
fmSystemSlipIPNetMask = MibScalar((1, 3, 6, 1, 4, 1, 22, 51, 1, 1, 15), IpAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fmSystemSlipIPNetMask.setStatus('mandatory')
if mibBuilder.loadTexts: fmSystemSlipIPNetMask.setDescription('SLIP IP Network Mask This is object is available only when slip interface exist ')
fmSystemSlipBaudRate = MibScalar((1, 3, 6, 1, 4, 1, 22, 51, 1, 1, 16), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("baud1200", 0), ("baud2400", 1), ("baud4800", 2), ("baud9600", 3), ("baud19200", 4), ("baud38400", 5)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: fmSystemSlipBaudRate.setStatus('mandatory')
if mibBuilder.loadTexts: fmSystemSlipBaudRate.setDescription('SLIP Baud rate This is object is available only when slip interface exist ')
fmSystemSlipParity = MibScalar((1, 3, 6, 1, 4, 1, 22, 51, 1, 1, 17), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2))).clone(namedValues=NamedValues(("none", 0), ("odd", 1), ("even", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: fmSystemSlipParity.setStatus('mandatory')
if mibBuilder.loadTexts: fmSystemSlipParity.setDescription('SLIP Parity This is object is available only when slip interface exist ')
fmSystemSlipStopBits = MibScalar((1, 3, 6, 1, 4, 1, 22, 51, 1, 1, 18), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("one", 0), ("two", 1)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: fmSystemSlipStopBits.setStatus('mandatory')
if mibBuilder.loadTexts: fmSystemSlipStopBits.setDescription('SLIP Stop Bits This is object is available only when slip interface exist ')
pfmSystemIpAddr = MibScalar((1, 3, 6, 1, 4, 1, 22, 51, 1, 2, 7), IpAddress()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: pfmSystemIpAddr.setStatus('mandatory')
if mibBuilder.loadTexts: pfmSystemIpAddr.setDescription('IP address of the agent')
pfmSystemIPNetMask = MibScalar((1, 3, 6, 1, 4, 1, 22, 51, 1, 2, 8), IpAddress()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: pfmSystemIPNetMask.setStatus('mandatory')
if mibBuilder.loadTexts: pfmSystemIPNetMask.setDescription('IP Network Mask')
pfmSystemIPDefGway = MibScalar((1, 3, 6, 1, 4, 1, 22, 51, 1, 2, 9), IpAddress()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: pfmSystemIPDefGway.setStatus('mandatory')
if mibBuilder.loadTexts: pfmSystemIPDefGway.setDescription('Default Gateway Address')
pfmSystemFileServer = MibScalar((1, 3, 6, 1, 4, 1, 22, 51, 1, 2, 10), IpAddress()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: pfmSystemFileServer.setStatus('mandatory')
if mibBuilder.loadTexts: pfmSystemFileServer.setDescription('IP address to which a TFTP for boot is sent.')
pfmSystemBootFile = MibScalar((1, 3, 6, 1, 4, 1, 22, 51, 1, 2, 11), OctetString()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: pfmSystemBootFile.setStatus('mandatory')
if mibBuilder.loadTexts: pfmSystemBootFile.setDescription('Path and file name that is sent as a TFTP request')
pfmSystemBootMode = MibScalar((1, 3, 6, 1, 4, 1, 22, 51, 1, 2, 12), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("internal-memory", 1), ("bootp", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: pfmSystemBootMode.setStatus('mandatory')
if mibBuilder.loadTexts: pfmSystemBootMode.setDescription('Method for booting')
pfmSystemReadCommunity = MibScalar((1, 3, 6, 1, 4, 1, 22, 51, 1, 2, 13), OctetString()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: pfmSystemReadCommunity.setStatus('mandatory')
if mibBuilder.loadTexts: pfmSystemReadCommunity.setDescription('Community string for reading When reading the instance of this object the value has no meaning.')
pfmSystemWriteCommunity = MibScalar((1, 3, 6, 1, 4, 1, 22, 51, 1, 2, 14), OctetString()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: pfmSystemWriteCommunity.setStatus('mandatory')
if mibBuilder.loadTexts: pfmSystemWriteCommunity.setDescription('Community string for writing When reading the instance of this object the value has no meaning.')
pfmSystemSlipIpAddr = MibScalar((1, 3, 6, 1, 4, 1, 22, 51, 1, 2, 15), IpAddress()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: pfmSystemSlipIpAddr.setStatus('mandatory')
if mibBuilder.loadTexts: pfmSystemSlipIpAddr.setDescription('SLIP IP address This is object is available only when slip interface exist ')
pfmSystemSlipIPNetMask = MibScalar((1, 3, 6, 1, 4, 1, 22, 51, 1, 2, 16), IpAddress()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: pfmSystemSlipIPNetMask.setStatus('mandatory')
if mibBuilder.loadTexts: pfmSystemSlipIPNetMask.setDescription('SLIP IP Network Mask This is object is available only when slip interface exist ')
pfmSystemSlipBaudRate = MibScalar((1, 3, 6, 1, 4, 1, 22, 51, 1, 2, 17), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("baud1200", 0), ("baud2400", 1), ("baud4800", 2), ("baud9600", 3), ("baud19200", 4), ("baud38400", 5)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: pfmSystemSlipBaudRate.setStatus('mandatory')
if mibBuilder.loadTexts: pfmSystemSlipBaudRate.setDescription('SLIP Baud rate This is object is available only when slip interface exist ')
pfmSystemSlipParity = MibScalar((1, 3, 6, 1, 4, 1, 22, 51, 1, 2, 18), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2))).clone(namedValues=NamedValues(("none", 0), ("odd", 1), ("even", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: pfmSystemSlipParity.setStatus('mandatory')
if mibBuilder.loadTexts: pfmSystemSlipParity.setDescription('SLIP Parity This is object is available only when slip interface exist ')
pfmSystemSlipStopBits = MibScalar((1, 3, 6, 1, 4, 1, 22, 51, 1, 2, 19), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("one", 0), ("two", 1)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: pfmSystemSlipStopBits.setStatus('mandatory')
if mibBuilder.loadTexts: pfmSystemSlipStopBits.setDescription('SLIP Stop Bits This is object is available only when slip interface exist ')
fmSlotMasterClear = MibScalar((1, 3, 6, 1, 4, 1, 22, 51, 2, 1), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: fmSlotMasterClear.setStatus('mandatory')
if mibBuilder.loadTexts: fmSlotMasterClear.setDescription('Upon writing, performs a master clear command on all the slots. When reading the instance of this object the value has no meaning.')
fmSlotTable = MibTable((1, 3, 6, 1, 4, 1, 22, 51, 2, 2), )
if mibBuilder.loadTexts: fmSlotTable.setStatus('mandatory')
fmSlotEntry = MibTableRow((1, 3, 6, 1, 4, 1, 22, 51, 2, 2, 1), ).setIndexNames((0, "EDB-snmp", "fmSlotIndex"))
if mibBuilder.loadTexts: fmSlotEntry.setStatus('mandatory')
fmSlotIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 22, 51, 2, 2, 1, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fmSlotIndex.setStatus('mandatory')
if mibBuilder.loadTexts: fmSlotIndex.setDescription('Slot Number')
fmSlotID = MibTableColumn((1, 3, 6, 1, 4, 1, 22, 51, 2, 2, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 65537, 65540, 65544, 65545, 65548, 65552, 65553, 65560, 65562, 65563, 65568, 65576, 65580, 65584, 65588, 65589, 65591, 65590, 65592, 65594, 65595, 65550, 65551, 65566, 65567, 65578, 65541, 65542, 65543, 65557, 65558, 65559, 131072, 131073, 131075, 131077))).clone(namedValues=NamedValues(("unconfig", 0), ("empty", 1), ("cc832-10", 2), ("cc832-12", 3), ("cc832-20", 4), ("cc832-31", 5), ("cc832-32", 6), ("cc832-41", 7), ("cc832-42", 8), ("cc832-44", 9), ("cc832-46A", 10), ("cc892-832", 65537), ("lc322", 65540), ("cc892-201", 65544), ("cc892-202", 65545), ("cc892-214", 65548), ("cc892-321", 65552), ("cc892-46B", 65553), ("cc892-301", 65560), ("cc892-303", 65562), ("cc892-308", 65563), ("cc892-233", 65568), ("cc892-260", 65576), ("cc892-427", 65580), ("sw892-11X", 65584), ("cc892-432", 65588), ("cc892-420", 65589), ("cc892-421", 65591), ("cc892-422", 65590), ("cc892-401", 65592), ("cc892-240", 65594), ("cc892-241", 65595), ("cc892-211", 65550), ("cc892-212", 65551), ("lc303", 65566), ("lc308", 65567), ("lc312", 65578), ("cc832-10-ID", 65541), ("cc832-12-ID", 65542), ("cc832-20-ID", 65543), ("cc832-41-ID", 65557), ("cc832-42-ID", 65558), ("cc832-44-ID", 65559), ("general-smartcard", 131072), ("lc308-129", 131073), ("lc303-129", 131075), ("lc312-129", 131077)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: fmSlotID.setStatus('mandatory')
if mibBuilder.loadTexts: fmSlotID.setDescription('ID of the card in the slot')
fmSlotDescr = MibTableColumn((1, 3, 6, 1, 4, 1, 22, 51, 2, 2, 1, 3), OctetString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fmSlotDescr.setStatus('mandatory')
if mibBuilder.loadTexts: fmSlotDescr.setDescription('Ascii string. Description of the card')
fmSlotInfo = MibTableColumn((1, 3, 6, 1, 4, 1, 22, 51, 2, 2, 1, 4), OctetString()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: fmSlotInfo.setStatus('mandatory')
if mibBuilder.loadTexts: fmSlotInfo.setDescription('User general info for the slot. Can be the use of that slot, its location etc...')
fmSlotStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 22, 51, 2, 2, 1, 5), OctetString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fmSlotStatus.setStatus('mandatory')
if mibBuilder.loadTexts: fmSlotStatus.setDescription('8 bytes. 60 status bits of the card. For more information about the meaning of the status, read the specific user manual of each card. The channel leds are encoded into 2 bytes.')
fmSlotPrevStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 22, 51, 2, 2, 1, 6), OctetString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fmSlotPrevStatus.setStatus('mandatory')
if mibBuilder.loadTexts: fmSlotPrevStatus.setDescription('8 bytes. Previous 60 status bits of the card. This object id is used mainly for traps (see Card Trap)')
fmSlotRLBSet = MibTableColumn((1, 3, 6, 1, 4, 1, 22, 51, 2, 2, 1, 7), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: fmSlotRLBSet.setStatus('mandatory')
if mibBuilder.loadTexts: fmSlotRLBSet.setDescription('Argument: 1 - 4. Perform a RLB set operation on the channel passed as argument. When reading the instance of this object the value has no meaning.')
fmSlotRLBClear = MibTableColumn((1, 3, 6, 1, 4, 1, 22, 51, 2, 2, 1, 8), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: fmSlotRLBClear.setStatus('mandatory')
if mibBuilder.loadTexts: fmSlotRLBClear.setDescription('Argument: 1 - 4. Perform a RLB clear operation on the channel passed as argument. When reading the instance of this object the value has no meaning.')
fmSlotExpCode = MibTableColumn((1, 3, 6, 1, 4, 1, 22, 51, 2, 2, 1, 9), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: fmSlotExpCode.setStatus('mandatory')
if mibBuilder.loadTexts: fmSlotExpCode.setDescription('Perform an expanded command on the slot. For expanded codes, see specific card user manual. When reading the instance of this object the value has no meaning. Extended command codes for NDS cards ------------------------------------ 1. CC892.303 (Ethernet) Code (Dec/Hex) Command ----------------------------------- 02/02 Detach Port 13 03/03 Attach Port 13 04/04 Detach Port 01 05/05 Attach Port 01 06/06 Detach Port 02 07/07 Attach Port 02 08/08 Detach Port 03 09/09 Attach Port 03 10/0A Detach Port 04 11/0B Attach Port 04 12/0C Detach Port 05 13/0D Attach Port 05 14/0E Detach Port 06 15/0F Attach Port 06 16/10 Detach Port 07 17/11 Attach Port 07 18/12 Detach Port 08 19/13 Attach Port 08 20/14 Detach Port 09 21/15 Attach Port 09 22/16 Detach Port 10 23/17 Attach Port 10 24/18 Detach Port 11 25/19 Attach Port 11 26/1A Detach Port 12 27/1B Attach Port 12 28/1C Detach All Ports 29/1D Attach All Ports 30/1E Reset Card 31/1F Link Select ====================================================== 2. CC892.308 (Ethernet) Code (Dec/Hex) Command ----------------------------------- 02/02 Detach Port 01 03/03 Attach Port 01 04/04 Detach Port 02 05/05 Attach Port 02 06/06 Detach Port 03 07/07 Attach Port 03 08/08 Detach Port 04 09/09 Attach Port 04 10/0A Detach Port 05 11/0B Attach Port 05 12/0C Detach Port 06 13/0D Attach Port 06 14/0E Detach Port 07 15/0F Attach Port 07 16/10 Detach Port 08 17/11 Attach Port 08 ... 28/1C Detach All Ports 29/1D Attach All Ports 30/1E Reset Card 31/1F Link Select ================================================ 3. CC892.322 (Token-ring) Module 323 ---------- Code (Dec/Hex) Command ----------------------------------- 02/02 Detach Port 01 03/03 Attach Port 01 04/04 Detach Port 02 05/05 Attach Port 02 06/06 Detach Port 03 07/07 Attach Port 03 08/08 Detach Port 04 09/09 Attach Port 04 10/0A Detach Port 05 11/0B Attach Port 05 12/0C Detach Port 06 13/0D Attach Port 06 18/12 Detach Port 07 19/13 Attach Port 07 20/14 Detach Port 08 21/15 Attach Port 08 22/16 Detach Port 19 23/17 Attach Port 19 24/18 Detach Port 10 25/19 Attach Port 10 26/1A Detach Port 11 27/1B Attach Port 11 28/1C Detach Port 12 29/1D Attach Port 12 30/1E Reset Card 34/22 Detach Port 13 35/23 Attach Port 13 36/24 Detach Port 14 37/25 Attach Port 14 38/26 Detach Port 15 39/27 Attach Port 15 40/28 Detach Port 16 41/29 Attach Port 16 42/2A Detach Port 17 43/2B Attach Port 17 44/2C Detach Port 18 45/2D Attach Port 18 50/32 Detach Port 19 51/33 Attach Port 19 52/34 Detach Port 20 53/35 Attach Port 20 54/36 Detach Port 21 55/37 Attach Port 21 56/38 Detach Port 22 57/39 Attach Port 22 58/3A Detach Port 23 59/3B Attach Port 23 60/3C Detach Port 24 61/3D Attach Port 24 77/4D Detach All Ports 79/4F Attach All Ports ======================================================== Module 325 ---------- 30/1E Reset Card 80/50 Detach Local Port 1 (channel 1) 81/51 Attach Local Port 1 (channel 1) 82/52 Detach Local Port 2 (channel 1) 83/53 Attach Local Port 2 (channel 1) 88/58 Detach Local Port 1 (channel 3) 89/59 Attach Local Port 1 (channel 3) 90/5A Detach Local Port 2 (channel 3) 91/5B Attach Local Port 2 (channel 3) 77/4D Detach All Ports 79/4F Attach All Ports 4. CC892.427 (Voice) Code (Dec/Hex) Command ----------------------------------- 04/04 Loopback OFF on Port 1 05/05 Loopback ON on Port 1 06/06 Loopback OFF on Port 2 07/07 Loopback ON on Port 2 08/08 Loopback OFF on Port 3 09/09 Loopback ON on Port 3 10/0A Loopback OFF on Port 4 11/0B Loopback ON on Port 4 12/0C Loopback OFF on Port 5 13/0D Loopback ON on Port 5 14/0E Loopback OFF on Port 6 15/0F Loopback ON on Port 6 16/10 Loopback OFF on Port 7 17/11 Loopback ON on Port 7 18/12 Loopback OFF on Port 8 19/13 Loopback ON on Port 8 20/14 Loopback OFF on Port 9 21/15 Loopback ON on Port 9 22/16 Loopback OFF on Port 10 23/17 Loopback ON on Port 10 24/18 Loopback OFF on Port 11 25/19 Loopback ON on Port 11 26/1A Loopback OFF on Port 12 27/1B Loopback ON on Port 12 28/1C Loopback OFF on Port 13 29/1D Loopback ON on Port 13 30/1E Loopback OFF on Port 14 31/1F Loopback ON on Port 14 32/20 Loopback OFF on Port 15 33/21 Loopback ON on Port 15 34/22 Loopback OFF on Port 16 35/23 Loopback ON on Port 16 37/25 Loopback ALL on Ports 1-8 39/27 Loopback ALL on Ports 9-16 40/28 Alternate Mode on Channel Module #1 41/29 Normal Mode on Channel Module #1 42/2A Alternate Mode on Channel Module #2 43/2B Normal Mode on Channel Module #2 45/2D Configuration Load Module #1 47/2F Configuration Load Module #2 ====================================================== ')
fmSlotTrapMask = MibTableColumn((1, 3, 6, 1, 4, 1, 22, 51, 2, 2, 1, 10), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("no-mask", 0), ("mask", 1)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: fmSlotTrapMask.setStatus('mandatory')
if mibBuilder.loadTexts: fmSlotTrapMask.setDescription('When the value is 1, no more traps from that slot are sent, until next reset. (temporary mask)')
pfmSlotTrapMask = MibTableColumn((1, 3, 6, 1, 4, 1, 22, 51, 2, 2, 1, 11), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("no-mask", 0), ("mask", 1)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: pfmSlotTrapMask.setStatus('mandatory')
if mibBuilder.loadTexts: pfmSlotTrapMask.setDescription('When the value is 1, no more traps for that slot will be sent, starting after next reset (permanent mask)')
fmSlotIpAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 22, 51, 2, 2, 1, 12), IpAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fmSlotIpAddr.setStatus('mandatory')
if mibBuilder.loadTexts: fmSlotIpAddr.setDescription(' IP address of a channel card. This is object is available only for channel cards which have their own IP addresses (e.g., LC303/129)')
fmLUID = MibScalar((1, 3, 6, 1, 4, 1, 22, 51, 3, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10))).clone(namedValues=NamedValues(("unconfig", 0), ("none", 1), ("lu100", 2), ("lu101", 3), ("lu102", 4), ("lu103", 5), ("lu104", 6), ("lu105", 7), ("lu106", 8), ("lu107", 9), ("lu108", 10)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: fmLUID.setStatus('mandatory')
if mibBuilder.loadTexts: fmLUID.setDescription('Logic unit ID')
fmLUDescr = MibScalar((1, 3, 6, 1, 4, 1, 22, 51, 3, 2), OctetString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fmLUDescr.setStatus('mandatory')
if mibBuilder.loadTexts: fmLUDescr.setDescription('Ascii string. Description of the logic unit')
fmLUStatus = MibScalar((1, 3, 6, 1, 4, 1, 22, 51, 3, 3), OctetString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fmLUStatus.setStatus('mandatory')
if mibBuilder.loadTexts: fmLUStatus.setDescription('One byte of LU status')
fmLULinkSelect = MibScalar((1, 3, 6, 1, 4, 1, 22, 51, 3, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("main-link", 0), ("sec-link", 1)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: fmLULinkSelect.setStatus('mandatory')
if mibBuilder.loadTexts: fmLULinkSelect.setDescription('Setup LU link.')
fmLULoopBackSet = MibScalar((1, 3, 6, 1, 4, 1, 22, 51, 3, 5), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: fmLULoopBackSet.setStatus('mandatory')
if mibBuilder.loadTexts: fmLULoopBackSet.setDescription('Upon writing, performs LLB command. When reading the instance of this object the value has no meaning.')
fmLULoopBackClr = MibScalar((1, 3, 6, 1, 4, 1, 22, 51, 3, 6), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: fmLULoopBackClr.setStatus('mandatory')
if mibBuilder.loadTexts: fmLULoopBackClr.setDescription('Upon writing, clear LLB command. When reading the instance of this object the value has no meaning.')
fmLUTrapMask = MibScalar((1, 3, 6, 1, 4, 1, 22, 51, 3, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("no-mask", 0), ("mask", 1)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: fmLUTrapMask.setStatus('mandatory')
if mibBuilder.loadTexts: fmLUTrapMask.setDescription('When the value is 1, no more traps from the LU are sent, until next reset. (temporary mask)')
pfmLUTrapMask = MibScalar((1, 3, 6, 1, 4, 1, 22, 51, 3, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("no-mask", 0), ("mask", 1)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: pfmLUTrapMask.setStatus('mandatory')
if mibBuilder.loadTexts: pfmLUTrapMask.setDescription('When the value is 1, no more traps for the LU will be sent, starting after next reset (permanent mask)')
fmDiagConfig = MibScalar((1, 3, 6, 1, 4, 1, 22, 51, 5, 1), OctetString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fmDiagConfig.setStatus('mandatory')
if mibBuilder.loadTexts: fmDiagConfig.setDescription('Version of the station. The version includes station type, hardware version and software version. The string can include CR and LF')
fmDiagTrapInfo = MibScalar((1, 3, 6, 1, 4, 1, 22, 51, 5, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: fmDiagTrapInfo.setStatus('mandatory')
if mibBuilder.loadTexts: fmDiagTrapInfo.setDescription('Used for generic traps. The first word is the trap code. The rest of the string is the extra information. Contains CR and LF char.')
fmDiagFaultTable = MibTable((1, 3, 6, 1, 4, 1, 22, 51, 5, 3), )
if mibBuilder.loadTexts: fmDiagFaultTable.setStatus('optional')
if mibBuilder.loadTexts: fmDiagFaultTable.setDescription('Table of fault reports from the agent')
fmDiagFaultEntry = MibTableRow((1, 3, 6, 1, 4, 1, 22, 51, 5, 3, 1), ).setIndexNames((0, "EDB-snmp", "fmDiagFaultIndex"))
if mibBuilder.loadTexts: fmDiagFaultEntry.setStatus('optional')
fmDiagFaultIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 22, 51, 5, 3, 1, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fmDiagFaultIndex.setStatus('optional')
if mibBuilder.loadTexts: fmDiagFaultIndex.setDescription('The fault index in the fault table')
fmDiagFaultReport = MibTableColumn((1, 3, 6, 1, 4, 1, 22, 51, 5, 3, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: fmDiagFaultReport.setStatus('optional')
if mibBuilder.loadTexts: fmDiagFaultReport.setDescription('Get the faults detected by the agent')
fmDiagDebug = MibScalar((1, 3, 6, 1, 4, 1, 22, 51, 5, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("normal-mode", 0), ("debug-mode", 1)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: fmDiagDebug.setStatus('mandatory')
if mibBuilder.loadTexts: fmDiagDebug.setDescription('This object is for factory use only. Users must not write into this variable or improper operation can occur.')
fmPowerSupplyFail = NotificationType((1, 3, 6, 1, 4, 1, 22, 51) + (0,1)).setObjects(("EDB-snmp", "fmSystemPSOper"))
if mibBuilder.loadTexts: fmPowerSupplyFail.setDescription('This trap message is generated as soon as one of the power supply has failed')
fmPrimaryPowerSupplyOK = NotificationType((1, 3, 6, 1, 4, 1, 22, 51) + (0,2)).setObjects(("EDB-snmp", "fmSystemPSOper"))
if mibBuilder.loadTexts: fmPrimaryPowerSupplyOK.setDescription('This trap is issued when primary power supply return to work')
fmSecondPowerSupplyOK = NotificationType((1, 3, 6, 1, 4, 1, 22, 51) + (0,3)).setObjects(("EDB-snmp", "fmSystemPSOper"))
if mibBuilder.loadTexts: fmSecondPowerSupplyOK.setDescription('This trap is issued when second power supply return to work')
fmPowerSupplyChangeConfig = NotificationType((1, 3, 6, 1, 4, 1, 22, 51) + (0,4)).setObjects(("EDB-snmp", "fmSystemPSCfg"), ("EDB-snmp", "fmSystemPSOper"))
if mibBuilder.loadTexts: fmPowerSupplyChangeConfig.setDescription('Issued when a change in the configuration of the power supply is done')
fmLUOutOfSync = NotificationType((1, 3, 6, 1, 4, 1, 22, 51) + (0,7)).setObjects(("EDB-snmp", "fmLUID"), ("EDB-snmp", "fmLUStatus"))
if mibBuilder.loadTexts: fmLUOutOfSync.setDescription('Issued when the Logic unit goes out of synchronization')
fmLUReturnToSync = NotificationType((1, 3, 6, 1, 4, 1, 22, 51) + (0,8)).setObjects(("EDB-snmp", "fmLUID"), ("EDB-snmp", "fmLUStatus"))
if mibBuilder.loadTexts: fmLUReturnToSync.setDescription('Issues as soon as the logic unit returns to synchronization')
fmLUPassToMain = NotificationType((1, 3, 6, 1, 4, 1, 22, 51) + (0,9)).setObjects(("EDB-snmp", "fmLUID"), ("EDB-snmp", "fmLUStatus"))
if mibBuilder.loadTexts: fmLUPassToMain.setDescription('Issues as soon as the logic unit pass to main link')
fmLUPassToSecond = NotificationType((1, 3, 6, 1, 4, 1, 22, 51) + (0,10)).setObjects(("EDB-snmp", "fmLUID"), ("EDB-snmp", "fmLUStatus"))
if mibBuilder.loadTexts: fmLUPassToSecond.setDescription('Issues as soon as the logic unit pass to second link')
fmLUPrimaryLinkFail = NotificationType((1, 3, 6, 1, 4, 1, 22, 51) + (0,11)).setObjects(("EDB-snmp", "fmLUID"), ("EDB-snmp", "fmLUStatus"))
if mibBuilder.loadTexts: fmLUPrimaryLinkFail.setDescription('When primary link of the logic unit fails this trap is issued')
fmLUPrimaryLinkOK = NotificationType((1, 3, 6, 1, 4, 1, 22, 51) + (0,12)).setObjects(("EDB-snmp", "fmLUID"), ("EDB-snmp", "fmLUStatus"))
if mibBuilder.loadTexts: fmLUPrimaryLinkOK.setDescription('When primary link of the logic unit fails this trap is issued')
fmLUSecondLinkFail = NotificationType((1, 3, 6, 1, 4, 1, 22, 51) + (0,13)).setObjects(("EDB-snmp", "fmLUID"), ("EDB-snmp", "fmLUStatus"))
if mibBuilder.loadTexts: fmLUSecondLinkFail.setDescription('When second link of the logic unit fails this trap is issued')
fmLUSecondLinkOK = NotificationType((1, 3, 6, 1, 4, 1, 22, 51) + (0,14)).setObjects(("EDB-snmp", "fmLUID"), ("EDB-snmp", "fmLUStatus"))
if mibBuilder.loadTexts: fmLUSecondLinkOK.setDescription('When second link of the logic unit fails this trap is issued')
fmLULLBOn = NotificationType((1, 3, 6, 1, 4, 1, 22, 51) + (0,15)).setObjects(("EDB-snmp", "fmLUID"), ("EDB-snmp", "fmLUStatus"))
if mibBuilder.loadTexts: fmLULLBOn.setDescription('When the logic unit enters LLB mode')
fmLULLBOff = NotificationType((1, 3, 6, 1, 4, 1, 22, 51) + (0,16)).setObjects(("EDB-snmp", "fmLUID"), ("EDB-snmp", "fmLUStatus"))
if mibBuilder.loadTexts: fmLULLBOff.setDescription('When the logic unit exits LLB mode')
fmLUChangeConfig = NotificationType((1, 3, 6, 1, 4, 1, 22, 51) + (0,20)).setObjects(("EDB-snmp", "fmLUID"), ("EDB-snmp", "fmLUStatus"))
if mibBuilder.loadTexts: fmLUChangeConfig.setDescription('Issues when a change in the LU configuration is done')
fmSlotTrap = NotificationType((1, 3, 6, 1, 4, 1, 22, 51) + (0,25)).setObjects(("EDB-snmp", "fmSlotIndex"), ("EDB-snmp", "fmSlotID"), ("EDB-snmp", "fmSlotStatus"), ("EDB-snmp", "fmSlotPrevStatus"))
if mibBuilder.loadTexts: fmSlotTrap.setDescription('Generated when a significant status has changed in a slot. By xoring the 2 statuses, the NMS can identify the cause of the trap.')
fmSlotChangeConfig = NotificationType((1, 3, 6, 1, 4, 1, 22, 51) + (0,26)).setObjects(("EDB-snmp", "fmSlotIndex"), ("EDB-snmp", "fmSlotID"), ("EDB-snmp", "fmSlotStatus"))
if mibBuilder.loadTexts: fmSlotChangeConfig.setDescription('Issued when the system detects changes in its slots configuration')
fmDiagGenericTrap = NotificationType((1, 3, 6, 1, 4, 1, 22, 51) + (0,30)).setObjects(("EDB-snmp", "fmDiagTrapInfo"))
if mibBuilder.loadTexts: fmDiagGenericTrap.setDescription('Generic Trap information')
mibBuilder.exportSymbols("EDB-snmp", traperm=traperm, pfmLUTrapMask=pfmLUTrapMask, pfmSystemSlipParity=pfmSystemSlipParity, fmPowerSupplyChangeConfig=fmPowerSupplyChangeConfig, fmSystemSlipIPNetMask=fmSystemSlipIPNetMask, fmSystemVersion=fmSystemVersion, fmLUSecondLinkOK=fmLUSecondLinkOK, fmSlotDescr=fmSlotDescr, fmsystemrun=fmsystemrun, fmSystemSlipIpAddr=fmSystemSlipIpAddr, rTrapAddrState=rTrapAddrState, fmLULinkSelect=fmLULinkSelect, fmLUChangeConfig=fmLUChangeConfig, fmDiagFaultReport=fmDiagFaultReport, fmSlotTable=fmSlotTable, pTrapAddrState=pTrapAddrState, fmSlotChangeConfig=fmSlotChangeConfig, fmSystemSlipStopBits=fmSystemSlipStopBits, fmlu=fmlu, pfmSystemSlipIpAddr=pfmSystemSlipIpAddr, fmSlotTrapMask=fmSlotTrapMask, fmLUDescr=fmLUDescr, fmSystemPSAdmin=fmSystemPSAdmin, enterprises=enterprises, rTrapAddrAge=rTrapAddrAge, pTrapAddrType=pTrapAddrType, fmLUOutOfSync=fmLUOutOfSync, fmPrimaryPowerSupplyOK=fmPrimaryPowerSupplyOK, pfmSystemBootMode=pfmSystemBootMode, fmLUStatus=fmLUStatus, fmslot=fmslot, pTrapAddrComm=pTrapAddrComm, fmSlotPrevStatus=fmSlotPrevStatus, private=private, rTrapAddrTbl=rTrapAddrTbl, rTrapAddrEntry=rTrapAddrEntry, fmSlotRLBSet=fmSlotRLBSet, fmSystemBootFile=fmSystemBootFile, fmDiagFaultEntry=fmDiagFaultEntry, fmSecondPowerSupplyOK=fmSecondPowerSupplyOK, fmPowerSupplyFail=fmPowerSupplyFail, fmDiagDebug=fmDiagDebug, fmSystemReset=fmSystemReset, fmdiag=fmdiag, fmDiagConfig=fmDiagConfig, pfmSystemReadCommunity=pfmSystemReadCommunity, fmSlotExpCode=fmSlotExpCode, fmSystemIPDefGway=fmSystemIPDefGway, rTrapAddrType=rTrapAddrType, fmLUSecondLinkFail=fmLUSecondLinkFail, rTrapAddrVer=rTrapAddrVer, fmSlotID=fmSlotID, fmSlotInfo=fmSlotInfo, rTrapAging=rTrapAging, fmLUID=fmLUID, fibronics=fibronics, pTrapAging=pTrapAging, fmSystemPSOper=fmSystemPSOper, trapvar=trapvar, fmSlotTrap=fmSlotTrap, fm800=fm800, fmDiagFaultIndex=fmDiagFaultIndex, fmsystemperm=fmsystemperm, fmSlotMasterClear=fmSlotMasterClear, fmSystemSlipBaudRate=fmSystemSlipBaudRate, pTrapLearning=pTrapLearning, fmSystemBootMode=fmSystemBootMode, pfmSystemWriteCommunity=pfmSystemWriteCommunity, fmSlotIndex=fmSlotIndex, trap=trap, fmSlotIpAddr=fmSlotIpAddr, fmLUPassToSecond=fmLUPassToSecond, fmsystem=fmsystem, fmLULoopBackSet=fmLULoopBackSet, fmSystemPSCfg=fmSystemPSCfg, fmSystemIPNetMask=fmSystemIPNetMask, fmSlotEntry=fmSlotEntry, pfmSlotTrapMask=pfmSlotTrapMask, traprun=traprun, pfmSystemBootFile=pfmSystemBootFile, pfmSystemIPDefGway=pfmSystemIPDefGway, fmSystemSelfTestLevel=fmSystemSelfTestLevel, fmDiagGenericTrap=fmDiagGenericTrap, fmLUPrimaryLinkOK=fmLUPrimaryLinkOK, fmDiagFaultTable=fmDiagFaultTable, pfmSystemFileServer=pfmSystemFileServer, rTrapLearning=rTrapLearning, fmSystemIpAddr=fmSystemIpAddr, pTrapAddrTbl=pTrapAddrTbl, fmSystemSlipParity=fmSystemSlipParity, pfmSystemSlipIPNetMask=pfmSystemSlipIPNetMask, fmLUPassToMain=fmLUPassToMain, fmLULLBOn=fmLULLBOn, fmLULoopBackClr=fmLULoopBackClr, pfmSystemIpAddr=pfmSystemIpAddr, pTrapAddrEntry=pTrapAddrEntry, fmLULLBOff=fmLULLBOff, rTrapAddrAddr=rTrapAddrAddr, fmSlotRLBClear=fmSlotRLBClear, fmLUTrapMask=fmLUTrapMask, fmDiagTrapInfo=fmDiagTrapInfo, rTrapAddrFlag=rTrapAddrFlag, rTrapAddrComm=rTrapAddrComm, fmLUPrimaryLinkFail=fmLUPrimaryLinkFail, pfmSystemIPNetMask=pfmSystemIPNetMask, fmSystemFileServer=fmSystemFileServer, pfmSystemSlipStopBits=pfmSystemSlipStopBits, pTrapAddrVer=pTrapAddrVer, fmSystemDownLoad=fmSystemDownLoad, fmSlotStatus=fmSlotStatus, pfmSystemSlipBaudRate=pfmSystemSlipBaudRate, fmLUReturnToSync=fmLUReturnToSync, pTrapAddrAddr=pTrapAddrAddr)
|
n1 = float(input())
n2 = float(input())
meida = ((n1*3.5)+(n2*7.5))/(3.5+7.5)
print(f"MEDIA = {meida:.5f}") |
'''
数组中查找和为target的所有组合方式
'''
res = []
def find_sort(nums, target, tmp):
l = len(nums)
if l == 1:
if nums[0] == target:
lis = sorted(nums + tmp)
if lis not in res:
res.append(lis)
return
for i in range(l):
if nums[i] > target:
continue
elif nums[i] == target:
lis = sorted([nums[i]] + tmp)
if lis not in res:
res.append(lis)
continue
else:
find_sort(nums[i + 1:], target - nums[i], tmp + [nums[i]])
if __name__ == '__main__':
find_sort([1, 3, 5, 8, 7, 4, 1, 4], 8, [])
print(res)
|
# Rotate Image
'''
You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise).
You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.
Example 1:
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [[7,4,1],[8,5,2],[9,6,3]]
Example 2:
Input: matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]]
Output: [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]]
Example 3:
Input: matrix = [[1]]
Output: [[1]]
Example 4:
Input: matrix = [[1,2],[3,4]]
Output: [[3,1],[4,2]]
Constraints:
matrix.length == n
matrix[i].length == n
1 <= n <= 20
-1000 <= matrix[i][j] <= 1000
'''
class Solution:
def rotate(self, arr: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
def transpose(n):
for i in range(n):
for j in range(i, n):
arr[i][j], arr[j][i] = arr[j][i], arr[i][j]
def reverse(n):
for i in range(n):
for j in range(n//2):
arr[i][j], arr[i][n-j-1] = arr[i][n-j-1], arr[i][j]
n = len(arr[0])
transpose(n)
reverse(n)
|
# -*- coding: utf-8 -*-
def sort_by_counting(array: list) -> list:
"""
Сортировка подсчетом.
Суть: на каждом шаге подсчитывается в какую позицию результирующего массива result необходимо записать
очередной элемент исходного массива array.
* Сохраняет порядок элементов с одинаковыми значениями
Максимальная временная сложность: О(n^2)
Средняя временная сложность: О(n^2)
Минимальная временная сложность: О(n^2)
Пространственная сложность: О(n)
(*) Алгоритм устойчивой сортировки.
:param array: исходный массив
:return array: упорядоченный исходный массив
"""
n = len(array)
result = [0] * n
for i in range(n):
# вычисляем положение элемента в рез. массиве
k = 0
for j in range(n):
if array[j] < array[i] or (array[j] == array[i] and j < i):
k += 1
# включаем очередной элемент в рез. массив
result[k] = array[i]
for i in range(n):
array[i] = result[i]
return array
|
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
if len(s) == 0:
return 0
current_length = 0
max_length = 0
idx = 0
last_dup_index = -1
count = {}
while idx < len(s):
if s[idx] not in count or count[s[idx]] < last_dup_index:
count[s[idx]] = idx
current_length += 1
max_length = max(max_length, current_length)
else:
last_dup_index = count[s[idx]]
count[s[idx]] = idx
current_length = idx - last_dup_index
idx += 1
return max_length
|
produto = float(input("Digite o valor do produto: R$"))
d = produto - produto * 0.05
print("O valor do produto é {:.2f}, mas com desconto de 5% fica {:.2f}".format(produto, d))
#valor * porcentagem / 100 (d = produto - produto * 5 /100) |
class move_avg:
def __init__(self, bufmax):
self.buf = []
self.bufmax = bufmax
def add(self, val):
self.buf.append(val)
if len(self.buf) > self.bufmax:
del self.buf[0]
def get(self):
if len(self.buf) > 0:
avg = sum(self.buf)/len(self.buf)
else:
avg = 0
return avg
|
# coding: UTF-8
print(r'''
【程序41】题目:海滩上有一堆桃子,五只猴子来分。第一只猴子把这堆桃子凭据分为五份,多了一个,这只猴子把多的一个扔入海中,拿走了一份。第二只猴子把剩下的桃子又平均分成五份,又多了一个,它同样把多的一个扔入海中,拿走了一份,第三、第四、第五只猴子都是这样做的,问海滩上原来最少有多少个桃子?
''')
|
"""уровень 1"""
# pylint: disable=R0903
class User:
"""класс User"""
|
# -*- coding: utf-8 -*-
"""
Standard values for CoastalVarExtractor.
They should not need to be changed except to include more site value mappings.
They do not require any input values.
"""
sitemap = {
'Assawoman':{'region': 'Delmarva', 'site': 'Assawoman',
'code': 'assa',
'MHW':0.34, 'MLW':-0.55,
'id_init_val':200000,
'morph_state': 12},
'Cobb':{'region': 'Delmarva', 'site': 'Cobb',
'code': 'cobb',
'MHW':0.34, 'MLW':-0.56,
'id_init_val':160000,
'morph_state': 12},
'Cedar':{'region': 'Delmarva', 'site': 'Cedar',
'code': 'cei',
'MHW':0.34, 'MLW':-0.56,
'id_init_val':180000,
'morph_state': 12},
'Smith':{'region': 'Delmarva', 'site': 'Smith',
'code': 'smi',
'MHW':0.34, 'MLW':-0.56,
'id_init_val':120000,
'morph_state': 12},
'Fisherman':{'region': 'Delmarva', 'site': 'Fisherman', # transects extended manually
'code': 'fish',
'MHW':0.34, 'MLW':-0.52,
'id_init_val':110000,
'morph_state': 12},
'Assateague':{'region': 'Delmarva', 'site': 'Assateague',
'code': 'asis',
'MHW':0.34, 'MLW':-0.13,
'id_init_val':210000,
'morph_state': [12, 13]},
'ParkerRiver':{'region': 'Massachusetts', 'site': 'ParkerRiver',
'code': 'pr',
'MHW':1.22, 'MLW':-1.37,
'id_init_val':None,
'morph_state': 24},
'Monomoy':{'region': 'Massachusetts', 'site': 'Monomoy',
'code': 'mon',
'MHW':0.39, 'MLW':-0.95,
'id_init_val':None,
'morph_state': 22},
'CoastGuard':{'region': 'Massachusetts', 'site': 'CoastGuard',
'code': 'cg',
'MHW':0.98, 'MLW':-1.1,
'id_init_val':70000,
'morph_state': 22},
'Forsythe':{'region': 'NewJersey', 'site': 'Forsythe',
'code': 'ebf',
'MHW':0.43, 'MLW':-0.61,
'id_init_val':30000,
'morph_state': 15},
'FireIsland':{'region': 'NewYork', 'site': 'FireIsland',
'code': 'fiis',
'MHW':0.46, 'MLW':-1.01,
'id_init_val':10000,
'morph_state': 16},
'Rockaway':{'region': 'NewYork', 'site': 'Rockaway', # transects extended manually
'code': 'rock',
'MHW':0.46, 'MLW':-0.71,
'id_init_val':20000,
'morph_state': 16},
'CapeLookout':{'region': 'NorthCarolina', 'site': 'CapeLookout', # transects extended manually
'code': 'calo',
'MHW':0.26, 'MLW':-0.5,
'id_init_val':40000,
'morph_state': 11},
'Parramore':{'region': 'Delmarva', 'site': 'Parramore',
'code': 'pari',
'MHW':0.34, 'MLW':-0.56,
'id_init_val':170000,
'morph_state': 12},
'RhodeIsland':{'region': 'RhodeIsland', 'site': 'RhodeIsland',
'code': 'ri',
'MHW':0.29, 'MLW':-0.42,
'id_init_val':50000,
'morph_state': 17},
# 'RhodeIsland_West1':{'region': 'RhodeIsland', 'site': 'RhodeIsland',
# 'code': 'riw1',
# 'MHW':0.29, 'MLW':-0.,
# 'id_init_val':50000,
# 'morph_state': 17},
# 'RhodeIsland_West2':{'region': 'RhodeIsland', 'site': 'RhodeIsland',
# 'code': 'riw2',
# 'MHW':0.22, 'MLW':-0.,
# 'id_init_val':50000,
# 'morph_state': 17}
# 'RhodeIsland_East':{'region': 'RhodeIsland', 'site': 'RhodeIsland',
# 'code': 'riec',
# 'MHW':0.36, 'MLW':-0.,
# 'id_init_val':50000,
# 'morph_state': 18}
}
########### Default Values ##########################
tID_fld = "sort_ID" # name of transect ID field
pID_fld = "SplitSort" # name of point ID field
extendlength = 3000 # distance (m) by which to extend transects
fill = -99999 # Nulls will be replaced with this fill value
cell_size = 5 # Cell size for raster outputs
pt2trans_disttolerance = 25 # Maximum distance between transect and point for assigning values; originally 10 m
########### Field names ##########################
trans_flds = ['sort_ID','TRANSORDER', 'TRANSECTID','Azimuth',
'LRR', 'SL_x', 'SL_y', 'Bslope',
'DL_x', 'DL_y', 'DL_z', 'DL_zMHW', 'DL_snapX','DL_snapY',
'DH_x', 'DH_y', 'DH_z', 'DH_zMHW', 'DH_snapX','DH_snapY',
'Arm_x', 'Arm_y', 'Arm_z', 'Arm_zMHW',
'DistDH', 'DistDL', 'DistArm',
'Dist2Inlet', 'WidthPart', 'WidthLand', 'WidthFull',
'uBW', 'uBH', 'ub_feat', 'mean_Zmhw', 'max_Zmhw']
pt_flds = ['seg_x', 'seg_y', 'ptZ', 'ptSlp', 'Dist_Seg','SplitSort',
'Dist_MHWbay', 'DistSegDH', 'DistSegDL', 'DistSegArm', 'ptZmhw', 'sort_ID']
extra_fields = ["StartX", "StartY", "ORIG_FID", "Autogen", "ProcTime",
"SHAPE_Leng", "OBJECTID_1", "Shape_Length", "EndX", "EndY",
"BaselineID", "OBJECTID", "ORIG_OID", "TRANSORDER_1",
'LR2', 'LSE', 'LCI90']
extra_fields += [x.upper() for x in extra_fields]
sorted_pt_flds = ['SplitSort', 'seg_x', 'seg_y',
'Dist_Seg', 'Dist_MHWbay', 'DistSegDH', 'DistSegDL', 'DistSegArm',
'ptZ', 'ptSlp', 'ptZmhw',
'GeoSet', 'SubType', 'VegDens', 'VegType',
'sort_ID','TRANSORDER', 'TRANSECTID', 'DD_ID', 'Azimuth',
'LRR', 'SL_x', 'SL_y', 'Bslope',
'DL_x', 'DL_y', 'DL_z', 'DL_zmhw', 'DL_snapX','DL_snapY',
'DH_x', 'DH_y', 'DH_z', 'DH_zmhw', 'DH_snapX','DH_snapY',
'Arm_x', 'Arm_y', 'Arm_z', 'Arm_zmhw',
'DistDH', 'DistDL', 'DistArm',
'Dist2Inlet', 'WidthPart', 'WidthLand', 'WidthFull',
'uBW', 'uBH', 'ub_feat', 'mean_Zmhw', 'max_Zmhw',
'Construction', 'Development', 'Nourishment']
|
# -*- coding: utf-8; -*-
class ConsulSSLError(Exception):
"""
Error raised when https is defined in --host argument or
environmental variable and ssl certificates are not configured
or defined
"""
def __init__(self, msg):
self.msg = "https scheme defined without any ssl certificates provided"
def __str__(self):
return self.msg
|
TEMPLATES = {
"multilingual-record-dumper": "templates/invenio_record_dumper_multilingual.py.jinja2",
"record-multilingual": "templates/invenio_record_multilingual.py.jinja2",
"subschema-multilingual": "templates/invenio_schema_multilingual.py.jinja2",
"multi-search": "templates/invenio_record_search_multilingual.py.jinja2",
"subschema-i18n": "templates/invenio_schema_i18n.py.jinja2",
} |
# Getting input and converting to int
student_heights = input("Input a list of student heights ").split()
for n in range(0, len(student_heights)):
student_heights[n] = int(student_heights[n])
# Varibales to store sum and total and count
sum_of_heights = 0
total_height = 0
count_of_students = 0 # This is to find the number of elements in a list
# Logic for calculating average student height
for student in student_heights:
sum_of_heights += student
count_of_students += 1
total_height = sum_of_heights/count_of_students
# Rounding the total_height
print(round(total_height)) |
N, X = input().split()
A = list(map(int, input().split()))
B = []
for i in range(0, int(N)) :
if(A[i] < int(X)) :
print(A[i], end=" ") |
'''
A string S of lowercase letters is given. We want to partition this string into as many parts as possible
so that each letter appears in at most one part, and return a list of integers representing the size of these parts.
'''
class Solution:
def partitionLabels(self, S):
"""
:type S: str
:rtype: List[int]
"""
last={}
for i, s in enumerate(S):
last[s]=i
print(last)
result=[]
start_index=0
end_index=0
for i, s in enumerate(S):
# this is how to dynamically assign the end index for each sub part
end_index=max(last[s], end_index)
if end_index==i:
result.append(end_index-start_index+1)
start_index=i+1
return result
if __name__=='__main__':
solution=Solution()
test_case1="ababcbacadefegdehijhklij"
print(solution.partitionLabels(test_case1)) |
def main():
print("Welcome to the casino!")
print("Rules are simple, guess a number, if you get it right you win 100000 dollars~")
print("Else you loose 5 dollars")
while True:
try:
number = int(input("Choose a number: "))
except ValueError:
print("INVALID NUMBER!!!")
else:
break
if chooseNum(number) == number:
while True:
print("NOT POSSIVLE!!!!")
else:
print("You loose!")
def chooseNum(num):
return num + 1
if __name__ == "__main__":
main() |
# -*- coding: utf-8 -*-
class Config(object):
"""Configure me so examples work
Use me like this:
mysql.connector.Connect(**Config.dbinfo())
"""
HOST = 'localhost'
DATABASE = 'test'
USER = ''
PASSWORD = ''
PORT = 3306
CHARSET = 'utf8'
UNICODE = True
WARNINGS = True
@classmethod
def dbinfo(cls):
return {
'host': cls.HOST,
'port': cls.PORT,
'database': cls.DATABASE,
'user': cls.USER,
'password': cls.PASSWORD,
'charset': cls.CHARSET,
'use_unicode': cls.UNICODE,
'get_warnings': cls.WARNINGS,
}
|
class VectorIndex:
@property
def files(self):
return []
def save(self):
pass
def load(self):
pass
def build(self):
pass
def search(self):
pass
def search_index(self):
pass
def add(self, vector):
pass
def add_bulk(self, vectors):
pass
def set_bulk(self, indices, vectors):
pass
|
d = int(input('Por quantos dias o carro foi alugado? '))
k = float(input('Quantos km foram rodados? '))
v = 60 * d + 0.15 * k
print('O valor a ser pago é' , v)
|
class CallbackSettings(object):
@property
def JAVASCRIPT(self):
return super().JAVASCRIPT + (
'callback/modal.js',
)
@property
def INSTALLED_APPS(self):
apps = super().INSTALLED_APPS + [
'callback'
]
if not 'captcha' in apps:
apps += ['captcha']
return apps
default = CallbackSettings
|
#Duplicates of ReadyResult constants - keeps this class clean of imported modules leaking into the sandbox
NOT_READY = 'NotReady'
READY = 'Ready'
FAILED = 'Failed'
class ReadyResultHolder:
def __init__(self):
self.__readiness = READY
self.__reason = None
def ready(self):
self.__readiness = READY
return self
def not_ready(self):
self.__readiness = NOT_READY
return self
def notReady(self):
return self.not_ready()
def failed(self, reason):
self.__readiness = FAILED
self.__reason = str(reason)
return self
def is_ready(self):
return self.__readiness == READY
def has_failed(self):
return (self.__readiness == FAILED), self.__reason
def __str__(self):
return f'{self.__class__.__name__}(readiness: {self.__readiness}, reason: {self.__reason})'
def __repr__(self):
return f'{self.__class__.__name__}(readiness: {self.__readiness!r}, reason: {self.__reason!r}'
|
##############################################################################
# Copyright (c) 2017 ZTE Corp
# feng.xiaowei@zte.com.cn
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Apache License, Version 2.0
# which accompanies this distribution, and is available at
# http://www.apache.org/licenses/LICENSE-2.0
##############################################################################
not_found_base = 'Could Not Found'
exist_base = 'Already Exists'
def key_error(key):
return "KeyError: '{}'".format(key)
def no_file_uploaded():
return "Please upload a file."
def no_body():
return 'No Body'
def not_found(key, value):
return '{} {} [{}]'.format(not_found_base, key, value)
def missing(name):
return '{} Missing'.format(name)
def exist(key, value):
return '{} [{}] {}'.format(key, value, exist_base)
def bad_format(error):
return 'Bad Format [{}]'.format(error)
def unauthorized():
return 'No Authentication Header'
def invalid_token():
return 'Invalid Token'
def no_update():
return 'Nothing to update'
def must_int(name):
return '{} must be int'.format(name)
def no_auth():
return 'No permission to operate. Please ask Administrator for details.'
def invalid_credentials():
return 'Invalid UserName or Password'
def req_username():
return 'UserName is Required'
def req_password():
return 'Password is Required'
|
n = int(input())
pieces = {}
for _ in range(n):
piece, composer, key = input().split('|')
pieces[piece] = [composer, key]
while True:
line = input()
if line == 'Stop':
break
args = line.split('|')
command = args[0]
piece = args[1]
if command == 'Add':
composer = args[2]
key = args[3]
if piece in pieces:
print(f'{piece} is already in the collection!')
else:
pieces[piece] = [composer, key]
print(f'{piece} by {composer} in {key} added to the collection!')
elif command == 'Remove':
if piece not in pieces:
print(f'Invalid operation! {piece} does not exist in the collection.')
continue
pieces.pop(piece)
print(f'Successfully removed {piece}!')
elif command == 'ChangeKey':
new_key = args[2]
if piece not in pieces:
print(f'Invalid operation! {piece} does not exist in the collection.')
continue
value = pieces.pop(piece)
new_value = [value[0], new_key]
pieces[piece] = new_value
print(f'Changed the key of {piece} to {new_key}!')
sorted_pieces = dict(sorted(pieces.items(), key=lambda x: (x[0], x[1][0])))
for k, v in sorted_pieces.items():
print(f'{k} -> Composer: {v[0]}, Key: {v[1]}')
|
def map_llc_result_to_dictionary_list(land_charge_result):
"""Produce a list of jsonable dictionaries of an alchemy result set
"""
if not isinstance(land_charge_result, list):
return list(map(lambda land_charge: land_charge.to_dict(),
[land_charge_result]))
else:
return list(map(lambda land_charge: land_charge.to_dict(),
land_charge_result))
def map_llc_display_result_to_dictionary_list(land_charge_result):
"""Produce a list of jsonable dictionaries of an alchemy result set
"""
if not isinstance(land_charge_result, list):
return list(map(lambda land_charge: land_charge.to_display_dict(),
[land_charge_result]))
else:
return list(map(lambda land_charge: land_charge.to_display_dict(),
land_charge_result))
def map_llc_history_result_to_dictionary_list(land_charge_history):
"""Produce a list of jsonable dictionaries of an alchemy result set"""
if not isinstance(land_charge_history, list):
return list(map(lambda land_charge: land_charge.to_dict(),
[land_charge_history]))
else:
return list(map(lambda land_charge: land_charge.to_dict(),
land_charge_history))
|
DEBUG = True
PLUGINS = ["fastack_sqlmodel", "fastack_migrate"]
COMMANDS = []
DB_USER = "fastack_user"
DB_PASSWORD = "fastack_pass"
DB_HOST = "db"
DB_PORT = 5432
DB_NAME = "fastack_db"
SQLALCHEMY_DATABASE_URI = (
f"postgresql+psycopg2://{DB_USER}:{DB_PASSWORD}@{DB_HOST}:{DB_PORT}/{DB_NAME}"
)
SQLALCHEMY_OPTIONS = {}
|
"""
1. Clarification
2. Possible solutions
- Binary search I
- Binary search II
- Binary search III
3. Coding
4. Tests
"""
# T=O(lgn), S=O(1)
class Solution:
def search(self, nums: List[int], target: int) -> int:
if not nums: return -1
left, right = 0, len(nums) - 1
while left <= right:
pivot = left + (right - left) // 2
if nums[pivot] == target:
return pivot
elif target < nums[pivot]:
right = pivot - 1
else:
left = pivot + 1
return -1
# T=O(lgn), S=O(1)
class Solution:
def search(self, nums: List[int], target: int) -> int:
if not nums: return -1
left, right = 0, len(nums) - 1
while left < right:
mid = (left + right) // 2
if nums[mid] == target:
return mid
elif nums[mid] < target:
left = mid + 1
else:
right = mid
if nums[left] == target:
return left
return -1
# T=O(lgn), S=O(1)
class Solution:
def search(self, nums: List[int], target: int) -> int:
if not nums: return -1
left, right = 0, len(nums) - 1
while left + 1 < right:
mid = (left + right) // 2
if nums[mid] == target:
return mid
elif nums[mid] < target:
left = mid
else:
right = mid
if nums[left] == target: return left
if nums[right] == target: return right
return -1
|
a = input()
p = input()
if p in a + '*':
print("S")
else:
print("N")
|
'''
All python scripts are modules and collection modules are package
pip is used to install packages
'''
def Demo():
a = int(input('Enter a 1st number'))
b = int(input('Enter 2nd number'))
s = 0
s = a + b
return s
print(Demo())
print("I will run")
print(f'{__name__}')
def Solve():
print("Python is best")
if __name__ == "__main__": #...this cannot be imported as it is running from main file
Solve() #...__name__ == main_module while importing
#...__name__ == "__main__" while running directly from main file |
# https://www.python-course.eu/graphs_python.php
class Graph(object):
def __init__(self, vertices):
""" initializes a complete graph object """
graph_dict = {}
for node in vertices:
graph_dict[node] = []
for vertex in vertices:
if node != vertex:
graph_dict[node].append(vertex)
self._graph_dict = graph_dict
def edges(self, vertice):
""" returns a list of all the edges of a vertice"""
return self._graph_dict[vertice]
def all_vertices(self):
""" returns the vertices of a graph as a set """
return set(self._graph_dict.keys())
def all_edges(self):
""" returns the edges of a graph """
return self.__generate_edges()
def add_vertex(self, vertex):
""" If the vertex "vertex" is not in
self._graph_dict, a key "vertex" with an empty
list as a value is added to the dictionary.
Otherwise nothing has to be done.
"""
if vertex not in self._graph_dict:
self._graph_dict[vertex] = []
def add_edge(self, edge):
""" assumes that edge is of type set, tuple or list;
between two vertices can be multiple edges!
"""
edge = set(edge)
vertex1, vertex2 = tuple(edge)
for x, y in [(vertex1, vertex2), (vertex2, vertex1)]:
if x in self._graph_dict:
self._graph_dict[x].add(y)
else:
self._graph_dict[x] = [y]
def __generate_edges(self):
""" A static method generating the edges of the
graph "graph". Edges are represented as sets
with one (a loop back to the vertex) or two
vertices
"""
edges = []
for vertex in self._graph_dict:
for neighbour in self._graph_dict[vertex]:
if {neighbour, vertex} not in edges:
edges.append({vertex, neighbour})
return edges
def find_all_paths(self, start_vertex, end_vertex, path=[]):
graph = self._graph_dict
path = path + [start_vertex]
if start_vertex == end_vertex:
return [path]
if start_vertex not in graph:
return []
paths = []
for vertex in graph[start_vertex]:
if vertex not in path:
extended_paths = self.find_all_paths(vertex, end_vertex, path)
for p in extended_paths:
paths.append(p)
return paths
def __iter__(self):
self._iter_obj = iter(self._graph_dict)
return self._iter_obj
def __next__(self):
""" allows us to iterate over the vertices """
return next(self._iter_obj)
def __str__(self):
res = "vertices: "
for k in self._graph_dict:
res += str(k) + " "
res += "\nedges: "
for edge in self.__generate_edges():
res += str(edge) + " "
return res |
#!/usr/bin/env python3
def solution(array):
"""
Returns the maximal sum of a double slice.
Double Slice is a triplet (X, Y, Z), such that 0 ≤ X < Y < Z < N
and its sum is the sum of the elements between array[X+1] and array[Z-1] minus array[Y]
"""
n = len(array)
max_ending = [0] * n
max_starting = [0] * n
# finds the sums of the left and the right side of the double slice, respectively
for i in range(1, n - 1):
max_ending[i] = max(0, max_ending[i-1] + array[i])
max_starting[n - 1 - i] = max(0, max_starting[n - i] + array[n - 1 - i])
# combines the possible sums
result = 0
for i in range(1, n - 1):
result = max(result, max_ending[i-1] + max_starting[i+1])
return result
|
WALL = '#'
PASSABLE = '.'
class SquareGrid:
def __init__(self, width, height):
self.width = width
self.height = height
self.walls = set()
def in_bounds(self, id):
(x, y) = id
return 0 <= x < self.width and 0 <= y < self.height
def cost(self, from_node, to_node):
if from_node in self.walls or to_node in self.walls:
return float('inf')
else:
return 1
def neighbors(self, id):
(x, y) = id
results = [(x + 1, y), (x, y - 1), (x - 1, y), (x, y + 1)]
if (x + y) % 2 == 0: results.reverse() # aesthetics
results = filter(self.in_bounds, results)
return list(results)
def observe(self, position, obs_range=2):
(px, py) = position
nodes = [(x, y) for x in range(px - obs_range, px + obs_range + 1)
for y in range(py - obs_range, py + obs_range + 1)
if self.in_bounds((x, y))]
return {node: WALL if node in self.walls else PASSABLE for node in nodes}
class AgentViewGrid(SquareGrid):
def new_walls(self, observation):
walls_in_obs = {node for node, nodetype in observation.items()
if nodetype == WALL}
return walls_in_obs - self.walls
def update_walls(self, new_walls):
self.walls.update(new_walls)
|
s = ""
for x in range(33,127): # <33; 126>
s += chr(x)
print(s)
|
# split join enumerate
# string = 'Uma frase qualquer, uma frase bem bonita!'
# lista = string.split(' ')
# lista2 = string.split(',')
# string2 = '-'.join(lista)
lista = ['João', 'Pedro', 'Maria']
# for indice, valor in enumerate(lista):
# print(indice, valor)
#enumerate faz isso
lista = [
[0,'João'],
[1,'Pedro'],
[2,'Maria']
]
for indice, nome in lista:
print(indice, nome)
|
class RadioButtonFsm:
def __init__(self, title, position, command=None):
self.title = title
self.command = command
self.position = position
|
# Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
#
# An input string is valid if:
#
# Open brackets must be closed by the same type of brackets.
# Open brackets must be closed in the correct order.
# Note that an empty string is also considered valid.
#
# Example 1:
#
# Input: "()"
# Output: true
# Example 2:
#
# Input: "()[]{}"
# Output: true
# Example 3:
#
# Input: "(]"
# Output: false
# Example 4:
#
# Input: "([)]"
# Output: false
# Example 5:
#
# Input: "{[]}"
# Output: true
def isValid(s):
stack = []
for c in s:
if c == "(":
stack.append("(")
if c == ")":
if len(stack) == 0:
return False
if stack[-1] != "(":
return False
else:
stack.pop()
if c == "[":
stack.append("[")
if c == "]":
if len(stack) == 0:
return False
if stack[-1] != "[":
return False
else:
stack.pop()
if c == "{":
stack.append("{")
if c == "}":
if len(stack) == 0:
return False
if stack[-1] != "{":
return False
else:
stack.pop()
if len(stack) > 0:
return False
else:
return True
if __name__ == "__main__":
ex1 = "()"
ex2 = "()[]{}"
ex3 = "(]"
ex4 = "([)]"
ex5 = "{[]}"
print(ex1 + " is " + str(isValid(ex1)))
print(ex2 + " is " + str(isValid(ex2)))
print(ex3 + " is " + str(isValid(ex3)))
print(ex4 + " is " + str(isValid(ex4)))
print(ex5 + " is " + str(isValid(ex5)))
|
def calculadora(num1, num2):
operacao = input("Digite o sinal da operação desejada ( + - * / ): " )
if operacao == "+":
return num1 + num2
elif operacao == "-":
return num1 - num2
elif operacao == "*":
return num1 * num2
elif operacao == "/":
return num1 / num2
else:
return "NÃO ENTENDI !!!"
print(calculadora(float(input("Digite um número: ")), float(input("Digite um número: ")))) |
price = 24
item = 'banana'
print('The %s costs %d cents.' % (item, price))
print('The %+10s costs %5.2f cents.' % (item, price))
print('The %+10s costs %10.2f cents.' % (item, price))
itemdict = {'item': 'banana', 'cost': 24}
print('The %(item)s costs %(cost)7.1f cents.' % itemdict)
"""
The banana costs 24 cents.
The banana costs 24.00 cents.
The banana costs 24.00 cents.
The banana costs 24.0 cents.
"""
|
# Scrapy settings for tutorial project
#
# For simplicity, this file contains only the most important settings by
# default. All the other settings are documented here:
#
# http://doc.scrapy.org/topics/settings.html
#
BOT_NAME = 'tutorial'
SPIDER_MODULES = ['tutorial.spiders']
NEWSPIDER_MODULE = 'tutorial.spiders'
DOWNLOAD_DELAY = 2
#LOG_LEVEL = 'INFO'
COOKIES_ENABLED = False
RETRY_ENABLED = False
DOWNLOAD_TIMEOUT = 10
ITEM_PIPELINES = [
'tutorial.pipelines.SqlitePipeline',
]
DUPEFILTER_CLASS = 'tutorial.dupefilter.SqliteDupeFilter' |
"""
问题描述:构造一个特殊的栈,要求
1)使之pop()、push()和getMin() (求最小值) 的操作的时间复杂度都为O(1)
2)可以使用现成的栈类型
思路:使用两个栈,一个栈保存所有数据,一个栈保存最小数据集
"""
class MyStack:
def __init__(self):
self.datastack = list()
self.minstack = list()
def push(self, value):
length = len(self.minstack)
if length == 0:
self.minstack.append(value)
else:
if value <= self.minstack[-1]:
self.minstack.append(value)
self.datastack.append(value)
def pop(self):
if len(self.datastack) == 0:
raise RuntimeError('the stack is empty')
i = self.datastack.pop()
if i == self.get_min():
self.minstack.pop()
return i
def get_min(self):
if len(self.datastack) == 0:
raise RuntimeError('the stack is empty')
return self.minstack[-1]
if __name__ == '__main__':
stack = MyStack()
stack.push(3)
print(stack.get_min())
stack.push(4)
print(stack.get_min())
stack.push(1)
print(stack.get_min())
stack.pop()
print(stack.get_min()) |
class Solution:
def maxDepth(self, root: TreeNode) -> int:
if (root is None):
return 0
if (root.left is None and root.right is None):
return 1
left = self.maxDepth(root.left)
right = self.maxDepth(root.right)
return max(left, right) + 1 |
red_flags = []
class RedFlagsModel():
def __init__(self):
self.db = red_flags
def save(self, data):
id = len(red_flags) + 1
payload = {
"id": id,
"title": data['title'],
"description": data['description'],
"location": data['location'],
"type": data['type']
}
self.db.append(payload)
return self.db
def get_flags(self):
return self.db
def getSingleFlag(self, flag_id):
for flag in red_flags:
if flag['id'] == flag_id:
return flag
def deleteFlag(self, flag_id):
for flag in red_flags:
if flag['id'] == flag_id:
return red_flags.remove(flag)
def updateFlag(self, flag_id, data):
for flag in red_flags:
if flag['id'] == flag_id:
flag['title'] = data['title']
flag['description'] = data['description']
flag['location'] = data['location']
flag['type'] = data['type']
return flag
|
cumprimentos = ["Olá", "oi", "i aê!", "bom dia"]
respostas = [ "Estou às suas ordens","Pode falar,estou te ouvindo", "quais são suas ordens Mestre"]
dispensas = [ 'desligar', 'sair', 'tchau kali', 'tchau cali', 'dispensada', 'encerrar'] |
#------------------------------------------------------------------------------#
# Copyright 2018 Gabriele Valentini. All rights reserved. Use of this source #
# code is governed by a MIT license that can be found in the LICENSE file. #
#------------------------------------------------------------------------------#
__cli__ = 'betrack'
__version__ = '0.1.1'
|
"""
Expressões Lambda
- Conhecidas por expressões lambdas, são funções sem nome ou seja funções anônimas.
# Função em python
def soma(a,b):
return a+b
- Geralmente são usadas para ordenações e filtragem de dados.
"""
# Sintaxe
expre = lambda x: (4 * x) + (5/x)
print(expre(3))
# A função lambda só funciona quando é anexada a uma variável. Porém não é a melhor forma.
# Forma correta
pessoas = ['Élissa dos Santos', 'Matheus Thuron', 'Rômulo Rodrigues de Oliveira',
'Rodrigo Bijani']
print(pessoas)
pessoas.sort(key=lambda sobrenome: sobrenome.split(' ')[-1].lower())
print(pessoas)
def equacao_quadratica(a, b, c):
return lambda x: a * x ** 2 + b * x + c
print(equacao_quadratica(2, 7, -2)(2))
|
r"""
Git errors
This module provides subclasses of ``RuntimeError`` to indicate error
conditions when calling git.
AUTHORS:
- Julian Rueth: initial version
"""
#*****************************************************************************
# Copyright (C) 2013 Julian Rueth <julian.rueth@fsfe.org>
#
# Distributed under the terms of the GNU General Public License (GPL)
# as published by the Free Software Foundation; either version 2 of
# the License, or (at your option) any later version.
# http://www.gnu.org/licenses/
#*****************************************************************************
class GitError(RuntimeError):
r"""
Error raised when git exits with a non-zero exit code.
EXAMPLES::
sage: from sage.dev.git_error import GitError
sage: raise GitError(128, "git foo", None, None)
Traceback (most recent call last):
...
GitError: git returned with non-zero exit code (128) for "git foo".
"""
def __init__(self, exit_code, cmd, stdout, stderr, explain=None, advice=None):
r"""
Initialization.
TESTS::
sage: from sage.dev.git_error import GitError
sage: type(GitError(128, "git foo", None, None))
<class 'sage.dev.git_error.GitError'>
"""
self.exit_code = exit_code
self.cmd = cmd
self.stdout = stdout
self.stderr = stderr
self.explain = explain
self.advice = advice
msg = ['git returned with non-zero exit code ({0}) for "{1}".'.format(exit_code, cmd)]
if stdout:
msg.append("output to stdout:" + "\n".join( " " + l for l in stdout.splitlines() ))
if stderr:
msg.append("output to stderr:" + "\n".join( " " + l for l in stderr.splitlines() ))
RuntimeError.__init__(self, "\n".join(msg))
class DetachedHeadError(RuntimeError):
r"""
Error raised when a git command can not be executed because the repository
is in a detached HEAD state.
EXAMPLES::
sage: from sage.dev.git_error import DetachedHeadError
sage: raise DetachedHeadError()
Traceback (most recent call last):
...
DetachedHeadError: unexpectedly, git is in a detached HEAD state
"""
def __init__(self):
r"""
Initialization.
TESTS::
sage: from sage.dev.git_error import DetachedHeadError
sage: type(DetachedHeadError())
<class 'sage.dev.git_error.DetachedHeadError'>
"""
RuntimeError.__init__(self, "unexpectedly, git is in a detached HEAD state")
class InvalidStateError(RuntimeError):
r"""
Error raised when a git command can not be executed because the repository
is not in a clean state.
EXAMPLES::
sage: from sage.dev.git_error import InvalidStateError
sage: raise InvalidStateError()
Traceback (most recent call last):
...
InvalidStateError: unexpectedly, git is in an unclean state
"""
def __init__(self):
r"""
Initialization.
TESTS::
sage: from sage.dev.git_error import InvalidStateError
sage: type(InvalidStateError())
<class 'sage.dev.git_error.InvalidStateError'>
"""
RuntimeError.__init__(self, "unexpectedly, git is in an unclean state")
|
class Solution(object):
memo = {0: [], 1: [TreeNode(0)]}
def allPossibleFBT(self, N):
if N not in Solution.memo:
ans = []
for x in xrange(N):
y = N - 1 - x
for left in self.allPossibleFBT(x):
for right in self.allPossibleFBT(y):
bns = TreeNode(0)
bns.left = left
bns.right = right
ans.append(bns)
Solution.memo[N] = ans
return Solution.memo[N]
|
__all__ = ['cohort',
'daterange',
'dimension',
'metric',
'order',
'pivot',
'report_request',
'segment']
|
""" elstruct.writer._qchem5 parameters
"""
OPTION_EVAL_DCT = {
}
|
word = input("Give me a word: ")
wrong = True
while wrong:
if word == "banana":
wrong = False
print("END GAME")
else:
print("WRONG")
word = input("Give me a word: ") |
while True:
try:
line = input().strip().split(' ')
except EOFError:
break
winner = 3
for i in range(3):
if line[i] == 'pedra' and line[(i +1) % 3] == 'tesoura' and line[(i +1) % 3] == line[(i + 2) % 3]:
winner = i
break
elif line[i] == 'papel' and line[(i +1) % 3] == 'pedra' and line[(i +1) % 3] == line[(i + 2) % 3]:
winner = i
break
elif line[i] == 'tesoura' and line[(i +1) % 3] == 'papel' and line[(i +1) % 3] == line[(i + 2) % 3]:
winner = i
break
if winner == 0:
print("Os atributos dos monstros vao ser inteligencia, sabedoria...")
elif winner == 1:
print("Iron Maiden's gonna get you, no matter how far!")
elif winner == 2:
print("Urano perdeu algo muito precioso...")
else:
print("Putz vei, o Leo ta demorando muito pra jogar...")
|
# Solution A:
class Solution:
def reverse(self, x):
if -10 < x < 10:
return x
str_ = str(x)
if str_[0] != '-':
str_ = str_[::-1]
res = int(str_)
else:
str_ = str_[:0:-1]
res = int(str_)
res = -res
return res if -2 ** 31 < res < 2 ** 31 - 1 else 0
|
nodes = {}
node_stats = {}
buckets_summary = {}
stats_summary = {}
bucket_info = {}
buckets = {}
stats = {
"minute" : {
'disk_write_queue' : {},
'cmd_get' : {},
'cmd_set' : {},
'delete_hits' : {},
'curr_items' : {},
'vb_replica_curr_items' : {},
'curr_connections' : {},
'vb_active_queue_drain' : {},
'vb_replica_queue_drain' : {},
'disk_write_queue' : {},
},
"hour" : {
'disk_write_queue' : {},
'ep_cache_miss_rate' : {},
'ep_tap_total_total_backlog_size' : { },
'ep_oom_errors' : {},
'ep_tmp_oom_errors' : {},
'vb_active_num' : {},
'vb_replica_num' : {},
"mem_used" : {},
},
"day" : {
'curr_items' : {},
},
} |
n = int(input())
a = list(map(int,input().split()))
i = 0
money=0
while i<n-1:
while i<n-1 and a[i]>=a[i+1]:
i+=1
if i==n-1:
break
buy_at=i
i+=1
while i<n and a[i]>=a[i-1]:
i+=1
sell_at=i-1
money+=a[sell_at]-a[buy_at]
print(money) |
#
# PySNMP MIB module HUAWEI-NAP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HUAWEI-NAP-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:47:27 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, ValueSizeConstraint, ValueRangeConstraint, ConstraintsUnion, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ValueSizeConstraint", "ValueRangeConstraint", "ConstraintsUnion", "ConstraintsIntersection")
hwDatacomm, = mibBuilder.importSymbols("HUAWEI-MIB", "hwDatacomm")
ObjectGroup, ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ObjectGroup", "ModuleCompliance", "NotificationGroup")
TimeTicks, IpAddress, TextualConvention, Gauge32, ModuleIdentity, ObjectIdentity, Counter32, iso, NotificationType, Bits, MibScalar, MibTable, MibTableRow, MibTableColumn, MibIdentifier, Counter64, Integer32, Unsigned32 = mibBuilder.importSymbols("SNMPv2-SMI", "TimeTicks", "IpAddress", "TextualConvention", "Gauge32", "ModuleIdentity", "ObjectIdentity", "Counter32", "iso", "NotificationType", "Bits", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "MibIdentifier", "Counter64", "Integer32", "Unsigned32")
RowStatus, DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "RowStatus", "DisplayString", "TextualConvention")
hwNap = ModuleIdentity((1, 3, 6, 1, 4, 1, 2011, 5, 25, 206))
hwNap.setRevisions(('2009-03-17 10:27',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts: hwNap.setRevisionsDescriptions(('The initial revision of this MIB module .',))
if mibBuilder.loadTexts: hwNap.setLastUpdated('200903171027Z')
if mibBuilder.loadTexts: hwNap.setOrganization('Huawei Technologies Co.,Ltd.')
if mibBuilder.loadTexts: hwNap.setContactInfo('VRP Team Huawei Technologies Co.,Ltd. Huawei Bld.,NO.3 Xinxi Rd., Shang-Di Information Industry Base, Hai-Dian District Beijing P.R. China http://www.huawei.com Zip:100085 ')
if mibBuilder.loadTexts: hwNap.setDescription('The MIB module for nap between host and netmanager.')
class DateAndTime(TextualConvention, OctetString):
description = "A date-time specification. field octets contents range ----- ------ -------- ----- 1 1-2 year* 0..65536 2 3 month 1..12 3 4 day 1..31 4 5 hour 0..23 5 6 minutes 0..59 6 7 seconds 0..60 (use 60 for leap-second) 7 8 deci-seconds 0..9 8 9 direction from UTC '+' / '-' 9 10 hours from UTC* 0..13 10 11 minutes from UTC 0..59 * Notes: - the value of year is in network-byte order - daylight saving time in New Zealand is +13 For example, Tuesday May 26, 1992 at 1:30:15 PM EDT would be displayed as: 1992-5-26,13:30:15.0,-4:0 Note that if only local time is known, then timezone information (fields 8-10) is not present."
status = 'current'
displayHint = '2d-1d-1d,1d:1d:1d.1d,1a1d:1d'
subtypeSpec = OctetString.subtypeSpec + ConstraintsUnion(ValueSizeConstraint(8, 8), ValueSizeConstraint(11, 11), )
hwNapScalarObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 2011, 5, 25, 206, 1))
hwNapTableObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 2011, 5, 25, 206, 2))
hwNapNotifications = MibIdentifier((1, 3, 6, 1, 4, 1, 2011, 5, 25, 206, 3))
hwNapNeighborNum = MibScalar((1, 3, 6, 1, 4, 1, 2011, 5, 25, 206, 1, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hwNapNeighborNum.setStatus('current')
if mibBuilder.loadTexts: hwNapNeighborNum.setDescription('current configed nap neighbor num.')
hwNapNeighborTable = MibTable((1, 3, 6, 1, 4, 1, 2011, 5, 25, 206, 2, 1), )
if mibBuilder.loadTexts: hwNapNeighborTable.setStatus('current')
if mibBuilder.loadTexts: hwNapNeighborTable.setDescription('This table contains the records of configed nap neighbor.')
hwNapNeighborEntry = MibTableRow((1, 3, 6, 1, 4, 1, 2011, 5, 25, 206, 2, 1, 1), ).setIndexNames((0, "HUAWEI-NAP-MIB", "hwNapNeighborIndex"))
if mibBuilder.loadTexts: hwNapNeighborEntry.setStatus('current')
if mibBuilder.loadTexts: hwNapNeighborEntry.setDescription('Entry of hwNapNeighborTable.')
hwNapNeighborIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 206, 2, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 8))).setMaxAccess("readonly")
if mibBuilder.loadTexts: hwNapNeighborIndex.setStatus('current')
if mibBuilder.loadTexts: hwNapNeighborIndex.setDescription('Index of nap neighbor table.')
hwNapLocalPortName = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 206, 2, 1, 1, 2), OctetString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hwNapLocalPortName.setStatus('current')
if mibBuilder.loadTexts: hwNapLocalPortName.setDescription('The local port name of nap neighbor.')
hwNapNeighborStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 206, 2, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("detecting", 1), ("established", 2), ("ipAssigned", 3), ("abnormal", 4)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: hwNapNeighborStatus.setStatus('current')
if mibBuilder.loadTexts: hwNapNeighborStatus.setDescription('The status of nap neighbor.')
hwNapNeighborAbnormalReason = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 206, 2, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4))).clone(namedValues=NamedValues(("normal", 0), ("portNotSupport", 1), ("slaveDisable", 2), ("masterIpAssignError", 3), ("slaveIpAssignError", 4)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: hwNapNeighborAbnormalReason.setStatus('current')
if mibBuilder.loadTexts: hwNapNeighborAbnormalReason.setDescription('The abnormal reason for nap neighbor.')
hwNapStatusNotify = NotificationType((1, 3, 6, 1, 4, 1, 2011, 5, 25, 206, 3, 1)).setObjects(("HUAWEI-NAP-MIB", "hwNapLocalPortName"), ("HUAWEI-NAP-MIB", "hwNapNeighborStatus"), ("HUAWEI-NAP-MIB", "hwNapNeighborAbnormalReason"))
if mibBuilder.loadTexts: hwNapStatusNotify.setStatus('current')
if mibBuilder.loadTexts: hwNapStatusNotify.setDescription('If the system configuration is changed in given time, a notification will be generated.')
mibBuilder.exportSymbols("HUAWEI-NAP-MIB", hwNapNeighborNum=hwNapNeighborNum, hwNapNeighborAbnormalReason=hwNapNeighborAbnormalReason, hwNapTableObjects=hwNapTableObjects, hwNap=hwNap, hwNapLocalPortName=hwNapLocalPortName, hwNapNeighborStatus=hwNapNeighborStatus, hwNapNotifications=hwNapNotifications, hwNapStatusNotify=hwNapStatusNotify, hwNapNeighborTable=hwNapNeighborTable, DateAndTime=DateAndTime, hwNapNeighborEntry=hwNapNeighborEntry, PYSNMP_MODULE_ID=hwNap, hwNapScalarObjects=hwNapScalarObjects, hwNapNeighborIndex=hwNapNeighborIndex)
|
class Color():
def __init__(self, red=0, green=0, blue=0, type=False):
self.red = red
self.green = green
self.blue = blue
# False = 15bit, True = 24bit
self.__type = type
if self.__type:
self.assert24Bit()
else:
self.assert15Bit()
def getRed(self):
return self.red
def getGreen(self):
return self.green
def getBlue(self):
return self.blue
def getType(self):
return self.__type
def switchType(self):
if self.__type:
#24-bit to 15-bit
self.assert24Bit()
self.blue = self.blue // 8
self.green = self.green // 8
self.red = self.red // 8
self.__type = False
else:
#15-bit to 24-bit
self.assert15Bit()
self.red *= 8
self.red += self.red // 32
self.green *= 8
self.green += self.green // 32
self.blue *= 8
self.blue += self.blue // 32
self.__type = True
def get15BitColor(self):
if self.__type:
#24-bit to 15-bit
self.assert24Bit()
B = self.blue // 8
G = self.green // 8
R = self.red // 8
return B*1024 + G*32 + R
else:
self.assert15Bit()
return self.blue*1024 + self.green*32 + self.red
def get24BitColor(self):
if self.__type:
self.assert24Bit()
return self.red*0x010000 + self.green*0x0100 + self.blue
else:
#15-bit to 24-bit
self.assert15Bit()
R = self.red
R *= 8
R += R // 32
G = self.green
G *= 8
G += G // 32
B = self.blue
B *= 8
B += B // 32
return R*0x010000 + G*0x0100 + B
def assert15Bit(self):
assert((self.red >= 0) and (self.red < 32))
assert((self.green >= 0) and (self.green < 32))
assert((self.blue >= 0) and (self.blue < 32))
pass
def assert24Bit(self):
assert((self.red >= 0) and (self.red < 256))
assert((self.green >= 0) and (self.green < 256))
assert((self.blue >= 0) and (self.blue < 256))
pass
|
"""
Problem : Find out the missing number
Author : Alok Tripathi
"""
def getMissingNo(arr):
n = len(arr)
# Sum of (N+1) * (N+2) natural number [n is length of arr]
total = (n + 1) * (n + 2) / 2
sum_of_arr = sum(arr)
return int(total - sum_of_arr) # sum of n... natural no. - sum of array
if __name__ == "__main__":
arr = [1, 2, 3, 5]
miss = getMissingNo(arr)
print(miss)
|
a = int(input())
v = 0
for x in range(1,10+1):
print(v+1,"x",a,"=",a*(v+1))
v = v+ 1
|
"""
A OISC emulation using the Subleq operation.
Tom Findlay (findlaytel@gmail.com)
Feb. 2021
"""
class whisk:
def __init__(self, memory=30000):
self.memory = [0]*memory
def subleq(self,addr):
if addr < 0:
return None
A = self.memory[addr]
B = self.memory[addr+1]
C = self.memory[addr+2]
if B == -1:
print(chr(self.memory[A]), end="")
return addr+3
else:
sub = self.memory[B] - self.memory[A]
self.memory[B] = sub
if sub <= 0:
return C
return addr+3
def run(self, code):
code = code.split()
code = [int(i) for i in code]
self.memory[0:len(code)] = code
pc = 0
while pc != None:
pc = self.subleq(pc)
return True
if __name__ == "__main__":
f = open("output.slq", "r")
code = f.read()
f.close()
w = whisk()
w.run(code)
|
# Implementation using list
# Initializing queue using a list
myQueue = []
# Adding elements to the queue
myQueue.append(1)
myQueue.append(2)
myQueue.append(3)
# Printing the queue
print("Initial queue:", myQueue)
# Size of the queue
print("Size: ", len(myQueue))
# Check if queue is empty
if not myQueue:
print("Queue is empty")
else:
print("Queue is not empty")
# Peek operation
print("First element in the queue: ", myQueue[0])
# Removing an element from the queue
print("Dequeued element:", myQueue.pop(0))
print("Queue after dequeue operation:", myQueue) |
#!/usr/bin/env python3
def merge(A,l,m,r):
L,R = A[l:m+1],A[m+1:r+1] #copied
L.append(float("inf"))
R.append(float("inf"))
i,j = 0,0
for k in range(l,r+1):
A[k]= L[i] if L[i]<R[j] else R[j]
i,j =(1+i,j) if L[i]<R[j] else (i,j+1)
def merge_sort(A,l,r):
if l<r:
m = l+((r-l)>>1)
merge_sort(A,l,m)
merge_sort(A,m+1,r)
print(A,l,m,r)
merge(A,l,m,r)
A = [5,2,4,7,1,3,2,6]
merge_sort(A,0,len(A)-1)
print(A)
|
# str(Color())
class Color:
color = 'orange'
def __str__(self):
return Color.color
print(str(Color()))
|
# 1. Define a function that accepts 2 values and returns
# its sum, subtraction and multiplication.
# SOLUTION:
def result(a, b):
sum = a+b
sub = a-b
mul = a*b
print(f"Sum is {sum}, Sub is {sub}, & Multiply is {mul}")
a = int(input("Enter value of a: "))
b = int(input("Enter value of b: "))
result(a,b)
# 2. Define a function in python that accepts 3 digits
# and returns the highest of the three digits
def max(a, b, c):
if a > b and a > c:
print(f"{a} is maximum among all")
elif b > a and b > c:
print(f"{b} is maximum among all")
else:
print(f"{c} is maximum among all")
max(30,22,18)
# 3. Define a function that counts vowels
# and consonants in a word that you send in.
def count(val):
vov = 0
con = 0
for i in range(len(val)):
if val[i] in ['a','e','i','o','u']:
vov = vov+1
else:
con = con + 1
print("Count of vowels is ",vov)
print("Count of consonant is ",con)
x = input("Enter a word: ")
count(x) |
################################################################
### User input parameters for C3S-LAA
################################################################
### Required dependencies and input files
# Path for the AMOS package that contains minimus assembler
amos_path = "/usr/local/amos/bin/"
# C3S-LAA input files
primer_info_file = "primer_pairs_info.txt"
barcode_info_file = "barcode_pairs_info.txt"
fofn = "/mnt/data27/ffrancis/PacBio_sequence_files/EqPCR_raw/F03_1/Analysis_Results/m160901_060459_42157_c101086112550000001823264003091775_s1_p0.bas.h5"
ccs = "/mnt/data27/ffrancis/PacBio_sequence_files/old/primer_pair_based_grouping/Eq_wisser_PCR-ccs-opt-smrtanalysis-userdata-jobs-020-020256-data-reads_of_insert.fasta"
# Output path
consensus_output = "./output/"
### C3S-LAA parameters
trim_bp = 21 # number of bases corresponding to padding + barcode that need to be trimmed from the amplicon consensus
barcode_subset = 0 # (1: yes; 0: no)
min_read_length = 0 # reads >= "min_read_length" will be searched for the presence of primer sequences
min_read_len_filter = 1 # (1: filter; 0: no filter)
primer_search_space = 100 # searches for the primer sequence within n bases from the read terminals
max_barcode_length = 0 # barcode seq length
max_padding_length = 5 # padding seq length
### torque script settings
walltime = 190 # walltime for consensus calling
node = "1" # node no. for consensus calling
processors = 12 # no. processors for consensus calling
no_reads_threshold = 100 # consens sequences generated from >= "no_reads_threshold" will be used for assembly
|
# general
make_debug = False
make_task = ""
build_type = "Release"
app_name = "MyApp"
|
sum = 0
for num in range(1,1000):
if (num % 3 == 0 or num % 5 == 0):
sum += num
print(sum) |
num1 = int(input("Insira o primeiro numero: "))
num2 = int(input("Insira o segundo numero: "))
if num1 > num2:
print ("O maior número é:",num1)
else:
print ("O maior número é:",num2)
|
def split_lines(el):
return el.split('\n')
split_lines('10\n is\n the\n perfect\n number')
|
class Solution:
# @param {integer[]} prices
# @return {integer}
def maxProfit(self, prices):
if len(prices) < 2:
return 0
minn = prices[:-1]
maxn = prices[1:]
mi = minn[0]
for i in range(1, len(minn)):
if minn[i] > mi:
minn[i] = mi
else:
mi = minn[i]
ma = maxn[-1] # the last element
for i in range(len(maxn) - 1, 0, -1):
if maxn[i] > ma:
ma = maxn[i]
else:
maxn[i] = ma
res = 0
for i in range(len(maxn)):
if maxn[i] - minn[i] > res:
res = maxn[i] - minn[i]
return res
|
class ManagedFile:
"""
Manager for open with context manager
"""
def __init__(self,name):
self.name = name
def __enter__(self):
self.file = open(self.name, 'w')
return self.file
def __exit__(self, exc_type,exc_val, exc_tb):
if self.file:
self.file.close()
|
__all__ = ['UndefinedType', 'undefined']
class _SingletonMeta(type):
def __call__(self, *args, **kwargs):
if not hasattr(self, '__instance__'):
self.__instance__ = super().__call__(*args, **kwargs)
return self.__instance__
class UndefinedType(metaclass=_SingletonMeta):
'''A new singleton constant to Python that is passed in
when a parameter is not mapped to an argument.'''
__slots__ = () # instance has no property `__dict__`
__repr__ = staticmethod(lambda: 'undefined') # type: ignore # staticmethod for speed up
__bool__ = staticmethod(lambda: False)
undefined = UndefinedType()
|
def bubbleSort(alist):
for passnum in range(len(alist) - 1, 0, -1):
for i in range(passnum):
if alist[i] > alist[i + 1]:
temp = alist[i]
alist[i] = alist[i + 1]
alist[i + 1] = temp
alist = [54, 26, 93, 17, 77, 31, 44, 55, 20]
bubbleSort(alist)
print(alist)
# short bubble sort will return if the list doesn't need to sorted that much.
def shortBubbleSort(alist):
exchanges = True
passnum = len(alist) - 1
while passnum > 0 and exchanges:
exchanges = False
for i in range(passnum):
if alist[i] > alist[i + 1]:
exchanges = True
temp = alist[i]
alist[i] = alist[i + 1]
alist[i + 1] = temp
passnum = passnum - 1
alist = [20, 30, 40, 90, 50, 60, 70, 80, 100, 110]
shortBubbleSort(alist)
print(alist)
|
def format_search_terms(search_terms):
s=''
q=[]
if search_terms != None:
for term in search_terms:
q.append(term)
q.append('%20')
s= ''.join(q)
return s
def format_from_user(from_user):
s=''
q=[]
if from_user != None:
q.append('from%3A')
q.append(from_user)
q.append('%20')
s = ''.join(q)
return s
def format_reply_to(reply_to):
s=''
q=[]
if reply_to != None:
q.append('to%3A')
q.append(reply_to)
q.append('%20')
s = ''.join(q)
return s
def format_not_including(not_including):
s=''
q=[]
if not_including != None:
q.append('%2D')
q.append(not_including)
q.append('%20')
s = ''.join(q)
return s
def format_phrases(phrases):
s=''
q=[]
if phrases != None:
for phrase in phrases:
q.append('%22')
q.append(phrase)
q.append('%22')
q.append('%20')
s = ''.join(q)
return s
def format_filter(filters):
s=''
q=[]
if filters != None:
for filter in filters:
q.append('filter')
q.append('%3A')
q.append(filter)
q.append('%20')
s = ''.join(q)
return s
def format_not_filter(filters):
s=''
q=[]
if filters != None:
for filter in filters:
q.append('%2D')
q.append('filter')
q.append('%3A')
q.append(filter)
q.append('%20')
s = ''.join(q)
return s
def format_positive(positive):
s=''
if positive != None:
if positive is True:
s = '%3A%29%20'
else:
s = '%3A%28%20'
return s
def format_since(since):
s=''
q=[]
if since != None:
q.append('&')
q.append('since=')
q.append(since)
q.append('%20')
s = ''.join(q)
return s
def format_until(since):
s=''
q=[]
if since != None:
q.append('until%A')
q.append(since)
q.append('%20')
s = ''.join(q)
return s
def format_geocode(geocode):
s=''
q=[]
if geocode != None:
q.append('&geocode=')
q.append(geocode)
s = ''.join(q)
return s
def format_lang(lang):
s=''
q=[]
if lang != None:
q.append('&lang=')
q.append(lang)
s = ''.join(q)
return s
def format_locale(locale):
s=''
q=[]
if locale != None:
q.append('&locale=')
q.append(locale)
s = ''.join(q)
return s
def format_result_type(result_type):
s=''
q=[]
if result_type != None:
q.append('&result_type=')
q.append(result_type)
s = ''.join(q)
return s
def format_count(count):
s=''
q=[]
if count != None:
q.append('&count=')
q.append(count)
s = ''.join(q)
return s
def format_since_id(since_id):
s=''
q=[]
if since_id != None:
q.append('&since_id=')
q.append(since_id)
s = ''.join(q)
return s
def format_max_id(max_id):
s=''
q=[]
if max_id != None:
q.append('&max_id=')
q.append(max_id)
s = ''.join(q)
return s
def format_include_entities(include_entities):
s=''
q=[]
if include_entities != None:
q.append('&include_entities=')
q.append(include_entities)
s = ''.join(q)
return s |
class EventBrokerError(Exception):
pass
class EventBrokerAuthError(EventBrokerError):
pass
|
# We'll use a greedy algorithm to check to see if we have a
# new max sum as we iterate along the along. If at any time
# our sum becomes negative, we reset the sum.
def largestContiguousSum(arr):
maxSum = 0
currentSum = 0
for i, _ in enumerate(arr):
currentSum += arr[i]
maxSum = max(currentSum, maxSum)
if currentSum < 0:
currentSum = 0
return maxSum
# Tests
print(largestContiguousSum([5, -9, 6, -2, 3])) # should print 7
print(largestContiguousSum([1, 23, 90, 0, -9])) # should print 114
print(largestContiguousSum([2, 3, -8, -1, 2, 4, -2, 3])) # should print 7
|
#Exercício Python 11: Faça um programa que leia a largura e a altura de uma parede em metros, calcule a sua área e a quantidade de tinta necessária para pintá-la, sabendo que cada litro de tinta pinta uma área de 2 metros quadrados.
largura = float(input("Largura da parede: "))
altura = float(input("Altura da parede: "))
area = altura*largura
print("Você irá precisar de {} litros de tinta para pintar os {} m2 de parede.".format(area/2, area)) |
def diagonalDifference(arr):
diagonal1 = 0
diagonal2 = 0
for pos, line in enumerate(arr):
diagonal1 += line[pos]
diagonal2 += line[len(arr)-1 - pos]
return abs(diagonal1 - diagonal2)
|
class MaterialSubsurfaceScattering:
back = None
color = None
color_factor = None
error_threshold = None
front = None
ior = None
radius = None
scale = None
texture_factor = None
use = None
|
shiboken_library_soversion = str(6.1)
version = "6.1.1"
version_info = (6, 1, 1, "", "")
__build_date__ = '2021-06-03T07:46:50+00:00'
__setup_py_package_version__ = '6.1.1'
|
# S1
input_list = []
for i in range(int(6)):
input_list.append(input())
win_counter = 0
loss_counter = 0
for i in input_list:
if i == "W":
win_counter += 1
else:
loss_counter += 1
if win_counter == 1 or win_counter == 2:
print("3")
elif win_counter == 3 or win_counter == 4:
print("2")
elif win_counter == 5 or win_counter == 6:
print("1")
else:
print("-1")
# S2
def row_sum(matrix, row_num):
sum = 0
for i in range(4):
sum += int(matrix[row_num][i])
return sum
def col_sum(matrix, col_num):
sum = 0
for i in range(4):
sum += int(matrix[i][col_num])
return sum
input_list = []
for i in range(int(4)):
input_list.append(input().split())
#horizontal sum
h_sum = 0
sum_row_1 = row_sum(input_list, 0)
sum_row_2 = row_sum(input_list, 1)
sum_row_3 = row_sum(input_list, 2)
sum_row_4 = row_sum(input_list, 3)
sum_col_1 = col_sum(input_list, 0)
sum_col_2 = col_sum(input_list, 1)
sum_col_3 = col_sum(input_list, 2)
sum_col_4 = col_sum(input_list, 3)
if sum_row_1 == sum_row_2 == sum_row_3 == sum_row_4 == sum_col_1 == sum_col_2 == sum_col_3 == sum_col_4:
print('MAGIC')
else:
print("NOT MAGIC")
S3
a = input()
def palindromes(word):
i = 0
j = len(word) - 1
if len(word) == 0:
return 0
while i != j and i+1 != j:
if word[i] == word[j]:
i += 1
j -= 1
else:
return 0
if i+1 == j:
if word[i] != word[j]:
return 0
return len(word)
# check
result_num = 0
for i in range(len(a)):
for j in range(len(a), -1, -1):
word = a[i:j]
max_num = palindromes(word)
result_num = max(max_num, result_num)
print (result_num)
print(palindromes(a))
# S4
d_time = list(input())
del d_time[2]
# converting to integers
x = 0
while x < len(d_time):
d_time[x] = int(d_time[x])
x += 1
ten = [1, 0, 0, 0]
time = 0
add_time = 1
# Cycling through two hours of time
while time != 120:
# Defining rush hour
if d_time[1] >= 7 and d_time[1] <= 9 or d_time == ten:
rush_hour = True
else:
rush_hour = False
if rush_hour == True:
add_time = 0.5
else:
add_time = 1
# new minute
if d_time[3] != 9 and d_time[1] != 4:
d_time[3] += 1
# new multiple of ten miinutes
elif d_time[3] == 9 and d_time[2] != 5:
d_time[3] = 0
d_time[2] += 1
# new one-digit hour
elif d_time[3] == 9 and d_time[2] == 5 and d_time[1] != 9:
d_time[1] += 1
d_time[2] = 0
d_time[3] = 0
# switch to 10
elif d_time[1] == 9 and d_time[2] == 5 and d_time[3] == 9:
d_time[0] = 1
d_time[1] = 0
d_time[2] = 0
d_time[3] = 0
# new two-digit time
elif d_time[2] == 5 and d_time[3] == 9 and d_time[0] == 1:
# not to 20
if d_time[1] != 9:
d_time[1] += 1
# to 20
elif d_time[1] == 9:
d_time[0] = 2
d_time[1] = 0
d_time[2] = 0
d_time[3] = 0
# to 00:01
elif d_time[0] == 2 and d_time[1] == 4:
d_time[0] = 0
d_time[1] = 0
d_time[2] = 0
d_time[3] = 1
time += add_time
print(d_time[0], d_time[1], ':', d_time[2], d_time[3])
#S5
question = int(input())
num_people = int(input())
dmoj_v = input().split()
peg_v = input().split()
# convert lists to ints
for s in range(len(dmoj_v)):
dmoj_v[s] = int(dmoj_v[s])
for s in range(len(peg_v)):
peg_v[s] = int(peg_v[s])
# problem one
if question == 1:
x, total_speed = 0, 0
while x < num_people:
speeds = [max(dmoj_v), max(peg_v)]
bike_speed = max(speeds)
# take used up speeds off of the list
dmoj_v.pop(dmoj_v.index(max(dmoj_v)))
peg_v.pop(peg_v.index(max(peg_v)))
# add to total speed and reset bike speed
total_speed += bike_speed
bike_speed = 0
x += 1
elif question == 2:
x, total_speed = 0,0
while x < num_people:
speeds = [max(dmoj_v), min(peg_v)]
bike_speed = max(speeds)
dmoj_v.pop(dmoj_v.index(max(dmoj_v)))
peg_v.pop(peg_v.index(min(peg_v)))
total_speed += bike_speed
bike_speed = 0
x += 1
# output results
print(total_speed)
|
"""
Given a list of possibly overlapping intervals, return a new list of
intervals where all overlapping intervals have been merged.
The input list is not necessarily ordered in any way.
For example, given [(1, 3), (5, 8), (4, 10), (20, 25)], you should
return [(1, 3), (4, 10), (20, 25)].
Source: Daily Coding Problems (https://www.dailycodingproblem.com/)
"""
|
class Evaluator:
@staticmethod
def zip_evaluate(coefs, words):
if (len(coefs) != len(words)):
return -1
return sum([coeff * len(word) for (coeff, word)
in zip(coefs, words)])
@staticmethod
def enumerate_evaluate(coefs, words):
if (len(coefs) != len(words)):
return -1
return sum([coef * len(words[i]) for (i, coef) in enumerate(coefs)])
words = ["Le", "Lorem", "Ipsum", "est", "simple"]
coefs = [1.0, 2.0, 1.0, 4.0, 0.5]
print(Evaluator.zip_evaluate(coefs, words))
words = ["Le", "Lorem", "Ipsum", "est", "simple"]
coefs = [1.0, 2.0, 1.0, 4.0, 0.5]
print(Evaluator.enumerate_evaluate(coefs, words))
words = ["Le", "Lorem", "Ipsum", "n'", "est", "pas", "simple"]
coefs = [0.0, -1.0, 1.0, -12.0, 0.0, 42.42]
print(Evaluator.enumerate_evaluate(coefs, words))
|
# You are given an array of desired filenames in the order of their creation.
# Since two files cannot have equal names, the one which comes later will have
# an addition to its name in a form of (k), where k is the smallest positive
# integer such that the obtained name is not used yet.
#
# Return an array of names that will be given to the files.
#
# Example
#
# For names = ["doc", "doc", "image", "doc(1)", "doc"], the output should be
# fileNaming(names) = ["doc", "doc(1)", "image", "doc(1)(1)", "doc(2)"].
def fileNaming(names):
new_names = []
for name in names:
if name in new_names:
name = add_suffix(name, new_names)
new_names.append(name)
return new_names
def add_suffix(name, new_names):
count = 1
new_name = name + "(" + str(count) + ")"
while new_name in new_names:
count += 1
new_name = name + "(" + str(count) + ")"
return new_name
print(fileNaming(["doc", "doc", "image", "doc(1)", "doc"]))
|
load("@dwtj_rules_markdown//markdown:defs.bzl", "markdown_library")
def index_md(name = "index_md"):
markdown_library(
name = name,
srcs = ["INDEX.md"],
)
|
length_check_fields=['reset_pc', 'physical_addr_size']
bsc_cmd = '''bsc -u -verilog -elab -vdir {0} -bdir {1} -info-dir {1} \
+RTS -K40000M -RTS -check-assert -keep-fires \
-opt-undetermined-vals -remove-false-rules -remove-empty-rules \
-remove-starved-rules -remove-dollar -unspecified-to X -show-schedule \
-show-module-use {2}'''
bsc_defines = ''
verilator_cmd = ''' -O3 -LDFLAGS "-static" --x-assign fast \
--x-initial fast --noassert sim_main.cpp --bbox-sys -Wno-STMTDLY \
-Wno-UNOPTFLAT -Wno-WIDTH -Wno-lint -Wno-COMBDLY -Wno-INITIALDLY \
--autoflush {0} {1} --threads {2} -DBSV_RESET_FIFO_HEAD \
-DBSV_RESET_FIFO_ARRAY --output-split 20000 \
--output-split-ctrace 10000'''
makefile_temp='''
VERILOGDIR:={0}
BSVBUILDDIR:={1}
BSVOUTDIR:={2}
BSCCMD:={3}
BSC_DEFINES:={4}
BSVINCDIR:={5}
BS_VERILOG_LIB:={6}lib/Verilog/
TOP_MODULE:={7}
TOP_DIR:={8}
TOP_FILE:={9}
XLEN:={10}
TOP_BIN={11}
ISA={12}
FPGA=xc7a100tcsg324-1
SYNTHTOP=fpga_top
BSCAN2E=enable
include depends.mk
'''
dependency_yaml='''
c-class:
url: https://gitlab.com/shaktiproject/cores/c-class
checkout: 1.9.6
caches_mmu:
url: https://gitlab.com/shaktiproject/uncore/caches_mmu
checkout: 8.2.1
common_bsv:
url: https://gitlab.com/shaktiproject/common_bsv
checkout: master
fabrics:
url: https://gitlab.com/shaktiproject/uncore/fabrics
checkout: 1.2.0
common_verilog:
url: https://gitlab.com/shaktiproject/common_verilog
checkout: master
patch:
devices:
url: https://gitlab.com/shaktiproject/uncore/devices
checkout: 6.3.0
'''
|
BOT_NAME = 'naver_movie'
SPIDER_MODULES = ['naver_movie.spiders']
NEWSPIDER_MODULE = 'naver_movie.spiders'
ROBOTSTXT_OBEY = False
DOWNLOAD_DELAY = 2
COOKIES_ENABLED = True
DEFAULT_REQUEST_HEADERS = {
"Referer": "https://movie.naver.com/"
}
DOWNLOADER_MIDDLEWARES = {
'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware': None,
'scrapy.downloadermiddlewares.retry.RetryMiddleware': None,
'scrapy_fake_useragent.middleware.RandomUserAgentMiddleware': 400,
'scrapy_fake_useragent.middleware.RetryUserAgentMiddleware': 401,
}
RETRY_ENABLED = True
RETRY_TIMES = 2
ITEM_PIPELINES = {
'naver_movie.pipelines.NaverMoviePipeline': 300,
}
|
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
if not head or not head.next:
return True
# print(head)
slow, fast = head, head
pre = None
while fast and fast.next:
pre = slow
slow = slow.next
fast = fast.next.next
def helper(node):
if not node.next: return node
last = helper(node.next)
node.next.next = node
node.next = None
return last
tmp = head
p1, last = head, helper(slow)
p2 = last
while p1 and p2:
if p1.val == p2.val:
p1 = p1.next
p2 = p2.next
else:
pre.next = helper(last)
return False
pre.next = helper(last)
# print(head)
return True
|
#
# @lc app=leetcode id=557 lang=python
#
# [557] Reverse Words in a String III
#
# https://leetcode.com/problems/reverse-words-in-a-string-iii/description/
#
# algorithms
# Easy (63.15%)
# Likes: 624
# Dislikes: 67
# Total Accepted: 127.4K
# Total Submissions: 198.3K
# Testcase Example: `"Let's take LeetCode contest"`
#
# Given a string, you need to reverse the order of characters in each word
# within a sentence while still preserving whitespace and initial word order.
#
# Example 1:
#
# Input: "Let's take LeetCode contest"
# Output: "s'teL ekat edoCteeL tsetnoc"
#
#
#
# Note:
# In the string, each word is separated by single space and there will not be
# any extra space in the string.
#
#
class Solution(object):
def _reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
sl = s.split()
ls = []
for l in sl:
ls.append(''.join(list(l)[::-1]))
return ' '.join(ls)
def __reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
sl = s.split()
for index, value in enumerate(sl):
sl[index] = ''.join(list(value)[::-1])
return ' '.join(sl)
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
return ' '.join(s.split()[::-1])[::-1]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.