content stringlengths 7 1.05M |
|---|
'''Write a program that returns a list that contains common
elements between two input lists without duplicates. Ensure
it works for lists of two different sizes.'''
# list of random numbers
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
# newlist:
# sets ensure unique values
# evaluations for each number in a if it's also in b
newlist = list(set([i for i in a if i in b]))
# return the new list
print(newlist) |
class StrategyStateMachine :
def discovery() :
pass
def composition() :
pass
def usage() :
pass
def end() :
pass
|
# This file is generated by sync-deps, do not edit!
load("@rules_jvm_external//:defs.bzl", "maven_install")
load("@rules_jvm_external//:specs.bzl", "maven")
def default_install(artifacts, repositories, excluded_artifacts = []):
maven_install(
artifacts = artifacts,
fetch_sources = True,
repositories = repositories,
excluded_artifacts = excluded_artifacts,
maven_install_json = "//3rdparty:maven-install.json",
)
def maven_dependencies(install=None):
if install == None:
install = default_install
install(
artifacts=[
maven.artifact(group = "ch.qos.logback", artifact = "logback-classic", version = "1.2.3", neverlink = False),
maven.artifact(group = "ch.qos.logback", artifact = "logback-core", version = "1.2.3", neverlink = False),
maven.artifact(group = "com.fasterxml.jackson.core", artifact = "jackson-annotations", version = "2.9.6", neverlink = False),
maven.artifact(group = "com.fasterxml.jackson.core", artifact = "jackson-core", version = "2.9.6", neverlink = False),
maven.artifact(group = "com.fasterxml.jackson.core", artifact = "jackson-databind", version = "2.9.6", neverlink = False),
maven.artifact(group = "com.fasterxml.jackson.dataformat", artifact = "jackson-dataformat-yaml", version = "2.9.6", neverlink = False),
maven.artifact(group = "com.fasterxml.jackson.datatype", artifact = "jackson-datatype-guava", version = "2.9.6", neverlink = False),
maven.artifact(group = "com.geirsson", artifact = "scalafmt-core_2.12", version = "1.5.1", neverlink = False),
maven.artifact(group = "com.geirsson", artifact = "metaconfig-core_2.12", version = "0.4.0", neverlink = False),
maven.artifact(group = "com.geirsson", artifact = "metaconfig-typesafe-config_2.12", version = "0.4.0", neverlink = False),
maven.artifact(group = "com.github.tomas-langer", artifact = "chalk", version = "1.0.2", neverlink = False),
maven.artifact(group = "com.google.auto.value", artifact = "auto-value", version = "1.6.2", neverlink = False),
maven.artifact(group = "com.google.auto.value", artifact = "auto-value-annotations", version = "1.6.2", neverlink = False),
maven.artifact(group = "com.google.code.findbugs", artifact = "annotations", version = "3.0.1", neverlink = False),
maven.artifact(group = "com.google.code.findbugs", artifact = "jsr305", version = "3.0.2", neverlink = False),
maven.artifact(group = "com.google.errorprone", artifact = "error_prone_annotations", version = "2.3.1", neverlink = False),
maven.artifact(group = "com.google.googlejavaformat", artifact = "google-java-format", version = "1.6", neverlink = False),
maven.artifact(group = "com.google.guava", artifact = "guava", version = "23.6.1-jre", neverlink = False),
maven.artifact(group = "com.google.protobuf", artifact = "protobuf-java", version = "3.8.0", neverlink = False),
maven.artifact(group = "com.google.jimfs", artifact = "jimfs", version = "1.1", neverlink = False),
maven.artifact(group = "com.squareup.okio", artifact = "okio", version = "1.15.0", neverlink = False),
maven.artifact(group = "net.sf.jopt-simple", artifact = "jopt-simple", version = "5.0.4", neverlink = False),
maven.artifact(group = "org.hamcrest", artifact = "java-hamcrest", version = "2.0.0.0", neverlink = False),
maven.artifact(group = "org.scala-lang", artifact = "scala-compiler", version = "2.12.6", neverlink = False),
maven.artifact(group = "org.scala-lang", artifact = "scala-library", version = "2.12.6", neverlink = False),
maven.artifact(group = "org.scala-lang", artifact = "scala-reflect", version = "2.12.6", neverlink = False),
maven.artifact(group = "org.slf4j", artifact = "slf4j-api", version = "1.7.25", neverlink = False)
],
repositories=[
"https://repo.maven.apache.org/maven2/"
],
excluded_artifacts=[
maven.exclusion(group = "com.google.guava", artifact = "guava-jdk5"),
maven.exclusion(group = "org.slf4j", artifact = "slf4j-log4j12")
],
)
|
skill = input()
command = input()
while command != "For Azeroth":
command = command.split(" ")
command = command[0]
if command == "GladiatorStance":
skill = skill.upper()
print(skill)
break
elif command == "DefensiveStance":
skill = skill.lower()
print(skill)
break
elif command == "Dispel":
index = command[1]
letter = command[2]
if index > len(skill) - 1 or index < 0:
skill = skill.remove(index, 1)
skill = skill.insert(index, letter)
print("Dispel too weak")
else:
print("Success!")
break
|
product_list = ["풀", "가위", "크래파스"]
price_list = [800, 2500, 5000]
product_dict = {x:y for x, y in zip(product_list,price_list)}
print(product_dict) |
class DropboxException(Exception):
"""All errors related to making an API request extend this."""
def __init__(self, request_id, *args, **kwargs):
# A request_id can be shared with Dropbox Support to pinpoint the exact
# request that returns an error.
super(DropboxException, self).__init__(request_id, *args, **kwargs)
self.request_id = request_id
def __str__(self):
return repr(self)
class ApiError(DropboxException):
"""Errors produced by the Dropbox API."""
def __init__(self, request_id, error, user_message_text, user_message_locale):
"""
:param (str) request_id: A request_id can be shared with Dropbox
Support to pinpoint the exact request that returns an error.
:param error: An instance of the error data type for the route.
:param (str) user_message_text: A human-readable message that can be
displayed to the end user. Is None, if unavailable.
:param (str) user_message_locale: The locale of ``user_message_text``,
if present.
"""
super(ApiError, self).__init__(request_id, error)
self.error = error
self.user_message_text = user_message_text
self.user_message_locale = user_message_locale
def __repr__(self):
return 'ApiError({!r}, {})'.format(self.request_id, self.error)
class HttpError(DropboxException):
"""Errors produced at the HTTP layer."""
def __init__(self, request_id, status_code, body):
super(HttpError, self).__init__(request_id, status_code, body)
self.status_code = status_code
self.body = body
def __repr__(self):
return 'HttpError({!r}, {}, {!r})'.format(self.request_id,
self.status_code, self.body)
class PathRootError(HttpError):
"""Error caused by an invalid path root."""
def __init__(self, request_id, error=None):
super(PathRootError, self).__init__(request_id, 422, None)
self.error = error
def __repr__(self):
return 'PathRootError({!r}, {!r})'.format(self.request_id, self.error)
class BadInputError(HttpError):
"""Errors due to bad input parameters to an API Operation."""
def __init__(self, request_id, message):
super(BadInputError, self).__init__(request_id, 400, message)
self.message = message
def __repr__(self):
return 'BadInputError({!r}, {!r})'.format(self.request_id, self.message)
class AuthError(HttpError):
"""Errors due to invalid authentication credentials."""
def __init__(self, request_id, error):
super(AuthError, self).__init__(request_id, 401, None)
self.error = error
def __repr__(self):
return 'AuthError({!r}, {!r})'.format(self.request_id, self.error)
class RateLimitError(HttpError):
"""Error caused by rate limiting."""
def __init__(self, request_id, error=None, backoff=None):
super(RateLimitError, self).__init__(request_id, 429, None)
self.error = error
self.backoff = backoff
def __repr__(self):
return 'RateLimitError({!r}, {!r}, {!r})'.format(
self.request_id, self.error, self.backoff)
class InternalServerError(HttpError):
"""Errors due to a problem on Dropbox."""
def __repr__(self):
return 'InternalServerError({!r}, {}, {!r})'.format(
self.request_id, self.status_code, self.body)
|
{
"targets": [
{
"target_name": "waznutilities",
"sources": [
"src/main.cc",
"src/cryptonote_core/cryptonote_format_utils.cpp",
"src/crypto/tree-hash.c",
"src/crypto/crypto.cpp",
"src/crypto/crypto-ops.c",
"src/crypto/crypto-ops-data.c",
"src/crypto/hash.c",
"src/crypto/keccak.c",
"src/common/base58.cpp",
],
"include_dirs": [
"src",
"src/contrib/epee/include",
"<!(node -e \"require('nan')\")",
],
"link_settings": {
"libraries": [
"-lboost_system",
"-lboost_date_time",
]
},
"cflags_c": [
"-fno-exceptions -std=gnu11 -march=native -fPIC -DNDEBUG -Ofast -funroll-loops -fvariable-expansion-in-unroller -ftree-loop-if-convert-stores -fmerge-all-constants -fbranch-target-load-optimize2"
],
"cflags_cc": [
"-fexceptions -frtti -std=gnu++11 -march=native -fPIC -DNDEBUG -Ofast -s -funroll-loops -fvariable-expansion-in-unroller -ftree-loop-if-convert-stores -fmerge-all-constants -fbranch-target-load-optimize2"
],
"xcode_settings": {
"OTHER_CFLAGS": [ "-fexceptions -frtti" ]
}
}
]
}
|
# We must set a certain amount of money
my_money = 13
# We make a decision
if my_money > 20:
print("I'm going to the cinema and buy popcorn!")
elif my_money > 10:
print("I'm going to the cinema, but not buy popcorn!")
else:
print("I'm staying home!")
|
ix.enable_command_history()
app = ix.application
clarisse_win = app.get_event_window()
app.open_rename_item_window(clarisse_win)
ix.disable_command_history() |
# Input: 2D array of "map"
# Output: Shortest distance to exit from cell
# Revision 2 with help from my python book and some documentation
class deque(object):
# A custom implementation of collections.deque that is about 0.4s faster
def __init__(self, iterable=(), maxsize=-1):
if not hasattr(self, 'data'):
self.left = self.right = 0
self.data = {}
self.maxsize = maxsize
self.extend(iterable)
def append(self, x):
self.data[self.right] = x
self.right += 1
if self.maxsize != -1 and len(self) > self.maxsize:
self.popleft()
def popleft(self):
if self.left == self.right:
raise IndexError('cannot pop from empty deque')
elem = self.data[self.left]
del self.data[self.left]
self.left += 1
return elem
def extend(self, iterable):
for elem in iterable:
self.append(elem)
class Node:
def __init__(self, x, y, remove_uses, hallway_map):
# X, Y, number of walls I can take down, the entire map
self.x = x
self.y = y
self.remove_uses = remove_uses
self.hallway_map = hallway_map
def __eq__(self, comp):
return self.x == comp.x and self.y == comp.y and self.remove_uses == comp.remove_uses
def __hash__(self):
return self.x + len(self.hallway_map) * self.y
def getClosest(self):
# Return all surounding nodes
# Location of current node
x = self.x
y = self.y
# Initalize Vars
vertices = []
remove_uses = self.remove_uses
hallway_map = self.hallway_map
width = len(hallway_map[0])
height = len(hallway_map)
# Make sure that notes are not placed beyond the walls
if x > 0:
wall = hallway_map[y][x - 1] == 1
if wall:
if remove_uses > 0:
# Subtract from number of wals I can take down until I have run out of walls
vertices.append(Node(x - 1, y, remove_uses - 1, hallway_map))
else:
pass
else:
# Do nothing if the node is a hallway
vertices.append(Node(x - 1, y, remove_uses, hallway_map))
# The exact same thing for all other walls below:
if x < width - 1:
wall = hallway_map[y][x + 1] == 1
if wall:
if remove_uses > 0:
vertices.append(Node(x + 1, y, remove_uses - 1, hallway_map))
else:
pass
else:
vertices.append(Node(x + 1, y, remove_uses, hallway_map))
if y > 0:
wall = hallway_map[y - 1][x] == 1
if wall:
if remove_uses > 0:
vertices.append(Node(x, y - 1, remove_uses - 1, hallway_map))
else:
pass
else:
vertices.append(Node(x, y - 1, remove_uses, hallway_map))
if y < height - 1:
wall = hallway_map[y + 1][x]
if wall:
if remove_uses > 0:
vertices.append(Node(x, y + 1, remove_uses - 1, hallway_map))
else:
pass
else:
vertices.append(Node(x, y + 1, remove_uses, hallway_map))
# Return all touching nodes
return vertices
class PathFinder:
def __init__(self, hallway_map, remove_uses):
# New path finder
self.hallway_map = hallway_map
self.height = len(hallway_map)
self.width = len(hallway_map[0])
self.remove_uses = remove_uses # Number of walls I can take down
def getShortestPath(self):
# Use breadth-first search
start = Node(0, 0, self.remove_uses, self.hallway_map)
# Create a double-ended queue
queue = deque([start])
distances = {start: 1}
while queue:
# Get the next node from the deque
current_node = queue.popleft()
# If the current_node location happens to be the exit, return the distance
if current_node.x == self.width - 1 and current_node.y == self.height - 1:
return distances[current_node]
# If not at end of maze, add some more nodes
for neighbor in current_node.getClosest():
if neighbor not in distances.keys():
# Add next node to the deque
distances[neighbor] = distances[current_node] + 1
queue.append(neighbor)
def answer(input_map):
# Create an object of the map using a Path Finder
# 1 = How many walls can I take down?
# Useless for foobar, just something to play around with
router = PathFinder(input_map, 1)
# The most important part
return router.getShortestPath()
# Used to debug
# for _ in range(0,4):
# print answer([[0, 0, 0, 0, 0, 0],
# [1, 1, 1, 1, 1, 0],
# [0, 0, 0, 0, 0, 0],
# [0, 1, 1, 1, 1, 1],
# [0, 1, 1, 1, 1, 1],
# [0, 0, 0, 0, 0, 0]]) |
# encoding=utf-8
class Expression(object):
pass
|
# -*- coding: utf-8 -*-
"""
This software is licensed under the License (MIT) located at
https://github.com/ephreal/rollbot/Licence
Please see the license for any restrictions or rights granted to you by the
License.
"""
def check_author(author):
"""
Checks to see if the author of a message is the same as the author
passed in.
"""
def check_message(message):
return message.author == author
return check_message
|
# -*- coding: utf-8 -*-
'''Snippets for combination.
'''
# Usage:
# combination = Combination(max_value=10 ** 5 + 100)
# combination.count_nCr(n, r)
class Combination:
''' Count the total number of combinations.
nCr % mod.
nHr % mod = (n + r - 1)Cr % mod.
Args:
max_value: Max size of list. The default is 500,050
mod : Modulo. The default is 10 ** 9 + 7.
Landau notation: O(n)
See:
http://drken1215.hatenablog.com/entry/2018/06/08/210000
'''
def __init__(self, max_value=500050, mod=10 ** 9 + 7):
self.max_value = max_value
self.mod = mod
self.fac = [0 for _ in range(self.max_value)]
self.finv = [0 for _ in range(self.max_value)]
self.inv = [0 for _ in range(self.max_value)]
self.fac[0] = 1
self.fac[1] = 1
self.finv[0] = 1
self.finv[1] = 1
self.inv[1] = 1
for i in range(2, self.max_value):
self.fac[i] = self.fac[i - 1] * i % self.mod
self.inv[i] = self.mod - self.inv[self.mod % i] * (self.mod // i) % self.mod
self.finv[i] = self.finv[i - 1] * self.inv[i] % self.mod
def count_nCr(self, n, r):
'''Count the total number of combinations.
nCr % mod.
nHr % mod = (n + r - 1)Cr % mod.
Args:
n : Elements. Int of number (greater than 1).
r : The number of r-th combinations. Int of number
(greater than 0).
Returns:
The total number of combinations.
Landau notation: O(1)
'''
if n < r:
return 0
if n < 0 or r < 0:
return 0
return self.fac[n] * (self.finv[r] * self.finv[n - r] % self.mod) % self.mod
|
class Command(object):
"""
Abstract command class
"""
name = ''
description = ''
parser = None
def __init__(self, args):
self.args = args
@classmethod
def create_parser(cls, subparsers):
cls.parser = subparsers.add_parser(cls.name, help=cls.description)
cls.parser.set_defaults(command_class=cls)
cls.add_arguments()
return cls.parser
@classmethod
def add_arguments(cls):
pass
@classmethod
def help(cls):
cls.parser.print_help()
def do_job(self):
raise NotImplementedError()
def __get_available_commands(command_class):
commands = command_class.__subclasses__()
for c in list(commands):
commands.extend(__get_available_commands(c))
return commands
def get_available_commands():
return __get_available_commands(Command)
def get_available_command_names():
return [c.name for c in get_available_commands()]
def get_command(command_name):
for c in get_available_commands():
if c.name == command_name:
return c
raise ValueError('Invalid command name: %s' % command_name)
|
# -*- coding: utf-8 -*-
class Student(object):
def __init__(self, name, score):
self.__name = name
self.__score = score
def print_score(self):
print('%s: %s' % (self.__name, self.__score))
def get_name(self):
return self.__name
def get_score(self):
return self.__score
def set_score(self, score):
if 0 <= score <= 100:
self.__score = score
else:
raise ValueError('bad score')
bart = Student('Bart Simpson', 59)
#print(bart._name)
print(bart.get_name())
|
# Copyright (c) 2015 Filipe Negrão
# Version 0.1
#------------------------------------------------------------
# FUNCTIONS
#------------------------------------------------------------
def draw_ruling(x,y):
spaceBetween = 1.5*cm #space between ruling lines
line((x, y), (x, y+xHeight+descender+ascender)) #vertical line
line((x, y), (lineW, y)) # descender
line((x, y+descender), (lineW, y+descender)) # baseline
line((x, y+xHeight+descender), (lineW, y+xHeight+descender)) #x-height
line((x, y+xHeight+descender+ascender), (lineW, y+xHeight+descender+ascender))
def draw_angle(angle,catop,start_x,start_y):
stroke(.5)
angleDegrees = 90-float(nib_angle)
angleRad = radians(angleDegrees)
catadj = tan(angleRad) * catop
line((start_x,start_y), (catadj+start_x, catop+start_y))
#text properties
fill(0.7)
font("Georgia")
fontSize(10)
txt = str(nib_angle)+"°"
text(txt, (x+2.5*broadNib, y+descender+xHeight/2))
def draw_squares(x,y,broadNib):
n = (xHeight+ascender+descender)/broadNib
increment=0
while n > 0:
fill(0)
if n == (xHeight+ascender+descender)/broadNib:
rect(x,y,broadNib,broadNib)
elif (n%2)==0:
rect(x,y+broadNib*increment,broadNib,broadNib)
else:
rect(x+broadNib,y+broadNib*increment,broadNib,broadNib)
increment+=1
n-=1
#------------------------------------------------------------
# SIZES
#------------------------------------------------------------
#convert cm and mm to pt
cm = 28.3465
mm = 2.83465
#paper sizes
A4w, A4h = 297*mm, 210*mm
A3w, A3h = 297*mm, 420*mm
# create a new page and define it's format
size(A4w, A4h)
#------------------------------------------------------------
# UI
#------------------------------------------------------------
Variable([
dict(name="nib_size", ui="EditText", args=dict(text="3.5")),
dict(name="nib_angle", ui="EditText", args=dict(text="30")),
dict(name="nib_angle_w", ui="Slider",
args=dict(
value=50,
minValue=10,
maxValue=200)),
dict(name="xHeight", ui="EditText", args=dict(text="3.5")),
dict(name="ascender", ui="EditText", args=dict(text="2.5")),
dict(name="descender", ui="EditText", args=dict(text="2")),
dict(name="X", ui="Slider",
args=dict(
value=2*cm,
minValue=1*cm,
maxValue=5*cm)),
dict(name="Y", ui="Slider",
args=dict(
value=2*cm,
minValue=1*cm,
maxValue=5*cm))
], globals())
#------------------------------------------------------------
# VARIABLES
#------------------------------------------------------------
#define your pen size
broadNib = float(nib_size) * mm
#define your ascender height
ascender = float(ascender) * broadNib
#define your x-height
xHeight = float(xHeight) * broadNib
#define your descender line
descender = float(descender) * broadNib
#define nib angle
nibAngle = float(nib_angle)
#define the weight of the lines considering a margin of 2cm
lineW = A4w-2*cm
#stroke color and width
stroke(0)
strokeWidth(.5)
#ruling total size
ruling = descender + xHeight + ascender
#margins
x=X
y=Y
#total nibs
n = (xHeight+ascender+descender)/broadNib
#broad nib angle's line
angleDegrees = 90-float(nib_angle)
angle = radians(angleDegrees)
#------------------------------------------------------------
# LOOPS
#------------------------------------------------------------
while A4h>=0:
spaceBetween = 1.5*cm #space between ruling lines
draw_ruling(x,y)
draw_angle(30,nib_angle_w,x,y+descender+xHeight/2)
draw_squares(x,y,broadNib)
y+=spaceBetween+xHeight+descender+ascender
A4h = A4h-ruling-spaceBetween-2*cm
# save it as pdf on the current users desktop
#saveImage(["~/Desktop/001.pdf"])
|
#! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Author:_defined
@Time: 2018/8/28 19:18
@Description:
"""
__all__ = ["Timeout", "NoCookiesException", "VerificationCodeError",
"OverrideAttrException", "NoTaskException", "SpiderBanError"]
class Timeout(Exception):
"""
Functions run out of time
"""
class NoCookiesException(Exception):
"""
Has no cookies in redis
"""
class VerificationCodeError(Exception):
"""
Verification Codes identify error
"""
class OverrideAttrException(Exception):
"""
Override class attributions exception
"""
class NoTaskException(Exception):
"""
No task to access exception
"""
class SpiderBanError(Exception):
"""
spider has been banned
"""
|
# import simplejson as json
# import pandas as pd
# import numpy as np
# import psycopg2
# from itertools import repeat
# from psycopg2.extras import RealDictCursor, DictCursor
def execSql(cursor):
out = None
sqlString = '''
set search_path to demounit1;
-- GstInputAll (ExtGstTranD only) based on "isInput"
with cte1 as (
select "tranDate", "autoRefNo", "userRefNo", "tranType", "gstin", d."amount" - "cgst" - "sgst" - "igst" as "aggregate", "cgst", "sgst", "igst", d."amount",
"accName",h."remarks", "dc", "lineRefNo", d."remarks" as "lineRemarks"
from "TranH" h
join "TranD" d
on h."id" = d."tranHeaderId"
join "ExtGstTranD" e
on d."id" = e."tranDetailsId"
join "AccM" a
on a."id" = d."accId"
join "TranTypeM" t
on t."id" = h."tranTypeId"
where
("cgst" <> 0 or
"sgst" <> 0 or
"igst" <> 0) and
"isInput" = true and
"finYearId" = 2021
-- "finYearId" = %(finYearId)s and
-- "branchId" = %(branchId)s and
-- ("tranDate" between %(fromDate)s and %(toDate)s)
order by "tranDate", h."id"),
-- GstOutputAll (ExtGstTrand) based on "isInput"
cte2 as (
select "tranDate", "autoRefNo", "userRefNo", "tranType", "gstin", d."amount" - "cgst" - "sgst" - "igst" as "aggregate", "cgst", "sgst", "igst", d."amount",
"accName",h."remarks", "dc", "lineRefNo", d."remarks" as "lineRemarks"
from "TranH" h
join "TranD" d
on h."id" = d."tranHeaderId"
join "ExtGstTranD" e
on d."id" = e."tranDetailsId"
join "AccM" a
on a."id" = d."accId"
join "TranTypeM" t
on t."id" = h."tranTypeId"
where
("cgst" <> 0 or
"sgst" <> 0 or
"igst" <> 0) and
"isInput" = false and
"finYearId" = 2021
-- "finYearId" = %(finYearId)s and
-- "branchId" = %(branchId)s and
-- ("tranDate" between %(fromDate)s and %(toDate)s)
order by "tranDate", h."id"),
-- GstNetSales (considering only table SalePurchaseDetails)
cte3 as (
select "tranDate", "autoRefNo", "userRefNo", "tranType",
(select "gstin" from "ExtGstTranD" where "tranDetailsId" = d."id") as "gstin",
"gstRate",
CASE WHEN "tranTypeId" = 4 THEN (s."amount" - "cgst" - "sgst" - "igst") ELSE -(s."amount" - "cgst" - "sgst" - "igst") END as "aggregate",
CASE WHEN "tranTypeId" = 4 THEN "cgst" ELSE -"cgst" END as "cgst",
CASE WHEN "tranTypeId" = 4 THEN "sgst" ELSE -"sgst" END as "sgst",
CASE WHEN "tranTypeId" = 4 THEN "igst" ELSE -"igst" END as "igst",
CASE WHEN "tranTypeId" = 4 THEN s."amount" ELSE -s."amount" END as "amount",
"accName", h."remarks", "dc", "lineRefNo", d."remarks" as "lineRemarks"
from "TranH" h
join "TranD" d
on h."id" = d."tranHeaderId"
-- join "ExtGstTranD" e
-- on d."id" = e."tranDetailsId"
join "AccM" a
on a."id" = d."accId"
join "TranTypeM" t
on t."id" = h."tranTypeId"
join "SalePurchaseDetails" s
on d."id" = s."tranDetailsId"
where
("cgst" <> 0 or
"sgst" <> 0 or
"igst" <> 0) and
"tranTypeId" in (4,9) and
-- "isInput" = false and
"finYearId" = 2021
-- "finYearId" = %(finYearId)s and
-- "branchId" = %(branchId)s and
-- ("tranDate" between %(fromDate)s and %(toDate)s)
order by "tranDate", h."id"
),
-- GstNetPurchases (considering only table SalePurchaseDetails)
cte4 as (
select "tranDate", "autoRefNo", "userRefNo", "tranType",
(select "gstin" from "ExtGstTranD" where "tranDetailsId" = d."id") as "gstin",
"gstRate",
CASE WHEN "tranTypeId" = 5 THEN (s."amount" - "cgst" - "sgst" - "igst") ELSE -(s."amount" - "cgst" - "sgst" - "igst") END as "aggregate",
CASE WHEN "tranTypeId" = 5 THEN "cgst" ELSE -"cgst" END as "cgst",
CASE WHEN "tranTypeId" = 5 THEN "sgst" ELSE -"sgst" END as "sgst",
CASE WHEN "tranTypeId" = 5 THEN "igst" ELSE -"igst" END as "igst",
CASE WHEN "tranTypeId" = 5 THEN s."amount" ELSE -s."amount" END as "amount",
"accName", h."remarks", "dc", "lineRefNo", d."remarks" as "lineRemarks"
from "TranH" h
join "TranD" d
on h."id" = d."tranHeaderId"
-- join "ExtGstTranD" e
-- on d."id" = e."tranDetailsId"
join "AccM" a
on a."id" = d."accId"
join "TranTypeM" t
on t."id" = h."tranTypeId"
join "SalePurchaseDetails" s
on d."id" = s."tranDetailsId"
where
("cgst" <> 0 or
"sgst" <> 0 or
"igst" <> 0) and
"tranTypeId" in (5,10) and
-- "isInput" = false and
"finYearId" = 2021
-- "finYearId" = %(finYearId)s and
-- "branchId" = %(branchId)s and
-- ("tranDate" between %(fromDate)s and %(toDate)s)
order by "tranDate", h."id"
),
-- gstInputVouchers
cte5 as (
select "tranDate", "autoRefNo", "userRefNo", "tranType",
"gstin", "rate",
d."amount" - "cgst" - "sgst" - "igst" as "aggregate", "cgst", "sgst", "igst", d."amount",
"accName", h."remarks", "dc", "lineRefNo", d."remarks" as "lineRemarks"
from "TranH" h
join "TranD" d
on h."id" = d."tranHeaderId"
join "ExtGstTranD" e
on d."id" = e."tranDetailsId"
join "AccM" a
on a."id" = d."accId"
join "TranTypeM" t
on t."id" = h."tranTypeId"
-- join "SalePurchaseDetails" s
-- on d."id" = s."tranDetailsId"
where
("cgst" <> 0 or
"sgst" <> 0 or
"igst" <> 0) and
"rate" is not null and -- When it is not a sale / purchase i.e voucher, then "gstRate" value exists in "ExtGstTranD" table otherwise not
"isInput" = true and -- Only applicable for GST through vouchers
"finYearId" = 2021
-- "finYearId" = %(finYearId)s and
-- "branchId" = %(branchId)s and
-- ("tranDate" between %(fromDate)s and %(toDate)s)
order by "tranDate", h."id"
)
select json_build_object(
'gstInputAll', (SELECT json_agg(row_to_json(a)) from cte1 a),
'gstOutputAll', (SELECT json_agg(row_to_json(b)) from cte2 b),
'gstNetSales', (SELECT json_agg(row_to_json(c)) from cte3 c),
'gstNetPurchases', (SELECT json_agg(row_to_json(d)) from cte4 d),
'gstInputVouchers', (SELECT json_agg(row_to_json(e)) from cte5 e)
) as "jsonResult" '''
cursor.execute(sqlString)
out = cursor.fetchall()
return out
def trialBalance(data):
df = pd.DataFrame(data)
pivot = pd.pivot_table(df, index=["accCode", "accName", "accType"], columns=["dc"],
values="amount", aggfunc=np.sum, fill_value=0)
pivot.rename(
columns={
'O': 'Opening',
'D': 'Debit',
'C': 'Credit'
},
inplace=True
)
pivot['Closing'] = pivot['Opening'] + pivot['Debit'] - pivot['Credit']
pivot.loc['Total', 'Closing'] = pivot['Closing'].sum()
pivot.loc['Total', 'Debit'] = pivot['Debit'].sum()
pivot.loc['Total', 'Credit'] = pivot['Credit'].sum()
pivot.loc['Total', 'Opening'] = pivot['Opening'].sum()
pivot['Closing_dc'] = pivot['Closing'].apply(lambda x: 'Dr' if x >= 0 else 'Cr')
pivot['Closing'] = pivot['Closing'].apply(lambda x: x if x>=0 else -x) # remove minus sign
pivot['Opening_dc'] = pivot['Opening'].apply(lambda x: 'Dr' if x >= 0 else 'Cr')
pivot['Opening'] = pivot['Opening'].apply(lambda x: x if x>=0 else -x) # remove minus sign
pivot = pivot.reindex(columns= ['Opening', 'Opening_dc', 'Debit', 'Credit', 'Closing', 'Closing_dc'])
print(pivot)
j = pivot.to_json(orient='table')
jsonObj = json.loads(j)
dt = jsonObj["data"]
return dt
try:
connection = None
with open('adam/config.json') as f:
cfg = json.load(f)
connection = psycopg2.connect(
user=cfg["user"], password=cfg["password"], host=cfg["host"], port=cfg["port"], database=cfg["database"])
cursor = connection.cursor(cursor_factory=RealDictCursor)
data = execSql(cursor)
d = trialBalance(data)
# print(d)
connection.commit()
except (Exception, psycopg2.Error) as error:
print("Error while connecting to PostgreSQL", error)
if connection:
connection.rollback()
finally:
if connection:
cursor.close()
connection.close()
print("PostgreSQL connection is closed")
|
class ListenKeyExpired:
def __init__(self):
self.eventType = ''
self.eventTime = 0
@staticmethod
def json_parse(json_data):
result = ListenKeyExpired()
result.eventType = json_data.get_string('e')
result.eventTime = json_data.get_int('E')
return result
|
class Option:
"""Description of a single configurable option.
Args:
name: The name of the option, i.e. its key in the config.
description: Description of the option.
default: Default value of the option.
path: Path segments to the option in the config.
"""
def __init__(self, name, description, default, path=()):
self._name = name
self._description = description
self._default = default
self._path = tuple(path)
@property
def name(self):
"The name of the option."
return self._name
@property
def description(self):
"The description of the option."
return self._description
@property
def default(self):
"The default value of the option."
return self._default
@property
def path(self):
"Path leading to option in the config."
return self._path
def __repr__(self):
return "Option(name='{}', description='{}', default={}, path={})".format(
self.name, self.description, self.default, self.path)
def __str__(self):
return "{}: {} [default={}]".format(self.name, self.description, self.default)
def build_default_config(options):
"""Build a default config from an iterable of options.
"""
config = {}
for option in options:
subconfig = config
for segment in option.path:
subconfig = subconfig.setdefault(segment, {})
subconfig[option.name] = option.default
return config
|
b1 = float(input('Primeiro Bimestre: '))
b2 = float(input('Segundo Bimestre: '))
tot = (b1 + b2) / 2
if tot < 6:
print('''
Sua nota do primeiro bimestre é {:.1f} e no segundo é {:.1f}, sua média final é de {:.1f}.
Infelizmente você foi reprovado.
'''.format(b1, b2, tot))
else:
print('''
Sua nota no primeiro bimestre é {:.1f} e no segundo é {:.1f}, sua média final é de {:.1f}.
Parabéns, você foi aprovado.
'''. format(b1, b2, tot)) |
self.description = "Remove a package with a modified file marked for backup and has existing pacsaves"
self.filesystem = ["etc/dummy.conf.pacsave",
"etc/dummy.conf.pacsave.1",
"etc/dummy.conf.pacsave.2"]
p1 = pmpkg("dummy")
p1.files = ["etc/dummy.conf*"]
p1.backup = ["etc/dummy.conf"]
self.addpkg2db("local", p1)
self.args = "-R %s" % p1.name
self.addrule("PACMAN_RETCODE=0")
self.addrule("!PKG_EXIST=dummy")
self.addrule("!FILE_EXIST=etc/dummy.conf")
self.addrule("FILE_PACSAVE=etc/dummy.conf")
self.addrule("FILE_EXIST=etc/dummy.conf.pacsave.1")
self.addrule("FILE_EXIST=etc/dummy.conf.pacsave.2")
self.addrule("FILE_EXIST=etc/dummy.conf.pacsave.3")
|
"""
Exercise 3
PART 1: Gather Information
Gather information about the source of the error and paste your findings here. E.g.:
- What is the expected vs. the actual output?
- What error message (if any) is there?
- What line number is causing the error?
- What can you deduce about the cause of the error?
PART 2: State Assumptions
State your assumptions here or say them out loud to your partner ...
Make sure to be SPECIFIC about what each of your assumptions is!
HINT: It may help to draw a picture to clarify what your assumptions are.
Answer:
line 26, in insertion_sort
while key < arr[j] :
IndexError: list index out of range
This index error happens when j -= 1 makes j < 1. This can be solved by adding an additional constraint to the while loop, while j >= 0 and key < arr[j].
"""
def insertion_sort(arr):
"""Performs an Insertion Sort on the array arr."""
for i in range(1, len(arr)):
key = arr[i]
j = i-1
while j>= 0 and key < arr[j] :
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key
return arr
if __name__ == '__main__':
print('### Problem 3 ###')
answer = insertion_sort([5, 2, 3, 1, 6])
print(answer)
|
# =====================================
# generator=datazen
# version=2.1.0
# hash=ae83e4ad65b0e39560e7ca039248aa55
# =====================================
"""
Useful defaults and other package metadata.
"""
DESCRIPTION = "Simplify project workflows by standardizing use of GNU Make."
PKG_NAME = "vmklib"
VERSION = "1.6.6"
|
def quote():
# TODO store to indexes.json
indexes = [
{ source : 'BOVESPA', ticker:'IBOV'},
{ source : 'CRYPTO', ticker:'BTCBRL'}
]
return indexes |
class AttributeRange(object):
# value_start: float
# value_end: float
# duration_seconds: int
def __init__(self, left: float,
right: float, duration_seconds: int):
self.left = left
self.right = right
self.duration_seconds = duration_seconds
def __iter__(self):
yield self.left
yield self.right
@property
def reverse(self):
"""
Sort order is reverse (descending)
"""
return self.left > self.right
def __str__(self):
return str((self.left, self.right, self.duration_seconds))
class Line(object):
# attribute_name: str
def __init__(self, attribute_name, *ranges: AttributeRange):
self.ranges = ranges
self.attribute_name = attribute_name
def __str__(self):
return '\n'.join([str((p.left, p.right, p.duration_seconds)) for p in self.ranges])
|
# coding=utf-8
"""
**The brief introduction**:
This package (:py:mod:`poco.sdk.interfaces`) defines the main standards for communication interfaces between poco and
poco-sdk. If poco-sdk is integrated with an app running on another host or in different language, then poco-sdk is
called `remote runtime`. The implementation of these interfaces can be done either remotely or locally depending on
your own choice. If it is done locally, refer to :py:mod:`poco.freezeui` for more information.
Poco needs to communicate with the app runtime under the convention of interfaces described below and these interfaces
must be properly implemented. Any object implementing the same interface is replaceable and the communication protocol
or transport layer has no limitation. Furthermore, in many cases the communication can be customized that one part of
interfaces can use HTTP protocol and other can use TCP.
"""
|
'''
Filippo Aleotti
filippo.aleotti2@unibo.it
29 November 2019
I PROFESSIONAL MASTER'S PROGRAM, II LEVEL "SIMUR", Imola 2019
Modify the function realised in the previous exercise to return (inside the dict, using the key min) also the value with minimum frequency.
If more values have the same minimum frequency, then return the lowest one
'''
def are_equals(dict1, dict2):
''' check if two dict are equal.
Both the dicts have str keys and integer values
'''
for k,v in dict1.items():
if k not in dict2.keys():
return False
if dict2[k] != v:
return False
return True
def frequency_extractor(input_list):
output_dict = {}
for element in input_list:
if str(element) not in output_dict.keys():
output_dict[str(element)] = 1
else:
output_dict[str(element)] += 1
min_value = None
#NOTE: val are str, so we need an int cast to obtain integer values
for val, freq in output_dict.items():
if min_value == None:
#NOTE: at first iteration, we will always enter here
min_value = int(val)
else:
if freq < output_dict[str(min_value)]:
# this frequency value is lower than the frequency of the current minimum,
# so we have to update the current minimum
min_value = int(val)
elif freq == output_dict[str(min_value)] and min_value > int(val):
# the frequency is equal to the frequency of minimum.
# We have to update the minimum only if the current minimum
# is greather than this value
min_value = int(val)
output_dict['min'] = min_value
return output_dict
frequency_1 = frequency_extractor([0,1,0,2,2,1,2,1,0,0,2,1,1])
frequency_2 = frequency_extractor([1,2,2,2,1,5,3,1])
assert are_equals(frequency_1, {'0':4,'1':5,'2':4,'min':0}) == True
assert are_equals(frequency_2, {'1':3,'2':3,'3':1,'5':1, 'min':3}) == True
|
# AUTOGENERATED BY NBDEV! DO NOT EDIT!
__all__ = ["index", "modules", "custom_doc_links", "git_url"]
index = {"say_hello": "test_example.ipynb",
"say_goodbye": "00_core.ipynb"}
modules = ["core.py",
"test_example.py"]
doc_url = "https://daviderzmann.github.io/designkit_test/"
git_url = "https://github.com/daviderzmann/designkit_test/tree/master/"
def custom_doc_links(name): return None
|
n=int(input())
S=input()
k=int(input())
i=S[k-1]
for s in S:print(s if s==i else "*",end="") |
class Solution:
def findPoisonedDuration(self, timeSeries: List[int], duration: int) -> int:
if len(timeSeries) == 0:
return 0
total_poisoned = 0
for i in range(len(timeSeries)-1):
total_poisoned += min(duration, timeSeries[i+1] - timeSeries[i])
total_poisoned += duration
return total_poisoned
|
#
# PySNMP MIB module CISCO-LWAPP-RF-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-LWAPP-RF-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:06:16 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)
#
OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols("ASN1", "OctetString", "ObjectIdentifier", "Integer")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsUnion, ValueRangeConstraint, ValueSizeConstraint, SingleValueConstraint, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "ValueRangeConstraint", "ValueSizeConstraint", "SingleValueConstraint", "ConstraintsIntersection")
CLApIfType, = mibBuilder.importSymbols("CISCO-LWAPP-TC-MIB", "CLApIfType")
cLAPGroupName, = mibBuilder.importSymbols("CISCO-LWAPP-WLAN-MIB", "cLAPGroupName")
ciscoMgmt, = mibBuilder.importSymbols("CISCO-SMI", "ciscoMgmt")
SnmpAdminString, = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpAdminString")
ModuleCompliance, NotificationGroup, ObjectGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup", "ObjectGroup")
NotificationType, TimeTicks, iso, Integer32, ModuleIdentity, Gauge32, Unsigned32, ObjectIdentity, Counter64, Bits, IpAddress, MibScalar, MibTable, MibTableRow, MibTableColumn, MibIdentifier, Counter32 = mibBuilder.importSymbols("SNMPv2-SMI", "NotificationType", "TimeTicks", "iso", "Integer32", "ModuleIdentity", "Gauge32", "Unsigned32", "ObjectIdentity", "Counter64", "Bits", "IpAddress", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "MibIdentifier", "Counter32")
StorageType, DisplayString, TextualConvention, RowStatus, TruthValue = mibBuilder.importSymbols("SNMPv2-TC", "StorageType", "DisplayString", "TextualConvention", "RowStatus", "TruthValue")
ciscoLwappRFMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 9, 9, 778))
ciscoLwappRFMIB.setRevisions(('2012-04-27 00:00', '2012-01-27 00:00', '2011-11-01 00:00',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts: ciscoLwappRFMIB.setRevisionsDescriptions(('Add 11n MCS rates support in profile, cLRFProfileMcsDataRateTable is added for this rate setting.', ' Below new objects have been added to the cLRFProfileTable cLRFProfileHighDensityMaxRadioClients cLRFProfileBandSelectProbeResponse cLRFProfileBandSelectCycleCount cLRFProfileBandSelectCycleThreshold cLRFProfileBandSelectExpireSuppression cLRFProfileBandSelectExpireDualBand cLRFProfileBandSelectClientRSSI cLRFProfileLoadBalancingWindowSize cLRFProfileLoadBalancingDenialCount cLRFProfileCHDDataRSSIThreshold cLRFProfileCHDVoiceRSSIThreshold cLRFProfileCHDClientExceptionLevel cLRFProfileCHDCoverageExceptionLevel cLRFProfileMulticastDataRate One new scalar object has been added cLRFProfileOutOfBoxAPConfig', 'Initial version of this MIB module.',))
if mibBuilder.loadTexts: ciscoLwappRFMIB.setLastUpdated('201111010000Z')
if mibBuilder.loadTexts: ciscoLwappRFMIB.setOrganization('Cisco Systems Inc.')
if mibBuilder.loadTexts: ciscoLwappRFMIB.setContactInfo('Cisco Systems, Customer Service Postal: 170 West Tasman Drive San Jose, CA 95134 USA Tel: +1 800 553-NETS Email: cs-wnbu-snmp@cisco.com')
if mibBuilder.loadTexts: ciscoLwappRFMIB.setDescription("This MIB is intended to be implemented on all those devices operating as Central Controllers (CC) that terminate the Light Weight Access Point Protocol tunnel from Cisco Light-weight LWAPP Access Points. This MIB helps to manage the Radio Frequency (RF) parameters on the controller. The relationship between CC and the LWAPP APs can be depicted as follows: +......+ +......+ +......+ +......+ + + + + + + + + + CC + + CC + + CC + + CC + + + + + + + + + +......+ +......+ +......+ +......+ .. . . . .. . . . . . . . . . . . . . . . . . . . . . . . +......+ +......+ +......+ +......+ +......+ + + + + + + + + + + + AP + + AP + + AP + + AP + + AP + + + + + + + + + + + +......+ +......+ +......+ +......+ +......+ . . . . . . . . . . . . . . . . . . . . . . . . +......+ +......+ +......+ +......+ +......+ + + + + + + + + + + + MN + + MN + + MN + + MN + + MN + + + + + + + + + + + +......+ +......+ +......+ +......+ +......+ The LWAPP tunnel exists between the controller and the APs. The MNs communicate with the APs through the protocol defined by the 802.11 standard. LWAPP APs, upon bootup, discover and join one of the controllers and the controller pushes the configuration, that includes the WLAN parameters, to the LWAPP APs. The APs then encapsulate all the 802.11 frames from wireless clients inside LWAPP frames and forward the LWAPP frames to the controller. GLOSSARY Access Point ( AP ) An entity that contains an 802.11 medium access control ( MAC ) and physical layer ( PHY ) interface and provides access to the distribution services via the wireless medium for associated clients. LWAPP APs encapsulate all the 802.11 frames in LWAPP frames and sends it to the controller to which it is logically connected to. Central Controller ( CC ) The central entity that terminates the LWAPP protocol tunnel from the LWAPP APs. Throughout this MIB, this entity also referred to as 'controller'. Light Weight Access Point Protocol ( LWAPP ) This is a generic protocol that defines the communication between the Access Points and the controllers. Mobile Node ( MN ) A roaming 802.11 wireless device in a wireless network associated with an access point. 802.1x The IEEE ratified standard for enforcing port based access control. This was originally intended for use on wired LANs and later extended for use in 802.11 WLAN environments. This defines an architecture with three main parts - a supplicant (Ex. an 802.11 wireless client), an authenticator (the AP) and an authentication server(a Radius server). The authenticator passes messages back and forth between the supplicant and the authentication server to enable the supplicant get authenticated to the network. Radio Frequency ( RF ) Radio frequency (RF) is a rate of oscillation in the range of about 3 kHz to 300 GHz, which corresponds to the frequency of radio waves, and the alternating currents which carry radio signals. Received Signal Strength Indicator ( RSSI ) A measure of the strength of the signal as observed by the entity that received it, expressed in 'dbm'. Coverage Hole Detection ( CHD ) If clients on an Access Point are detected at low RSSI levels, it is considered a coverage hole by the Access Points. This indicates the existence of an area where clients are continually getting poor signal coverage, without having a viable location to roam to. REFERENCE [1] Wireless LAN Medium Access Control ( MAC ) and Physical Layer ( PHY ) Specifications. [2] Draft-obara-capwap-lwapp-00.txt, IETF Light Weight Access Point Protocol [3] IEEE 802.11 - The original 1 Mbit/s and 2 Mbit/s, 2.4 GHz RF and IR standard.")
ciscoLwappRFMIBNotifs = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 778, 0))
ciscoLwappRFMIBObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 778, 1))
ciscoLwappRFMIBConform = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 778, 2))
ciscoLwappRFConfig = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 778, 1, 1))
ciscoLwappRFGlobalObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 778, 1, 2))
class CiscoLwappRFApDataRates(TextualConvention, Integer32):
description = "This field indicates the data rates supported by an AP 'disabled' The rate is not supported by the AP 'supported' The rate is supported by the AP 'mandatoryRate' The rate is required by the AP 'notApplicable' The rate is notApplicable."
status = 'current'
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))
namedValues = NamedValues(("disabled", 0), ("supported", 1), ("mandatoryRate", 2), ("notApplicable", 3))
cLAPGroupsRFProfileTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 778, 1, 1, 1), )
if mibBuilder.loadTexts: cLAPGroupsRFProfileTable.setStatus('current')
if mibBuilder.loadTexts: cLAPGroupsRFProfileTable.setDescription('This table lists the mapping between an RF profile and an AP group.')
cLAPGroupsRFProfileEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 778, 1, 1, 1, 1), ).setIndexNames((0, "CISCO-LWAPP-WLAN-MIB", "cLAPGroupName"))
if mibBuilder.loadTexts: cLAPGroupsRFProfileEntry.setStatus('current')
if mibBuilder.loadTexts: cLAPGroupsRFProfileEntry.setDescription("An entry containing the configuration attributes that affect the operation of the APs within a group. Entries can be added/deleted by explicit management action from NMS/EMS through the 'bsnAPGroupsVlanRowStatus' object in bsnAPGroupsVlanTable as defined by the AIRESPACE-WIRELESS-MIB.")
cLAPGroups802dot11bgRFProfileName = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 778, 1, 1, 1, 1, 1), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(0, 64))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cLAPGroups802dot11bgRFProfileName.setStatus('current')
if mibBuilder.loadTexts: cLAPGroups802dot11bgRFProfileName.setDescription("This object specifies the RF profile name assigned to this site on the 802.11bg radio. This profile being assigned should exist in the 'cLRFProfileTable'. To disassociate a profile with this site a string of zero length should be set.")
cLAPGroups802dot11aRFProfileName = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 778, 1, 1, 1, 1, 2), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(0, 64))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cLAPGroups802dot11aRFProfileName.setStatus('current')
if mibBuilder.loadTexts: cLAPGroups802dot11aRFProfileName.setDescription("This object specifies the RF profile name assigned to this site on the 802.11a radio. This profile being assigned should exist in the 'cLRFProfileTable'. To disassociate a profile with this site a string of zero length should be set.")
cLRFProfileTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 778, 1, 1, 2), )
if mibBuilder.loadTexts: cLRFProfileTable.setStatus('current')
if mibBuilder.loadTexts: cLRFProfileTable.setDescription('This table lists the configuration for each RF profile.')
cLRFProfileEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 778, 1, 1, 2, 1), ).setIndexNames((0, "CISCO-LWAPP-RF-MIB", "cLRFProfileName"))
if mibBuilder.loadTexts: cLRFProfileEntry.setStatus('current')
if mibBuilder.loadTexts: cLRFProfileEntry.setDescription('An entry containing the configuration attributes that affect the operation of 802.11 RF domain. Entries can be added/deleted by explicit management action from NMS/EMS or through user console.')
cLRFProfileName = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 778, 1, 1, 2, 1, 1), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 64)))
if mibBuilder.loadTexts: cLRFProfileName.setStatus('current')
if mibBuilder.loadTexts: cLRFProfileName.setDescription('This object uniquely identifies a RF Profile.')
cLRFProfileDescr = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 778, 1, 1, 2, 1, 2), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(0, 64))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: cLRFProfileDescr.setStatus('current')
if mibBuilder.loadTexts: cLRFProfileDescr.setDescription('This object specifies a human-readable description of the profile.')
cLRFProfileTransmitPowerMin = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 778, 1, 1, 2, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-10, 30)).clone(-10)).setUnits('dbm').setMaxAccess("readcreate")
if mibBuilder.loadTexts: cLRFProfileTransmitPowerMin.setStatus('current')
if mibBuilder.loadTexts: cLRFProfileTransmitPowerMin.setDescription('This object specifies the lower bound of transmit power value supported by an AP.')
cLRFProfileTransmitPowerMax = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 778, 1, 1, 2, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-10, 30)).clone(30)).setUnits('dbm').setMaxAccess("readcreate")
if mibBuilder.loadTexts: cLRFProfileTransmitPowerMax.setStatus('current')
if mibBuilder.loadTexts: cLRFProfileTransmitPowerMax.setDescription('This object specifies the uppoer bound of transmit power value supported by an AP.')
cLRFProfileTransmitPowerThresholdV1 = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 778, 1, 1, 2, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-80, -50)).clone(-70)).setUnits('dbm').setMaxAccess("readcreate")
if mibBuilder.loadTexts: cLRFProfileTransmitPowerThresholdV1.setStatus('current')
if mibBuilder.loadTexts: cLRFProfileTransmitPowerThresholdV1.setDescription('This object specifies the transmit power control version 1 threshold for the radio resource management algorithm.')
cLRFProfileTransmitPowerThresholdV2 = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 778, 1, 1, 2, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-80, -50)).clone(-67)).setUnits('dbm').setMaxAccess("readcreate")
if mibBuilder.loadTexts: cLRFProfileTransmitPowerThresholdV2.setStatus('current')
if mibBuilder.loadTexts: cLRFProfileTransmitPowerThresholdV2.setDescription('This object specifies the transmit power control version 2 threshold for the radio resource management algorithm.')
cLRFProfileDataRate1Mbps = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 778, 1, 1, 2, 1, 7), CiscoLwappRFApDataRates().clone('mandatoryRate')).setMaxAccess("readcreate")
if mibBuilder.loadTexts: cLRFProfileDataRate1Mbps.setStatus('current')
if mibBuilder.loadTexts: cLRFProfileDataRate1Mbps.setDescription('This object specifies the configuration for this data rate.')
cLRFProfileDataRate2Mbps = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 778, 1, 1, 2, 1, 8), CiscoLwappRFApDataRates().clone('mandatoryRate')).setMaxAccess("readcreate")
if mibBuilder.loadTexts: cLRFProfileDataRate2Mbps.setStatus('current')
if mibBuilder.loadTexts: cLRFProfileDataRate2Mbps.setDescription('This object specifies the configuration for this data rate.')
cLRFProfileDataRate5AndHalfMbps = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 778, 1, 1, 2, 1, 9), CiscoLwappRFApDataRates().clone('mandatoryRate')).setMaxAccess("readcreate")
if mibBuilder.loadTexts: cLRFProfileDataRate5AndHalfMbps.setStatus('current')
if mibBuilder.loadTexts: cLRFProfileDataRate5AndHalfMbps.setDescription('This object specifies the configuration for this data rate.')
cLRFProfileDataRate11Mbps = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 778, 1, 1, 2, 1, 10), CiscoLwappRFApDataRates().clone('mandatoryRate')).setMaxAccess("readcreate")
if mibBuilder.loadTexts: cLRFProfileDataRate11Mbps.setStatus('current')
if mibBuilder.loadTexts: cLRFProfileDataRate11Mbps.setDescription('This object specifies the configuration for this data rate.')
cLRFProfileDataRate6Mbps = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 778, 1, 1, 2, 1, 11), CiscoLwappRFApDataRates().clone('supported')).setMaxAccess("readcreate")
if mibBuilder.loadTexts: cLRFProfileDataRate6Mbps.setStatus('current')
if mibBuilder.loadTexts: cLRFProfileDataRate6Mbps.setDescription('This object specifies the configuration for this data rate.')
cLRFProfileDataRate9Mbps = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 778, 1, 1, 2, 1, 12), CiscoLwappRFApDataRates().clone('supported')).setMaxAccess("readcreate")
if mibBuilder.loadTexts: cLRFProfileDataRate9Mbps.setStatus('current')
if mibBuilder.loadTexts: cLRFProfileDataRate9Mbps.setDescription('This object specifies the configuration for this data rate.')
cLRFProfileDataRate12Mbps = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 778, 1, 1, 2, 1, 13), CiscoLwappRFApDataRates().clone('supported')).setMaxAccess("readcreate")
if mibBuilder.loadTexts: cLRFProfileDataRate12Mbps.setStatus('current')
if mibBuilder.loadTexts: cLRFProfileDataRate12Mbps.setDescription('This object specifies the configuration for this data rate.')
cLRFProfileDataRate18Mbps = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 778, 1, 1, 2, 1, 14), CiscoLwappRFApDataRates().clone('supported')).setMaxAccess("readcreate")
if mibBuilder.loadTexts: cLRFProfileDataRate18Mbps.setStatus('current')
if mibBuilder.loadTexts: cLRFProfileDataRate18Mbps.setDescription('This object specifies the configuration for this data rate.')
cLRFProfileDataRate24Mbps = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 778, 1, 1, 2, 1, 15), CiscoLwappRFApDataRates().clone('supported')).setMaxAccess("readcreate")
if mibBuilder.loadTexts: cLRFProfileDataRate24Mbps.setStatus('current')
if mibBuilder.loadTexts: cLRFProfileDataRate24Mbps.setDescription('This object specifies the configuration for this data rate.')
cLRFProfileDataRate36Mbps = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 778, 1, 1, 2, 1, 16), CiscoLwappRFApDataRates().clone('supported')).setMaxAccess("readcreate")
if mibBuilder.loadTexts: cLRFProfileDataRate36Mbps.setStatus('current')
if mibBuilder.loadTexts: cLRFProfileDataRate36Mbps.setDescription('This object specifies the configuration for this data rate.')
cLRFProfileDataRate48Mbps = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 778, 1, 1, 2, 1, 17), CiscoLwappRFApDataRates().clone('supported')).setMaxAccess("readcreate")
if mibBuilder.loadTexts: cLRFProfileDataRate48Mbps.setStatus('current')
if mibBuilder.loadTexts: cLRFProfileDataRate48Mbps.setDescription('This object specifies the configuration for this data rate.')
cLRFProfileDataRate54Mbps = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 778, 1, 1, 2, 1, 18), CiscoLwappRFApDataRates().clone('supported')).setMaxAccess("readcreate")
if mibBuilder.loadTexts: cLRFProfileDataRate54Mbps.setStatus('current')
if mibBuilder.loadTexts: cLRFProfileDataRate54Mbps.setDescription('This object specifies the configuration for this data rate.')
cLRFProfileRadioType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 778, 1, 1, 2, 1, 19), CLApIfType()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: cLRFProfileRadioType.setStatus('current')
if mibBuilder.loadTexts: cLRFProfileRadioType.setDescription('This object is used to configure the radio type for this profile.')
cLRFProfileStorageType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 778, 1, 1, 2, 1, 20), StorageType().clone('nonVolatile')).setMaxAccess("readcreate")
if mibBuilder.loadTexts: cLRFProfileStorageType.setStatus('current')
if mibBuilder.loadTexts: cLRFProfileStorageType.setDescription('This object represents the storage type for this conceptual row.')
cLRFProfileRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 778, 1, 1, 2, 1, 21), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: cLRFProfileRowStatus.setStatus('current')
if mibBuilder.loadTexts: cLRFProfileRowStatus.setDescription('This is the status column for this row and used to create and delete specific instances of rows in this table.')
cLRFProfileHighDensityMaxRadioClients = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 778, 1, 1, 2, 1, 22), Unsigned32().clone(200)).setMaxAccess("readcreate")
if mibBuilder.loadTexts: cLRFProfileHighDensityMaxRadioClients.setStatus('current')
if mibBuilder.loadTexts: cLRFProfileHighDensityMaxRadioClients.setDescription('This object specifies the maximum number of clients per AP radio.')
cLRFProfileBandSelectProbeResponse = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 778, 1, 1, 2, 1, 23), TruthValue().clone('false')).setMaxAccess("readcreate")
if mibBuilder.loadTexts: cLRFProfileBandSelectProbeResponse.setStatus('current')
if mibBuilder.loadTexts: cLRFProfileBandSelectProbeResponse.setDescription("This object specifies the AP's probe response with clients to verify whether client can associate on both 2.4 GHz and 5Ghz spectrum. When set to true, AP suppresses probe response to new clients for all SSIDs that are not being Band Select disabled.")
cLRFProfileBandSelectCycleCount = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 778, 1, 1, 2, 1, 24), Unsigned32().clone(2)).setMaxAccess("readcreate")
if mibBuilder.loadTexts: cLRFProfileBandSelectCycleCount.setStatus('current')
if mibBuilder.loadTexts: cLRFProfileBandSelectCycleCount.setDescription('This object specifies the maximum number of cycles not responding.')
cLRFProfileBandSelectCycleThreshold = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 778, 1, 1, 2, 1, 25), Unsigned32().clone(200)).setMaxAccess("readcreate")
if mibBuilder.loadTexts: cLRFProfileBandSelectCycleThreshold.setStatus('current')
if mibBuilder.loadTexts: cLRFProfileBandSelectCycleThreshold.setDescription('This object specifies the cycle threshold for band select.')
cLRFProfileBandSelectExpireSuppression = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 778, 1, 1, 2, 1, 26), Unsigned32().clone(20)).setMaxAccess("readcreate")
if mibBuilder.loadTexts: cLRFProfileBandSelectExpireSuppression.setStatus('current')
if mibBuilder.loadTexts: cLRFProfileBandSelectExpireSuppression.setDescription('This object specifies the expire of suppression.')
cLRFProfileBandSelectExpireDualBand = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 778, 1, 1, 2, 1, 27), Unsigned32().clone(60)).setMaxAccess("readcreate")
if mibBuilder.loadTexts: cLRFProfileBandSelectExpireDualBand.setStatus('current')
if mibBuilder.loadTexts: cLRFProfileBandSelectExpireDualBand.setDescription('This object specifies the expire of dual band.')
cLRFProfileBandSelectClientRSSI = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 778, 1, 1, 2, 1, 28), Integer32().clone(-80)).setUnits('dbm').setMaxAccess("readcreate")
if mibBuilder.loadTexts: cLRFProfileBandSelectClientRSSI.setStatus('current')
if mibBuilder.loadTexts: cLRFProfileBandSelectClientRSSI.setDescription('This object specifies the minimum dBM of a client RSSI to respond to probe.')
cLRFProfileLoadBalancingWindowSize = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 778, 1, 1, 2, 1, 29), Unsigned32().clone(5)).setMaxAccess("readcreate")
if mibBuilder.loadTexts: cLRFProfileLoadBalancingWindowSize.setStatus('current')
if mibBuilder.loadTexts: cLRFProfileLoadBalancingWindowSize.setDescription('This object specifies the number of clients associated between APs.')
cLRFProfileLoadBalancingDenialCount = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 778, 1, 1, 2, 1, 30), Unsigned32().clone(3)).setMaxAccess("readcreate")
if mibBuilder.loadTexts: cLRFProfileLoadBalancingDenialCount.setStatus('current')
if mibBuilder.loadTexts: cLRFProfileLoadBalancingDenialCount.setDescription('This object specifies number of clients denial with respect to AP.')
cLRFProfileCHDDataRSSIThreshold = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 778, 1, 1, 2, 1, 31), Integer32().clone(-80)).setUnits('dbm').setMaxAccess("readcreate")
if mibBuilder.loadTexts: cLRFProfileCHDDataRSSIThreshold.setStatus('current')
if mibBuilder.loadTexts: cLRFProfileCHDDataRSSIThreshold.setDescription('This object specifies the RSSI threshold value for data packets.')
cLRFProfileCHDVoiceRSSIThreshold = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 778, 1, 1, 2, 1, 32), Integer32().clone(-80)).setUnits('dbm').setMaxAccess("readcreate")
if mibBuilder.loadTexts: cLRFProfileCHDVoiceRSSIThreshold.setStatus('current')
if mibBuilder.loadTexts: cLRFProfileCHDVoiceRSSIThreshold.setDescription('This object specifies RSSI threshold value for voice packets.')
cLRFProfileCHDClientExceptionLevel = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 778, 1, 1, 2, 1, 33), Unsigned32().clone(3)).setMaxAccess("readcreate")
if mibBuilder.loadTexts: cLRFProfileCHDClientExceptionLevel.setStatus('current')
if mibBuilder.loadTexts: cLRFProfileCHDClientExceptionLevel.setDescription('This object specifies the client minimum exception level.')
cLRFProfileCHDCoverageExceptionLevel = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 778, 1, 1, 2, 1, 34), Unsigned32().clone(25)).setMaxAccess("readcreate")
if mibBuilder.loadTexts: cLRFProfileCHDCoverageExceptionLevel.setStatus('current')
if mibBuilder.loadTexts: cLRFProfileCHDCoverageExceptionLevel.setDescription('This object specifies the coverage exception level.')
cLRFProfileMulticastDataRate = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 778, 1, 1, 2, 1, 35), Unsigned32()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: cLRFProfileMulticastDataRate.setStatus('current')
if mibBuilder.loadTexts: cLRFProfileMulticastDataRate.setDescription('This object specifies the minimum multicast data rate. A value 0 indicates that AP will automatically adjust data rates.')
cLRFProfile11nOnly = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 778, 1, 1, 2, 1, 36), TruthValue().clone('false')).setMaxAccess("readcreate")
if mibBuilder.loadTexts: cLRFProfile11nOnly.setStatus('current')
if mibBuilder.loadTexts: cLRFProfile11nOnly.setDescription('This object specifies if 11n-client-only mode is enabled.')
cLRFProfileHDClientTrapThreshold = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 778, 1, 1, 2, 1, 37), Unsigned32()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: cLRFProfileHDClientTrapThreshold.setStatus('current')
if mibBuilder.loadTexts: cLRFProfileHDClientTrapThreshold.setDescription('This object specifies the threshold number of clients per AP radio to trigger a trap. The trap ciscoLwappApClientThresholdNotify will be triggered once the count of clients on the AP radio reaches this limit. A value of zero indicates that the trap is disabled.')
cLRFProfileInterferenceThreshold = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 778, 1, 1, 2, 1, 38), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(0, 100))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cLRFProfileInterferenceThreshold.setStatus('current')
if mibBuilder.loadTexts: cLRFProfileInterferenceThreshold.setDescription('This object specifies the threshold number of interference between 0 and 100 percent.')
cLRFProfileNoiseThreshold = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 778, 1, 1, 2, 1, 39), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-127, 0))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cLRFProfileNoiseThreshold.setStatus('current')
if mibBuilder.loadTexts: cLRFProfileNoiseThreshold.setDescription('This object specifies the threshold number of noise threshold between -127 and 0 dBm.')
cLRFProfileUtilizationThreshold = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 778, 1, 1, 2, 1, 40), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(0, 100))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cLRFProfileUtilizationThreshold.setStatus('current')
if mibBuilder.loadTexts: cLRFProfileUtilizationThreshold.setDescription('This object specifies the threshold number of utlization threshold between 0 and 100 percent.')
cLRFProfileDCAForeignContribution = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 778, 1, 1, 2, 1, 41), TruthValue()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cLRFProfileDCAForeignContribution.setStatus('current')
if mibBuilder.loadTexts: cLRFProfileDCAForeignContribution.setDescription('This object specifies whether foreign interference is taken into account for the DCA metrics.')
cLRFProfileDCAChannelWidth = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 778, 1, 1, 2, 1, 42), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("min", 1), ("medium", 2), ("max", 3)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cLRFProfileDCAChannelWidth.setStatus('current')
if mibBuilder.loadTexts: cLRFProfileDCAChannelWidth.setDescription('This object specifies how the system performs DCA channel width selection for the RFProfile min - Min channel width(20Mhz) the radio supports medium - Medium channel width(40Mhz) supported by this radio. max - Max channel width(80Mhz) supported by this radio.')
cLRFProfileDCAChannelList = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 778, 1, 1, 2, 1, 43), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 500))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cLRFProfileDCAChannelList.setStatus('current')
if mibBuilder.loadTexts: cLRFProfileDCAChannelList.setDescription('This object specifies the 802.11 channels available to the RF Profile. A comma separated list of integers.')
cLRFProfileRxSopThreshold = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 778, 1, 1, 2, 1, 44), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("auto", 0), ("low", 1), ("medium", 2), ("high", 3))).clone('auto')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cLRFProfileRxSopThreshold.setStatus('current')
if mibBuilder.loadTexts: cLRFProfileRxSopThreshold.setDescription('Configures the receiver start of packet threshold for the rf profile.')
cLRFProfileOutOfBoxAPConfig = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 778, 1, 2, 1), TruthValue()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cLRFProfileOutOfBoxAPConfig.setStatus('current')
if mibBuilder.loadTexts: cLRFProfileOutOfBoxAPConfig.setDescription('This object specifies the out of box AP group.')
cLRFProfileMcsDataRateTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 778, 1, 1, 3), )
if mibBuilder.loadTexts: cLRFProfileMcsDataRateTable.setStatus('current')
if mibBuilder.loadTexts: cLRFProfileMcsDataRateTable.setDescription('This object specifies the 11n MCS rates supported by the RF profile, indexed by the MCS rate, ranging from 1 to 24, corresponding to rate MCS-0, MCS-1, ... MCS-23.')
cLRFProfileMcsDataRateEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 778, 1, 1, 3, 1), ).setIndexNames((0, "CISCO-LWAPP-RF-MIB", "cLRFProfileMcsName"), (0, "CISCO-LWAPP-RF-MIB", "cLRFProfileMcsRate"))
if mibBuilder.loadTexts: cLRFProfileMcsDataRateEntry.setStatus('current')
if mibBuilder.loadTexts: cLRFProfileMcsDataRateEntry.setDescription('An entry containing MCS date rate information applicable to a particular profile.')
cLRFProfileMcsName = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 778, 1, 1, 3, 1, 1), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 64)))
if mibBuilder.loadTexts: cLRFProfileMcsName.setStatus('current')
if mibBuilder.loadTexts: cLRFProfileMcsName.setDescription('This object uniquely identifies a RF Profile.')
cLRFProfileMcsRate = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 778, 1, 1, 3, 1, 2), Unsigned32())
if mibBuilder.loadTexts: cLRFProfileMcsRate.setStatus('current')
if mibBuilder.loadTexts: cLRFProfileMcsRate.setDescription('This object uniquely identifies the MCS data rate for a particular profile.')
cLRFProfileMcsRateSupport = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 778, 1, 1, 3, 1, 3), TruthValue().clone('true')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cLRFProfileMcsRateSupport.setStatus('current')
if mibBuilder.loadTexts: cLRFProfileMcsRateSupport.setDescription("This object is used to enable or disable the data rate. When this object is set to 'true' the MCS support is enabled. When this object is set to 'false' the MCS support is disabled..")
ciscoLwappRFMIBCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 778, 2, 1))
ciscoLwappRFMIBGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 778, 2, 2))
ciscoLwappRFMIBCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 9, 9, 778, 2, 1, 1)).setObjects(("CISCO-LWAPP-RF-MIB", "ciscoLwappRFConfigGroup"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoLwappRFMIBCompliance = ciscoLwappRFMIBCompliance.setStatus('deprecated')
if mibBuilder.loadTexts: ciscoLwappRFMIBCompliance.setDescription('The compliance statement for the SNMP entities that implement the ciscoLwappRFMIB module. This compliance is deprecated and replaced by ciscoLwappRFMIBComplianceVer1 .')
ciscoLwappRFMIBComplianceVer1 = ModuleCompliance((1, 3, 6, 1, 4, 1, 9, 9, 778, 2, 1, 2)).setObjects(("CISCO-LWAPP-RF-MIB", "ciscoLwappRFConfigGroup"), ("CISCO-LWAPP-RF-MIB", "ciscoLwappRFConfigGroup1"), ("CISCO-LWAPP-RF-MIB", "ciscoLwappRFGlobalConfigGroup"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoLwappRFMIBComplianceVer1 = ciscoLwappRFMIBComplianceVer1.setStatus('current')
if mibBuilder.loadTexts: ciscoLwappRFMIBComplianceVer1.setDescription('The compliance statement for the SNMP entities that implement the ciscoLwappRFMIB module.')
ciscoLwappRFMIBComplianceVer2 = ModuleCompliance((1, 3, 6, 1, 4, 1, 9, 9, 778, 2, 1, 3)).setObjects(("CISCO-LWAPP-RF-MIB", "ciscoLwappRFConfigGroup"), ("CISCO-LWAPP-RF-MIB", "ciscoLwappRFConfigGroup1"), ("CISCO-LWAPP-RF-MIB", "ciscoLwappRFGlobalConfigGroup"), ("CISCO-LWAPP-RF-MIB", "ciscoLwappRFConfigGroup2"), ("CISCO-LWAPP-RF-MIB", "ciscoLwappRFConfigGroup3"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoLwappRFMIBComplianceVer2 = ciscoLwappRFMIBComplianceVer2.setStatus('current')
if mibBuilder.loadTexts: ciscoLwappRFMIBComplianceVer2.setDescription('The compliance statement for the SNMP entities that implement the ciscoLwappRFMIB module. Added ciscoLwappRFConfigGroup2 to add object to raise trap when client count exceeds threshold and ciscoLwappRFConfigGroup3 to address DCA settings')
ciscoLwappRFConfigGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 778, 2, 2, 1)).setObjects(("CISCO-LWAPP-RF-MIB", "cLAPGroups802dot11bgRFProfileName"), ("CISCO-LWAPP-RF-MIB", "cLAPGroups802dot11aRFProfileName"), ("CISCO-LWAPP-RF-MIB", "cLRFProfileDescr"), ("CISCO-LWAPP-RF-MIB", "cLRFProfileTransmitPowerMin"), ("CISCO-LWAPP-RF-MIB", "cLRFProfileTransmitPowerMax"), ("CISCO-LWAPP-RF-MIB", "cLRFProfileTransmitPowerThresholdV1"), ("CISCO-LWAPP-RF-MIB", "cLRFProfileTransmitPowerThresholdV2"), ("CISCO-LWAPP-RF-MIB", "cLRFProfileDataRate1Mbps"), ("CISCO-LWAPP-RF-MIB", "cLRFProfileDataRate2Mbps"), ("CISCO-LWAPP-RF-MIB", "cLRFProfileDataRate5AndHalfMbps"), ("CISCO-LWAPP-RF-MIB", "cLRFProfileDataRate11Mbps"), ("CISCO-LWAPP-RF-MIB", "cLRFProfileDataRate6Mbps"), ("CISCO-LWAPP-RF-MIB", "cLRFProfileDataRate9Mbps"), ("CISCO-LWAPP-RF-MIB", "cLRFProfileDataRate12Mbps"), ("CISCO-LWAPP-RF-MIB", "cLRFProfileDataRate18Mbps"), ("CISCO-LWAPP-RF-MIB", "cLRFProfileDataRate24Mbps"), ("CISCO-LWAPP-RF-MIB", "cLRFProfileDataRate36Mbps"), ("CISCO-LWAPP-RF-MIB", "cLRFProfileDataRate48Mbps"), ("CISCO-LWAPP-RF-MIB", "cLRFProfileDataRate54Mbps"), ("CISCO-LWAPP-RF-MIB", "cLRFProfileRadioType"), ("CISCO-LWAPP-RF-MIB", "cLRFProfileStorageType"), ("CISCO-LWAPP-RF-MIB", "cLRFProfileRowStatus"), ("CISCO-LWAPP-RF-MIB", "cLRFProfile11nOnly"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoLwappRFConfigGroup = ciscoLwappRFConfigGroup.setStatus('deprecated')
if mibBuilder.loadTexts: ciscoLwappRFConfigGroup.setDescription('This collection of objects specifies the configuration of RF parameters on the controller to be passed to an LWAPP AP.This config group ciscoLwappRFConfigGroup is deprecated and replaced by ciscoLwappRFConfigGroupVer1')
ciscoLwappRFConfigGroupVer1 = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 778, 2, 2, 2)).setObjects(("CISCO-LWAPP-RF-MIB", "cLAPGroups802dot11bgRFProfileName"), ("CISCO-LWAPP-RF-MIB", "cLAPGroups802dot11aRFProfileName"), ("CISCO-LWAPP-RF-MIB", "cLRFProfileDescr"), ("CISCO-LWAPP-RF-MIB", "cLRFProfileTransmitPowerMin"), ("CISCO-LWAPP-RF-MIB", "cLRFProfileTransmitPowerMax"), ("CISCO-LWAPP-RF-MIB", "cLRFProfileTransmitPowerThresholdV1"), ("CISCO-LWAPP-RF-MIB", "cLRFProfileTransmitPowerThresholdV2"), ("CISCO-LWAPP-RF-MIB", "cLRFProfileDataRate1Mbps"), ("CISCO-LWAPP-RF-MIB", "cLRFProfileDataRate2Mbps"), ("CISCO-LWAPP-RF-MIB", "cLRFProfileDataRate5AndHalfMbps"), ("CISCO-LWAPP-RF-MIB", "cLRFProfileDataRate11Mbps"), ("CISCO-LWAPP-RF-MIB", "cLRFProfileDataRate6Mbps"), ("CISCO-LWAPP-RF-MIB", "cLRFProfileDataRate9Mbps"), ("CISCO-LWAPP-RF-MIB", "cLRFProfileDataRate12Mbps"), ("CISCO-LWAPP-RF-MIB", "cLRFProfileDataRate18Mbps"), ("CISCO-LWAPP-RF-MIB", "cLRFProfileDataRate24Mbps"), ("CISCO-LWAPP-RF-MIB", "cLRFProfileDataRate36Mbps"), ("CISCO-LWAPP-RF-MIB", "cLRFProfileDataRate48Mbps"), ("CISCO-LWAPP-RF-MIB", "cLRFProfileDataRate54Mbps"), ("CISCO-LWAPP-RF-MIB", "cLRFProfileRadioType"), ("CISCO-LWAPP-RF-MIB", "cLRFProfileStorageType"), ("CISCO-LWAPP-RF-MIB", "cLRFProfileRowStatus"), ("CISCO-LWAPP-RF-MIB", "cLRFProfile11nOnly"), ("CISCO-LWAPP-RF-MIB", "cLRFProfileMcsName"), ("CISCO-LWAPP-RF-MIB", "cLRFProfileMcsRate"), ("CISCO-LWAPP-RF-MIB", "cLRFProfileMcsRateSupport"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoLwappRFConfigGroupVer1 = ciscoLwappRFConfigGroupVer1.setStatus('current')
if mibBuilder.loadTexts: ciscoLwappRFConfigGroupVer1.setDescription('This collection of objects specifies the configuration of RF parameters on the controller to be passed to an LWAPP AP.')
ciscoLwappRFConfigGroup1 = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 778, 2, 2, 5)).setObjects(("CISCO-LWAPP-RF-MIB", "cLRFProfileHighDensityMaxRadioClients"), ("CISCO-LWAPP-RF-MIB", "cLRFProfileBandSelectProbeResponse"), ("CISCO-LWAPP-RF-MIB", "cLRFProfileBandSelectCycleCount"), ("CISCO-LWAPP-RF-MIB", "cLRFProfileBandSelectCycleThreshold"), ("CISCO-LWAPP-RF-MIB", "cLRFProfileBandSelectExpireSuppression"), ("CISCO-LWAPP-RF-MIB", "cLRFProfileBandSelectExpireDualBand"), ("CISCO-LWAPP-RF-MIB", "cLRFProfileBandSelectClientRSSI"), ("CISCO-LWAPP-RF-MIB", "cLRFProfileLoadBalancingWindowSize"), ("CISCO-LWAPP-RF-MIB", "cLRFProfileLoadBalancingDenialCount"), ("CISCO-LWAPP-RF-MIB", "cLRFProfileCHDDataRSSIThreshold"), ("CISCO-LWAPP-RF-MIB", "cLRFProfileCHDVoiceRSSIThreshold"), ("CISCO-LWAPP-RF-MIB", "cLRFProfileCHDClientExceptionLevel"), ("CISCO-LWAPP-RF-MIB", "cLRFProfileCHDCoverageExceptionLevel"), ("CISCO-LWAPP-RF-MIB", "cLRFProfileMulticastDataRate"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoLwappRFConfigGroup1 = ciscoLwappRFConfigGroup1.setStatus('current')
if mibBuilder.loadTexts: ciscoLwappRFConfigGroup1.setDescription('This collection of objects specifies the configuration of RF parameters on the controller to be passed to an LWAPP AP.')
ciscoLwappRFGlobalConfigGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 778, 2, 2, 3)).setObjects(("CISCO-LWAPP-RF-MIB", "cLRFProfileOutOfBoxAPConfig"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoLwappRFGlobalConfigGroup = ciscoLwappRFGlobalConfigGroup.setStatus('current')
if mibBuilder.loadTexts: ciscoLwappRFGlobalConfigGroup.setDescription('This is the RF global config parameter.')
ciscoLwappRFConfigGroup2 = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 778, 2, 2, 4)).setObjects(("CISCO-LWAPP-RF-MIB", "cLRFProfileHDClientTrapThreshold"), ("CISCO-LWAPP-RF-MIB", "cLRFProfileInterferenceThreshold"), ("CISCO-LWAPP-RF-MIB", "cLRFProfileNoiseThreshold"), ("CISCO-LWAPP-RF-MIB", "cLRFProfileUtilizationThreshold"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoLwappRFConfigGroup2 = ciscoLwappRFConfigGroup2.setStatus('current')
if mibBuilder.loadTexts: ciscoLwappRFConfigGroup2.setDescription('This object specifies the configuration of Trap threshold to be configured on the interface of an LWAPP AP.')
ciscoLwappRFConfigGroup3 = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 778, 2, 2, 6)).setObjects(("CISCO-LWAPP-RF-MIB", "cLRFProfileDCAForeignContribution"), ("CISCO-LWAPP-RF-MIB", "cLRFProfileDCAChannelWidth"), ("CISCO-LWAPP-RF-MIB", "cLRFProfileDCAChannelList"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoLwappRFConfigGroup3 = ciscoLwappRFConfigGroup3.setStatus('current')
if mibBuilder.loadTexts: ciscoLwappRFConfigGroup3.setDescription('This object specifies the configuration DCA for RF Profiles.')
ciscoLwappRFConfigGroup4 = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 778, 2, 2, 7)).setObjects(("CISCO-LWAPP-RF-MIB", "cLRFProfileRxSopThreshold"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoLwappRFConfigGroup4 = ciscoLwappRFConfigGroup4.setStatus('current')
if mibBuilder.loadTexts: ciscoLwappRFConfigGroup4.setDescription('This object specifies the receiver start of packet threshold for RF Profiles.')
mibBuilder.exportSymbols("CISCO-LWAPP-RF-MIB", cLRFProfileOutOfBoxAPConfig=cLRFProfileOutOfBoxAPConfig, cLRFProfileDCAForeignContribution=cLRFProfileDCAForeignContribution, cLRFProfileDataRate11Mbps=cLRFProfileDataRate11Mbps, ciscoLwappRFGlobalObjects=ciscoLwappRFGlobalObjects, ciscoLwappRFMIB=ciscoLwappRFMIB, cLRFProfileBandSelectCycleCount=cLRFProfileBandSelectCycleCount, cLRFProfileRadioType=cLRFProfileRadioType, cLRFProfileRxSopThreshold=cLRFProfileRxSopThreshold, cLRFProfileMcsRateSupport=cLRFProfileMcsRateSupport, cLRFProfileDataRate2Mbps=cLRFProfileDataRate2Mbps, cLRFProfileRowStatus=cLRFProfileRowStatus, cLAPGroups802dot11bgRFProfileName=cLAPGroups802dot11bgRFProfileName, cLRFProfileBandSelectClientRSSI=cLRFProfileBandSelectClientRSSI, ciscoLwappRFMIBNotifs=ciscoLwappRFMIBNotifs, cLRFProfileHighDensityMaxRadioClients=cLRFProfileHighDensityMaxRadioClients, ciscoLwappRFConfigGroup4=ciscoLwappRFConfigGroup4, cLRFProfileDataRate12Mbps=cLRFProfileDataRate12Mbps, cLRFProfileDataRate1Mbps=cLRFProfileDataRate1Mbps, cLRFProfile11nOnly=cLRFProfile11nOnly, cLRFProfileNoiseThreshold=cLRFProfileNoiseThreshold, cLRFProfileTransmitPowerMin=cLRFProfileTransmitPowerMin, cLRFProfileStorageType=cLRFProfileStorageType, cLRFProfileDescr=cLRFProfileDescr, cLRFProfileCHDDataRSSIThreshold=cLRFProfileCHDDataRSSIThreshold, cLRFProfileCHDClientExceptionLevel=cLRFProfileCHDClientExceptionLevel, cLRFProfileBandSelectCycleThreshold=cLRFProfileBandSelectCycleThreshold, cLRFProfileMcsDataRateEntry=cLRFProfileMcsDataRateEntry, ciscoLwappRFMIBObjects=ciscoLwappRFMIBObjects, cLRFProfileDataRate9Mbps=cLRFProfileDataRate9Mbps, ciscoLwappRFConfig=ciscoLwappRFConfig, cLRFProfileInterferenceThreshold=cLRFProfileInterferenceThreshold, ciscoLwappRFMIBComplianceVer2=ciscoLwappRFMIBComplianceVer2, cLRFProfileCHDCoverageExceptionLevel=cLRFProfileCHDCoverageExceptionLevel, ciscoLwappRFConfigGroupVer1=ciscoLwappRFConfigGroupVer1, cLRFProfileDataRate5AndHalfMbps=cLRFProfileDataRate5AndHalfMbps, ciscoLwappRFConfigGroup3=ciscoLwappRFConfigGroup3, cLRFProfileTransmitPowerThresholdV2=cLRFProfileTransmitPowerThresholdV2, cLRFProfileDCAChannelList=cLRFProfileDCAChannelList, cLRFProfileTransmitPowerThresholdV1=cLRFProfileTransmitPowerThresholdV1, cLRFProfileDataRate6Mbps=cLRFProfileDataRate6Mbps, cLRFProfileDataRate36Mbps=cLRFProfileDataRate36Mbps, cLRFProfileTransmitPowerMax=cLRFProfileTransmitPowerMax, cLRFProfileDataRate48Mbps=cLRFProfileDataRate48Mbps, cLRFProfileBandSelectExpireDualBand=cLRFProfileBandSelectExpireDualBand, ciscoLwappRFMIBComplianceVer1=ciscoLwappRFMIBComplianceVer1, CiscoLwappRFApDataRates=CiscoLwappRFApDataRates, cLRFProfileBandSelectExpireSuppression=cLRFProfileBandSelectExpireSuppression, cLRFProfileHDClientTrapThreshold=cLRFProfileHDClientTrapThreshold, cLAPGroups802dot11aRFProfileName=cLAPGroups802dot11aRFProfileName, cLAPGroupsRFProfileTable=cLAPGroupsRFProfileTable, cLRFProfileName=cLRFProfileName, cLRFProfileDataRate18Mbps=cLRFProfileDataRate18Mbps, ciscoLwappRFMIBCompliances=ciscoLwappRFMIBCompliances, ciscoLwappRFConfigGroup=ciscoLwappRFConfigGroup, cLRFProfileMcsRate=cLRFProfileMcsRate, cLRFProfileEntry=cLRFProfileEntry, ciscoLwappRFMIBCompliance=ciscoLwappRFMIBCompliance, cLRFProfileDataRate24Mbps=cLRFProfileDataRate24Mbps, cLRFProfileMulticastDataRate=cLRFProfileMulticastDataRate, PYSNMP_MODULE_ID=ciscoLwappRFMIB, cLRFProfileUtilizationThreshold=cLRFProfileUtilizationThreshold, ciscoLwappRFMIBConform=ciscoLwappRFMIBConform, cLAPGroupsRFProfileEntry=cLAPGroupsRFProfileEntry, cLRFProfileTable=cLRFProfileTable, cLRFProfileDataRate54Mbps=cLRFProfileDataRate54Mbps, ciscoLwappRFMIBGroups=ciscoLwappRFMIBGroups, cLRFProfileDCAChannelWidth=cLRFProfileDCAChannelWidth, cLRFProfileMcsName=cLRFProfileMcsName, cLRFProfileLoadBalancingWindowSize=cLRFProfileLoadBalancingWindowSize, cLRFProfileMcsDataRateTable=cLRFProfileMcsDataRateTable, ciscoLwappRFGlobalConfigGroup=ciscoLwappRFGlobalConfigGroup, ciscoLwappRFConfigGroup1=ciscoLwappRFConfigGroup1, ciscoLwappRFConfigGroup2=ciscoLwappRFConfigGroup2, cLRFProfileBandSelectProbeResponse=cLRFProfileBandSelectProbeResponse, cLRFProfileLoadBalancingDenialCount=cLRFProfileLoadBalancingDenialCount, cLRFProfileCHDVoiceRSSIThreshold=cLRFProfileCHDVoiceRSSIThreshold)
|
def bubble_sort(array):
for i in range(len(array)):
for j in range(len(array) - 1):
if array[j] > array[j + 1]:
array[j], array[j + 1] = array[j + 1], array[j]
|
class FilePathSimilarityCalculator:
"""
This class handles file path similarity score calculating operations.
"""
@staticmethod
def path_separator(file_string):
return file_string.split("/")
def longest_common_prefix_similarity(self, file1, file2):
file1 = self.path_separator(file1)
file2 = self.path_separator(file2)
common_file_path = 0
min_length = min(len(file1), len(file2))
for i in range(min_length):
if file1[i] == file2[i]:
common_file_path += 1
else:
break
return common_file_path
def longest_common_suffix_similarity(self, file1, file2):
file1 = self.path_separator(file1)
file2 = self.path_separator(file2)
common_file_path = 0
rng = range(min(len(file1), len(file2)))
rng = reversed(rng)
for i in rng:
if file1[i] == file2[i]:
common_file_path += 1
else:
break
return common_file_path
def longest_common_sub_string_similarity(self, file1, file2):
file1 = self.path_separator(file1)
file2 = self.path_separator(file2)
common_file_path = 0
if len(set(file1) & set(file2)) > 0:
matrix = [[0 for x in range(len(file2) + 1)] for x in range(len(file1) + 1)]
for i in range(len(file1) + 1):
for j in range(len(file2) + 1):
if i == 0 or j == 0:
matrix[i][j] = 0
elif file1[i - 1] == file2[j - 1]:
matrix[i][j] = matrix[i - 1][j - 1] + 1
common_file_path = max(common_file_path, matrix[i][j])
else:
matrix[i][j] = 0
return common_file_path
def longest_common_sub_sequence_similarity(self, file1, file2):
file1 = self.path_separator(file1)
file2 = self.path_separator(file2)
common_file_path = 0
if len(set(file1) & set(file2)) > 0:
lst = [[0 for x in range(len(file2) + 1)] for x in range(len(file1) + 1)]
for i in range(len(file1) + 1):
for j in range(len(file2) + 1):
if i == 0 or j == 0:
lst[i][j] = 0
elif file1[i - 1] == file2[j - 1]:
lst[i][j] = lst[i - 1][j - 1] + 1
else:
lst[i][j] = max(lst[i - 1][j], lst[i][j - 1])
common_file_path = lst[len(file1)][len(file2)]
return common_file_path
@staticmethod
def add_file_path_similarity_ranking(data_frame):
data_frame["file_path_rank"] = data_frame["file_similarity"].rank(method='min', ascending=False)
|
n=int(input())
if n<3:
print("NO")
else:
a=[]
b=[]
asum=0
bsum=0
for i in range(n,0,-1):
if asum<bsum:
asum+=i
a.append(i)
else:
bsum+=i
b.append(i)
if asum==bsum:
print("YES")
print(len(a))
print(' '.join(map(str,a)))
print(len(b))
print(' '.join(map(str,b)))
else:
print("NO") |
DESCRIPTION = "sets a variable for the current module"
def autocomplete(shell, line, text, state):
# todo, here we can provide some defaults for bools/enums? i.e. True/False
if len(line.split(" ")) >= 3:
return None
env = shell.plugins[shell.state]
options = [x.name + " " for x in env.options.options if x.name.upper().startswith(text.upper()) and not x.hidden]
options += [x.alias + " " for x in env.options.options if x.alias.upper().startswith(text.upper()) and not x.hidden and x.alias]
try:
return options[state]
except:
return None
def help(shell):
pass
def execute(shell, cmd):
env = shell.plugins[shell.state]
splitted = cmd.split(" ")
if len(splitted) >= 2:
key = splitted[1].upper()
value = env.options.get(key)
if value != None:
# if it's >=3, we set the third argument
if len(splitted) >= 3:
value = " ".join(splitted[2:])
if not env.options.set(key, value):
shell.print_error("That value is invalid")
return
shell.print_good("%s => %s" % (key, value))
else:
shell.print_error("Option '%s' not found." % (key))
|
"""
RSA Private/Public Key Parameters
----------------------------------
KEY_BIT_SIZE: bit size of keys
e: exponent
"""
KEY_BIT_SIZE = 4000
e = int("""130499359017053281556458431345533123778363781651270565436082977439613579949
5471732291742574936464294335429130852137501781519767363426995264206489
9070346494524853207171672967384456879272614309142468488188894961980326
4210652869136872341373046618500443845129257644095534241153647067619323
000920769040063242820133""".replace(" ", "").replace("\n", ""))
"""
Diffie Hellman Public keys
----------------------------------
g: generator
p: prime
"""
g = int("""9677178152764243356585979556264224589944191744979699073371576738861236
5663820546922607619786124954900448084138704336019707101781113070799068
5744514558595068941725067952556006237862391064159647193542530329259333
4424851756939418426847120076462424229265080004033026690789716709345894
8676163784692008959171172634206184380581278989999081666391528267108503
9813609522242829719587993249808317734238106660385861768230295679126590
8390972444782203928717828427457583267560097495187522617809715033399571
0124142927808606451916188467080375525692807503004072582957175996256741
6958199028585508053574180142683126826804771118716296486230523760774389
7157494791542352379311268259974895147341335235499016003307513390038990
1582196141853936279863966997543171337135092681583084518153432642302837
0436056697857918994988629688023563560002153140124962200937852164145182
1610847931627295268929335901602846813690082539801509776517015975714046
5455848263618069464889478247144935435822126939965077545376582476552939
5288811662441509565199205733657279155210616750060391443188845224391244
5982465119470715706942563826139640100216780957119233780885476576542097
8318327126238727841787217270826207296485682133095572761510633060271315""".replace(" ", "").replace("\n", ""))
p = int("""2773513095749167337576358874942831569385761553923082020361322269992944
8489006798120232791463013505228500900024049333039459029366992215417394
0703109337560451078293297821188778260938274928421790028940882569457077
8270715497001472804773372159699487464437256876108641279314813575799288
0353560828726390302647822163531592190925834713707675874151479095828997
9709275760692869280803757520668776451222054720062078905947201506921948
2248258148634825249349597280042484353178956233483223727571140311838306
9497997993896536595853659564600179648675284862073335665278820295284039
2441154268228992660874384047813295938635270043470524847835602162062324
6182957756186469188241103927864116660349640671385022766484753851141361
3324705366794734356249759513986782234719409680441184269264165474240174
7019497972779105025866714266206768504640255640079527841905839126323963
3600041551667467165519541808705130094613958692430907777974227738480151
9284479867895217795687886082284763600753200413473134257852188910038101
0022934537091672256327978299054218233790927484338926431601990283936699
4034965244475466733634646851920984543901636177633543005383561910647171
8158178526713140623881625988429186051133467385983636059069118372099145
33050012879383""".replace(" ", "").replace("\n", ""))
|
class When_we_have_a_test:
def when_things_happen(self):
pass
def it_should_do_this_test(self):
assert 1 == 1
def test_we_still_run_regular_pytest_scripts():
assert 2 == 2
|
# -*- coding:utf-8-*-
stop = ""
print("欢迎来到贝拉贝拉电影院")
stop_1 = 0
stop_2 = ""
while stop_1 < 5:
stop = raw_input("请问您的年龄是?")
stop_1 = stop_1 + 1
stop_2 = stop
if stop_2 == "q!":
break
else:
if int(stop) < 3:
z = 3
elif int(stop) < 13:
z = 10
elif int(stop) < 100:
z = 15
print("您的年龄所对应的票价是: " + str(z))
|
######################## Errors ##########################
PAYLOAD_NOT_FOUND_ERROR = 'Payload can not be found.'
KEYWORD_NOT_FOUND_ERROR = "Keywords can to be empty."
TYPE_NOT_CORRECT_ERROR = 'Payload type is incorrect, please upload text.'
MODEL_NOT_FOUND_ERROR = 'The ML model not found. (default name: en_core_web_sm)'
DATA_MODEL_ERROR = 'Data model, text or source ML model has some problems, please check.' |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
This is Webmention tools!
"""
__version__ = '0.4.1'
|
class Solution:
def findLengthOfLCIS(self, nums: List[int]) -> int:
if not nums:
return 0
dp = [1] * len(nums)
if len(nums) < 2:
return 1
result = 1
for i in range(1, len(nums)):
if nums[i] > nums[i - 1]:
dp[i] = dp[i - 1] + 1
result = max(result, dp[i])
return result |
class Symbol:
key = '#'
author = '@'
goto = '>'
condition = '?'
action = '!'
comment = '%'
left = '{'
right = '}'
def prefixcount(string, prefix):
i = 0
while string[i] == prefix:
i += 1
return i
def extract(string, startsymbol, endsymbol):
if not startsymbol in string and endsymbol in string:
return ('', string)
start = string.find(startsymbol) + len(startsymbol)
end = -1
depth = 0
for i in range(start, len(string)):
s = string[i:]
if not depth and s.startswith(endsymbol):
end = i
break
depth += s.startswith(Symbol.left)
depth -= s.startswith(Symbol.right)
if end == -1:
return ('', string)
extraction = string[start:end]
return (extraction, string.replace(startsymbol + extraction + endsymbol, ''))
def extractattribute(string, symbol):
return extract(string, symbol + Symbol.left, Symbol.right)
def extractkey(string):
return extractattribute(string, Symbol.key)[0]
def isempty(string):
return string == '' or string.isspace()
class Line:
def __init__(self, key, text='', author='', goto='', choices=[], condition='', action='', comment=''):
self.key = key
self.text = text
self.author = author
self.goto = goto
self.choices = choices
self.condition = condition
self.action = action
self.comment = comment
def __repr__(self) -> str:
return self.author + ': ' + self.text
class Talk:
def __init__(self):
self.lines = {}
self.key = ''
@staticmethod
def fromString(talkString):
talk = Talk()
while '\\\n\t' in talkString:
talkString = talkString.replace('\\\n\t', '\\\n')
while '\\\n' in talkString:
talkString = talkString.replace('\\\n', '')
lines = [line for line in talkString.splitlines() if not isempty(line)]
for i, line in enumerate(lines):
if isempty(extractkey(line)):
lines[i] = line + Symbol.key + Symbol.left + Symbol.key + str(i) + Symbol.right
previousauthor = ''
for i, line in enumerate(lines):
choices = []
goto, text = extractattribute(line, Symbol.goto)
if isempty(goto):
tabs_i = prefixcount(line, '\t')
if tabs_i % 2 == 0:
tabs_min = tabs_i
for j in range(i + 1, len(lines)):
tabs_j = prefixcount(lines[j], '\t')
tabs_min = min(tabs_j, tabs_min)
if tabs_j <= tabs_min:
if choices:
break
if tabs_j % 2 == 0:
goto = extractkey(lines[j])
break
if tabs_j == tabs_i + 1:
choices.append(extractkey(lines[j]))
elif i + 1 < len(lines):
goto = extractkey(lines[i + 1])
key, text = extractattribute(text, Symbol.key)
author, text = extractattribute(text, Symbol.author)
condition, text = extractattribute(text, Symbol.condition)
action, text = extractattribute(text, Symbol.action)
comment, text = extractattribute(text, Symbol.comment)
talk.addLine(Line(
key,
text = text.strip(),
author = author if not isempty(author) else previousauthor,
goto = goto,
choices = choices,
condition = condition,
action = action,
comment = comment
))
if i == 0:
talk.key = key
previousauthor = author
return talk
def addLine(self, line: Line):
self.lines[line.key] = line
def talk(self):
string = ''
line = self.lines[self.key]
while isempty(line.text):
self.key = line.goto
line = self.lines[self.key]
string += str(line) + '\n'
choices = [l for l in self.lines.values() if l.key in line.choices]
if choices:
for i, choice in enumerate(choices):
string += str(i) + ' ' + str(choice) + '\n'
return string
def input(self, string):
line = self.lines[self.key]
choices = [l.key for l in self.lines.values() if l.key in line.choices]
if choices:
try:
self.key = choices[int(string)]
except:
self.key = choices[0]
else:
self.key = line.goto
|
#value=input().split()
#B,G=value
#B=int(B) #B=ball
#G=int(G) #G=need
B=int(input())
G=int(input())
result = G//2
also_need=result-B
if (result<=B):
print("Amelia tem todas bolinhas!")
else:
print("Faltam",also_need,"bolinha(s)") |
def GenerateCombination(N, ObjectNumber):
# initiate the object B and C positions
# Get all permutations of length 2
combinlist = []
for i in range(N):
if i < N-1:
j = i + 1
else:
j = 0
combin = [ObjectNumber, i, j]
combinlist.append(combin)
return combinlist
|
class OTBDeepConfig:
fhog_params = {'fname': 'fhog',
'num_orients': 9,
'cell_size': 4,
'compressed_dim': 10,
# 'nDim': 9 * 3 + 5 -1
}
#cn_params = {"fname": 'cn',
# "table_name": "CNnorm",
# "use_for_color": True,
# "cell_size": 4,
# "compressed_dim": 3,
# # "nDim": 10
# }
# ic_params = {'fname': 'ic',
# "table_name": "intensityChannelNorm6",
# "use_for_color": False,
# "cell_size": 4,
# "compressed_dim": 3,
# # "nDim": 10
# }
cnn_params = {'fname': "cnn-resnet50",
'compressed_dim': [16, 64]
}
# cnn_params = {'fname': "cnn-vgg16",
# 'compressed_dim': [16, 64]
# }
features = [fhog_params, cnn_params]
# feature parameters
normalize_power = 2
normalize_size = True
normalize_dim = True
square_root_normalization = False
# image sample parameters
search_area_shape = 'square'
search_area_scale = 4.5
min_image_sample_size = 200 ** 2
max_image_sample_size = 250 ** 2
# detection parameters
refinement_iterations = 1 # number of iterations used to refine the resulting position in a frame
newton_iterations = 5
clamp_position = False # clamp the target position to be inside the image
# learning parameters
output_sigma_factor = 1 / 8. # label function sigma
learning_rate = 0.010
num_samples = 50
sample_replace_startegy = 'lowest_prior'
lt_size = 0
train_gap = 5
skip_after_frame = 1
use_detection_sample = True
# factorized convolution parameters
use_projection_matrix = True
update_projection_matrix = True
proj_init_method = 'pca'
projection_reg = 5e-8
# generative sample space model parameters
use_sample_merge = True
sample_merge_type = 'merge'
distance_matrix_update_type = 'exact'
# CG paramters
CG_iter = 5
init_CG_iter = 15 * 15
init_GN_iter = 15
CG_use_FR = False
CG_standard_alpha = True
CG_forgetting_rate = 75
precond_data_param = 0.3
precond_reg_param= 0.015
precond_proj_param = 35
# regularization window paramters
use_reg_window = True
reg_window_min = 1e-4
reg_window_edge = 10e-3
reg_window_power = 2
reg_sparsity_threshold = 0.05
# interpolation parameters
interp_method = 'bicubic'
interp_bicubic_a = -0.75
interp_centering = True
interp_windowing = False
# scale parameters
number_of_scales = 5
scale_step = 1.02# 1.015
use_scale_filter = False
vis=True |
DECOY_PREFIX = 'decoy_'
HEADER_SPECFILE = '#SpecFile'
HEADER_SCANNR = 'ScanNum'
HEADER_SPECSCANID = 'SpecID'
HEADER_CHARGE = 'Charge'
HEADER_PEPTIDE = 'Peptide'
HEADER_PROTEIN = 'Protein'
HEADER_GENE = 'Gene ID'
HEADER_SYMBOL = 'Gene Name'
HEADER_DESCRIPTION = 'Description'
HEADER_PRECURSOR_MZ = 'Precursor'
HEADER_PRECURSOR_QUANT = 'MS1 area'
HEADER_PREC_PURITY = 'Precursor ion fraction'
HEADER_PRECURSOR_FWHM = 'FWHM'
HEADER_MASTER_PROT = 'Master protein(s)'
HEADER_PG_CONTENT = 'Protein group(s) content'
HEADER_PG_AMOUNT_PROTEIN_HITS = 'Amount of matching proteins in group(s)'
HEADER_PG = [HEADER_MASTER_PROT, HEADER_PG_CONTENT,
HEADER_PG_AMOUNT_PROTEIN_HITS]
HEADER_SVMSCORE = 'percolator svm-score'
HEADER_MISSED_CLEAVAGE = 'missed_cleavage'
HEADER_PSMQ = 'PSM q-value'
HEADER_PEPTIDE_Q = 'peptide q-value'
HEADER_TARGETDECOY = 'TD'
HEADER_MSGFSCORE = 'MSGFScore'
HEADER_EVALUE = 'EValue'
HEADER_SETNAME = 'Biological set'
HEADER_RETENTION_TIME = 'Retention time(min)'
HEADER_INJECTION_TIME = 'Ion injection time(ms)'
HEADER_ION_MOB = 'Ion mobility(Vs/cm2)'
MOREDATA_HEADER = [HEADER_RETENTION_TIME, HEADER_INJECTION_TIME, HEADER_ION_MOB]
PERCO_HEADER = [HEADER_SVMSCORE, HEADER_PSMQ, HEADER_PEPTIDE_Q, HEADER_TARGETDECOY]
|
# The path to the ROM file to load:
# SpaceInvaders starts to render visible pixels when
# the cpu halfClkCount reaches about 11000
#romFile = 'roms/SpaceInvaders.bin'
#romFile = 'roms/Pitfall.bin'
romFile = 'roms/DonkeyKong.bin'
# 8kb ROM, spins reading 0x282 switches
#romFile = 'roms/Asteroids.bin'
# 2kb ROM
#romFile = 'roms/Adventure.bin'
#romFile = 'roms/SpaceInvaders.bin'
imageOutputDir = 'outFrames'
# Files describing each chip's network of transistors and wires.
# Also contains names for various wires, some of which are the
# chips input and output pads.
#
chip6502File = 'chips/net_6502.pkl'
chipTIAFile = 'chips/net_TIA.pkl'
# How many simulation clock changes to run between updates
# of the OpenGL rendering.
numTIAHalfClocksPerRender = 128
# If you'd like to provide additional common sense names for
# a chip's wires, data like the following can be provided to
# CircuitSimulatorBase.updateWireNames(arrayOfArrays) which
# sets entries in the wireNames dictionary like:
# wireNames['A0'] = 737; wireNames['A1'] = 1234
# wireNames['X3'] = 1648
#
# The node numbers are listed in the status pane of the
# visual6502.org simulation when you left-click the chip
# image to select part of the circuit:
# http://visual6502.org/JSSim
# The 6502 chip data, node numbers, and names are the same
# here in this 2600 console simulation as they are in the
# visual6502 online javascript simulation.
#
# # A, X, and Y register bits from lsb to msb
mos6502WireInit = [['A', 737, 1234, 978, 162, 727, 858, 1136, 1653],
['X', 1216, 98, 1, 1648, 85, 589, 448, 777],
['Y', 64, 1148, 573, 305, 989, 615, 115, 843],
# stack. only low address has to be stored
['S', 1403, 183, 81, 1532, 1702, 1098, 1212, 1435],
# Program counter low byte, from lsb to msb
['PCL', 1139, 1022, 655, 1359, 900, 622, 377, 1611],
# Program counter high byte, from lsb to msb
['PCH', 1670, 292, 502, 584, 948, 49, 1551, 205],
# status register: C,Z,I,D,B,_,V,N (C is held in LSB)
# 6502 programming manual pgmManJan76 pg 24
['P', 687, 1444, 1421, 439, 1119, 0, 77, 1370],
]
scanlineNumPixels = 228 # for hblank and visible image
frameHeightPixels = 262 # 3 lines vsync, 37 lines vblank,
# 192 lines of image, 30 lines overscan
# The order in which these are listed matters. For busses, they should
# be from lsb to msb.
tiaAddressBusPadNames = ['AB0', 'AB1', 'AB2', 'AB3', 'AB4', 'AB5']
cpuAddressBusPadNames = ['AB0', 'AB1', 'AB2', 'AB3', 'AB4', 'AB5', 'AB6', 'AB7',
'AB8', 'AB9', 'AB10', 'AB11', 'AB12', 'AB13', 'AB14', 'AB15']
tiaInputPadNames = ['I0', 'I1', 'I2', 'I3', 'I4', 'I5']
dataBusPadNames = ['DB0', 'DB1', 'DB2', 'DB3', 'DB4', 'DB5', 'DB6', 'DB7']
tiaDataBusDrivers = ['DB6_drvLo', 'DB6_drvHi', 'DB7_drvHi', 'DB7_drvHi']
|
# https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/
# Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
#
# Find all the elements of [1, n] inclusive that do not appear in this array.
#
# Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.
class Solution(object):
# TimeLimitExceeded
def findDisappearedNumbers1(self, nums):
totalNums = [val for val in range(1,len(nums) + 1)]
return [val for val in totalNums if val not in set(nums)]
# TimeLimitExceeded
def findDisappearedNumbers2(self, nums):
out = [] # output list
for i in range(len(nums)):
if (i+1) not in nums:
out.append(i+1)
return out
def findDisappearedNumbers3(self, nums):
return list(set([i for i in range(1, len(nums) + 1)]) - set(nums))
|
def setStringLength(string,length,align:"left"):
"""
:param string: A str which is you want to set length
:param length: Integer
:param align: left, mid or right
:return:
"""
real_str_len=len(string)
if real_str_len<length:
if align=="left":
text_which_add=""
for i in range(0,length-real_str_len):
text_which_add += " "
return string + text_which_add
elif align=="right":
text_which_add = ""
for i in range(0, length - real_str_len):
text_which_add += " "
return text_which_add + string
elif align=="mid":
left_text=""
rigth_text=""
for i in range(0, (length - real_str_len)):
if i%2==0:
left_text += " "
elif i%2==1:
rigth_text += " "
return left_text + string + rigth_text
if align not in ("left", "mid", "right"):
print("Align must be \"left\", \"mid\" or \"right\" !!")
return
elif real_str_len>length:
if align=="left":
return string[0:length]
elif align=="right":
return string[-(length):]
elif align=="mid":
mid_index_of_text=int(real_str_len/2)
if length%2==0:
left_length=int(length/2)
rigth_length=int(length/2)
elif length%2==1:
left_length=int(length/2)+1
rigth_length=int(length/2)
var_x=int(mid_index_of_text-left_length+1)
var_y=int(mid_index_of_text+rigth_length+1)
return string[var_x:var_y]
if not align in ("left", "mid", "right"):
print("Align must be \"left\", \"mid\" or \"right\" !!")
return
def addCharOnString(string,char,amount,type:"pre-post"):
"""
:param string: Text is which you want to add smth pre, post or both
:param char: Must be just one character
:param amount: int
:param type: pre, post, pre-post
:return:
"""
if type not in ("pre","post","pre-post"):
print("Type must be \"pre\", \"post\" or \"pre-post\" !!")
return
if not len(char)==1:
print("Lenght of char must be 1")
text_which_add=""
for i in range(0,amount):
text_which_add += f"{char}"
if type == "pre":
return text_which_add+string
elif type == "post":
return string+text_which_add
elif type == "pre-post":
return text_which_add+string+text_which_add
|
# 全排列
def dfs(u):
# 说明走到头了,该输出了
if u == n:
for i in range(n):
print(path[i], end=" ")
print()
for i in range(1, n + 1):
if not st[i]: # 如果这个点没有被用过
path[u] = i
st[i] = True
dfs(u + 1)
st[i] = False # 恢复现场
N = 10
path, st = [0] * N, [False] * N
n = int(input())
dfs(0)
|
class RegionModel:
def __init__(self, dbRow):
self.ID = dbRow["ID"]
self.RegionName = dbRow["RegionName"]
self.RegionCode = dbRow["RegionCode"]
self.RegionChat = dbRow["RegionChat"] |
def test_correct_abi_right_padding(tester, w3, get_contract_with_gas_estimation):
selfcall_code_6 = """
@external
def hardtest(arg1: Bytes[64], arg2: Bytes[64]) -> Bytes[128]:
return concat(arg1, arg2)
"""
c = get_contract_with_gas_estimation(selfcall_code_6)
assert c.hardtest(b"hello" * 5, b"hello" * 10) == b"hello" * 15
# Make sure underlying structe is correctly right padded
classic_contract = c._classic_contract
func = classic_contract.functions.hardtest(b"hello" * 5, b"hello" * 10)
tx = func.buildTransaction({
"gasPrice": 0,
})
del tx["chainId"]
del tx["gasPrice"]
tx["from"] = w3.eth.accounts[0]
res = w3.toBytes(hexstr=tester.call(tx))
static_offset = int.from_bytes(res[:32], "big")
assert static_offset == 32
dyn_section = res[static_offset:]
assert len(dyn_section) % 32 == 0 # first right pad assert
len_value = int.from_bytes(dyn_section[:32], "big")
assert len_value == len(b"hello" * 15)
assert dyn_section[32 : 32 + len_value] == b"hello" * 15
# second right pad assert
assert dyn_section[32 + len_value :] == b"\x00" * (len(dyn_section) - 32 - len_value)
|
def primera_letra(lista_de_palabras):
primeras_letras = []
for palabra in lista_de_palabras:
assert type(palabra) == str, f'{palabra} no es str'
assert len(palabra) > 0, 'No se permiten str vacios'
primeras_letras.append(palabra[0])
return primeras_letras |
load("@bazel_skylib//lib:paths.bzl", "paths")
load(":common.bzl", "declare_caches", "write_cache_manifest")
load("//dotnet/private:context.bzl", "dotnet_exec_context", "make_builder_cmd")
load("//dotnet/private:providers.bzl", "DotnetPublishInfo")
def pack(ctx):
info = ctx.attr.target[DotnetPublishInfo]
restore = info.restore
dotnet = dotnet_exec_context(ctx, False, False, restore.target_framework)
package_id = getattr(ctx.attr, "package_id", None)
if not package_id:
package_id = paths.split_extension(ctx.file.project_file.basename)[0]
nupkg = ctx.actions.declare_file(package_id + "." + ctx.attr.version + ".nupkg")
cache = declare_caches(ctx, "pack")
cache_manifest = write_cache_manifest(ctx, cache, info.caches)
args, cmd_outputs = make_builder_cmd(ctx, dotnet, "pack", restore.directory_info, restore.assembly_name)
args.add_all(["--version", ctx.attr.version, "--runfiles_manifest", info.runfiles_manifest])
inputs = depset(
[cache_manifest, info.runfiles_manifest],
transitive = [info.files, info.library.runfiles],
)
outputs = [nupkg, cache.result] + cmd_outputs
ctx.actions.run(
mnemonic = "DotnetPack",
inputs = inputs,
outputs = outputs,
executable = dotnet.sdk.dotnet,
arguments = [args],
env = dotnet.env,
tools = dotnet.builder.files,
)
return nupkg
|
'''
FISCO BCOS/Python-SDK is a python client for FISCO BCOS2.0 (https://github.com/FISCO-BCOS/)
FISCO BCOS/Python-SDK is free software: you can redistribute it and/or modify it under the
terms of the MIT License as published by the Free Software Foundation. This project is
distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. Thanks for
authors and contributors of eth-abi, eth-account, eth-hash,eth-keys, eth-typing, eth-utils,
rlp, eth-rlp , hexbytes ... and relative projects
@file: consensus_precompile.py
@function:
@author: yujiechen
@date: 2019-07
'''
class PrecompileCommon:
"""
define common values related to precompile
"""
SYS_TABLE = "_sys_tables_"
USER_TABLE_PREFIX = "_user_"
SYS_TABLE_ACCESS = "_sys_table_access_"
SYS_CONSENSUS = "_sys_consensus_"
SYS_CNS = "_sys_cns_"
SYS_CONFIG = "_sys_config_"
# define the error information
error_code = {}
error_code["-50000"] = "PermissionPrecompiled: Permission Denied"
error_code["-50001"] = "CRUD: Table Exist"
error_code["-51502"] = "CRUD: Undefined operator"
error_code["-51501"] = "CRUD: Parse condition error"
error_code["-51500"] = "CRUD: Parse Entry error"
error_code["-51000"] = "PermissionPrecompiled: Already Granted"
error_code["-51001"] = "PermissionPrecompiled: TableName And Account Not Exist"
error_code["-51100"] = "Invalid NodeId"
error_code["-51101"] = "Last Sealer"
error_code["-51102"] = "P2p Network"
error_code["-51103"] = "Group Peers"
error_code["-51104"] = "Sealer List"
error_code["-51105"] = "Observer List"
error_code["-51200"] = "CNS: ContractNameAndVersion Exist"
error_code["-51201"] = "CNS: Version Exceeds"
error_code["-51300"] = "SysConfig: Invalid Key, must be tx_gas_limit or tx_count_limit"
|
numbers = [value**3 for value in range(1,11)]
for number in numbers:
print(number)
#value不能用,局部变量 |
#===============================================================
# DMXIS Macro (c) 2010 db audioware limited
#===============================================================
RgbColour(255,127,80)
|
def remote_pip_install_simple(name, silent):
return remote_pip_install(name, True, 'python3', 'pip3', silent)
def remote_pip_install(name, usermode, py, pip, silent):
return lib_install(name, usermode=usermode, py=py, pip=pip, silent=silent)
|
class RandomObjects:
prefix = ''
postfix = ''
def __init__(self):
self.displacements = {}
self.velocities = {}
self.accelerations = {}
self.load_vectors = {}
self.spc_forces = {}
self.mpc_forces = {}
self.crod_force = {}
self.conrod_force = {}
self.ctube_force = {}
self.cbar_force = {}
self.cbeam_force = {}
self.cbush_stress = {}
self.cbush_strain = {}
self.crod_stress = {}
self.conrod_stress = {}
self.ctube_stress = {}
self.cbar_stress = {}
self.cbeam_stress = {}
self.crod_strain = {}
self.conrod_strain = {}
self.ctube_strain = {}
self.cbar_strain = {}
self.cbeam_strain = {}
self.ctetra_strain = {}
self.cpenta_strain = {}
self.chexa_strain = {}
self.ctetra_stress = {}
self.cpenta_stress = {}
self.chexa_stress = {}
self.celas1_stress = {}
self.celas2_stress = {}
self.celas3_stress = {}
self.celas4_stress = {}
self.celas1_strain = {}
self.celas2_strain = {}
self.celas3_strain = {}
self.celas4_strain = {}
self.celas1_force = {}
self.celas2_force = {}
self.celas3_force = {}
self.celas4_force = {}
self.ctria3_force = {}
self.ctria6_force = {}
self.ctriar_force = {}
self.cquad4_force = {}
self.cquad8_force = {}
self.cquadr_force = {}
self.ctria3_stress = {}
self.ctria6_stress = {}
self.cquad4_stress = {}
self.cquad8_stress = {}
self.cquadr_stress = {}
self.ctriar_stress = {}
self.ctria3_strain = {}
self.ctria6_strain = {}
self.cquad4_strain = {}
self.cquad8_strain = {}
self.cquadr_strain = {}
self.ctriar_strain = {}
self.cbend_stress = {}
self.cbend_strain = {}
self.cbend_force = {}
self.cshear_stress = {}
self.cshear_strain = {}
self.cshear_force = {}
self.cbush_force = {}
self.cdamp1_force = {}
self.cdamp2_force = {}
self.cdamp3_force = {}
self.cdamp4_force = {}
self.cvisc_force = {}
self.cquad4_composite_stress = {}
self.cquad8_composite_stress = {}
self.cquadr_composite_stress = {}
self.ctria3_composite_stress = {}
self.ctria6_composite_stress = {}
self.ctriar_composite_stress = {}
self.cquad4_composite_strain = {}
self.cquad8_composite_strain = {}
self.cquadr_composite_strain = {}
self.ctria3_composite_strain = {}
self.ctria6_composite_strain = {}
self.ctriar_composite_strain = {}
def get_table_types(self):
tables = [
'displacements', 'velocities', 'accelerations',
'load_vectors', 'spc_forces', 'mpc_forces',
'celas1_force', 'celas2_force', 'celas3_force', 'celas4_force',
'crod_force', 'conrod_force', 'ctube_force',
'cbar_force', 'cbeam_force',
'cquad4_force', 'cquad8_force', 'cquadr_force',
'ctria3_force', 'ctria6_force', 'ctriar_force',
'celas1_stress', 'celas2_stress', 'celas3_stress', 'celas4_stress',
'crod_stress', 'conrod_stress', 'ctube_stress',
'cbar_stress', 'cbeam_stress',
'ctria3_stress', 'ctriar_stress', 'ctria6_stress',
'cquadr_stress', 'cquad4_stress', 'cquad8_stress',
'ctetra_stress', 'cpenta_stress', 'chexa_stress',
'celas1_strain', 'celas2_strain', 'celas3_strain', 'celas4_strain',
'crod_strain', 'conrod_strain', 'ctube_strain',
'cbar_strain', 'cbeam_strain',
'ctria3_strain', 'ctriar_strain', 'ctria6_strain',
'cquadr_strain', 'cquad4_strain', 'cquad8_strain',
'ctetra_strain', 'cpenta_strain', 'chexa_strain',
'cquad4_composite_stress', 'cquad8_composite_stress', 'cquadr_composite_stress',
'ctria3_composite_stress', 'ctria6_composite_stress', 'ctriar_composite_stress',
'cquad4_composite_strain', 'cquad8_composite_strain', 'cquadr_composite_strain',
'ctria3_composite_strain', 'ctria6_composite_strain', 'ctriar_composite_strain',
'cbend_stress', 'cbend_strain', 'cbend_force',
'cbush_stress', 'cbush_strain',
'cshear_stress', 'cshear_strain', 'cshear_force',
'cbush_force',
'cdamp1_force', 'cdamp2_force', 'cdamp3_force', 'cdamp4_force',
'cvisc_force',
]
return [self.prefix + table + self.postfix for table in tables]
class AutoCorrelationObjects(RandomObjects):
"""storage class for the ATO objects"""
prefix = 'ato.'
#postfix = ''
class PowerSpectralDensityObjects(RandomObjects):
"""storage class for the PSD objects"""
prefix = 'psd.'
#postfix = ''
class RootMeansSquareObjects(RandomObjects):
"""storage class for the RMS objects"""
prefix = 'rms.'
#postfix = ''
class CumulativeRootMeansSquareObjects(RandomObjects):
"""storage class for the CRMS objects"""
prefix = 'crm.'
#postfix = ''
class NumberOfCrossingsObjects(RandomObjects):
"""storage class for the NO objects"""
prefix = 'no.'
#postfix = ''
class RAECONS:
"""storage class for the RAECONS objects"""
def __init__(self):
self.ctria3_strain = {}
self.cquad4_strain = {}
self.chexa_strain = {}
def get_table_types(self):
tables = [
'chexa_strain',
'ctria3_strain', 'cquad4_strain',
]
return ['RAECONS.' + table for table in tables]
class RASCONS:
"""storage class for the RASCONS objects"""
def __init__(self):
self.ctetra_stress = {}
self.cpenta_stress = {}
self.chexa_stress = {}
self.ctetra_strain = {}
self.cpenta_strain = {}
self.chexa_strain = {}
self.ctria3_stress = {}
self.ctria6_stress = {}
self.cquad4_stress = {}
self.cquad8_stress = {}
self.cquadr_stress = {}
self.ctriar_stress = {}
self.ctria3_strain = {}
self.ctria6_strain = {}
self.cquad4_strain = {}
self.cquad8_strain = {}
self.cquadr_strain = {}
self.ctriar_strain = {}
def get_table_types(self):
tables = [
# OES - isotropic CTRIA3/CQUAD4 stress
'ctria3_stress', 'ctriar_stress', 'ctria6_stress',
'cquadr_stress', 'cquad4_stress', 'cquad8_stress',
# OES - isotropic CTRIA3/CQUAD4 strain
'ctria3_strain', 'ctriar_strain', 'ctria6_strain',
'cquadr_strain', 'cquad4_strain', 'cquad8_strain',
'ctetra_stress', 'chexa_stress', 'cpenta_stress',
'ctetra_strain', 'chexa_strain', 'cpenta_strain',
]
return ['RASCONS.' + table for table in tables]
class RAPCONS:
"""storage class for the RAPCONS objects"""
def __init__(self):
self.cquad4_composite_stress = {}
self.cquad8_composite_stress = {}
self.cquadr_composite_stress = {}
self.ctria3_composite_stress = {}
self.ctria6_composite_stress = {}
self.ctriar_composite_stress = {}
def get_table_types(self):
tables = [
'cquad4_composite_stress',
'cquad8_composite_stress',
'cquadr_composite_stress',
'ctria3_composite_stress',
'ctria6_composite_stress',
'ctriar_composite_stress',
#'cquad4_composite_strain',
#'cquad8_composite_strain',
#'cquadr_composite_strain',
#'ctria3_composite_strain',
#'ctria6_composite_strain',
#'ctriar_composite_strain',
]
return ['RAPCONS.' + table for table in tables]
class RAPEATC:
"""storage class for the RAPEATC objects"""
def __init__(self):
self.cquad4_composite_stress = {}
self.cquad8_composite_stress = {}
self.cquadr_composite_stress = {}
self.ctria3_composite_stress = {}
self.ctria6_composite_stress = {}
self.ctriar_composite_stress = {}
def get_table_types(self):
tables = [
'cquad4_composite_stress',
'cquad8_composite_stress',
'cquadr_composite_stress',
'ctria3_composite_stress',
'ctria6_composite_stress',
'ctriar_composite_stress',
#'cquad4_composite_strain',
#'cquad8_composite_strain',
#'cquadr_composite_strain',
#'ctria3_composite_strain',
#'ctria6_composite_strain',
#'ctriar_composite_strain',
]
return ['RAPEATC.' + table for table in tables]
class RAFCONS:
"""storage class for the RAFCONS objects"""
def __init__(self):
self.cbar_force = {}
self.cquad4_force = {}
self.cbush_force = {}
def get_table_types(self):
tables = [
'cbar_force',
'cquad4_force',
'cbush_force',
]
return ['RAFCONS.' + table for table in tables]
class RAGCONS:
"""storage class for the RAGCONS objects"""
def __init__(self):
self.grid_point_forces = {}
def get_table_types(self):
tables = [
'grid_point_forces',
]
return ['RAGCONS.' + table for table in tables]
class RAGEATC:
"""storage class for the RAGEATC objects"""
def __init__(self):
self.grid_point_forces = {}
def get_table_types(self):
tables = [
'grid_point_forces',
]
return ['RAGEATC.' + table for table in tables]
class RANCONS:
"""storage class for the RANCONS objects"""
def __init__(self):
self.cbar_strain_energy = {}
self.cbush_strain_energy = {}
self.chexa_strain_energy = {}
self.ctria3_strain_energy = {}
self.cquad4_strain_energy = {}
def get_table_types(self):
tables = [
'cbar_strain_energy', 'cbush_strain_energy',
'chexa_strain_energy',
'ctria3_strain_energy', 'cquad4_strain_energy',
]
return ['RANCONS.' + table for table in tables]
class RADEFFM:
"""storage class for the RADEFFM objects"""
def __init__(self):
self.eigenvectors = {}
def get_table_types(self):
tables = [
'eigenvectors',
]
return ['RADEFFM.' + table for table in tables]
class RADCONS:
def __init__(self):
self.eigenvectors = {}
def get_table_types(self):
tables = [
'eigenvectors',
]
return ['RADCONS.' + table for table in tables]
class RADEATC:
"""storage class for the RADEATC objects"""
def __init__(self):
self.eigenvectors = {}
def get_table_types(self):
tables = [
'eigenvectors',
]
return ['RADEATC.' + table for table in tables]
class RANEATC:
"""storage class for the RANEATC objects"""
def __init__(self):
self.cbar_strain_energy = {}
self.cbush_strain_energy = {}
self.chexa_strain_energy = {}
self.ctria3_strain_energy = {}
self.cquad4_strain_energy = {}
def get_table_types(self):
tables = [
'cbar_strain_energy', 'cbush_strain_energy',
'chexa_strain_energy',
'ctria3_strain_energy', 'cquad4_strain_energy',
]
return ['RANEATC.' + table for table in tables]
class ROUGV1:
"""storage class for the ROUGV1 objects"""
def __init__(self):
self.displacements = {}
self.velocities = {}
self.accelerations = {}
self.eigenvectors = {}
def get_table_types(self):
tables = [
'displacements', 'velocities', 'accelerations', 'eigenvectors',
]
return ['ROUGV1.' + table for table in tables]
class RAFEATC:
"""storage class for the RAFEATC objects"""
def __init__(self):
self.cbar_force = {}
self.cquad4_force = {}
self.cbush_force = {}
def get_table_types(self):
tables = [
'cbar_force',
'cquad4_force',
'cbush_force',
]
return ['RAFEATC.' + table for table in tables]
class RASEATC:
"""storage class for the RASEATC objects"""
def __init__(self):
self.chexa_stress = {}
self.cquad4_stress = {}
def get_table_types(self):
tables = [
'chexa_stress',
'cquad4_stress',
]
return ['RASEATC.' + table for table in tables]
class RAEEATC:
"""storage class for the RAEEATC objects"""
def __init__(self):
self.chexa_strain = {}
self.ctria3_strain = {}
self.cquad4_strain = {}
def get_table_types(self):
tables = [
'chexa_strain',
'ctria3_strain', 'cquad4_strain',
]
return ['RAEEATC.' + table for table in tables]
|
N = int(input())
hh = 0
mm = 0
ss = 0
count = 0
while not(hh == N and mm == 59 and ss == 59):
# tic toc
ss += 1
if ss == 60:
ss = 0
mm += 1
if mm == 60:
mm = 0
hh += 1
# print(f'{hh}:{mm}:{ss}')
# count
if '3' in str(hh):
count += 1
continue
if '3' in str(mm):
count += 1
continue
if '3' in str(ss):
count += 1
continue
print(count)
'''
<Lesson learned>
완전 탐색의 경우, 대부분 시간 복잡도가 좋지 않다.
따라서 전체 데이터의 개수가 100만 개 이하일때 사용해야 적절하다.
파이썬에서 시간 나타내는 것 저렇게 3중 for문으로 쉽다.
숫자 자리수마다 비교하는것. 파이썬에서는 str로 바꿔서 in 쓰면 쉽다.
<Answer>
h = int(input())
count = 0
for i in range(h + 1):
for j in range(60):
for k in range(60):
if '3' in str(i) + str(j) + str(k):
count += 1
print(count)
''' |
"""
python 是顺序执行的
若遇到函数,则将函数添加到属性中,暂不调用。
等到实际执行的时候,才会寻找函数来调用。
其中,dir()函数的作用是:返回当前范围内的变量、方法和定义的类型列表
举例如下
"""
def test():
print('222')
fun()
print(dir())
# test() # 若在此处调用,则会在打印完222之后报错
def fun():
print('111')
print(dir())
test()
|
# @Title: 快速公交 (快速公交)
# @Author: KivenC
# @Date: 2020-09-13 13:17:50
# @Runtime: 180 ms
# @Memory: 15.3 MB
class Solution:
def busRapidTransit(self, target: int, inc: int, dec: int, jump: List[int], cost: List[int]) -> int:
@functools.lru_cache(None)
def helper(target):
if target == 0:
return 0
if target == 1:
return inc
res = target * inc
for j, c in zip(jump, cost):
res = min(res, helper(target // j) + c + (target % j) * inc)
if target % j > 0:
res = min(res, helper(target // j + 1) + c + (j - target % j) * dec)
return res
return helper(target) % (10 ** 9 + 7)
|
largura = float(input('largura da parede: '))
altura = float(input('altura da parede: '))
area = largura*altura
print('A área da parede é de {}m².\n Sabendo que um 1l de tinta pintam 2m², serão necessários {}l de tinta.'.format(area,area/2))
|
"""
Raise: Sirve para lanzar (de forma intencional) excepciones en Python.
Esto tambien hace que el programa, pare su ejecución como si de un error se tratara.
"""
def evaluar_nota(nota):
if nota < 0:
raise ValueError("No se permiten valores negativos...") # El mensaje es personalizado.
elif nota >= 8:
print("Excelente")
elif nota >= 5:
print("Aprobado")
else:
print("Desaprobado")
evaluar_nota(8)
print("Esta línea se ejecuta?")
|
###########################################
# EXERCICIO 062 #
###########################################
'''MELHORE O DESAFIO EX061, PERGUNTANDO PARA
O USUARIO SE ELE QUER MOSTAR MAIS ALGUNS TERMOS
O PROGRAMA ENCERRA QUANDO ELE DISSER QUE QUER
MOSTRAR 0 TERMOS'''
num = int(input('DIGITE O PRIMEIRO TERMO...:'))
razao = int(input('DIGITE A RAZÃO DA PA ....:'))
termos = int(input('DIGITE NUMERO DE TERMOS....:'))
cont = 0
total = termos
while termos != 0 and termos > cont:
print('{} '.format(num),end='')
num += razao
cont += 1
if cont == termos:
print('PAUSA')
termos = int(input('VOCÊ GOSTARIA DE LISTAR MAIS QUANTOS TERMOS: '))
total += termos
cont = 0
print('\nPROGRAMA FINALIZADO, FOI MOSTRADO {} TERMOS'.format(total))
|
def pytest_addoption(parser):
selenium_class_names = ("Android", "Chrome", "Firefox", "Ie", "Opera", "PhantomJS", "Remote", "Safari")
parser.addoption("--webdriver", action="store", choices=selenium_class_names,
default="PhantomJS",
help="Selenium WebDriver interface to use for running the test. Default: PhantomJS")
parser.addoption("--webdriver-options", action="store", default="{}",
help="Python dictionary of options to pass to the Selenium WebDriver class. Default: {}")
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (c) 2021, Simone Persiani <iosonopersia@gmail.com>
#
# Permission to use, copy, modify, and/or distribute this software for any purpose
# with or without fee is hereby granted, provided that the above copyright notice
# and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
# REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
# FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT,
# OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
# DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
# ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
# SOFTWARE.
# REQUIRED DIRECTORIES
meta_csv_output_dir = '<path>/meta_folder/csv_output/' # INPUT DIR
citations_csv_dir = '<path>/converter_folder/citations/' # INPUT DIR
converter_citations_csv_output_dir = '<path>/citations_folder/csv_output/' # OUTPUT DIR
converter_citations_rdf_output_dir = '<path>/citations_folder/rdf_output/' # OUTPUT DIR
# TRIPLESTORE and OC_OCDM
base_iri = "https://w3id.org/oc/meta/"
triplestore_url = "http://localhost:9999/blazegraph/sparql"
query_timeout = 3 # seconds
context_path = "https://w3id.org/oc/corpus/context.json"
info_dir = "<path>/meta_folder/info_dir/"
dir_split_number = 10000 # This must be multiple of the following one
items_per_file = 1000
default_dir = "_"
resp_agent = "https://w3id.org/oc/meta/prov/pa/1"
supplier_prefix = ""
# OPTIONS
rdf_output_in_chunks = True
|
# Time: O(m * n)
# Space: O(min(m, n))
class Solution(object):
def longestCommonSubsequence(self, text1, text2):
"""
:type text1: str
:type text2: str
:rtype: int
"""
if len(text1) < len(text2):
return self.longestCommonSubsequence(text2, text1)
dp = [[0 for _ in range(len(text2)+1)] for _ in range(2)]
for i in range(1, len(text1)+1):
for j in range(1, len(text2)+1):
dp[i%2][j] = dp[(i-1)%2][j-1]+1 if text1[i-1] == text2[j-1] \
else max(dp[(i-1)%2][j], dp[i%2][j-1])
return dp[len(text1)%2][len(text2)]
|
class FeatureGenerator():
"""
Base class for feature generators
"""
def fit(self, timeseries):
"""
Fit the feature generator
inputs:
timeseries: the timeseries (numpy array) (num_series x series_length)
"""
raise NotImplementedError('FeatureGenerator.fit() not implemented')
def transform(self, timeseries):
"""
Generate features
inputs:
timeseries: the timeseries (numpy array) (num_series x series_length)
"""
raise NotImplementedError('FeatureGenerator.transform() not implemented')
def fit_transform(self, timeseries):
self.fit(timeseries)
return self.transform(timeseries) |
dpi = 400
dpcm = dpi / 2.54
INFTY = float('inf')
PAPER = {
'letter': {
'qr_left': (0.0, 0.882, 0.152, 1.0),
'qr_right': (0.848, 0.882, 1.0, 1.0),
'tick': (0.17, 0.88, 0.91, 1.0),
'uin': (0.49, 0.11, 0.964, 0.54)
}
}
|
'''Soma Simples'''
A = int(input())
B = int(input())
def CalculaSomaSimples(a: int, b: int):
resultado = int(a+b)
return('SOMA = {}'.format(resultado))
print(CalculaSomaSimples(A,B))
|
pkgname = "libgpg-error"
pkgver = "1.43"
pkgrel = 0
build_style = "gnu_configure"
hostmakedepends = ["pkgconf"]
pkgdesc = "Library for error values used by GnuPG components"
maintainer = "q66 <q66@chimera-linux.org>"
license = "LGPL-2.1-or-later"
url = "https://www.gnupg.org"
source = f"{url}/ftp/gcrypt/{pkgname}/{pkgname}-{pkgver}.tar.bz2"
sha256 = "a9ab83ca7acc442a5bd846a75b920285ff79bdb4e3d34aa382be88ed2c3aebaf"
# needs qemu and patching
options = ["!cross"]
def post_install(self):
self.rm(self.destdir / "usr/share/common-lisp", recursive = True)
@subpackage("libgpg-error-devel")
def _devel(self):
return self.default_devel()
@subpackage("libgpg-error-progs")
def _progs(self):
return self.default_progs()
|
class Person:
name = None
age = 0
gender = None
def __init__(self, n, a, g):
self.name = n
self.age = a
self.gender = g
def walk(self):
print('I am walking')
def eat(self):
print('I am eating :)')
def __str__(self): # string representation of the object
return 'name: {}\tage: {}\tgender: {}'.format(self.name, self.age, self.gender)
p1 = Person('Ahmed', 20, 'm')
p2 = Person('Attia', 25, 'm')
p1.walk()
p2.eat()
print(p1)
print(p2)
|
list=input().split()
re=[int(e) for e in input().split()]
new=[]
for i in re:
new.append(list[i])
for l in new:
print(l,end=" ")
|
shopping_list = []
def show_help():
print("Enter the items/amount for your shopping list")
print("Enter DONE once you have completed the list, Enter Help if you require assistance")
def add_to_list(item):
shopping_list.append(item)
print("Added! List has {} items.".format(len(shopping_list)))
def show_list():
print("Here is your list")
for item in shopping_list:
print(item)
show_help()
while True:
new_item = input("item>")
if new_item == 'DONE':
break
elif new_item == 'HELP':
show_help()
continue
elif new_item == 'SHOW':
show_list()
continue
else:
add_to_list(new_item)
continue
show_list() |
# Copyright (c) Microsoft Corporation
# Licensed under the MIT License.
"""Defines the Constant strings related to Error Analysis."""
class ErrorAnalysisDashboardInterface(object):
"""Dictionary properties shared between python and javascript object."""
TREE_URL = "treeUrl"
MATRIX_URL = "matrixUrl"
ENABLE_PREDICT = 'enablePredict'
|
"""
LIST: MINIMUM AND MAXIMUM ITEMS
"""
__author__ = 'Sol Amour - amoursol@gmail.com'
__twitter__ = '@solamour'
__version__ = '1.0.0'
"""
SYNTAX: min(iterable[, key = x])
min = Return the smallest item in an iterable or the smallest of two or more arguments
iterable = An iterable element (Such as a list, tuple, dictionary)
[,key] = An optional 'key' argument to specificy how to find the minimum argument
"""
dataSingle = [ 1, 2, 3, 4, 5 ] # A data list of numbers
dataDouble = [["A", 11], ["B", 7], ["C", 9]] # A data list of lists (Paired alphabetic
# and numeric characters)
minimumItem = min(dataSingle) # Will return the lowest natural sort item of '1'
maximumItem = max(dataSingle) # Will return the highest natural sort item of '5'
minimumItemKey = min(dataDouble, key = lambda d : d[1] ) # Will return the middle pairing of
# '["B", 7]' as we use an anonymous function (Lambda) as our key that simple states we're parsing
# the 'minimum item' based off Index 1 (Our numbers)
maximumItemKey = max(dataDouble, key = lambda d : d[1] ) # Will return the first pairing of
# '["A", 11]' as we use an anonymous function (Lambda) as our key that simple states we're parsing
# the 'maximum item' based off Index 1 (Our numbers)
OUT = minimumItem,maximumItem,minimumItemKey,maximumItemKey
|
def safe_chr(data, oneline=False):
"""Returns a byte or iterable of bytes as ASCII, using ANSI color codes to
represent non-printables. If oneline is set, \n is treated as a special
character, otherwise it is passed through unchanged. The following color
codes are used:
- green 'n': newline
- green 'r': carriage return
- green 't': horizontal tab
- red number: control codes 0 through 9
- red uppercase up to V: control code 10 through 31
- dark gray dot: code 32 (space)
- bright character: code 33 through 126 (printables)
- red 'Y': control code 127
- red '^': code 128 through 255
"""
if not hasattr(data, '__iter__'):
data = [data]
s = ['\033[1m']
for value in data:
if value == ord('\n'):
if oneline:
s.append('\033[32mn')
else:
s.append('\n')
elif value == ord('\r'):
s.append('\033[32mr')
elif value == ord('\t'):
s.append('\033[32mt')
elif value < 10:
s.append('\033[31m%d' % value)
elif value < 32:
s.append('\033[31m%s' % chr(ord('A') + value))
elif value == 32:
s.append('\033[30m·')
elif value < 127:
s.append('\033[37m%s' % chr(value))
elif value == 127:
s.append('\033[31mY')
else:
s.append('\033[31m^')
return ''.join(s) + '\033[0m'
def binary(data, bits, valid=True):
"""Returns a python integer or list of integers as a (concatenated)
std_logic_vector string of the given bitcount per element. If valid is
specified and false, don't-cares are returned instead."""
if not hasattr(data, '__iter__'):
data = [data]
s = []
for value in data:
if valid:
s.append(('{:0%db}' % bits).format(value & (2**bits-1)))
else:
s.append('-' * bits)
return ''.join(s)
def is_std_logic(value):
"""Returns whether the given value is the Python equivalent of an
std_logic."""
return value is True or value is False
def is_unsigned(value, bits):
"""Returns whether the given value is the Python equivalent of an
unsigned with the given length."""
return not (value & ~(2**bits-1))
def is_signed(value, bits):
"""Returns whether the given value is the Python equivalent of an
signed with the given length."""
return value >= -2**(bits-1) and value < 2**(bits-1)
def is_std_logic_vector(value, bits):
"""Returns whether the given value is the Python equivalent of an
std_logic_vector with the given length."""
return value & ~(2**bits-1) in [0, -1]
def is_byte_array(value, count):
"""Returns whether the given value is the Python equivalent of a
byte array."""
return isinstance(value, tuple) and len(value) == count and all(map(lambda x: x >= 0 and x <= 255, value))
|
GET_HOSTS = [
{
'device_id': '00000000000000000000000000000000',
'cid': '11111111111111111111111111111111',
'agent_load_flags': '0',
'agent_local_time': '2021-12-08T15:16:24.360Z',
'agent_version': '6.30.14406.0',
'bios_manufacturer': 'Amazon EC2',
'bios_version': '1.0',
'build_number': '11111',
'config_id_base': '11111111',
'config_id_build': '11111',
'config_id_platform': '1',
'cpu_signature': '111111',
'external_ip': '10.0.0.1',
'mac_address': '00-00-00-00-00-00',
'instance_id': 'i-01',
'service_provider': 'AWS_EC2',
'service_provider_account_id': '000000000000',
'hostname': 'test',
'first_seen': '2022-03-14T04:13:28Z',
'last_seen': '2022-03-15T07:42:07Z',
'local_ip': '10.0.0.1',
'machine_domain': 'example.com',
'major_version': '4',
'minor_version': '14',
'os_version': 'Amazon Linux 2',
'os_build': '241',
'ou': ['test'],
'platform_id': '3',
'platform_name': 'Linux',
'policies': [],
'reduced_functionality_mode': 'no',
'device_policies': {},
'groups': ['00000000000000000000000000000001'],
'group_hash': '0000000000000000000000000000000000000000000000000000000000000000',
'product_type': '3',
'product_type_desc': 'Server',
'provision_status': 'Provisioned',
'serial_number': '00000000-0000-0000-0000-000000000000',
'service_pack_major': '0',
'service_pack_minor': '0',
'pointer_size': '8',
'site_name': 'Default-First-Site-Name',
'status': 'normal',
'system_manufacturer': 'Amazon EC2',
'system_product_name': 't3.small',
'tags': ['SensorGroupingTags/test'],
'modified_timestamp': '2022-03-15T07:42:10Z',
'slow_changing_modified_timestamp': '2022-03-15T06:16:42Z',
'meta': {'version': '6433'},
'zone_group': 'us-east-1a',
'kernel_version': '4.14.241-184.433.amzn2.x86_64',
},
]
|
# *****************************************************************************
# Copyright (c) 2020, Intel Corporation All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
# EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# *****************************************************************************
def knn_python(
train,
train_labels,
test,
k,
classes_num,
train_size,
test_size,
predictions,
queue_neighbors_lst,
votes_to_classes_lst,
data_dim,
):
for i in range(test_size):
queue_neighbors = queue_neighbors_lst[i]
for j in range(k):
# dist = euclidean_dist(train[j], test[i])
x1 = train[j]
x2 = test[i]
distance = 0.0
for jj in range(data_dim):
diff = x1[jj] - x2[jj]
distance += diff * diff
dist = distance ** 0.5
queue_neighbors[j, 0] = dist
queue_neighbors[j, 1] = train_labels[j]
# sort_queue(queue_neighbors)
for j in range(len(queue_neighbors)):
# push_queue(queue_neighbors, queue_neighbors[i], i)
new_distance = queue_neighbors[j, 0]
new_neighbor_label = queue_neighbors[j, 1]
index = j
while index > 0 and new_distance < queue_neighbors[index - 1, 0]:
queue_neighbors[index, 0] = queue_neighbors[index - 1, 0]
queue_neighbors[index, 1] = queue_neighbors[index - 1, 1]
index = index - 1
queue_neighbors[index, 0] = new_distance
queue_neighbors[index, 1] = new_neighbor_label
for j in range(k, train_size):
# dist = euclidean_dist(train[j], test[i])
x1 = train[j]
x2 = test[i]
distance = 0.0
for jj in range(data_dim):
diff = x1[jj] - x2[jj]
distance += diff * diff
dist = distance ** 0.5
if dist < queue_neighbors[k - 1][0]:
# queue_neighbors[k - 1] = new_neighbor
queue_neighbors[k - 1][0] = dist
queue_neighbors[k - 1][1] = train_labels[j]
# push_queue(queue_neighbors, queue_neighbors[k - 1])
new_distance = queue_neighbors[k - 1, 0]
new_neighbor_label = queue_neighbors[k - 1, 1]
index = k - 1
while index > 0 and new_distance < queue_neighbors[index - 1, 0]:
queue_neighbors[index, 0] = queue_neighbors[index - 1, 0]
queue_neighbors[index, 1] = queue_neighbors[index - 1, 1]
index = index - 1
queue_neighbors[index, 0] = new_distance
queue_neighbors[index, 1] = new_neighbor_label
votes_to_classes = votes_to_classes_lst[i]
for j in range(len(queue_neighbors)):
votes_to_classes[int(queue_neighbors[j, 1])] += 1
max_ind = 0
max_value = 0
for j in range(classes_num):
if votes_to_classes[j] > max_value:
max_value = votes_to_classes[j]
max_ind = j
predictions[i] = max_ind
|
"""
1. Faça X = 0.0 e Y = 18. Verifique o tipo de dado que o Python atribuiu a cada um.
Faça Z = X + Y e verifique o resultado calculado e armazenado em Z.
Verifique com qual tipo de dado foi criado o objeto Z.
"""
x = 0.0
y = 18
print(type(x))
print(type(y))
z = x + y
print('O resultado calculado: {} '.format(z))
print('A variavel z veio do tipo: ', type(z))
#exercicio resolvido |
class Solution(object):
def minPathSum(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
nc = len(grid)
nr = len(grid[0])
for x in range(1, nr):
grid[0][x] += grid[0][x-1]
for x in range(1, nc):
grid[x][0] += grid[x-1][0]
for y in range(1, nr):
grid[x][y] += min(grid[x - 1][y], grid[x][y - 1])
return grid[nc-1][nr-1]
|
class WordWithTag:
word = ""
tag = ""
separator = ''
def __init__(self, separator):
self.separator = separator
|
class NvramBatteryStatusEnum(basestring):
"""
ok|partially discharged|fully discharged|not present|near
eol|eol|unknown|over charged|fully charged
Possible values:
<ul>
<li> "battery_ok" ,
<li> "battery_partially_discharged" ,
<li> "battery_fully_discharged" ,
<li> "battery_not_present" ,
<li> "battery_near_end_of_life" ,
<li> "battery_at_end_of_life" ,
<li> "battery_unknown" ,
<li> "battery_over_charged" ,
<li> "battery_fully_charged"
</ul>
"""
@staticmethod
def get_api_name():
return "nvram-battery-status-enum"
|
#!/usr/bin/env python3
def hash_tabla_letrehoz():
tabla = []
for i in range(26):
tabla.append([])
return tabla
def key(szo):
if ord(szo[0]) >= 97 and ord(szo[0]) <= 122:
return ord(szo[0])
else:
raise ValueError("A(z) '{}' karakter nem hashelhető, adj meg ékezet nélküli, kisbetűvel kezdődő szót.".format(szo[0]))
def hash_tabla_betesz(tabla, szo):
kulcs = key(szo)
if szo not in tabla[kulcs - 97]:
tabla[kulcs - 97].append(szo)
return tabla
def hash_tabla_debug(tabla):
for i in range(len(tabla)):
print("{:2} ({}): {}".format(i, chr(i + 97), tabla[i]))
def hash_tabla_benne_van(tabla, szo):
kulcs = key(szo)
return szo in tabla[kulcs - 97]
def hash_tabla_kivesz(tabla, szo):
kulcs = key(szo)
if szo in tabla[kulcs - 97]:
tabla[kulcs - 97].remove(szo)
return tabla
def hash_tabla_listaz(tabla):
for lista in tabla:
for elem in lista:
print(elem, end=" ")
print("")
def main():
hasht = hash_tabla_letrehoz()
hash_tabla_betesz(hasht, "eper")
hash_tabla_betesz(hasht, "alma")
hash_tabla_betesz(hasht, "zab")
hash_tabla_betesz(hasht, "ananasz")
hash_tabla_kivesz(hasht, "ananasz")
#hash_tabla_debug(hasht)
#print(hash_tabla_benne_van(hasht, "ananasz"))
hash_tabla_listaz(hasht)
main()
|
class Solution:
def minOperations(self, n: int) -> int:
num_ops = 0
for i in range(0, n // 2, 1):
num_ops += n - (2 * i + 1)
return num_ops |
input = """
3 2 2 3 1 0 4
2 5 2 0 1 2 3
1 1 2 1 5 4
2 6 2 0 2 2 3
1 1 2 0 6 4
1 4 0 0
3 3 7 8 9 1 0 10
2 11 3 0 1 7 8 9
1 1 2 1 11 10
2 12 3 0 2 7 8 9
1 1 2 0 12 10
1 10 0 0
1 13 1 0 9
1 14 1 0 8
1 15 1 0 7
1 16 1 0 9
1 17 1 0 7
1 18 1 1 17
1 19 2 0 14 13
1 20 3 0 14 18 15
1 1 2 1 20 2
1 1 2 1 19 3
0
16 i
3 e
20 s
13 f
9 a
14 g
17 l
8 b
18 p
2 d
19 r
15 h
7 c
0
B+
0
B-
1
0
1
"""
output = """
INCOHERENT
"""
|
'''
Largest Continuous Sum Problem
Given an array of integers (positive and negative) find the largest continous sum
'''
def large_cont_sum(arr):
#if array is all positive we return the result as summ of all numbers
#the negative numbers int he array will cause us to need to begin checkin sequences
## Check to see if array is Length 0
if len(arr) == 0:
return 0
max_sum = current_sum = arr[0] #equal to first element
for num in arr[1:]: #We check each number in array not including the first num arr[0]
current_sum = max(current_sum+num, num) #find out which one is larger: current sum + num or the num
max_sum = max(current_sum,max_sum) #we keep track of which one is larger
return max_sum
print(large_cont_sum([1,2,-1,3,4,10,10,-10,-1])) |
data = (
's', # 0x00
't', # 0x01
'u', # 0x02
'v', # 0x03
'w', # 0x04
'x', # 0x05
'y', # 0x06
'z', # 0x07
'A', # 0x08
'B', # 0x09
'C', # 0x0a
'D', # 0x0b
'E', # 0x0c
'F', # 0x0d
'G', # 0x0e
'H', # 0x0f
'I', # 0x10
'J', # 0x11
'K', # 0x12
'L', # 0x13
'M', # 0x14
'N', # 0x15
'O', # 0x16
'P', # 0x17
'Q', # 0x18
'R', # 0x19
'S', # 0x1a
'T', # 0x1b
'U', # 0x1c
'V', # 0x1d
'W', # 0x1e
'X', # 0x1f
'Y', # 0x20
'Z', # 0x21
'a', # 0x22
'b', # 0x23
'c', # 0x24
'd', # 0x25
'e', # 0x26
'f', # 0x27
'g', # 0x28
'h', # 0x29
'i', # 0x2a
'j', # 0x2b
'k', # 0x2c
'l', # 0x2d
'm', # 0x2e
'n', # 0x2f
'o', # 0x30
'p', # 0x31
'q', # 0x32
'r', # 0x33
's', # 0x34
't', # 0x35
'u', # 0x36
'v', # 0x37
'w', # 0x38
'x', # 0x39
'y', # 0x3a
'z', # 0x3b
'A', # 0x3c
'B', # 0x3d
'C', # 0x3e
'D', # 0x3f
'E', # 0x40
'F', # 0x41
'G', # 0x42
'H', # 0x43
'I', # 0x44
'J', # 0x45
'K', # 0x46
'L', # 0x47
'M', # 0x48
'N', # 0x49
'O', # 0x4a
'P', # 0x4b
'Q', # 0x4c
'R', # 0x4d
'S', # 0x4e
'T', # 0x4f
'U', # 0x50
'V', # 0x51
'W', # 0x52
'X', # 0x53
'Y', # 0x54
'Z', # 0x55
'a', # 0x56
'b', # 0x57
'c', # 0x58
'd', # 0x59
'e', # 0x5a
'f', # 0x5b
'g', # 0x5c
'h', # 0x5d
'i', # 0x5e
'j', # 0x5f
'k', # 0x60
'l', # 0x61
'm', # 0x62
'n', # 0x63
'o', # 0x64
'p', # 0x65
'q', # 0x66
'r', # 0x67
's', # 0x68
't', # 0x69
'u', # 0x6a
'v', # 0x6b
'w', # 0x6c
'x', # 0x6d
'y', # 0x6e
'z', # 0x6f
'A', # 0x70
'B', # 0x71
'C', # 0x72
'D', # 0x73
'E', # 0x74
'F', # 0x75
'G', # 0x76
'H', # 0x77
'I', # 0x78
'J', # 0x79
'K', # 0x7a
'L', # 0x7b
'M', # 0x7c
'N', # 0x7d
'O', # 0x7e
'P', # 0x7f
'Q', # 0x80
'R', # 0x81
'S', # 0x82
'T', # 0x83
'U', # 0x84
'V', # 0x85
'W', # 0x86
'X', # 0x87
'Y', # 0x88
'Z', # 0x89
'a', # 0x8a
'b', # 0x8b
'c', # 0x8c
'd', # 0x8d
'e', # 0x8e
'f', # 0x8f
'g', # 0x90
'h', # 0x91
'i', # 0x92
'j', # 0x93
'k', # 0x94
'l', # 0x95
'm', # 0x96
'n', # 0x97
'o', # 0x98
'p', # 0x99
'q', # 0x9a
'r', # 0x9b
's', # 0x9c
't', # 0x9d
'u', # 0x9e
'v', # 0x9f
'w', # 0xa0
'x', # 0xa1
'y', # 0xa2
'z', # 0xa3
'i', # 0xa4
'j', # 0xa5
'', # 0xa6
'', # 0xa7
'Alpha', # 0xa8
'Beta', # 0xa9
'Gamma', # 0xaa
'Delta', # 0xab
'Epsilon', # 0xac
'Zeta', # 0xad
'Eta', # 0xae
'Theta', # 0xaf
'Iota', # 0xb0
'Kappa', # 0xb1
'Lamda', # 0xb2
'Mu', # 0xb3
'Nu', # 0xb4
'Xi', # 0xb5
'Omicron', # 0xb6
'Pi', # 0xb7
'Rho', # 0xb8
'Theta', # 0xb9
'Sigma', # 0xba
'Tau', # 0xbb
'Upsilon', # 0xbc
'Phi', # 0xbd
'Chi', # 0xbe
'Psi', # 0xbf
'Omega', # 0xc0
'nabla', # 0xc1
'alpha', # 0xc2
'beta', # 0xc3
'gamma', # 0xc4
'delta', # 0xc5
'epsilon', # 0xc6
'zeta', # 0xc7
'eta', # 0xc8
'theta', # 0xc9
'iota', # 0xca
'kappa', # 0xcb
'lamda', # 0xcc
'mu', # 0xcd
'nu', # 0xce
'xi', # 0xcf
'omicron', # 0xd0
'pi', # 0xd1
'rho', # 0xd2
'sigma', # 0xd3
'sigma', # 0xd4
'tai', # 0xd5
'upsilon', # 0xd6
'phi', # 0xd7
'chi', # 0xd8
'psi', # 0xd9
'omega', # 0xda
'', # 0xdb
'', # 0xdc
'', # 0xdd
'', # 0xde
'', # 0xdf
'', # 0xe0
'', # 0xe1
'', # 0xe2
'', # 0xe3
'', # 0xe4
'', # 0xe5
'', # 0xe6
'', # 0xe7
'', # 0xe8
'', # 0xe9
'', # 0xea
'', # 0xeb
'', # 0xec
'', # 0xed
'', # 0xee
'', # 0xef
'', # 0xf0
'', # 0xf1
'', # 0xf2
'', # 0xf3
'', # 0xf4
'', # 0xf5
'', # 0xf6
'', # 0xf7
'', # 0xf8
'', # 0xf9
'', # 0xfa
'', # 0xfb
'', # 0xfc
'', # 0xfd
'', # 0xfe
'', # 0xff
)
|
salario = float(input('Meu salario atual é de R$: '))
nsal = salario + (salario * 15 / 100)
print(f'Meu salário era {salario:.2f} para R${nsal:.2f}')
|
# -*- coding: utf-8 -*-
"""
"main concept of MongoDB is embed whenever possible"
Ref: http://stackoverflow.com/questions/4655610#comment5129510_4656431
"""
transcript = dict(
# The ensemble transcript id
transcript_id=str, # required=True
# The hgnc gene id
hgnc_id=int,
### Protein specific predictions ###
# The ensemble protein id
protein_id=str,
# The sift consequence prediction for this transcript
sift_prediction=str, # choices=CONSEQUENCE
# The polyphen consequence prediction for this transcript
polyphen_prediction=str, # choices=CONSEQUENCE
# The swiss protein id for the product
swiss_prot=str,
# The pfam id for the protein product
pfam_domain=str,
# The prosite id for the product
prosite_profile=str,
# The smart id for the product
smart_domain=str,
# The biotype annotation for the transcript
biotype=str,
# The functional annotations for the transcript
functional_annotations=list, # list(str(choices=SO_TERM_KEYS))
# The region annotations for the transcripts
region_annotations=list, # list(str(choices=FEATURE_TYPES))
# The exon number in the transcript e.g '2/7'
exon=str,
# The intron number in the transcript e.g '4/6'
intron=str,
# The strand of the transcript e.g '+'
strand=str,
# the CDNA change of the transcript e.g 'c.95T>C'
coding_sequence_name=str,
# The amino acid change on the transcript e.g. 'p.Phe32Ser'
protein_sequence_name=str,
# If the transcript is relevant
is_canonical=bool,
# The MANE select transcript
mane_transcript=str,
)
|
# MIT licensed
# Copyright (c) 2013-2020 lilydjwg <lilydjwg@gmail.com>, et al.
GEMS_URL = 'https://rubygems.org/api/v1/versions/%s.json'
async def get_version(name, conf, *, cache, **kwargs):
key = conf.get('gems', name)
data = await cache.get_json(GEMS_URL % key)
return data[0]['number']
|
def msgme(*names):
for i in names:
print(i)
msgme("abc")
msgme("xyz",100)
msgme("apple","mango",1,2,3,7)
|
n1= int(input('digite um numero : '))
n2 = int(input('digi um segundo número :'))
if n1<n2:
print(' o primeiro numero {} é menor que o segundo número {}'.format( n1,n2 ))
elif n1>n2:
print('o segundo número {} é menor que o primeiro número {}'.format(n2,n1))
elif n1==n2:
print('os numeros {} e {} são numeros iguais '.format (n1, n2))
|
class Dog:
species = 'caniche'
def __init__(self, name, age):
self.name = name
self.age = age
bambi = Dog("Bambi", 5)
mikey = Dog("Rufus", 6)
blacky = Dog("Fosca", 9)
coco = Dog("Coco", 13)
perla = Dog("Neska", 3)
print("{} is {} and {} is {}.". format(bambi.name, bambi.age, mikey.name, mikey.age))
if bambi.species == "caniche":
print("{0} is a {1}!".format(bambi.name, bambi.species))
def get_biggest_number (*argument):
max=0
for i in argument:
if (type(i) is int) == False:
return ("Error: Arguments must be integers")
if i>max:
max=i
return (max)
print('The biggest number among the given is: ' , get_biggest_number(1 , 4 , 5 , -4 , 6 , 123 , 0)) |
class Student:
def __init__(self, name="", age=0, score=0, sex=""):
self.name = name
self.age = age
self.score = score
self.sex = sex
list_student = [
Student("悟空", 26, 96, "男"),
Student("八戒", 25, 50, "男"),
Student("唐僧", 23, 53, "女"),
Student("小白龙", 29, 85, "女"),
]
# 定义函数,查找所有姓名小于三个字的学生
def find_students_by_name():
for stu in list_student:
if len(stu.name) < 3:
yield stu
for item in find_students_by_name():
print(item.__dict__)
students_by_name = (stu for stu in list_student if len(stu.name) < 3)
for item in students_by_name:
print(item.__dict__)
# 定义函数,查找所有女同学
def find_students_by_sex():
for stu in list_student:
if stu.sex == "女":
yield stu
# 延迟操作/惰性操作 --> 立即操作
list_student_by_sex = list(find_students_by_sex())
print(list_student_by_sex[-1].__dict__)
students_by_sex = (stu for stu in list_student if stu.sex == "女")
# 定义函数,查找所有成绩小于60的同学姓名
def get_student_names():
for stu in list_student:
if stu.score < 60:
yield stu.name
student_names = (stu.name for stu in list_student if stu.score < 60)
# 定义函数,查找成绩最高的学生
def get_max_by_score():
max_value = list_student[0]
for i in range(1, len(list_student)):
if max_value.score < list_student[i].score:
max_value = list_student[i]
return max_value
|
"""
[11/3/2012] Challenge #110 [Difficult] You can't handle the truth!
https://www.reddit.com/r/dailyprogrammer/comments/12k3xw/1132012_challenge_110_difficult_you_cant_handle/
**Description:**
[Truth Tables](http://en.wikipedia.org/wiki/Truth_table) are a simple table that demonstrates all possible results
given a Boolean algebra function. An example Boolean algebra function would be "A or B", where there are four possible
combinations, one of which is "A:false, B:false, Result: false"
Your goal is to write a Boolean algebra function truth-table generator for statements that are up to 4 variables
(always A, B, C, or D) and for only the following operators: [not](http://en.wikipedia.org/wiki/Logical_NOT),
[and](http://en.wikipedia.org/wiki/Logical_AND), [or](http://en.wikipedia.org/wiki/Logical_OR),
[nand](http://en.wikipedia.org/wiki/Logical_NAND), and [nor](http://en.wikipedia.org/wiki/Logical_NOR).
Note that you must maintain order of operator correctness, though evaluate left-to-right if there are ambiguous
statements.
**Formal Inputs & Outputs:**
*Input Description:*
String BoolFunction - A string of one or more variables (always A, B, C, or D) and keyboards (not, and, or, nand, nor).
This string is guaranteed to be valid
*Output Description:*
Your application must print all possible combinations of states for all variables, with the last variable being
"Result", which should the correct result if the given variables were set to the given values. An example row would be
"A:false, B:false, Result: false"
**Sample Inputs & Outputs:**
Given "A and B", your program should print the following:
A:false, B:false, Result: false
A:true, B:false, Result: false
A:false, B:true, Result: false
A:true, B:true, Result: true
**Notes:**
To help with cycling through all boolean combinations, realize that when counting from 0 to 3 in binary, you generate a
table of all combinations of 2 variables (00, 01, 10, 11). You can extrapolate this out to itterating through all table
rows for a given variable count. [Challenge
#105](http://www.reddit.com/r/dailyprogrammer/comments/11shtj/10202012_challenge_105_intermediate_boolean_logic/) has a
very similar premise to this challenge.
"""
def main():
pass
if __name__ == "__main__":
main()
|
# Exercico 36
# Emprestimo bancario, valor, salario, não pode exeder 30% do salario.
casa = float(input('Valor das casa:R$ '))
salario = float(input('Salario do comprador:R$ '))
anos = int (input('Quantos anos de financiamemto:R$ '))
prestação = casa / ( anos * 12)
minimo = salario * 30 / 100
print('Para pagas uma casa de R${:.2f} em {} anos'.format(casa, anos), end='')
print(' a prestação será de R$ {:.2f}'.format(prestação))
if prestação <= minimo:
print('Emprestimo pode ser concedido!')
else:
print('Empréstimo negado!') |
# Faça um algoritmo que leia o preço de um produto e mostre seu novo preço, com 5% de desconto.
preco = float(input("\nDigite o preço do produto: R$"))
desconto = preco - (preco * 0.05)
print("\nO novo preço do produto com 5% de desconto é R${:.2f}.".format(desconto))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.