content
stringlengths 7
1.05M
|
---|
class Solution:
def minSubArrayLen(self, s, nums):
"""
:type s: int
:type nums: List[int]
:rtype: int
------------------------------
15 / 15 test cases passed.
Status: Accepted
Runtime: 72 ms
"""
l, sum, res = 0, 0, len(nums) + 1
for r in range(len(nums)):
sum += nums[r]
while l <= r and sum >= s:
res = min(res, r - l + 1)
sum -= nums[l]
l += 1
return res if res != len(nums) + 1 else 0
if __name__ == '__main__':
print(Solution().minSubArrayLen(15, [1, 2, 3, 4, 5]))
print(Solution().minSubArrayLen(7, [2, 3, 1, 2, 4, 3]))
|
def get_paginated_result(query, page, per_page, field, timestamp):
new_query = query
if page != 1 and timestamp != None:
new_query = query.filter(
field < timestamp
)
try:
return new_query.paginate(
per_page=per_page,
page=page
).items, 200
except:
response_object = {
'status': 'error',
'message': 'end of content',
}
return response_object, 470
|
# -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2015-2018 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Errors for Invenio-Records module."""
class RecordsError(Exception):
"""Base class for errors in Invenio-Records module."""
class MissingModelError(RecordsError):
"""Error raised when a record has no model."""
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
功能实现:创建平面字典中所有键的平面列表。
解读:
使用dict.keys()返回给定字典中的键值。
返回前一个结果的list()。
"""
def keys_only(flat_dict):
return list(flat_dict.keys())
# Examples
ages = {
'Peter': 10,
'Isabel': 11,
'Anna': 9,
}
print(keys_only(ages))
# output:
# ['Peter', 'Isabel', 'Anna']
|
#!/usr/bin/env python3
# encoding: utf-8
def _subclasses(cls):
try:
return cls.__subclasses__()
except TypeError:
return type.__subclasses__(cls)
class _SubclassNode:
__slots__ = frozenset(('cls', 'children'))
def __init__(self, cls, children=None):
self.cls = cls
self.children = children or []
def __repr__(self):
if not self.children:
return repr(self.cls)
return '<{0.__class__.__qualname__} {0.cls} {0.children}>'.format(self)
def subclasses(cls, root=None):
root = root or _SubclassNode(cls)
root.children.extend(map(_SubclassNode, _subclasses(cls)))
for child in root.children:
subclasses(child.cls, child)
return root
if __name__ == '__main__':
class A: pass
class B(A): pass
class C(A): pass
class D(B, C): pass
class E(A): pass
print(subclasses(A))
|
def longest_uppercase(input,k):
final_out = 0
for i in input:
test_letters = i
for j in input:
if len(test_letters) == k :
break
if test_letters.find(j) >= 0:
pass
else:
test_letters += j
max = 0
count = 0
for m in input :
if test_letters.find(m) == -1:
if count > max:
max = count
count = 0
else:
count += 1
if len(input) <= k:
return len(input)
if final_out < max:
final_out = max
return final_out
|
# The following dependencies were calculated from:
#
# generate_workspace --artifact=io.opencensus:opencensus-api:0.12.2 --artifact=io.opencensus:opencensus-contrib-zpages:0.12.2 --artifact=io.opencensus:opencensus-exporter-trace-logging:0.12.2 --artifact=io.opencensus:opencensus-impl:0.12.2 --repositories=http://repo.maven.apache.org/maven2
def opencensus_maven_jars():
# io.opencensus:opencensus-impl-core:jar:0.12.2 got requested version
# io.opencensus:opencensus-contrib-zpages:jar:0.12.2 got requested version
# io.opencensus:opencensus-contrib-grpc-metrics:jar:0.12.2 got requested version
# io.opencensus:opencensus-api:jar:0.12.2
# io.opencensus:opencensus-exporter-trace-logging:jar:0.12.2 got requested version
# io.opencensus:opencensus-impl:jar:0.12.2 got requested version
native.maven_jar(
name = "com_google_code_findbugs_jsr305",
artifact = "com.google.code.findbugs:jsr305:3.0.1",
repository = "http://repo.maven.apache.org/maven2/",
sha1 = "f7be08ec23c21485b9b5a1cf1654c2ec8c58168d",
)
# io.opencensus:opencensus-api:jar:0.12.2
native.maven_jar(
name = "io_grpc_grpc_context",
artifact = "io.grpc:grpc-context:1.9.0",
repository = "http://repo.maven.apache.org/maven2/",
sha1 = "28b0836f48c9705abf73829bbc536dba29a1329a",
)
native.maven_jar(
name = "io_opencensus_opencensus_exporter_trace_logging",
artifact = "io.opencensus:opencensus-exporter-trace-logging:0.12.2",
repository = "http://repo.maven.apache.org/maven2/",
sha1 = "15b8b3d2c9b3ffd2d8e242d252ee056a1c30d203",
)
# io.opencensus:opencensus-impl-core:jar:0.12.2 got requested version
# io.opencensus:opencensus-contrib-zpages:jar:0.12.2 got requested version
# io.opencensus:opencensus-contrib-grpc-metrics:jar:0.12.2 got requested version
# io.opencensus:opencensus-api:jar:0.12.2
# io.opencensus:opencensus-exporter-trace-logging:jar:0.12.2 got requested version
# io.opencensus:opencensus-impl:jar:0.12.2 got requested version
native.maven_jar(
name = "com_google_errorprone_error_prone_annotations",
artifact = "com.google.errorprone:error_prone_annotations:2.2.0",
repository = "http://repo.maven.apache.org/maven2/",
sha1 = "88e3c593e9b3586e1c6177f89267da6fc6986f0c",
)
native.maven_jar(
name = "io_opencensus_opencensus_contrib_zpages",
artifact = "io.opencensus:opencensus-contrib-zpages:0.12.2",
repository = "http://repo.maven.apache.org/maven2/",
sha1 = "44f8d5b81b20f9f0d34091baecffd67c2ce0c952",
)
# io.opencensus:opencensus-impl:jar:0.12.2
native.maven_jar(
name = "com_lmax_disruptor",
artifact = "com.lmax:disruptor:3.3.9",
repository = "http://repo.maven.apache.org/maven2/",
sha1 = "7898f8e8dc2d908d4ae5240fbb17eb1a9c213b9b",
)
# io.opencensus:opencensus-impl-core:jar:0.12.2 got requested version
# io.opencensus:opencensus-contrib-zpages:jar:0.12.2 got requested version
# io.opencensus:opencensus-api:jar:0.12.2
# io.opencensus:opencensus-exporter-trace-logging:jar:0.12.2 got requested version
native.maven_jar(
name = "com_google_guava_guava",
artifact = "com.google.guava:guava:19.0",
repository = "http://repo.maven.apache.org/maven2/",
sha1 = "6ce200f6b23222af3d8abb6b6459e6c44f4bb0e9",
)
# io.opencensus:opencensus-contrib-zpages:jar:0.12.2
native.maven_jar(
name = "io_opencensus_opencensus_contrib_grpc_metrics",
artifact = "io.opencensus:opencensus-contrib-grpc-metrics:0.12.2",
repository = "http://repo.maven.apache.org/maven2/",
sha1 = "20dd982bd8942fc6d612fedd4466cda0461267ec",
)
# io.opencensus:opencensus-impl-core:jar:0.12.2 got requested version
# io.opencensus:opencensus-contrib-zpages:jar:0.12.2 got requested version
# io.opencensus:opencensus-contrib-grpc-metrics:jar:0.12.2 got requested version
# io.opencensus:opencensus-exporter-trace-logging:jar:0.12.2 got requested version
# io.opencensus:opencensus-impl:jar:0.12.2 got requested version
native.maven_jar(
name = "io_opencensus_opencensus_api",
artifact = "io.opencensus:opencensus-api:0.12.2",
repository = "http://repo.maven.apache.org/maven2/",
sha1 = "a2d524b62869350942106ab8f9a1f5adb1212775",
)
# io.opencensus:opencensus-impl:jar:0.12.2
native.maven_jar(
name = "io_opencensus_opencensus_impl_core",
artifact = "io.opencensus:opencensus-impl-core:0.12.2",
repository = "http://repo.maven.apache.org/maven2/",
sha1 = "9e059704131a4455b3bd6d84cfa8e6875551d647",
)
native.maven_jar(
name = "io_opencensus_opencensus_impl",
artifact = "io.opencensus:opencensus-impl:0.12.2",
repository = "http://repo.maven.apache.org/maven2/",
sha1 = "4e5cd57bddbd9b47cd16cc8b0b608b43355b223f",
)
def opencensus_java_libraries():
native.java_library(
name = "com_google_code_findbugs_jsr305",
visibility = ["//visibility:public"],
exports = ["@com_google_code_findbugs_jsr305//jar"],
)
native.java_library(
name = "io_grpc_grpc_context",
visibility = ["//visibility:public"],
exports = ["@io_grpc_grpc_context//jar"],
)
native.java_library(
name = "io_opencensus_opencensus_exporter_trace_logging",
visibility = ["//visibility:public"],
exports = ["@io_opencensus_opencensus_exporter_trace_logging//jar"],
runtime_deps = [
":com_google_code_findbugs_jsr305",
":com_google_errorprone_error_prone_annotations",
":com_google_guava_guava",
":io_opencensus_opencensus_api",
],
)
native.java_library(
name = "com_google_errorprone_error_prone_annotations",
visibility = ["//visibility:public"],
exports = ["@com_google_errorprone_error_prone_annotations//jar"],
)
native.java_library(
name = "io_opencensus_opencensus_contrib_zpages",
visibility = ["//visibility:public"],
exports = ["@io_opencensus_opencensus_contrib_zpages//jar"],
runtime_deps = [
":com_google_code_findbugs_jsr305",
":com_google_errorprone_error_prone_annotations",
":com_google_guava_guava",
":io_opencensus_opencensus_api",
":io_opencensus_opencensus_contrib_grpc_metrics",
],
)
native.java_library(
name = "com_lmax_disruptor",
visibility = ["//visibility:public"],
exports = ["@com_lmax_disruptor//jar"],
)
native.java_library(
name = "com_google_guava_guava",
visibility = ["//visibility:public"],
exports = ["@com_google_guava_guava//jar"],
)
native.java_library(
name = "io_opencensus_opencensus_contrib_grpc_metrics",
visibility = ["//visibility:public"],
exports = ["@io_opencensus_opencensus_contrib_grpc_metrics//jar"],
runtime_deps = [
":com_google_code_findbugs_jsr305",
":com_google_errorprone_error_prone_annotations",
":io_opencensus_opencensus_api",
],
)
native.java_library(
name = "io_opencensus_opencensus_api",
visibility = ["//visibility:public"],
exports = ["@io_opencensus_opencensus_api//jar"],
runtime_deps = [
":com_google_code_findbugs_jsr305",
":com_google_errorprone_error_prone_annotations",
":com_google_guava_guava",
":io_grpc_grpc_context",
],
)
native.java_library(
name = "io_opencensus_opencensus_impl_core",
visibility = ["//visibility:public"],
exports = ["@io_opencensus_opencensus_impl_core//jar"],
runtime_deps = [
":com_google_code_findbugs_jsr305",
":com_google_errorprone_error_prone_annotations",
":com_google_guava_guava",
":io_opencensus_opencensus_api",
],
)
native.java_library(
name = "io_opencensus_opencensus_impl",
visibility = ["//visibility:public"],
exports = ["@io_opencensus_opencensus_impl//jar"],
runtime_deps = [
":com_google_code_findbugs_jsr305",
":com_google_errorprone_error_prone_annotations",
":com_google_guava_guava",
":com_lmax_disruptor",
":io_opencensus_opencensus_api",
":io_opencensus_opencensus_impl_core",
],
)
|
'''
Write a program that asks the user how many Fibonnaci numbers to generate and then generates them. Take this opportunity to think about how you can use functions. Make sure to ask the user to enter the number of numbers in the sequence to generate.(Hint: The Fibonnaci seqence is a sequence of numbers where the next number in the sequence is the sum of the previous two numbers in the sequence. The sequence looks like this: 1, 1, 2, 3, 5, 8, 13, …)
'''
def fibonacci():
num_1 = 1
num_2 = 1
list_fib = [num_1, num_2]
i = 0
while i < 10:
list_fib.append(num_1 + num_2)
num_1 = num_2
num_2 = list_fib[-1]
i = i + 1
return list_fib
def main():
print(fibonacci())
if __name__ == '__main__':
main()
|
# -- Project information -----------------------------------------------------
project = 'showyourwork'
copyright = '2021, Rodrigo Luger'
author = 'Rodrigo Luger'
release = '1.0.0'
# -- General configuration ---------------------------------------------------
extensions = []
templates_path = ['_templates']
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
master_doc = 'index'
# -- Options for HTML output -------------------------------------------------
html_theme = 'sphinx_book_theme'
html_copy_source = True
html_show_sourcelink = True
html_sourcelink_suffix = ""
html_title = "showyourwork"
html_logo = "_static/logo.png"
html_static_path = ["_static"]
html_css_files = []
html_theme_options = {
"repository_url": "https://github.com/rodluger/showyourwork",
"repository_branch": "main",
"use_edit_page_button": True,
"use_issues_button": True,
"use_repository_button": True,
"use_download_button": True,
"logo_only": True,
"use_fullscreen_button": False,
"path_to_docs": "docs/",
}
|
#!/usr/bin/env python3
"""
Bubble Sort Script
"""
def bubble_sort(L):
"""
Sorts a list in increasing order. Because of lists are mutable
this function does not have to return something.
This algorithm uses bubble sort.
@param L: a list (in general unsorted)
"""
for i in range(len(L) - 1):
already_sorted = True
for j in range(len(L) - i - 1):
if L[j] > L[j + 1]:
already_sorted = False
L[j], L[j + 1]= L[j + 1], L[j]
# if no swaps were developed in the previous loop,
# it means that the list is already sorted. Thus,
# loop is exited and function terminates (returns None)
if already_sorted:
break
list1 = [1, -2, 3, 2, 0, 4, -1, 2, 0, 1, -5, 5, -6]
#list1 = [2, 1, -1]
bubble_sort(list1)
print(list1)
|
class ScriptMessageSent:
""" Triggered when a message is sent using the ScriptConnector
message:str - the message that was sent
index:int - the index into the script (agent.messages) """
def __init__(self, message, index):
self.message = message
self.index = index
def __str__(self):
return "ScriptMessageSent: " + self.message
|
'''
#3-1
b=0
c=0
while 1 :
a=input("Enthe an integer, the input ends if it is :")
if((a>0)|(a<0)):
if a>0:
b=a
else:
c=-a
if(a==0):
print("zheng shu {},fushu {},pingjunshu {}".format(b,c,(b+c)))
break
'''
'''
#3-2
j = 0
for i in range(15):
s = 10000+10000*0.05
j = j + s
if i==10:
a = j
print(a)
if i == 11:
b = j
d = b-a
print(d)
print(j-a)
'''
'''
#3-3
s=10000
for i in range(10):
s=s+s*0.05
print(s)
n=s
for i in range(4):
n=n+n*0.05
print(n)
'''
'''
#3-4
a=0
for i in range(100,1000):
if(i%5==0 and i%6==0):
a=a+1
print("%3d" % i, end=" ")
if(a%10==0):
print(" ")
'''
'''
#3-5
import math
n=0.0
while 1:
n = n+1.0
if n*n*n<12000:
print(n)
break
if n*n>=12000:
print(n)
break
'''
'''
#3-5
n=1
while(n<12000):
if(n*n>12000):
print(n)
break
n=n+1
s=1
while(s<12000):
if(s*s*s>12000):
print(s-1)
break
s=s+1
'''
'''
#3-6
p = eval(raw_input(">>"))
y = eval(raw_input(">>"))
n = 0.05
while n<8.125:
n = n+0.125
s = p*pow((1.0+n),1)
print(s)
m = s/12
print(m)
'''
'''
#3-7
n=0
for i in range(1,50001):
n=n+1/i
print(n)
s=50000
m=0
while(s>0):
m=m+1/s
s=s-1
print(m)
'''
'''
#3-8
a=1.0
b=3.0
sum1=0
while (a<=97):
sum1=sum1+a/b
a=a+2
b=b+2
print(sum1)
'''
'''
#3-9
#_*_coding:utf8-
a=input(">>")
b=0
sum=0
for i in range(1,a+1):
sum+=pow((-1),(a+1))/2*a-1
b=sum*4
print(b)
'''
'''
#3-9-2
n=0
for i in range(1,100000):
n=n+pow((-1),i+1)/(2*i-1)
if(i%10000==0):
print(4*n)
'''
'''
#3-10
for i in range(1,10001):
n=0
for j in range(1,i/2+1):
if(i%j==0):
n=n+j
if(n==i):
print(i)
'''
'''
#3-11
a=0
for i in range(1,8):
for j in range(i+1,8):
print("sum {}".format((i)+(j)))
a=a+1
print "sum",a
'''
|
def mergeSort(myList):
print("Splitting ",myList)
if (len(myList) > 1):
mid = len(myList)//2
leftList = myList[:mid]
rightList = myList[mid:]
mergeSort(leftList)
mergeSort(rightList)
i = 0
j = 0
k = 0
while ((i < len(leftList)) and (j < len(rightList))):
if (leftList[i] < rightList[j]):
myList[k] = leftList[i]
i = i + 1
else:
myList[k] = rightList[j]
j = j + 1
k = k + 1
while (i < len(leftList)):
myList[k] = leftList[i]
i = i + 1
k = k + 1
while (j < len(rightList)):
myList[k] = rightList[j]
j = j + 1
k = k + 1
print("Merging ",myList)
myList = [3,1,4,10,9,6,2,5,8,7]
mergeSort(myList)
print(myList)
|
while True:
relax = master.relax()
relax.optimize()
pi = [c.Pi for c in relax.getConstrs()]
knapsack = Model("KP")
knapsack.ModelSense=-1
y = {}
for i in range(m):
y[i] = knapsack.addVar(ub=q[i], vtype="I", name="y[%d]"%i)
knapsack.update()
knapsack.addConstr(quicksum(w[i]*y[i] for i in range(m)) <= B, "width")
knapsack.setObjective(quicksum(pi[i]*y[i] for i in range(m)), GRB.MAXIMIZE)
knapsack.optimize()
if knapsack.ObjVal < 1+EPS:
break
pat = [int(y[i].X+0.5) for i in y]
t.append(pat)
col = Column()
for i in range(m):
if t[K][i] > 0:
col.addTerms(t[K][i], orders[i])
x[K] = master.addVar(obj=1, vtype="I", name="x[%d]"%K, column=col)
master.update()
K += 1
master.optimize()
rolls = []
for k in x:
for j in range(int(x[k].X + .5)):
rolls.append(sorted([w[i] for i in range(m) if t[k][i]>0 for j in range(t[k][i])]))
rolls.sort()
return rolls
t = []
m = len(w)
for i in range(m):
pat = [0]*m
pat[i] = int(B/w[i])
t.append(pat)
|
def hasDoubleDigits(p):
previous = ''
for c in p:
if c == previous:
return True
previous = c
return False
def neverDecreases(p):
previous = -1
for c in p:
current = int(c)
if current < previous:
return False
previous = current
return True
def isValidPassword(p):
return hasDoubleDigits(p) and neverDecreases(p)
def findNumberOfPasswords(min, max):
current = min
count = 0
while current <= max:
s = str(current)
if isValidPassword(s):
count += 1
current += 1
return count
MIN_VALUE = 245182
MAX_VALUE = 790572
print(findNumberOfPasswords(MIN_VALUE, MAX_VALUE))
|
# a red shadow with some blur and a offset
cmykShadow((3, 3), 10, (1, 0, 0, 0))
# draw a rect
rect(100, 100, 30, 30)
|
#
# PySNMP MIB module NSLDAP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/NSLDAP-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:25:08 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
ObjectIdentifier, OctetString, Integer = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "OctetString", "Integer")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsIntersection, ConstraintsUnion, ValueSizeConstraint, ValueRangeConstraint, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ConstraintsUnion", "ValueSizeConstraint", "ValueRangeConstraint", "SingleValueConstraint")
URLString, DistinguishedName, applIndex = mibBuilder.importSymbols("NETWORK-SERVICES-MIB", "URLString", "DistinguishedName", "applIndex")
ObjectGroup, ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ObjectGroup", "ModuleCompliance", "NotificationGroup")
iso, NotificationType, Integer32, Counter32, ObjectIdentity, ModuleIdentity, Counter64, Gauge32, Unsigned32, MibScalar, MibTable, MibTableRow, MibTableColumn, NotificationType, Bits, MibIdentifier, TimeTicks, enterprises, IpAddress = mibBuilder.importSymbols("SNMPv2-SMI", "iso", "NotificationType", "Integer32", "Counter32", "ObjectIdentity", "ModuleIdentity", "Counter64", "Gauge32", "Unsigned32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "NotificationType", "Bits", "MibIdentifier", "TimeTicks", "enterprises", "IpAddress")
DisplayString, TimeStamp, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TimeStamp", "TextualConvention")
netscape = MibIdentifier((1, 3, 6, 1, 4, 1, 1450))
nsldap = ModuleIdentity((1, 3, 6, 1, 4, 1, 1450, 7))
if mibBuilder.loadTexts: nsldap.setLastUpdated('9707310000Z')
if mibBuilder.loadTexts: nsldap.setOrganization('Netscape Communications Corp')
if mibBuilder.loadTexts: nsldap.setContactInfo(' Frank Chen Postal: Netscape Communications Corp 501 East Middlefield Rd Mountain View, CA 94043 Tel: (415) 937 - 3703 Fax: (415) 937 - 4164 E-mail: [email protected]')
if mibBuilder.loadTexts: nsldap.setDescription(' An implementation of the MADMAN mib for monitoring LDAP/CLDAP and X.500 directories described in internet draft: draft-ietf-madman-ds-mib-103.txt used for iPlanet Directory Server 5')
dsOpsTable = MibTable((1, 3, 6, 1, 4, 1, 1450, 7, 1), )
if mibBuilder.loadTexts: dsOpsTable.setStatus('current')
if mibBuilder.loadTexts: dsOpsTable.setDescription(' The table holding information related to the DS operations.')
dsOpsEntry = MibTableRow((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1), ).setIndexNames((0, "NETWORK-SERVICES-MIB", "applIndex"))
if mibBuilder.loadTexts: dsOpsEntry.setStatus('current')
if mibBuilder.loadTexts: dsOpsEntry.setDescription(' Entry containing operations related statistics for a DS.')
dsAnonymousBinds = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 1), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dsAnonymousBinds.setStatus('current')
if mibBuilder.loadTexts: dsAnonymousBinds.setDescription(' Number of anonymous binds to this DS from UAs since application start.')
dsUnAuthBinds = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 2), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dsUnAuthBinds.setStatus('current')
if mibBuilder.loadTexts: dsUnAuthBinds.setDescription(' Number of un-authenticated binds to this DS since application start.')
dsSimpleAuthBinds = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 3), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dsSimpleAuthBinds.setReference(' CCITT Blue Book Fascicle VIII.8 - Rec. X.511, 1988: Section 8.1.2.1.1. and, RFC1777 Section 4.1')
if mibBuilder.loadTexts: dsSimpleAuthBinds.setStatus('current')
if mibBuilder.loadTexts: dsSimpleAuthBinds.setDescription(' Number of binds to this DS that were authenticated using simple authentication procedures since application start.')
dsStrongAuthBinds = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 4), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dsStrongAuthBinds.setReference(' CCITT Blue Book Fascicle VIII.8 - Rec. X.511, 1988: Sections 8.1.2.1.2 & 8.1.2.1.3. and, RFC1777 Section 4.1.')
if mibBuilder.loadTexts: dsStrongAuthBinds.setStatus('current')
if mibBuilder.loadTexts: dsStrongAuthBinds.setDescription(' Number of binds to this DS that were authenticated using the strong authentication procedures since application start. This includes the binds that were authenticated using external authentication procedures.')
dsBindSecurityErrors = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 5), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dsBindSecurityErrors.setReference(' CCITT Blue Book Fascicle VIII.8 - Rec. X.511, 1988: Section 12.7.2 and, RFC1777 Section 4.')
if mibBuilder.loadTexts: dsBindSecurityErrors.setStatus('current')
if mibBuilder.loadTexts: dsBindSecurityErrors.setDescription(' Number of bind operations that have been rejected by this DS due to inappropriateAuthentication or invalidCredentials.')
dsInOps = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 6), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dsInOps.setStatus('current')
if mibBuilder.loadTexts: dsInOps.setDescription(' Number of operations forwarded to this DS from UAs or other DSs since application start up.')
dsReadOps = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 7), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dsReadOps.setReference(' CCITT Blue Book Fascicle VIII.8 - Rec. X.511, 1988: Section 9.1.')
if mibBuilder.loadTexts: dsReadOps.setStatus('current')
if mibBuilder.loadTexts: dsReadOps.setDescription(' Number of read operations serviced by this DS since application startup.')
dsCompareOps = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 8), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dsCompareOps.setReference(' CCITT Blue Book Fascicle VIII.8 - Rec. X.511, 1988: Section 9.2. and, RFC1777 section 4.8')
if mibBuilder.loadTexts: dsCompareOps.setStatus('current')
if mibBuilder.loadTexts: dsCompareOps.setDescription(' Number of compare operations serviced by this DS since application startup.')
dsAddEntryOps = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 9), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dsAddEntryOps.setReference(' CCITT Blue Book Fascicle VIII.8 - Rec. X.511, 1988: Section 11.1. and, RFC1777 Section 4.5.')
if mibBuilder.loadTexts: dsAddEntryOps.setStatus('current')
if mibBuilder.loadTexts: dsAddEntryOps.setDescription(' Number of addEntry operations serviced by this DS since application startup.')
dsRemoveEntryOps = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 10), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dsRemoveEntryOps.setReference(' CCITT Blue Book Fascicle VIII.8 - Rec. X.511, 1988: Section 11.2. and, RFC1777 Section 4.6.')
if mibBuilder.loadTexts: dsRemoveEntryOps.setStatus('current')
if mibBuilder.loadTexts: dsRemoveEntryOps.setDescription(' Number of removeEntry operations serviced by this DS since application startup.')
dsModifyEntryOps = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 11), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dsModifyEntryOps.setReference(' CCITT Blue Book Fascicle VIII.8 - Rec. X.511, 1988: Section 11.3. and, RFC1777 Section 4.4.')
if mibBuilder.loadTexts: dsModifyEntryOps.setStatus('current')
if mibBuilder.loadTexts: dsModifyEntryOps.setDescription(' Number of modifyEntry operations serviced by this DS since application startup.')
dsModifyRDNOps = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 12), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dsModifyRDNOps.setReference(' CCITT Blue Book Fascicle VIII.8 - Rec. X.511, 1988: Section 11.4.and, RFC1777 Section 4.7')
if mibBuilder.loadTexts: dsModifyRDNOps.setStatus('current')
if mibBuilder.loadTexts: dsModifyRDNOps.setDescription(' Number of modifyRDN operations serviced by this DS since application startup.')
dsListOps = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 13), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dsListOps.setReference(' CCITT Blue Book Fascicle VIII.8 - Rec. X.511, 1988: Section 10.1.')
if mibBuilder.loadTexts: dsListOps.setStatus('current')
if mibBuilder.loadTexts: dsListOps.setDescription(' Number of list operations serviced by this DS since application startup.')
dsSearchOps = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 14), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dsSearchOps.setReference(' CCITT Blue Book Fascicle VIII.8 - Rec. X.511, 1988: Section 10.2. and, RFC1777 Section 4.3.')
if mibBuilder.loadTexts: dsSearchOps.setStatus('current')
if mibBuilder.loadTexts: dsSearchOps.setDescription(' Number of search operations- baseObject searches, oneLevel searches and wholeSubtree searches, serviced by this DS since application startup.')
dsOneLevelSearchOps = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 15), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dsOneLevelSearchOps.setReference(' CCITT Blue Book Fascicle VIII.8 - Rec. X.511, 1988: Section 10.2.2.2. and, RFC1777 Section 4.3.')
if mibBuilder.loadTexts: dsOneLevelSearchOps.setStatus('current')
if mibBuilder.loadTexts: dsOneLevelSearchOps.setDescription(' Number of oneLevel search operations serviced by this DS since application startup.')
dsWholeSubtreeSearchOps = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 16), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dsWholeSubtreeSearchOps.setReference(' CCITT Blue Book Fascicle VIII.8 - Rec. X.511, 1988: Section 10.2.2.2. and, RFC1777 Section 4.3.')
if mibBuilder.loadTexts: dsWholeSubtreeSearchOps.setStatus('current')
if mibBuilder.loadTexts: dsWholeSubtreeSearchOps.setDescription(' Number of wholeSubtree search operations serviced by this DS since application startup.')
dsReferrals = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 17), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dsReferrals.setReference(' CCITT Blue Book Fascicle VIII.8 - Rec. X.511, 1988: Section 12.6.')
if mibBuilder.loadTexts: dsReferrals.setStatus('current')
if mibBuilder.loadTexts: dsReferrals.setDescription(' Number of referrals returned by this DS in response to requests for operations since application startup.')
dsChainings = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 18), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dsChainings.setReference(' CCITT Blue Book Fascicle VIII.8 - Rec. X.518, 1988: Section 14.')
if mibBuilder.loadTexts: dsChainings.setStatus('current')
if mibBuilder.loadTexts: dsChainings.setDescription(' Number of operations forwarded by this DS to other DSs since application startup.')
dsSecurityErrors = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 19), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dsSecurityErrors.setReference(' CCITT Blue Book Fascicle VIII.8 - Rec. X.511, 1988: Section 12.7. and, RFC1777 Section 4.')
if mibBuilder.loadTexts: dsSecurityErrors.setStatus('current')
if mibBuilder.loadTexts: dsSecurityErrors.setDescription(' Number of operations forwarded to this DS which did not meet the security requirements. ')
dsErrors = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 20), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dsErrors.setReference(' CCITT Blue Book Fascicle VIII.8 - Rec. X.511, 1988: Sections 12.4, 12.5, 12.8 & 12.9. and, RFC1777 Section 4.')
if mibBuilder.loadTexts: dsErrors.setStatus('current')
if mibBuilder.loadTexts: dsErrors.setDescription(' Number of operations that could not be serviced due to errors other than security errors, and referrals. A partially serviced operation will not be counted as an error. The errors include NameErrors, UpdateErrors, Attribute errors and ServiceErrors.')
dsEntriesTable = MibTable((1, 3, 6, 1, 4, 1, 1450, 7, 2), )
if mibBuilder.loadTexts: dsEntriesTable.setStatus('current')
if mibBuilder.loadTexts: dsEntriesTable.setDescription(' The table holding information related to the entry statistics and cache performance of the DSs.')
dsEntriesEntry = MibTableRow((1, 3, 6, 1, 4, 1, 1450, 7, 2, 1), ).setIndexNames((0, "NETWORK-SERVICES-MIB", "applIndex"))
if mibBuilder.loadTexts: dsEntriesEntry.setStatus('current')
if mibBuilder.loadTexts: dsEntriesEntry.setDescription(' Entry containing statistics pertaining to entries held by a DS.')
dsMasterEntries = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 2, 1, 1), Gauge32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dsMasterEntries.setStatus('current')
if mibBuilder.loadTexts: dsMasterEntries.setDescription(' Number of entries mastered in the DS.')
dsCopyEntries = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 2, 1, 2), Gauge32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dsCopyEntries.setStatus('current')
if mibBuilder.loadTexts: dsCopyEntries.setDescription(' Number of entries for which systematic (slave) copies are maintained in the DS.')
dsCacheEntries = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 2, 1, 3), Gauge32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dsCacheEntries.setStatus('current')
if mibBuilder.loadTexts: dsCacheEntries.setDescription(' Number of entries cached (non-systematic copies) in the DS. This will include the entries that are cached partially. The negative cache is not counted.')
dsCacheHits = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 2, 1, 4), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dsCacheHits.setStatus('current')
if mibBuilder.loadTexts: dsCacheHits.setDescription(' Number of operations that were serviced from the locally held cache since application startup.')
dsSlaveHits = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 2, 1, 5), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dsSlaveHits.setStatus('current')
if mibBuilder.loadTexts: dsSlaveHits.setDescription(' Number of operations that were serviced from the locally held object replications ( shadow entries) since application startup.')
dsIntTable = MibTable((1, 3, 6, 1, 4, 1, 1450, 7, 3), )
if mibBuilder.loadTexts: dsIntTable.setStatus('current')
if mibBuilder.loadTexts: dsIntTable.setDescription(' Each row of this table contains some details related to the history of the interaction of the monitored DSs with their respective peer DSs.')
dsIntEntry = MibTableRow((1, 3, 6, 1, 4, 1, 1450, 7, 3, 1), ).setIndexNames((0, "NETWORK-SERVICES-MIB", "applIndex"), (0, "NSLDAP-MIB", "dsIntIndex"))
if mibBuilder.loadTexts: dsIntEntry.setStatus('current')
if mibBuilder.loadTexts: dsIntEntry.setDescription(' Entry containing interaction details of a DS with a peer DS.')
dsIntIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 3, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647)))
if mibBuilder.loadTexts: dsIntIndex.setStatus('current')
if mibBuilder.loadTexts: dsIntIndex.setDescription(' Together with applIndex it forms the unique key to identify the conceptual row which contains useful info on the (attempted) interaction between the DS (referred to by applIndex) and a peer DS.')
dsName = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 3, 1, 2), DistinguishedName()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dsName.setStatus('current')
if mibBuilder.loadTexts: dsName.setDescription(' Distinguished Name of the peer DS to which this entry pertains.')
dsTimeOfCreation = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 3, 1, 3), TimeStamp()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dsTimeOfCreation.setStatus('current')
if mibBuilder.loadTexts: dsTimeOfCreation.setDescription(' The value of sysUpTime when this row was created. If the entry was created before the network management subsystem was initialized, this object will contain a value of zero.')
dsTimeOfLastAttempt = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 3, 1, 4), TimeStamp()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dsTimeOfLastAttempt.setStatus('current')
if mibBuilder.loadTexts: dsTimeOfLastAttempt.setDescription(' The value of sysUpTime when the last attempt was made to contact this DS. If the last attempt was made before the network management subsystem was initialized, this object will contain a value of zero.')
dsTimeOfLastSuccess = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 3, 1, 5), TimeStamp()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dsTimeOfLastSuccess.setStatus('current')
if mibBuilder.loadTexts: dsTimeOfLastSuccess.setDescription(' The value of sysUpTime when the last attempt made to contact this DS was successful. If there have been no successful attempts this entry will have a value of zero. If the last successful attempt was made before the network management subsystem was initialized, this object will contain a value of zero.')
dsFailuresSinceLastSuccess = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 3, 1, 6), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dsFailuresSinceLastSuccess.setStatus('current')
if mibBuilder.loadTexts: dsFailuresSinceLastSuccess.setDescription(' The number of failures since the last time an attempt to contact this DS was successful. If there has been no successful attempts, this counter will contain the number of failures since this entry was created.')
dsFailures = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 3, 1, 7), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dsFailures.setStatus('current')
if mibBuilder.loadTexts: dsFailures.setDescription(' Cumulative failures since the creation of this entry.')
dsSuccesses = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 3, 1, 8), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dsSuccesses.setStatus('current')
if mibBuilder.loadTexts: dsSuccesses.setDescription(' Cumulative successes since the creation of this entry.')
dsURL = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 3, 1, 9), URLString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dsURL.setStatus('current')
if mibBuilder.loadTexts: dsURL.setDescription(' URL of the DS application.')
dsEntityTable = MibTable((1, 3, 6, 1, 4, 1, 1450, 7, 5), )
if mibBuilder.loadTexts: dsEntityTable.setStatus('current')
if mibBuilder.loadTexts: dsEntityTable.setDescription('This table holds general information related to an installed instance of a directory server')
dsEntityEntry = MibTableRow((1, 3, 6, 1, 4, 1, 1450, 7, 5, 1), ).setIndexNames((0, "NETWORK-SERVICES-MIB", "applIndex"))
if mibBuilder.loadTexts: dsEntityEntry.setStatus('current')
if mibBuilder.loadTexts: dsEntityEntry.setDescription('Entry of general information about an installed instance of a directory server')
dsEntityDescr = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 5, 1, 1), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: dsEntityDescr.setStatus('mandatory')
if mibBuilder.loadTexts: dsEntityDescr.setDescription('A general textual description of this directory server.')
dsEntityVers = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 5, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: dsEntityVers.setStatus('mandatory')
if mibBuilder.loadTexts: dsEntityVers.setDescription('The version of this directory server')
dsEntityOrg = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 5, 1, 3), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: dsEntityOrg.setStatus('mandatory')
if mibBuilder.loadTexts: dsEntityOrg.setDescription('Organization responsible for directory server at this installation')
dsEntityLocation = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 5, 1, 4), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: dsEntityLocation.setStatus('mandatory')
if mibBuilder.loadTexts: dsEntityLocation.setDescription('Physical location of this entity (directory server). For example: hostname, building number, lab number, etc.')
dsEntityContact = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 5, 1, 5), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: dsEntityContact.setStatus('mandatory')
if mibBuilder.loadTexts: dsEntityContact.setDescription('Contact person(s)responsible for the directory server at this installation, together with information on how to conact.')
dsEntityName = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 5, 1, 6), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: dsEntityName.setStatus('mandatory')
if mibBuilder.loadTexts: dsEntityName.setDescription('Name assigned to this entity at the installation site')
nsDirectoryServerDown = NotificationType((1, 3, 6, 1, 4, 1, 1450) + (0,7001)).setObjects(("NSLDAP-MIB", "dsEntityDescr"), ("NSLDAP-MIB", "dsEntityVers"), ("NSLDAP-MIB", "dsEntityLocation"), ("NSLDAP-MIB", "dsEntityContact"))
if mibBuilder.loadTexts: nsDirectoryServerDown.setDescription('This trap is generated whenever the agent detects the directory server to be (potentially) Down.')
nsDirectoryServerStart = NotificationType((1, 3, 6, 1, 4, 1, 1450) + (0,7002)).setObjects(("NSLDAP-MIB", "dsEntityDescr"), ("NSLDAP-MIB", "dsEntityVers"), ("NSLDAP-MIB", "dsEntityLocation"))
if mibBuilder.loadTexts: nsDirectoryServerStart.setDescription('This trap is generated whenever the agent detects the directory server to have (re)started.')
mibBuilder.exportSymbols("NSLDAP-MIB", dsEntityTable=dsEntityTable, dsSuccesses=dsSuccesses, dsOpsTable=dsOpsTable, dsAnonymousBinds=dsAnonymousBinds, dsReadOps=dsReadOps, dsOpsEntry=dsOpsEntry, dsErrors=dsErrors, nsDirectoryServerDown=nsDirectoryServerDown, dsSimpleAuthBinds=dsSimpleAuthBinds, netscape=netscape, nsDirectoryServerStart=nsDirectoryServerStart, dsEntriesTable=dsEntriesTable, dsSearchOps=dsSearchOps, dsModifyEntryOps=dsModifyEntryOps, dsEntityVers=dsEntityVers, dsFailures=dsFailures, dsOneLevelSearchOps=dsOneLevelSearchOps, dsSecurityErrors=dsSecurityErrors, dsMasterEntries=dsMasterEntries, dsChainings=dsChainings, dsEntityName=dsEntityName, dsBindSecurityErrors=dsBindSecurityErrors, dsCacheEntries=dsCacheEntries, dsInOps=dsInOps, dsCompareOps=dsCompareOps, dsRemoveEntryOps=dsRemoveEntryOps, dsWholeSubtreeSearchOps=dsWholeSubtreeSearchOps, dsReferrals=dsReferrals, dsEntityOrg=dsEntityOrg, dsSlaveHits=dsSlaveHits, dsName=dsName, dsListOps=dsListOps, dsModifyRDNOps=dsModifyRDNOps, dsTimeOfLastAttempt=dsTimeOfLastAttempt, nsldap=nsldap, dsEntityLocation=dsEntityLocation, dsURL=dsURL, dsEntityEntry=dsEntityEntry, dsIntTable=dsIntTable, PYSNMP_MODULE_ID=nsldap, dsCacheHits=dsCacheHits, dsIntIndex=dsIntIndex, dsFailuresSinceLastSuccess=dsFailuresSinceLastSuccess, dsStrongAuthBinds=dsStrongAuthBinds, dsTimeOfLastSuccess=dsTimeOfLastSuccess, dsEntityContact=dsEntityContact, dsAddEntryOps=dsAddEntryOps, dsTimeOfCreation=dsTimeOfCreation, dsEntityDescr=dsEntityDescr, dsCopyEntries=dsCopyEntries, dsIntEntry=dsIntEntry, dsUnAuthBinds=dsUnAuthBinds, dsEntriesEntry=dsEntriesEntry)
|
H, W = map(int, input().split())
S = []
for _ in range(H):
tmp = list(input())
S.append(tmp)
for h in range(H):
for w in range(W):
if S[h][w] == '#':
# 上
if h > 0 and S[h-1][w] == '#':
continue
# 下
elif h < H-1 and S[h+1][w] == '#':
continue
# 左
elif w > 0 and S[h][w-1] == '#':
continue
# 右
elif w < W-1 and S[h][w+1] == '#':
continue
print('No')
exit(0)
print('Yes')
|
def deleteDigit(n):
n = str(n)
return max([int(n[:index] + n[index + 1:]) for index in range(len(n))])
print(deleteDigit(152))
|
'''
Desenvolva um programa que leia quatro valores pelo teclado e guarde-os em uma tupla. No final, mostre:
a) Quantas vezes apareceu o valor 9
b) Em que posição foi digitado o primeiro valor 3
c) Quais foram os números pares
'''
n = (int(input('Digite um número: ')),
int(input('Digite um número: ')),
int(input('Digite um número: ')),
int(input('Digite um número: ')))
print('Você digitou os valores: {}'.format(n))
print('O número 9 aparece {} vezes.'.format(n.count(9)))
if 3 in n:
print('O número 3 apareceu na posição {}.'.format(n.index(3) + 1))
else:
print('\033[31mO número 3 não foi digitado\033[m')
print('Os valores pares digitados foram:')
for cont in n:
if cont % 2 == 0:
print(cont)
|
#coding:utf-8
def replace():
line=open('templates/space.html').read()
str='<div class="hex grid-3 tertiary"><a href="{{hrefadd}}" title="播放类型"><div class="inner"><img src="../static/assets/img/[email protected]" width="140" height="77" alt="Info on Buffalo\'s Website dev process" /></div><div class="hex-1"><span class="after"></span></div><div class="hex-2"><span class="after"></span></div><span class="after"></span></a></div>'
fb=open('templates/space.html','w')
fb.write(line[0:line.find('<div class="list-hex-grid list-inline-block clearfix">')+len('<div class="list-hex-grid list-inline-block clearfix">')+1]+str+line[line.find('<div class="list-hex-grid list-inline-block clearfix">')+len('<div class="list-hex-grid list-inline-block clearfix">')+1:len(line)+1])
fb.close()
|
# SPDX-FileCopyrightText: 2021 Neradoc [email protected]
#
# SPDX-License-Identifier: MIT
"""
Extended list of consumer controls.
"""
__version__ = "0.0.0-auto.0"
__repo__ = "https://github.com/Neradoc/Circuitpython_Keyboard_Layouts.git"
class ConsumerControlExtended:
UNASSIGNED = 0x00
CONSUMER_CONTROL = 0x01
NUMERIC_KEY_PAD = 0x02
PROGRAMMABLE_BUTTONS = 0x03
PLUS10 = 0x20
PLUS100 = 0x21
AM_PM = 0x22 # AM/PM
AM = AM_PM
PM = AM_PM
POWER = 0x30
RESET = 0x31
SLEEP = 0x32
SLEEP_AFTER = 0x33
SLEEP_MODE = 0x34
ILLUMINATION = 0x35
FUNCTION_BUTTONS = 0x36
MENU = 0x40
MENU_PICK = 0x41
MENU_UP = 0x42
MENU_DOWN = 0x43
MENU_LEFT = 0x44
MENU_RIGHT = 0x45
MENU_ESCAPE = 0x46
MENU_VALUE_INCREASE = 0x47
MENU_VALUE_DECREASE = 0x48
DATA_ON_SCREEN = 0x60
CLOSED_CAPTION = 0x61
CLOSED_CAPTION_SELECT = 0x62
VCR_TV = 0x63 # VCR/TV
# VCR = VCR_TV
# TV = VCR_TV
BROADCAST_MODE = 0x64
SNAPSHOT = 0x65
STILL = 0x66
SELECTION = 0x80
ASSIGN_SELECTION = 0x81
MODE_STEP = 0x82
RECALL_LAST = 0x83
ENTER_CHANNEL = 0x84
ORDER_MOVIE = 0x85
CHANNEL = 0x86
MEDIA_SELECTION = 0x87
MEDIA_SELECT_COMPUTER = 0x88
MEDIA_SELECT_TV = 0x89
MEDIA_SELECT_WWW = 0x8A
MEDIA_SELECT_DVD = 0x8B
MEDIA_SELECT_TELEPHONE = 0x8C
MEDIA_SELECT_PROGRAM_GUIDE = 0x8D
MEDIA_SELECT_VIDEO_PHONE = 0x8E
MEDIA_SELECT_GAMES = 0x8F
MEDIA_SELECT_MESSAGES = 0x90
MEDIA_SELECT_CD = 0x91
MEDIA_SELECT_VCR = 0x92
MEDIA_SELECT_TUNER = 0x93
QUIT = 0x94
HELP = 0x95
MEDIA_SELECT_TAPE = 0x96
MEDIA_SELECT_CABLE = 0x97
MEDIA_SELECT_SATELLITE = 0x98
MEDIA_SELECT_SECURITY = 0x99
MEDIA_SELECT_HOME = 0x9A
MEDIA_SELECT_CALL = 0x9B
CHANNEL_INCREMENT = 0x9C
CHANNEL_DECREMENT = 0x9D
MEDIA_SELECT_SAP = 0x9E
VCR_PLUS = 0xA0
ONCE = 0xA1
DAILY = 0xA2
WEEKLY = 0xA3
MONTHLY = 0xA4
PLAY = 0xB0
PAUSE = 0xB1
RECORD = 0xB2
FAST_FORWARD = 0xB3
REWIND = 0xB4
SCAN_NEXT_TRACK = 0xB5
SCAN_PREVIOUS_TRACK = 0xB6
STOP = 0xB7
EJECT = 0xB8
RANDOM_PLAY = 0xB9
SELECT_DISC = 0xBA
ENTER_DISC = 0xBB
REPEAT = 0xBC
TRACKING = 0xBD
TRACK_NORMAL = 0xBE
SLOW_TRACKING = 0xBF
FRAME_FORWARD = 0xC0
FRAME_BACK = 0xC1
MARK = 0xC2
CLEAR_MARK = 0xC3
REPEAT_FROM_MARK = 0xC4
RETURN_TO_MARK = 0xC5
SEARCH_MARK_FORWARD = 0xC6
SEARCH_MARK_BACKWARDS = 0xC7
COUNTER_RESET = 0xC8
SHOW_COUNTER = 0xC9
TRACKING_INCREMENT = 0xCA
TRACKING_DECREMENT = 0xCB
VOLUME = 0xE0
BALANCE = 0xE1
MUTE = 0xE2
BASS = 0xE3
TREBLE = 0xE4
BASS_BOOST = 0xE5
SURROUND_MODE = 0xE6
LOUDNESS = 0xE7
MPX = 0xE8
VOLUME_UP = 0xE9
VOLUME_DOWN = 0xEA
SPEED_SELECT = 0xF0
PLAYBACK_SPEED = 0xF1
STANDARD_PLAY = 0xF2
LONG_PLAY = 0xF3
EXTENDED_PLAY = 0xF4
SLOW = 0xF5
FAN_ENABLE = 0x100
FAN_SPEED = 0x101
LIGHT = 0x102
LIGHT_ILLUMINATION_LEVEL = 0x103
CLIMATE_CONTROL_ENABLE = 0x104
ROOM_TEMPERATURE = 0x105
SECURITY_ENABLE = 0x106
FIRE_ALARM = 0x107
POLICE_ALARM = 0x108
BALANCE_RIGHT = 0x150
BALANCE_LEFT = 0x151
BASS_INCREMENT = 0x152
BASS_DECREMENT = 0x153
TREBLE_INCREMENT = 0x154
TREBLE_DECREMENT = 0x155
SPEAKER_SYSTEM = 0x160
CHANNEL_LEFT = 0x161
CHANNEL_RIGHT = 0x162
CHANNEL_CENTER = 0x163
CHANNEL_FRONT = 0x164
CHANNEL_CENTER_FRONT = 0x165
CHANNEL_SIDE = 0x166
CHANNEL_SURROUND = 0x167
CHANNEL_LOW_FREQUENCY_ENHANCEMENT = 0x168
CHANNEL_TOP = 0x169
CHANNEL_UNKNOWN = 0x16A
SUB_CHANNEL = 0x170
SUB_CHANNEL_INCREMENT = 0x171
SUB_CHANNEL_DECREMENT = 0x172
ALTERNATE_AUDIO_INCREMENT = 0x173
ALTERNATE_AUDIO_DECREMENT = 0x174
APPLICATION_LAUNCH_BUTTONS = 0x180
AL_LAUNCH_BUTTON_CONFIGURATION_TOOL = 0x181
AL_PROGRAMMABLE_BUTTON_CONFIGURATION = 0x182
AL_CONSUMER_CONTROL_CONFIGURATION = 0x183
AL_WORD_PROCESSOR = 0x184
AL_TEXT_EDITOR = 0x185
AL_SPREADSHEET = 0x186
AL_GRAPHICS_EDITOR = 0x187
AL_PRESENTATION_APP = 0x188
AL_DATABASE_APP = 0x189
AL_EMAIL_READER = 0x18A
AL_NEWSREADER = 0x18B
AL_VOICEMAIL = 0x18C
AL_CONTACTS = 0x18D # AL_CONTACTS/ADDRESS_BOOK
AL_ADDRESS_BOOK = AL_CONTACTS
AL_CALENDAR = 0x18E # AL_CALENDAR/SCHEDULE
AL_SCHEDULE = AL_CALENDAR
AL_PROJECT_MANAGER = 0x18F # AL_TASK/PROJECT_MANAGER
# AL_TASK_MANAGER = AL_PROJECT_MANAGER
AL_LOG = 0x193 # AL_LOG/JOURNAL/TIMECARD
AL_JOURNAL = AL_LOG
AL_TIMECARD = AL_LOG
AL_CHECKBOOK = 0x191 # AL_CHECKBOOK/FINANCE
AL_FINANCE = AL_CHECKBOOK
AL_CALCULATOR = 0x192
AL_AV_CAPTURE_PLAYBACK = 0x193 # AL_A/V_CAPTURE/PLAYBACK
AL_LOCAL_MACHINE_BROWSER = 0x194
AL_LAN_BROWSER = 0x195 # AL_LAN/WAN_BROWSER
AL_WAN_BROWSER = AL_LAN_BROWSER
AL_INTERNET_BROWSER = 0x196
AL_REMOTE_NETWORKING = 0x197 # AL_REMOTE_NETWORKING/ISP_CONNECT
AL_ISP_CONNECT = AL_REMOTE_NETWORKING
AL_NETWORK_CONFERENCE = 0x198
AL_NETWORK_CHAT = 0x199
AL_TELEPHONY = 0x19A # AL_TELEPHONY/DIALER
AL_DIALER = AL_TELEPHONY
AL_LOGON = 0x19B
AL_LOGOFF = 0x19C
AL_LOGON_LOGOFF = 0x19D # AL_LOGON/LOGOFF
AL_TERMINAL_LOCK = 0x19E # AL_TERMINAL_LOCK/SCREENSAVER
AL_SCREENSAVER = AL_TERMINAL_LOCK
AL_CONTROL_PANEL = 0x19F
AL_COMMAND_LINE_PROCESSOR = 0x1A0 # AL_COMMAND_LINE_PROCESSOR/RUN
AL_RUN = AL_COMMAND_LINE_PROCESSOR
AL_PROCESS_MANAGER = 0x1A1 # AL_PROCESS/TASK_MANAGER
AL_TASK_MANAGER = AL_PROCESS_MANAGER
AL_SELECT_TASK = 0x1A2 # AL_SELECT_TASK/APPLICATION
AL_SELECT_APPLICATION = AL_SELECT_TASK
AL_NEXT_TASK = 0x1A3 # AL_NEXT_TASK/APPLICATION
AL_NEXT_APPLICATION = AL_NEXT_TASK
AL_PREVIOUS_TASK = 0x1A4 # AL_PREVIOUS_TASK/APPLICATION
AL_PREVIOUS_APPLICATION = AL_PREVIOUS_TASK
AL_PREEMPTIVE_HALT_TASK = 0x1A5 # AL_PREEMPTIVE_HALT_TASK/APPLICATION
AL_PREEMPTIVE_HALT_APPLICATION = AL_PREEMPTIVE_HALT_TASK
GENERIC_GUI_APPLICATION_CONTROLS = 0x200
AC_NEW = 0x201
AC_OPEN = 0x202
AC_CLOSE = 0x203
AC_EXIT = 0x204
AC_MAXIMIZE = 0x205
AC_MINIMIZE = 0x206
AC_SAVE = 0x207
AC_PRINT = 0x208
AC_PROPERTIES = 0x209
AC_UNDO = 0x21A
AC_COPY = 0x21B
AC_CUT = 0x21C
AC_PASTE = 0x21D
AC_SELECT_ALL = 0x21E
AC_FIND = 0x21F
AC_FIND_AND_REPLACE = 0x220
AC_SEARCH = 0x221
AC_GO_TO = 0x222
AC_HOME = 0x223
AC_BACK = 0x224
AC_FORWARD = 0x225
AC_STOP = 0x226
AC_REFRESH = 0x227
AC_PREVIOUS_LINK = 0x228
AC_NEXT_LINK = 0x229
AC_BOOKMARKS = 0x22A
AC_HISTORY = 0x22B
AC_SUBSCRIPTIONS = 0x22C
AC_ZOOM_IN = 0x22D
AC_ZOOM_OUT = 0x22E
AC_ZOOM = 0x22F
AC_FULL_SCREEN_VIEW = 0x230
AC_NORMAL_VIEW = 0x231
AC_VIEW_TOGGLE = 0x232
AC_SCROLL_UP = 0x233
AC_SCROLL_DOWN = 0x234
AC_SCROLL = 0x235
AC_PAN_LEFT = 0x236
AC_PAN_RIGHT = 0x237
AC_PAN = 0x238
AC_NEW_WINDOW = 0x239
AC_TILE_HORIZONTALLY = 0x23A
AC_TILE_VERTICALLY = 0x23B
AC_FORMAT = 0x23C
|
'''
Maximum sum with modified positions
Status: Accepted
'''
###############################################################################
def main():
"""Read input and print output"""
_ = input()
numbers = list(map(int, input().split()))
unmoved, zero_index = 0, numbers.index(0)
for coeff, i in enumerate(numbers, start=1):
unmoved += coeff * i
maximal, nsum = unmoved, unmoved
for i in numbers[zero_index + 1:]:
nsum -= i
maximal = max(nsum, maximal)
nsum = unmoved
for i in reversed(numbers[:zero_index]):
nsum += i
maximal = max(nsum, maximal)
print(maximal)
###############################################################################
if __name__ == '__main__':
main()
|
name = 'tinymce'
authors = 'Joost Cassee'
version = 'trunk'
release = version
|
n = input('Digite o seu nome completo: ') .strip()
print('Seu nome com todas as letras maiúsculas: {}.'.format(n.upper()))
print('Seu nome com todas as letras minúsculas: {}.' .format(n.lower()))
print('Seu nome tem {} letras.' .format(len(n.replace(' ', ''))))
print('Seu primeiro nome tem {} letras.' .format(len(n.split()[0])))
|
#
# PySNMP MIB module PPVPN-TC (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/PPVPN-TC
# Produced by pysmi-0.3.4 at Mon Apr 29 20:33:05 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")
ConstraintsIntersection, ValueRangeConstraint, ValueSizeConstraint, ConstraintsUnion, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ValueRangeConstraint", "ValueSizeConstraint", "ConstraintsUnion", "SingleValueConstraint")
NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance")
Integer32, IpAddress, Gauge32, Unsigned32, ModuleIdentity, Bits, Counter64, Counter32, MibIdentifier, TimeTicks, MibScalar, MibTable, MibTableRow, MibTableColumn, iso, ObjectIdentity, NotificationType = mibBuilder.importSymbols("SNMPv2-SMI", "Integer32", "IpAddress", "Gauge32", "Unsigned32", "ModuleIdentity", "Bits", "Counter64", "Counter32", "MibIdentifier", "TimeTicks", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "iso", "ObjectIdentity", "NotificationType")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
class VPNId(TextualConvention, OctetString):
reference = "RFC 2685, Fox & Gleeson, 'Virtual Private Networks Identifier', September 1999."
status = 'current'
subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(0, 7)
mibBuilder.exportSymbols("PPVPN-TC", VPNId=VPNId)
|
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def removeElements(self, head, val):
"""
:type head: ListNode
:type val: int
:rtype: ListNode
"""
cur = head
head = tail = None
while cur:
if cur.val != val:
if head:
tail.next = cur
tail = cur
else:
head = tail = cur
cur = cur.next
if tail: tail.next = None
return head
|
# DESAFIO 043
# Desenvolva uma lógica que leia o peso e a altura de uma pessoa, calcule seu IMC e mostre seu status,
# de acordo com a tabela abaixo:
# Abaixo de 18.5: ABAIXO DO PESO, entre 18.5 e 25: PESO IDEAL, 25 a 30: SOBREPESO
# 30 até 40: OBESIDADE, acima de 40: OBESIDADE MÓRBIDA.
peso = float(input('Qual seu peso? (Kg) '))
alt = float(input('Qual sua altura? (m) '))
imc = peso / (alt ** 2)
print(f'Seu IMC é de {imc:.2f}')
if imc < 18.5:
print('Você está ABAIXO DO PESO')
elif imc < 25:
print('Você está no PESO IDEAL')
elif imc < 30:
print('Você está com SOBREPESO')
elif imc < 40:
print('Você está com OBESIDADE')
else:
print('Você está com OBESIDADE MÓRBIDA')
|
with open('../input.txt','rt') as f:
lst = set(map(int,f.readlines()))
for x in lst:
if 2020-x in lst:
print(x*(2020-x))
|
print("Calculator has started")
while True:
a = float(input("Enter first number "))
b = float(input("Enter second number "))
chooseop=1
while (chooseop == 1) | (chooseop == 2) | (chooseop == 3) | (chooseop == 4):
chooseop = int(input("Enter 1 for addition, 2 for subtraction, 3 for multiplication and 4 for division "))
print(chooseop)
if chooseop == 1:
print(a+b)
break
elif chooseop == 2:
print(a-b)
break
elif chooseop == 3:
print(a*b)
break
elif chooseop == 4:
if b == 0:
print("Can't divide by zero")
else:
print(a/b)
break
elif (chooseop != 1) & (chooseop != 2) & (chooseop != 3) & (chooseop != 4):
print("Invalid operation number")
|
class node:
def __init__(self,value=None):
self.value=value
self.left_child=None
self.right_child=None
self.parent=None # pointer to parent node in tree
self.height=1 # height of node in tree (max dist. to leaf) NEW FOR AVL
class AVLTree:
def __init__(self):
self.root=None
def __repr__(self):
if self.root==None: return ''
content='\n' # to hold final string
cur_nodes=[self.root] # all nodes at current level
cur_height=self.root.height # height of nodes at current level
sep=' '*(2**(cur_height-1)) # variable sized separator between elements
while True:
cur_height+=-1 # decrement current height
if len(cur_nodes)==0: break
cur_row=' '
next_row=''
next_nodes=[]
if all(n is None for n in cur_nodes):
break
for n in cur_nodes:
if n==None:
cur_row+=' '+sep
next_row+=' '+sep
next_nodes.extend([None,None])
continue
if n.value!=None:
buf=' '*int((5-len(str(n.value)))/2)
cur_row+='%s%s%s'%(buf,str(n.value),buf)+sep
else:
cur_row+=' '*5+sep
if n.left_child!=None:
next_nodes.append(n.left_child)
next_row+=' /'+sep
else:
next_row+=' '+sep
next_nodes.append(None)
if n.right_child!=None:
next_nodes.append(n.right_child)
next_row+='\ '+sep
else:
next_row+=' '+sep
next_nodes.append(None)
content+=(cur_height*' '+cur_row+'\n'+cur_height*' '+next_row+'\n')
cur_nodes=next_nodes
sep=' '*int(len(sep)/2) # cut separator size in half
return content
def insert(self,value):
if self.root==None:
self.root=node(value)
else:
self._insert(value,self.root)
def _insert(self,value,cur_node):
if value<cur_node.value:
if cur_node.left_child==None:
cur_node.left_child=node(value)
cur_node.left_child.parent=cur_node # set parent
self._inspect_insertion(cur_node.left_child)
else:
self._insert(value,cur_node.left_child)
elif value>cur_node.value:
if cur_node.right_child==None:
cur_node.right_child=node(value)
cur_node.right_child.parent=cur_node # set parent
self._inspect_insertion(cur_node.right_child)
else:
self._insert(value,cur_node.right_child)
else:
print("Value already in tree!")
def print_tree(self):
if self.root!=None:
self._print_tree(self.root)
def _print_tree(self,cur_node):
if cur_node!=None:
self._print_tree(cur_node.left_child)
print ('%s, h=%d'%(str(cur_node.value),cur_node.height))
self._print_tree(cur_node.right_child)
def height(self):
if self.root!=None:
return self._height(self.root,0)
else:
return 0
def _height(self,cur_node,cur_height):
if cur_node==None: return cur_height
left_height=self._height(cur_node.left_child,cur_height+1)
right_height=self._height(cur_node.right_child,cur_height+1)
return max(left_height,right_height)
def find(self,value):
if self.root!=None:
return self._find(value,self.root)
else:
return None
def _find(self,value,cur_node):
if value==cur_node.value:
return cur_node
elif value<cur_node.value and cur_node.left_child!=None:
return self._find(value,cur_node.left_child)
elif value>cur_node.value and cur_node.right_child!=None:
return self._find(value,cur_node.right_child)
def delete_value(self,value):
return self.delete_node(self.find(value))
def delete_node(self,node):
## -----
# Improvements since prior lesson
# Protect against deleting a node not found in the tree
if node==None or self.find(node.value)==None:
print("Node to be deleted not found in the tree!")
return None
## -----
# returns the node with min value in tree rooted at input node
def min_value_node(n):
current=n
while current.left_child!=None:
current=current.left_child
return current
# returns the number of children for the specified node
def num_children(n):
num_children=0
if n.left_child!=None: num_children+=1
if n.right_child!=None: num_children+=1
return num_children
# get the parent of the node to be deleted
node_parent=node.parent
# get the number of children of the node to be deleted
node_children=num_children(node)
# break operation into different cases based on the
# structure of the tree & node to be deleted
# CASE 1 (node has no children)
if node_children==0:
if node_parent!=None:
# remove reference to the node from the parent
if node_parent.left_child==node:
node_parent.left_child=None
else:
node_parent.right_child=None
else:
self.root=None
# CASE 2 (node has a single child)
if node_children==1:
# get the single child node
if node.left_child!=None:
child=node.left_child
else:
child=node.right_child
if node_parent!=None:
# replace the node to be deleted with its child
if node_parent.left_child==node:
node_parent.left_child=child
else:
node_parent.right_child=child
else:
self.root=child
# correct the parent pointer in node
child.parent=node_parent
# CASE 3 (node has two children)
if node_children==2:
# get the inorder successor of the deleted node
successor=min_value_node(node.right_child)
# copy the inorder successor's value to the node formerly
# holding the value we wished to delete
node.value=successor.value
# delete the inorder successor now that it's value was
# copied into the other node
self.delete_node(successor)
# exit function so we don't call the _inspect_deletion twice
return
if node_parent!=None:
# fix the height of the parent of current node
node_parent.height=1+max(self.get_height(node_parent.left_child),self.get_height(node_parent.right_child))
# begin to traverse back up the tree checking if there are
# any sections which now invalidate the AVL balance rules
self._inspect_deletion(node_parent)
def search(self,value):
if self.root!=None:
return self._search(value,self.root)
else:
return False
def _search(self,value,cur_node):
if value==cur_node.value:
return True
elif value<cur_node.value and cur_node.left_child!=None:
return self._search(value,cur_node.left_child)
elif value>cur_node.value and cur_node.right_child!=None:
return self._search(value,cur_node.right_child)
return False
# Functions added for AVL...
def _inspect_insertion(self,cur_node,path=[]):
if cur_node.parent==None: return
path=[cur_node]+path
left_height =self.get_height(cur_node.parent.left_child)
right_height=self.get_height(cur_node.parent.right_child)
if abs(left_height-right_height)>1:
path=[cur_node.parent]+path
self._rebalance_node(path[0],path[1],path[2])
return
new_height=1+cur_node.height
if new_height>cur_node.parent.height:
cur_node.parent.height=new_height
self._inspect_insertion(cur_node.parent,path)
def _inspect_deletion(self,cur_node):
if cur_node==None: return
left_height =self.get_height(cur_node.left_child)
right_height=self.get_height(cur_node.right_child)
if abs(left_height-right_height)>1:
y=self.taller_child(cur_node)
x=self.taller_child(y)
self._rebalance_node(cur_node,y,x)
self._inspect_deletion(cur_node.parent)
def _rebalance_node(self,z,y,x):
if y==z.left_child and x==y.left_child:
self._right_rotate(z)
elif y==z.left_child and x==y.right_child:
self._left_rotate(y)
self._right_rotate(z)
elif y==z.right_child and x==y.right_child:
self._left_rotate(z)
elif y==z.right_child and x==y.left_child:
self._right_rotate(y)
self._left_rotate(z)
else:
raise Exception('_rebalance_node: z,y,x node configuration not recognized!')
def _right_rotate(self,z):
sub_root=z.parent
y=z.left_child
t3=y.right_child
y.right_child=z
z.parent=y
z.left_child=t3
if t3!=None: t3.parent=z
y.parent=sub_root
if y.parent==None:
self.root=y
else:
if y.parent.left_child==z:
y.parent.left_child=y
else:
y.parent.right_child=y
z.height=1+max(self.get_height(z.left_child),
self.get_height(z.right_child))
y.height=1+max(self.get_height(y.left_child),
self.get_height(y.right_child))
def _left_rotate(self,z):
sub_root=z.parent
y=z.right_child
t2=y.left_child
y.left_child=z
z.parent=y
z.right_child=t2
if t2!=None: t2.parent=z
y.parent=sub_root
if y.parent==None:
self.root=y
else:
if y.parent.left_child==z:
y.parent.left_child=y
else:
y.parent.right_child=y
z.height=1+max(self.get_height(z.left_child),
self.get_height(z.right_child))
y.height=1+max(self.get_height(y.left_child),
self.get_height(y.right_child))
def get_height(self,cur_node):
if cur_node==None: return 0
return cur_node.height
def taller_child(self,cur_node):
left=self.get_height(cur_node.left_child)
right=self.get_height(cur_node.right_child)
return cur_node.left_child if left>=right else cur_node.right_child
|
"""
Bubbles_R-Us Inc
As pesquisas contínua da empresa Bubbles_R-Us Inc garantem que as várias máquinas
de bolhas espalhadas por várias partes do páis produzam as melhores bolhas de sabão.
Hoje eles estão testando uma nova amostragem o "fator bolhas" de inúmeras formulações
diferentes de sua solução nova de bolhas de sabão. Ou seja estão testando quantas bolhas
podem ser produzidas a partir de uma determinada solução.
O que a empresa Bubbles_R-Us Inc precisa que voçê desenvolva:
[x] - Como receberam vários testes novos de bolhas, eles precisam de um sistema que liste
as novas soluções e seus escores correspondentes. Ex: 'Bubble Solution #0 score: 60'
Os novos escores: 60, 50, 60, 58, 54, 54, 58, 50, 52, 54, 48, 69, 34, 55, 51, 52,
44, 51, 69, 64, 66, 55, 52, 61, 46, 31, 57, 52, 44, 18, 41, 53,
55, 61, 51, 44
[x] - Preciso visualizar o numero total de scores de bolhas. Ex: 'Bubbles tests: 36'
[x] - Preciso visualizar o numero de escore mais alto. Ex: 'Highest bubble score: 69'
[x] - Preciso visualizar cada solução que conteve o mesmo valor de escore mais alto.
[ ] - Notícia de ultima hora! Descobrir a melhor solução com o custo benefício. Com
esse dado final, definitivamente dominaremos o mercado de soluções de bolhas.
Segue a lista de custo: .25, .27, .25, .25, .25, .25, .33, .31, .25, .29, .27,
.22, .31, .25, .25, .33, .21, .25, .25, .25, .28, .25,
.24, .22, .20, .25, .30, .25, .24, .25, .25, .25, .27,
.25, .26, .29
"""
scores = [60, 50, 60, 58, 54, 54, 58, 50, 52, 54, 48, 69, 34, 55, 51, 52, 44, 51, 69, 64,
66, 55, 52, 61, 46, 31, 57, 52, 44, 18, 41, 53, 55, 61, 51, 44]
costs = [.25, .27, .25, .25, .25, .25, .33, .31, .25, .29, .27, .22, .31, .25, .25, .33,
.21, .25, .25, .25, .28, .25, .24, .22, .20, .25, .30, .25, .24, .25, .25, .25,
.27, .25, .26, .29]
highScore = 0
length = len(scores)
for i in range(length):
print('Bubble solution #' + str(i), 'score:', scores[i])
if scores[i] > highScore:
highScore = scores[i]
print('Bubbles tests: ', length)
print('Highest bubble score: ', highScore)
bestSolution = []
for i in range(length):
if highScore == scores[i]:
bestSolution.append(i)
print('Solutions with highest score: ', bestSolution)
cost = 100.0
mostEffective = 0
for i in range(len(bestSolution)):
index = bestSolution[i]
if cost > costs[index]:
mostEffective = index
cost = costs[index]
print('Solution', mostEffective, 'is the most effective with a cost of', costs[mostEffective])
|
# for i in range(1, 5):
# n = int(input('\tDigite um valor: '))
# print('\n\tFIM')
# n = -1
# while n != 0:
# n = int(input('\tDigite um valor (0 para finalizar): '))
# print('\n\tFIM')
resp = 'sim'
while resp == 'sim':
n = int(input('\n\tDigite um valor: '))
resp = input('\tDeseja continuar? (sim / não) >').strip().lower()
print('\n\tFIM')
input('\n\nPressione <enter> para continuar')
|
class Solution:
def lexicalOrder(self, n):
"""
:type n: int
:rtype: List[int]
"""
results = [n for n in range(1, n+1)]
results.sort(key= lambda x: str(x))
return results
|
class Boid():
def __init__(self, x,y,width,height):
self.position = Vector(x,y)
|
if __name__ == '__main__':
print('集合Set')
# 集合特性:
# 集合中元素无序;
# 集合中不存在重复元素;
# 任意元素一定存在或不存在一个集合中;
# 集合的成员运算在性能上要优于列表的成员运算,这是集合的底层存储特性(哈希存储)决定的
# 创建集合
# 创建集合的字面量语法(重复元素不会出现在集合中)
# {}中需要至少有一个元素,因为没有元素的{}并不是空集合而是一个空字典
set1 = {1, 2, 3, 3, 3, 2}
print(set1) # {1, 2, 3}
print(len(set1)) # 3
# 创建集合的构造器语法(后面会讲到什么是构造器)
set2 = set('hello')
print(set2) # {'h', 'l', 'o', 'e'}
# 将列表转换成集合(可以去掉列表中的重复元素)
set3 = set([1, 2, 3, 3, 2, 1])
print(set3) # {1, 2, 3}
# 创建集合的生成式语法(将列表生成式的[]换成{})
set4 = {num for num in range(1, 20) if num % 3 == 0 or num % 5 == 0}
print(set4) # {3, 5, 6, 9, 10, 12, 15, 18}
# 集合元素的循环遍历
for elem in set4:
print(elem)
# 集合中的元素必须是hashable类型,即能够计算出哈希码的数据类型;
# 通常不可变类型都是hashable类型,如整数、浮点、字符串、元组等,而可变类型都不是hashable类型;
# 集合本身也是可变类型,所以集合不能够作为集合中的元素;
# set5 = {[1, 2], [3, 3], [3, 2]}
# print(set5) # TypeError: unhashable type: 'list'
# 成员运算
set1 = {11, 12, 13, 14, 15}
print(10 in set1) # False
print(15 in set1) # True
set2 = {'Python', 'Java', 'Go', 'Swift'}
print('Ruby' in set2) # False
print('Java' not in set2) # False
# 交集、并集、差集运算
set1 = {1, 2, 3, 4, 5, 6, 7}
set2 = {2, 4, 6, 8, 10}
# 交集
# 方法一: 使用 & 运算符
print(set1 & set2) # {2, 4, 6}
# 方法二: 使用intersection方法
print(set1.intersection(set2)) # {2, 4, 6}
# 并集
# 方法一: 使用 | 运算符
print(set1 | set2) # {1, 2, 3, 4, 5, 6, 7, 8, 10}
# 方法二: 使用union方法
print(set1.union(set2)) # {1, 2, 3, 4, 5, 6, 7, 8, 10}
# 差集
# 方法一: 使用 - 运算符
print(set1 - set2) # {1, 3, 5, 7}
# 方法二: 使用difference方法
print(set1.difference(set2)) # {1, 3, 5, 7}
# 对称差
# 方法一: 使用 ^ 运算符
print(set1 ^ set2) # {1, 3, 5, 7, 8, 10}
# 方法二: 使用symmetric_difference方法
print(set1.symmetric_difference(set2)) # {1, 3, 5, 7, 8, 10}
# 方法三: 对称差相当于两个集合的并集减去交集
print((set1 | set2) - (set1 & set2)) # {1, 3, 5, 7, 8, 10}
# 复合赋值运算
set1 = {1, 3, 5, 7}
set2 = {2, 4, 6}
# 将set1和set2求并集再赋值给set1
# 也可以通过set1.update(set2)来实现
set1 |= set2
print(set1) # {1, 2, 3, 4, 5, 6, 7}
set3 = {3, 6, 9}
# 将set1和set3求交集再赋值给set1
# 也可以通过set1.intersection_update(set3)来实现
set1 &= set3
print(set1) # {3, 6}
# 比较运算,比较两个集合 子集、真子集、超集
set1 = {1, 3, 5}
set2 = {1, 2, 3, 4, 5}
set3 = set2
# <运算符表示真子集,<=运算符表示子集
print(set1 < set2, set1 <= set2) # True True
print(set2 < set3, set2 <= set3) # False True
# 通过issubset方法也能进行子集判断
print(set1.issubset(set2)) # True
# 反过来可以用issuperset或>运算符进行超集判断
print(set2.issuperset(set1)) # True
print(set2 > set1) # True
# 添加元素
# 创建一个空集合
set1 = set()
# 通过add方法或update方法添加元素
set1.add(33)
set1.add(55)
set1.update({1, 10, 100, 1000})
print(set1) # {33, 1, 100, 55, 1000, 10}
# 通过discard方法删除指定元素,若不存在不会报异常
set1.discard(100)
set1.discard(99)
print(set1) # {33, 1, 55, 1000, 10}
# 通过remove方法删除指定元素,建议先做成员运算再删除
# 否则元素如果不在集合中就会引发KeyError异常
if 10 in set1:
set1.remove(10)
print(set1) # {33, 1, 55, 1000}
# pop方法可以从集合中随机删除一个元素并返回该元素
print(set1.pop())
# clear方法可以清空整个集合
set1.clear()
print(set1) # set()
# 判断两个集合有没有相同的元素可以使用isdisjoint方法,没有相同元素返回True,否则返回False
set1 = {'Java', 'Python', 'Go', 'Kotlin'}
set2 = {'Kotlin', 'Swift', 'Java', 'Objective-C', 'Dart'}
set3 = {'HTML', 'CSS', 'JavaScript'}
print(set1.isdisjoint(set2)) # False
print(set1.isdisjoint(set3)) # True
# 不可变集合frozenset,不可变类型 ,有哈希码,可以当成set的元素。
# frozenset无法添加删除元素,其他方面与set一致
set1 = frozenset({1, 3, 5, 7})
set2 = frozenset(range(1, 6))
print(set1 & set2) # frozenset({1, 3, 5})
print(set1 | set2) # frozenset({1, 2, 3, 4, 5, 7})
print(set1 - set2) # frozenset({7})
print(set1 < set2) # False
|
class PaginationType:
LIMIT = 'limit'
OFFSET = 'offset'
PAGINATION_LIMIT = 100
class Pagination:
"""
"""
LIMIT = 20
OFFSET = 0
@staticmethod
def validate(pagination_type, value):
"""
:param pagination_type:
:param value:
:return:
"""
try:
if str(pagination_type).lower() == PaginationType.LIMIT:
if int(value) > PAGINATION_LIMIT:
value = PAGINATION_LIMIT
elif int(value) < 0:
value = Pagination.OFFSET
else:
if int(value) < 0:
value = Pagination.OFFSET
except Exception as err:
if str(pagination_type).lower() == PaginationType.LIMIT:
value = Pagination.LIMIT
else:
value = Pagination.OFFSET
return int(value)
class Order:
ASC = 'ASC'
DESC = 'DESC'
@staticmethod
def validate(value):
if value != Order.ASC:
value = Order.DESC
return value
|
# Area of a Triangle
print("Write a function that takes the base and height of a triangle and return its area.")
def area():
base = float(int(input("Enter the Base of the Triangle : ")))
height = float(int(input("Enter the height of the Triangle : ")))
total_area = (base * height)/2
print(total_area)
area()
# Program not closed emmidately
input("Please Click to Enter to End the Program ")
|
'''Faça um Programa para uma loja de tintas.
O programa deverá pedir o tamanho em metros quadrados da área a ser pintada.
Considere que a cobertura da tinta é de 1 litro para cada 6 metros quadrados e
que a tinta é vendida em latas de 18 litros,
que custam R$ 80,00 ou em galões de 3,6 litros, que custam R$ 25,00.
Informe ao usuário as quantidades de tinta a serem compradas e os respectivos preços em 3 situações:
comprar apenas latas de 18 litros;
comprar apenas galões de 3,6 litros;
misturar latas e galões, de forma que o desperdício de tinta seja menor.
Acrescente 10% de folga e sempre arredonde os valores para cima, isto é, considere latas cheias.'''
metros = float(input('Digite a o tamanho da area a ser pintada em metros:'))
litros = metros/6
latas = 18
galoes = 3.6
quantidade_latas = litros * latas
print('a quantiddade de latas a ser usadas é: ', quantidade_latas)
valor_latas = quantidade_latas * 80
print('O valor se opção latas R$ ' ,valor_latas )
quantidade_galoes = quantidade_latas * galoes
print('A quantidade se a opção for galões é: ', quantidade_galoes)
valor_galoes = quantidade_galoes * 25
print('O valor se opção for galões R$', valor_galoes)
|
"""
Exercise: <font color='red'>(⏰ 5 min) Define a function that
takes as input an RGB image and a pair of coordinates (row,
column), and returns a copy with a green letter H overlaid at
those coordinates. The coordinates point to the top-left corner
of the H.
The arms and strut of the H should have a width of 3 pixels,
and the H itself should have a height of 24 pixels and width of
20 pixels.
Start with the following template:
def draw_H(image, coords, color=(0, 255, 0)):
image_with_H = image.copy()
...
return image_with_H
"""
def draw_H(image, coords, color=(0, 255, 0)):
"""
Draws the letter H within an input image.
"""
image_with_H = image.copy()
canvas = image_with_H[coords[0]:coords[0] + 24,
coords[1]:coords[1] + 20]
canvas[:, :3] = color
canvas[:, -3:] = color
canvas[11:14] = color
return image_with_H
"""
Exercise: (⏰ 5 min) Display the different color channels of `chelsea`
along, each as a gray-scale image.
"""
chelsea = data.chelsea()
# First, assign each color channel to a different variable.
channel_r = chelsea[:, :, 0]
channel_g = chelsea[:, :, 1]
channel_b = chelsea[:, :, 2]
# Then, display the image and the red, green and blue channels.
_, (ax_r, ax_g, ax_b, ax_color) = plt.subplots(nrows=1, ncols=4, figsize=(16, 5))
ax_r.imshow(channel_r, cmap='gray')
ax_r.set_title('Red channel')
ax_r.axis('off')
ax_g.imshow(channel_g, cmap='gray')
ax_g.set_title('Green channel')
ax_g.axis('off')
ax_b.imshow(channel_b, cmap='gray')
ax_b.set_title('Blue channel')
ax_b.axis('off')
# Here we rebuild the color image stacking the R, G, and B layers again.
ax_color.imshow(np.stack([channel_r, channel_g, channel_b], axis=2))
ax_color.set_title('All channels');
ax_color.axis('off')
|
"""
Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.
Example:
Input: [1,2,3,null,5,null,4]
Output: [1, 3, 4]
Explanation:
1 <---
/ \
2 3 <---
\ \
5 4 <---
"""
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def rightSideView(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
"""
Method 1: BFS
Same BFS logic as 515, 451, 102
* Create a result array, res containing the root node value
* Create a queue with the res node and 'X'
* While queue: pop the first node
The first node can either be a node or 'X'
* IF 'X', then this indicates that we have
all the elements in that node of the tree;
then take the RIGHTmost element i.e. arr[-1]
to obtain the right side view
* ELSE append the left and right node elements
to the queue
Your runtime beats 96.51 % of python submissions.
"""
# #Boundary conditions
if not root:
return []
if root and ((not root.left) and (not root.right)):
return [root.val]
res = [root.val]
queue = [root, 'X']
while queue:
node = queue.pop(0)
if node == 'X':
if queue:
res.append([ele.val for ele in queue][-1])
queue.append('X')
else:
# #Left comes before right in level order traversal
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
# print([ele.val if ele != 'X' else ele for ele in queue])
return res
|
def make_pizza(*toppings):
print(toppings)
# for item in toppings:
# print("Add " + item)
|
class Solution:
def numSplits(self, s: str) -> int:
answer=0
left=[0]*26
right=[0]*26
for x in s:
right[ord(x)-ord('a')]+=1
leftNum=0
rightNum=sum(x > 0 for x in right)
for x in s:
index=ord(x)-ord('a')
if left[index]==0:
leftNum+=1
left[index]+=1
right[index]-=1
if right[index]==0:
rightNum-=1
if leftNum==rightNum:
answer+=1
return answer
|
#!/usr/bin/python3
# -*- mode: python; coding: utf-8 -*-
VERSION=1
TEMPLATE_KEY_PREFIX = 'jflow.template'
SEPARATOR_KEY = '.'
KEY_VERSION = 'version'
KEY_FORK = 'fork'
KEY_UPSTREAM = 'upstream'
KEY_PUBLIC = 'public'
KEY_DEBUG = 'debug'
KEY_REMOTE = 'remote'
KEY_MERGE_TO = 'merge-to'
KEY_EXTRA = 'extra'
# Template-only keys
KEY_PUBLIC_PREFIX = 'public-prefix'
KEY_PUBLIC_SUFFIX = 'public-suffix'
KEY_DEBUG_PREFIX = 'debug-prefix'
KEY_DEBUG_SUFFIX = 'debug-suffix'
KEY_REMOTE_PREFIX = 'remote-prefix'
KEY_REMOTE_SUFFIX = 'remote-suffix'
DEFAULT_DEBUG_PREFIX = 'feature/'
DEFAULT_DEBUG_SUFFIX = '.debug'
STGIT_SUFFIX = '.stgit'
def make_key(*items):
return SEPARATOR_KEY.join(items)
def make_prefix(*items):
return make_key(*items) + SEPARATOR_KEY
def make_suffix(*items):
return SEPARATOR_KEY + make_key(*items)
def branch_key_base(b):
return make_key('branch', b, 'jflow')
def branch_key_version(b):
return make_key(branch_key_base(b), KEY_VERSION)
def branch_key_fork(b):
return make_key(branch_key_base(b), KEY_FORK)
def branch_key_upstream(b):
return make_key(branch_key_base(b), KEY_UPSTREAM)
def branch_key_public(b):
return make_key(branch_key_base(b), KEY_PUBLIC)
def branch_key_debug(b):
return make_key(branch_key_base(b), KEY_DEBUG)
def branch_key_debug_prefix(b):
return make_key(branch_key_base(b), KEY_DEBUG_PREFIX)
def branch_key_debug_suffix(b):
return make_key(branch_key_base(b), KEY_DEBUG_SUFFIX)
def branch_key_remote(b):
return make_key(branch_key_base(b), KEY_REMOTE)
def branch_key_extra(b):
return make_key(branch_key_base(b), KEY_EXTRA)
def branch_key_merge_to(b):
return make_key(branch_key_base(b), KEY_MERGE_TO)
def branch_key_stgit_version(b):
return make_key('branch', b, 'stgit', 'stackformatversion')
def branch_key_description(b):
return make_key('branch', b, 'description')
def branch_stgit_name(b):
return b + STGIT_SUFFIX
def remote_key_url(r):
return make_key('remote', r, 'url')
|
"""
Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.
For example,
Given nums = [0, 1, 3] return 2.
Note:
Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space
complexity?
"""
__author__ = 'Daniel'
class Solution(object):
def missingNumber(self, nums):
"""
Algorithm:
Hashmap, but to save space, use the array itself as the hashmap
Notice:
nums[i], nums[nums[i]] = nums[nums[i]], nums[i]
Above is wrong, since evaluate from left to right; thus, when nums[nums[i]] on RHS is None, on LHS, nums[i] is
eval to None and nums[nums[i]] indexes by None, causing errors.
Alternatively, it is correct that:
nums[nums[i]], nums[i]= nums[i], nums[nums[i]]
To be safe, just use:
j = nums[i]
nums[i], nums[j] = nums[j], nums[i]
:type nums: List[int]
:rtype: int
"""
num_n = None
n = len(nums)
i = 0
while i < n:
if nums[i] == n:
num_n = nums[i]
nums[i] = None
i += 1
elif nums[i] is not None and nums[i] != i:
j = nums[i]
nums[i], nums[j] = nums[j], nums[i]
else:
i += 1
if not num_n:
return n
return nums.index(None)
if __name__ == "__main__":
assert Solution().missingNumber([2, 0]) == 1
|
while True:
print('Who are you?')
name=input()
if name!='Joe':
continue
print('Hello,Joe.What is the password?(it is a fish)')
password=input()
if password=='swordfish':
break
print('Access granted')
|
"""
Dinghy daily digest tool.
"""
__version__ = "0.12.0"
|
class SearchQuery(dict):
"""
A specialized dict which has helpers for creating and modifying a Search
Query document.
Example usage:
>>> from globus_sdk import SearchClient, SearchQuery
>>> sc = SearchClient(...)
>>> index_id = ...
>>> query = (SearchQuery(q='example query')
>>> .set_limit(100).set_offset(10)
>>> .add_filter('path.to.field1', ['foo', 'bar']))
>>> result = sc.post_search(index_id, query)
"""
def set_query(self, query):
self["q"] = query
return self
def set_limit(self, limit):
self["limit"] = limit
return self
def set_offset(self, offset):
self["offset"] = offset
return self
def set_advanced(self, advanced):
self["advanced"] = advanced
return self
def add_facet(
self,
name,
field_name,
type="terms",
size=None,
date_interval=None,
histogram_range=None,
**kwargs
):
self["facets"] = self.get("facets", [])
facet = {"name": name, "field_name": field_name, "type": type}
facet.update(kwargs)
if size is not None:
facet["size"] = size
if date_interval is not None:
facet["date_interval"] = date_interval
if histogram_range is not None:
low, high = histogram_range
facet["histogram_range"] = {"low": low, "high": high}
self["facets"].append(facet)
return self
def add_filter(self, field_name, values, type="match_all", **kwargs):
self["filters"] = self.get("filters", [])
new_filter = {"field_name": field_name, "values": values, "type": type}
new_filter.update(kwargs)
self["filters"].append(new_filter)
return self
def add_boost(self, field_name, factor, **kwargs):
self["boosts"] = self.get("boosts", [])
boost = {"field_name": field_name, "factor": factor}
boost.update(kwargs)
self["boosts"].append(boost)
return self
def add_sort(self, field_name, order=None, **kwargs):
self["sort"] = self.get("sort", [])
sort = {"field_name": field_name}
sort.update(kwargs)
if order is not None:
sort["order"] = order
self["sort"].append(sort)
return self
|
def GenerateConfig(context):
resources = []
haEnabled = context.properties['num_instances'] > 1
# Enabling services
services = {
'name': 'enable_services',
'type': 'enable_services.py',
'properties': {
'services': context.properties['services']
}
}
# Networking provisioning
networking = {
'name': 'networking',
'type': 'networking.py',
'properties': {
'ha_enabled': haEnabled,
'region': context.properties['region'],
'mgmt_network': context.properties['mgmt_network'],
'custom_route_tag': context.properties['custom_route_tag'],
# Using email from service_account's output
'service_account': '$(ref.service_accounts.email)',
'service_port': context.properties['service_port'],
'networks': context.properties['networks']
}
}
# Additional networtks
if 'inside_network' in context.properties:
networking['properties']['inside_network'] = context.properties['inside_network']
if 'outside_network' in context.properties:
networking['properties']['outside_network'] = context.properties['outside_network']
if 'dmz1_network' in context.properties:
networking['properties']['dmz1_network'] = context.properties['dmz1_network']
if 'dmz2_network' in context.properties:
networking['properties']['dmz2_network'] = context.properties['dmz2_network']
# Service Account
sa = {
'name': 'service_accounts',
'type': 'service_accounts.py',
'properties': {
'account_id': context.properties['account_id'],
'display_name': context.properties['display_name']
},
'metadata': {
'dependsOn': ['enable_services']
}
}
# Appliance VMs
vm = {
'name': 'vm',
'type': 'vm.py',
'properties': {
'vm_zones': context.properties['vm_zones'],
'num_instances': context.properties['num_instances'],
'cisco_product_version': context.properties['cisco_product_version'],
'vm_machine_type': context.properties['vm_machine_type'],
'vm_instance_labels': context.properties['vm_instance_labels'],
'vm_instance_tags': context.properties['vm_instance_tags'],
'admin_ssh_pub_key': context.properties['admin_ssh_pub_key'],
'day_0_config': context.properties['day_0_config'],
'service_account': '$(ref.service_accounts.email)',
'networks': context.properties['networks']
},
'metadata': {
'dependsOn': ['networking']
}
}
# Prepare all resources to be provisioned
resources += [services, sa, networking, vm]
outputs = [{
'name': 'vm_urls',
'value': '$(ref.vm.instance_urls)'
},{
'name': 'vm_external_ips',
'value': '$(ref.vm.vm_external_ips)'
}]
if haEnabled:
resources.append({
'name': 'load_balancer',
'type': 'load_balancer.py',
'properties': {
'region': context.properties['region'],
'num_instances': context.properties['num_instances'],
'vm_zones': context.properties['vm_zones'],
'named_ports': context.properties['named_ports'],
'service_port': context.properties['service_port'],
'allow_global_access': context.properties['allow_global_access'],
'inside_network': context.properties['inside_network'],
'use_internal_lb': context.properties['use_internal_lb']
# 'instance_urls': '$(ref.vm.instance_urls)'
},
'metadata': {
'dependsOn': ['vm']
}
})
outputs.append({
'name': 'external_lb_ip',
'value': '$(ref.load_balancer.external_lb_ip)'
})
if context.properties['use_internal_lb']:
outputs.append({
'name': 'internal_lb_ip',
'value': '$(ref.load_balancer.internal_lb_ip)'
})
return {'resources': resources, 'outputs': outputs}
|
# -*- encoding: utf-8 -*-
class UnWellcomeException(Exception):
"""
Base exception for all exceptions raised by this library.
"""
pass
|
# -*- encoding: utf-8 -*-
# Copyright (c) 2020 Modist Team <[email protected]>
# ISC License <https://choosealicense.com/licenses/isc>
"""Contains packaging information for the module."""
__name__ = "modist-client"
__repo__ = "https://github.com/modist-io/modist-client"
__version__ = "0.0.1"
__description__ = "The local client for managing Modist mods"
__author__ = "Modist Team"
__contact__ = "[email protected]"
__license__ = "ISC License"
|
minutos=int(input("digite os minutos de ligações: "))
if minutos<= 200:
conta=(minutos*0.20)
print("conta:R$ %.2f Reais" %conta)
if minutos >200<400:
conta=(minutos*0.18)
print("conta:R$ %.2f Reias" %conta)
elif minutos >400<800:
conta=(minutos*0.15)
print("conta:R$ %.2f Reais" %conta)
elif minutos >800:
conta=(minutos*0.08)
print("conta:R$ %.2f Reais" %conta)
|
def is_equivalent(str_a, str_b):
if len(str_a) % 2 != 0 or len(str_b) % 2 != 0:
if str_a == str_b:
return True
return False
elif str_a == str_b:
return True
else:
len_a = len(str_a)
len_b = len(str_b)
a1_i, a1_j = 0, (len_a // 2)
a2_i, a2_j = (len_a // 2), (len_a)
b1_i, b1_j = 0, (len_b // 2)
b2_i, b2_j = (len_b // 2), (len_b)
a1 = str_a[a1_i:a1_j]
a2 = str_a[a2_i:a2_j]
b1 = str_b[b1_i:b1_j]
b2 = str_b[b2_i:b2_j]
# print(a2_i)
# print(a2_j)
# print("a1: {} | a2: {}".format(a1, a2))
# print("b1: {} | b2: {}".format(b1, b2))
if is_equivalent(a1, b1) and is_equivalent(a2, b2):
return True
elif is_equivalent(a1, b2) and is_equivalent(a2, b1):
return True
return False
str_a = [el for el in input()]
str_b = [el for el in input()]
if is_equivalent(str_a, str_b):
print("YES")
else:
print("NO")
|
def test_nogarbage_fixture(testdir):
testdir.makepyfile("""
def test_fail(nogarbage):
assert False
def test_pass(nogarbage):
pass
def test_except(nogarbage):
try:
assert False
except AssertionError:
pass
def test_circular(nogarbage):
l1 = []
l2 = [l1]
l1.append(l2)
def test_collect(nogarbage):
import gc
gc.collect()
""")
result = testdir.runpytest(
'-v'
)
result.stdout.fnmatch_lines([
'*::test_fail FAIL*',
'*::test_pass PASS*',
'*::test_except PASS*',
'*::test_circular ERROR*',
'*::test_collect ERROR*',
])
assert result.ret != 0
|
def main():
# Store the total sum of multiples of 3 and 5
sum_multiples = 0
# Loop through every number less than 1000
for num in range(1,1000):
# Check if number is divisible by 3 or 5, i.e. a multiple
if num % 3 == 0 or num % 5 == 0:
sum_multiples += num
print(sum_multiples)
if __name__ == '__main__':
main()
|
# 177
# 10
# print(divmod(177, 10))
user = int(input())
user2 = int(input())
a = divmod(user, user2)
print(a[0])
print(a[1])
# for i in a:
# print(''.join(a[i]))
print(divmod(user,user2))
# print(divmod(user))
|
'''
Here we'll define exceptions to raise in the qtstyles package
'''
class QtStylesError(Exception):
""" Base-class for all exceptions raised by this module. """
class SheetPathTypeError(QtStylesError):
''' The style sheet path must be a string. '''
def __init__(self):
super(SheetPathTypeError, self).__init__(
"The style sheet path must be a string."
)
class SheetPathValueError(QtStylesError):
''' The style sheet path end in '.qss'. '''
def __init__(self):
super(SheetPathValueError, self).__init__(
"The style sheet path must end in '.qss'."
)
class SheetPathFileDoesntExist(QtStylesError):
''' The style sheet path must point to a file that exists. '''
def __init__(self):
super(SheetPathFileDoesntExist, self).__init__(
"No file exists at the path specified."
)
class StyleDoesntExistError(QtStylesError):
''' The provided style sheet path must exist. '''
def __init__(self):
super(StyleDoesntExistError, self).__init__(
"The requested style does not exist."
)
|
{
"targets": [{
"target_name": "node_hge",
"sources": [
"src/entry.cpp"
],
"include_dirs": [
"src/hge181/include",
"<!(node -e \"require('nan')\")"
],
"libraries": [
"../src/hge181/lib/vc/hge.lib",
"../src/hge181/lib/vc/hgehelp.lib"
],
"libraries!": [
"libc.lib"
],
"defines": [
"WIN32_LEAN_AND_MEAN"
],
"VCLinkerTool": {
"IgnoreSpecificDefaultLibraries": [
"libc.lib"
]
},
"copies": [{
"destination": "<(module_root_dir)/build/Release/",
"files": [ "<(module_root_dir)/src/hge181/hge.dll", "<(module_root_dir)/src/hge181/bass.dll" ]
}]
}]
}
|
question_replaceable_special_characters = {',', "'", '"', ';', '?', ':', '-', '(', ')', '[', ']', '{', '}'}
special_characters = ['*', '$']
punctuations = set()
pickled_questions_dir = "bin/data/questions"
pickle_files_extension = ".pickle"
questions_per_segment = 100
debug_print_len = 25
|
"""This problem was asked by Google.
Implement a key value store, where keys and values are integers, with the following methods:
update(key, vl): updates the value at key to val, or sets it if doesn't exist
get(key): returns the value with key, or None if no such value exists
max_key(val): returns the largest key with value val, or None if no key with that value exists
For example, if we ran the following calls:
kv.update(1, 1)
kv.update(2, 1)
And then called kv.max_key(1), it should return 2, since it's the largest key with value 1.
"""
|
# program r1_04.py
obiekt = 10
print(id(obiekt))
obiekt = "Wartość tekstowa"
print(id(obiekt))
obiekt = 3.14
print(id(obiekt))
obiekt = True
print(id(obiekt))
obiekt = [
3,
22.1,
"Adam",
]
print(id(obiekt))
obiekt = (33, "Linux", 5.873)
print(id(obiekt))
obiekt = {
2: "System",
"B": "Operacyjny",
5.5: 678,
"Adam": "Jurkiewicz",
}
print(id(obiekt))
|
class LoopiaError(Exception):
_exceptions = {}
code = None
message = None
def __init__(self, response=None):
super(LoopiaError, self).__init__(self.message)
self.response = response
@classmethod
def register(cls, exception):
if exception.code in cls._exceptions:
raise ValueError("'{}' already exists".format(exception.code))
cls._exceptions[exception.code] = exception
return exception
@classmethod
def from_code(cls, code, response=None):
if code not in cls._exceptions:
code = None
return cls._exceptions[code](response)
@LoopiaError.register
class UnknownError(LoopiaError):
code = None
message = "Unknown error"
@LoopiaError.register
class AuthError(LoopiaError):
code = "AUTH_ERROR"
message = u"Wrong username or password"
@LoopiaError.register
class DomainOccupiedError(LoopiaError):
code = "DOMAIN_OCCUPIED"
message = u"Domain is not available for registration"
@LoopiaError.register
class RateLimitedError(LoopiaError):
code = "RATE_LIMITED"
message = u"Maximum number of requests over time reached"
@LoopiaError.register
class BadIndataError(LoopiaError):
code = "BAD_INDATA"
message = u"Invalid parameters"
@LoopiaError.register
class InsufficientFundsError(LoopiaError):
code = "INSUFFICIENT_FUNDS"
message = u"Not enough funds to complete the task"
|
def paperwork(n, m):
if n < 0 or m < 0 : return 0
else: return n * m
print(paperwork(5,0))
|
def clocks(x, y, a, b, x2, y2):
a = a - x
b = b - y
if b < 0:
b = 60 + b
a = a - 1
if a < 0:
a = 24 + a
a2 = x2 + a
b2 = y2 + b
if b2 >= 60:
b2 = b2 - 60
a2 = a2 + 1
if a2 >= 24:
a2 = a2 - 24
print(a2, b2)
clocks(int(input()), int(input()), int(input()), int(input()), int(input()), int(input()))
|
#!/usr/bin/env python3
#
# Copyright (c) 2015, Roberto Riggio
# 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.
# * Neither the name of the CREATE-NET nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY CREATE-NET ''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 CREATE-NET 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.
"""Image Class."""
class Image(object):
"""Image object representing a VNF template.
Attributes:
nb_ports: Number of ports (Integer)
vnf: The virtual network function as a click script (str)
handlers: the list of handlers supported by the vnf
state_handlers: the list of state handlers supported by the vnf
"""
def __init__(self, nb_ports, vnf, state_handlers, handlers):
self.nb_ports = nb_ports
self.vnf = vnf
self.handlers = {}
self.state_handlers = []
self.add_handlers(handlers)
self.add_state_handlers(state_handlers)
def add_handlers(self, handlers):
"""add vnf-specifc handlers."""
for handler in handlers:
if not isinstance(handler, list):
raise ValueError("list expected")
if len(handler) != 2:
raise ValueError("list of length 2 expected")
self.handlers[handler[0]] = handler[1]
def add_state_handlers(self, state_handlers):
"""Add state handlers."""
for state_handler in state_handlers:
if state_handler not in self.handlers:
raise KeyError("state handler %s not found" % state_handler)
self.state_handlers.append(state_handler)
def to_dict(self):
""" Return a JSON-serializable dictionary representing the Poll """
return {'nb_ports': self.nb_ports,
'vnf': self.vnf,
'state_handlers': self.state_handlers,
'handlers': [(k, v) for k, v in self.handlers.items()]}
|
#_*_ coding: utf-8 -*-
{
'name': "Project Management",
'summary': """
It allows to manage the projects to be carried out in a company and jobs.""",
'description': """
This module allows you to manage the projects of a company from departments, employees and projects.
""",
'author': "Carlos Morales Aguilera",
'website': "http://www.example.com",
'category': 'Personal project',
'version':'0.1',
'application': True,
'depends': ['base'],
'data': [
'views/project.xml',
'views/project_ext.xml',
'views/department.xml',
'views/employee.xml',
],
'installable': True,
'auto_install': True,
}
|
n=6
a,b=0,0
arr=[1,2,4,4,5,6]
for i in range(int(n-1)):
if arr[i-1]>=arr[i]<=arr[i+1]:
a=a+1
if arr[i-1]<=arr[i]>=arr[i+1]:
b=b+1
print(b if a>b else a)
def howMany(sentence):
i = 0
ans = 0
n = len(sentence)
while (i < n):
c = 0
c2 = 0
c3 = 0
while (i < n and sentence[i] != ' '):
if ((sentence[i] >= 'a' and sentence[i] <= 'z') or (sentence[i] >= 'A' and sentence[i] <= 'Z') or sentence[i] == '-'):
c += 1
elif (sentence[i] and (sentence[i] == ',' or sentence[i] == '.' or sentence[i] == '?' or sentence[i] == '!')):
c3 += 1
c2 += 1
i += 1
if (c + c3 == c2 and c > 0):
ans += 1
while (i < n and sentence[i] == ' '):
i += 1
return ans
|
def currency(x, pos):
"""The two args are the value and tick position"""
if x >= 1e6:
s = '${:1.1f}M'.format(x*1e-6)
else:
s = '${:1.0f}K'.format(x*1e-3)
return s
|
# Parameters for compute_reference.py
# mpmath maximum precision when computing hypergeometric function values.
MAXPREC = 100000
# Range of a and b. PTS should be an odd number, since
# a = 0 and b = 0 are included in addition to positive and negative values.
UPPER = 2.3
PTS = 401
# Range of the logarithm of z values.
LOWER_Z = -2
UPPER_Z = 3
PTS_Z = 31
|
'''064 - SOMANDO VÁRIOS VALORES
Crie um programa que leia vários números inteiros pelo teclado.
O programa só vai parar quando o usuário digitar o valor 999, que é a condição de parada.
No final, mostre quantos números foram digitados e qual foi a soma entre eles (desconsiderando o flag).'''
soma = 0
contador = 0
numero = int(input('Escolha um valor - [999 é o comando para PARAR]: '))
while numero != 999:
contador = contador + 1
soma = soma + numero
numero = int(input('Escolha um valor - [999 é o comando para PARAR]: '))
print('A soma dos {} valores digitados é = {}.'.format(contador, soma))
|
#coding:utf-8
class Checker:
def __init__(self, check_type, length=-1):
self.type = check_type
self.length = length
def check(self,value):
'''
返回参数:
状态类型, 错误信息
'''
status = 1 # okay
message = ""
if type(value) != self.type:
status = 0
message = "类型错误: 请输入正确的参数类型"
return status,message
if self.length != -1:
if len(value) > self.length:
status = 0
message = "长度超过规定"
return status,message
|
'''
09 - Dictionary of lists
Some more data just came in! This time, you'll use the dictionary of lists method,
parsing the data column by column.
|date | small_sold | large_sold |
|-------------+---------------+------------|
|"2019-11-17" | 10859987 | 7674135 |
|"2019-12-01" | 9291631 | 6238096 |
Instructions:
- Create a dictionary of lists with the new data called avocados_dict.
- Convert the dictionary to a DataFrame called avocados_2019.
- Print your new DataFrame.
'''
# Create a dictionary of lists with new data
avocados_dict = {
"date": ["2019-11-17", "2019-12-01"],
"small_sold": [10859987, 9291631],
"large_sold": [7674135, 6238096]
}
# Convert dictionary into DataFrame
avocados_2019 = pd.DataFrame(avocados_dict)
# Print the new DataFrame
print(avocados_2019)
|
# -*- coding: utf-8 -*-
"""rackio/exception.py
This module defines all exceptions handle by Rackio.
"""
class RackioError(Exception):
"""Base class for other exceptions"""
pass
class InvalidTagNameError(RackioError):
"""Raised when an invalid tag name is defined"""
pass
class TagNotFoundError(RackioError):
"""Raised when a Tag Name was not found in repository"""
pass
class InvalidTagTypeError(RackioError):
"""Raised when a Tag is assigned a different type object"""
pass
class WorkerError(RackioError):
"""Raised when an error occurs in a Continous Worker"""
pass
|
n = int(input())
friends = list(input().split())
sum = 0
for i in friends:
sum += int(i)
ways = 0
for i in range(1,6):
if (sum+i)%(n+1) != 1:
ways += 1
print(ways)
|
# Rotate Array
class Solution:
def rotate(self, nums, k):
"""
Do not return anything, modify nums in-place instead.
"""
length = len(nums)
k = k % length
if k == 0:
return
front = nums[length - k:]
index = length - k - 1
while index >= 0:
nums[index + k] = nums[index]
index -= 1
for index, val in enumerate(front):
nums[index] = val
if __name__ == "__main__":
sol = Solution()
nums = [1,2,3,4,5,6,7]
k = 3
nums = [-1,-100,3,99]
k = 2
nums = [1, 2]
k = 2
sol.rotate(nums, k)
print(nums)
|
""" Main TACA module
"""
__version__ = '0.9.3'
|
tanya_list = [
'kenapa',
'bila',
'siapa',
'mengapa',
'apa',
'bagaimana',
'berapa',
'mana']
perintah_list = [
'jangan',
'sila',
'tolong',
'harap',
'usah',
'jemput',
'minta']
pangkal_list = [
'maka',
'alkisah',
'arakian',
'syahdah',
'adapun',
'bermula',
'kalakian']
bantu_list = [
'akan',
'telah',
'boleh',
'mesti',
'belum',
'sudah',
'dapat',
'masih',
'harus',
'hendak']
penguat_list = [
'paling',
'agak',
'sungguh',
'amat',
'terlalu',
'nian',
'benar',
'paling']
penegas_list = ['jua', 'juga', 'sahaja', 'hanya', 'memang', 'lagi', 'pun']
nafi_list = ['bukan', 'tidak', 'tak', 'tiada', 'tidaklah', 'tidakkah']
pemeri_list = ['ialah', 'adalah']
sendi_list = ['akan', 'kepada', 'terhadap', 'bagi', 'untuk', 'dari', 'daripada', 'di', 'dengan', 'hingga', 'sampai',
'ke', 'kepada', 'oleh', 'pada', 'sejak', 'seperti', 'umpama', 'bak', 'tentang', 'laksanabagai',
'semenjak', 'dalam', 'antara']
pembenar_list = ['ya', 'benar', 'betul']
nombor_list = [
'satu',
'dua',
'tiga',
'empat',
'lima',
'enam',
'tujuh',
'lapan',
'sembilan',
'kosong']
suku_bilangan_list = ['per', 'suku', 'setengah', 'separuh', 'tiga suku']
pisahan_list = ['setiap', 'tiap']
keterangan_list = ['begitu', 'begini', 'demikian', 'perlahan', 'cepat', 'lena', 'akan', 'sedang', 'belum',
'telah', 'sekarang', 'sebentar', 'semalam', 'mungkin', 'agak', 'barangkali', 'pasti', 'tentu',
'sudah', 'selalu', 'kadang', 'acapkali', 'sesekali', 'yang']
arah_list = [
'atas',
'bawah',
'tepi',
'antara',
'hadapan',
'utara',
'sisi',
'luar']
hubung_list = ['agar', 'apabila', 'atau', 'bahawa', 'dan', 'hingga', 'jika', 'jikalau', 'kecuali', 'kerana',
'lalu', 'manakala', 'sambil', 'serta', 'semenjak', 'sementara', 'sungguhpun', 'supaya', 'walaupun', 'tetapi', 'berkenan', 'berkenaan']
gantinama_list = ['aku', 'saya', 'hamba', 'patik', 'beta', 'kami', 'kita', 'anda', 'awak', 'engkau', 'tuanku', 'kalian',
'kamu', 'baginda', 'beliau', 'mereka', 'ini', 'itu', 'sini', 'situ', 'sana', 'kini', 'dia']
# pos permulaan[:-4]
permulaan = [
'bel',
'be',
'se',
'ter',
'men',
'memper',
'di',
'pe',
'me',
'ke',
'ber',
'pen',
'per']
# pos hujung [:1]
hujung = ['kan', 'kah', 'lah', 'tah', 'nya', 'an', 'wan', 'wati', 'ita']
alphabet = 'qwertyuiopasdfghjklzxcvbnm'
tatabahasa_dict = {'KT': tanya_list, 'KP': perintah_list, 'KPA': pangkal_list, 'KB': bantu_list, 'KPENGUAT': penguat_list,
'KPENEGAS': penegas_list, 'NAFI': nafi_list, 'KPEMERI': pemeri_list, 'KS': sendi_list, 'KPEMBENAR': pembenar_list,
'NO': nombor_list, 'SUKU': suku_bilangan_list, 'PISAHAN': pisahan_list, 'KETERANGAN': keterangan_list,
'ARAH': arah_list, 'KH': hubung_list, 'GN': gantinama_list}
|
# International morse code (sample)
Morse = {
# Letters
"a": ".-",
"b": "-...",
"c": "-.-.",
"d": "-..",
"e": ".",
"f": "..-.",
"g": "--.",
"h": "....",
"i": "..",
"j": ".---",
"k": "-.-",
"l": ".-..",
"m": "--",
"n": "-.",
"o": "---",
"p": ".--.",
"q": "--.-",
"r": ".-.",
"s": "...",
"t": "-",
"u": "..-",
"v": "...-",
"w": ".--",
"x": "-..-",
"y": "-.--",
"z": "--..",
# Numbers
"0": "-----",
"1": ".----",
"2": "..---",
"3": "...--",
"4": "....-",
"5": ".....",
"6": "-....",
"7": "--...",
"8": "---..",
"9": "----.",
# Punctuation
"&": ".-...",
"'": ".----.",
"@": ".--.-.",
")": "-.--.-",
"(": "-.--.",
":": "---...",
",": "--..--",
"=": "-...-",
"!": "-.-.--",
".": ".-.-.-",
"-": "-....-",
"+": ".-.-.",
'"': ".-..-.",
"?": "..--..",
"/": "-..-.",
}
def translate_text(text):
"""
Translates text to morse code
Accepts:
text(str): String to translate
Returns:
str: A translated string of morse code
"""
if text == "":
return "Please provide a valid text"
morse_code = ""
words = text.split(" ")
for word in words:
w = []
for char in word:
if char.lower() in Morse:
w.append(Morse[char.lower()])
morse_code += " ".join(w)
morse_code += " "
return morse_code.rstrip()
def translate_morse(morse_code):
"""
Translates morse code to english.
Accepts:
morse (str): A string of morse code to translate
Returns:
str: A translated string of text
"""
if morse_code == "":
return "Please provide a valid morse code."
text = ""
words = morse_code.split(" ")
for morse_word in words:
chars = morse_word.split(" ")
for char in chars:
for k, v in Morse.items():
if char == v:
text += k
text += " "
return text.rstrip()
if __name__ == "__main__":
text = "This string has been translated to morse code."
# Translate text to morse code
morse = translate_text(text)
# Translate morse code to text
translated_text = translate_morse(morse)
print(morse)
print(translated_text)
|
N = int(input())
result = 0
for i in range(1, N + 1):
if i % 3 == 0 or i % 5 == 0:
continue
result += i
print(result)
|
def findDecision(obj): #obj[0]: Coupon, obj[1]: Education
# {"feature": "Education", "instances": 127, "metric_value": 0.987, "depth": 1}
if obj[1]<=2:
# {"feature": "Coupon", "instances": 91, "metric_value": 0.9355, "depth": 2}
if obj[0]>1:
return 'True'
elif obj[0]<=1:
return 'True'
else: return 'True'
elif obj[1]>2:
# {"feature": "Coupon", "instances": 36, "metric_value": 0.9436, "depth": 2}
if obj[0]<=3:
return 'False'
elif obj[0]>3:
return 'False'
else: return 'False'
else: return 'False'
|
def ngram(text, n):
list = []
tsize = len(text)
for i in range(tsize - n + 1):
list.append(text[i:i + n])
return list
a = "paraparaparadise"
b = "paragraph"
abi = set(ngram(a, 2))
bbi = set(ngram(b, 2))
print(abi | bbi) #和集合
print(abi & bbi) #積集合
print(abi - bbi) #差集合
print("ok" if "se" in (abi or bbi) else "no")
|
class Solution:
def minimumTotal(self, triangle: List[List[int]]) -> int:
n = len(triangle)
if n == 1: return min(triangle[0])
row_curr = triangle[n-1]
for row in range(n-2, -1, -1):
row_up = triangle[row]
for ind in range(len(row_up)):
row_up[ind] = min(row_curr[ind] + triangle[row][ind],
row_curr[ind+1] + triangle[row][ind])
row_curr = row_up
return row_up[0]
|
extensions = dict(
required_params=['training_frame', 'x'],
validate_required_params="",
set_required_params="""
parms$training_frame <- training_frame
if(!missing(x)){
parms$ignored_columns <- .verify_datacols(training_frame, x)$cols_ignore
if(!missing(fold_column)){
parms$ignored_columns <- setdiff(parms$ignored_columns, fold_column)
}
}
""",
set_params="""
# Check if user_points is an acceptable set of user-specified starting points
if( is.data.frame(user_points) || is.matrix(user_points) || is.list(user_points) || is.H2OFrame(user_points) ) {
if ( length(init) > 1 || init == 'User') {
parms[["init"]] <- "User"
} else {
warning(paste0("Parameter init must equal 'User' when user_points is set. Ignoring init = '", init, "'. Setting init = 'User'."))
}
parms[["init"]] <- "User"
# Convert user-specified starting points to H2OFrame
if( is.data.frame(user_points) || is.matrix(user_points) || is.list(user_points) ) {
if( !is.data.frame(user_points) && !is.matrix(user_points) ) user_points <- t(as.data.frame(user_points))
user_points <- as.h2o(user_points)
}
parms[["user_points"]] <- user_points
# Set k
if( !(missing(k)) && k!=as.integer(nrow(user_points)) ) {
warning("Parameter k is not equal to the number of user-specified starting points. Ignoring k. Using specified starting points.")
}
parms[["k"]] <- as.numeric(nrow(user_points))
} else if ( is.character(init) ) { # Furthest, Random, PlusPlus{
parms[["user_points"]] <- NULL
} else{
stop ("argument init must be set to Furthest, Random, PlusPlus, or a valid set of user-defined starting points.")
}
""",
)
doc = dict(
preamble="""
Performs k-means clustering on an H2O dataset
""",
params=dict(
x="""A vector containing the \code{character} names of the predictors in the model."""
),
returns="""
an object of class \linkS4class{H2OClusteringModel}.
""",
seealso="""
\code{\link{h2o.cluster_sizes}}, \code{\link{h2o.totss}}, \code{\link{h2o.num_iterations}}, \code{\link{h2o.betweenss}}, \code{\link{h2o.tot_withinss}}, \code{\link{h2o.withinss}}, \code{\link{h2o.centersSTD}}, \code{\link{h2o.centers}}
""",
examples="""
library(h2o)
h2o.init()
prostate_path <- system.file("extdata", "prostate.csv", package = "h2o")
prostate <- h2o.uploadFile(path = prostate_path)
h2o.kmeans(training_frame = prostate, k = 10, x = c("AGE", "RACE", "VOL", "GLEASON"))
"""
)
|
#Accessing specific elemnts from a dictionary
Breakfast={
"Name":"dosa",
"cost": 45,
"Proteins": 4,
"Fat":2
}
#Finding the cost of Breakfast
p=Breakfast.get("cost")
print(p)
|
NPKT = 100000
# def getselfaddr():
# return socket.getaddrinfo(None, PORT, socket.AF_INET6, socket.SOCK_DGRAM,socket.IPPROTO_IP)[0]
|
"""Feature vector creation approaches for persistence diagrams.
This module contains feature vector creation approaches for persistence
diagrams that permit the use in modern machine learning algorithms.
"""
def _persistence(x, y):
"""Auxiliary function for calculating persistence of a tuple."""
return abs(x - y)
def featurise_distances(diagram):
"""Create feature vector by distance-to-diagonal calculation.
Creates a feature vector by calculating distances to the diagonal
for every point in the diagram and returning a sorted vector. The
representation is *stable* but might not be discriminative.
Parameters
----------
diagram : `PersistenceDiagram`
Persistence diagram to featurise. Can also be a generic 2D
container for iterating over tuples.
Returns
-------
Sorted vector of distances to diagonal. The vector is sorted in
descending order, such that high persistence points precede the
ones of low persistence.
"""
distances = [_persistence(x, y) for x, y in diagram]
return sorted(distances, reverse=True)
def featurise_pairwise_distances(diagram):
"""Create feature vector based on stable signatures.
Creates a feature vector by calculating the minimum of pairwise
distances and distances to the diagonal of each pair of points.
This representation follows the paper:
Mathieu Carrière, Steve Y. Oudot, and Maks Ovsjanikov
Stable Topological Signatures for Points on 3D Shapes
The representation is stable, but more costly to compute.
Parameters
----------
diagram : `PersistenceDiagram`
Persistence diagram to featurise. Can also be a generic 2D
container for iterating over tuples.
Returns
-------
Sorted vector of distances as described above. The vector is sorted
in *descending* order.
"""
distances = []
# Auxiliary function for calculating the infinity distance between
# the two points.
def _distance(a, b, x, y):
return max(abs(a - x), abs(b - y))
for i, (a, b) in enumerate(diagram):
for j, (x, y) in enumerate(diagram[i:]):
m = min(
_distance(a, b, x, y),
_persistence(a, b),
_persistence(x, y)
)
distances.append(m)
return sorted(distances, reverse=True)
|
"""
Configuration of flask application.
Everything that could be different between running
on your development platform or on ix.cs.uoregon.edu
(or on a different deployment target) shoudl be here.
"""
DEBUG = True
# Cookie key was obtained by:
# import uuid
# str(uuid.uuid4())
# We do it just once so that multiple processes
# will share the same key.
COOKIE_KEY = '48436e9a-ca70-451d-8e28-010c7787de40'
PORT=5000
DICT="data/dict.txt"
|
deliver_states = {
'DEFAULT': ['1', 'PENDING_ORDERS', 'ACCEPT_PENDING_JOLLOF', 'ACCEPT_PENDING_DELICACY', 'TO_PICKUP', 'PICKED_UP_JOLLOF', 'PICKED_UP_DELICACY', 'TO_DROPOFF', 'DROPPED_OFF_JOLLOF', 'DROPPED_OFF_DELICACY'],
'CANCELLED': ['DEFAULT'],
'FLASH_LOCATION': ['FLASH_LOCATION', 'CANCELLED'],
'REQUEST_PHONE': ['REQUEST_PHONE', 'CANCENCELLED'],
'PENDING_ORDERS': ['PENDING_ORDERS', 'ACCEPT_PENDING_JOLLOF', 'ACCEPT_PENDING_DELICACY', 'CANCELLED'],
'ACCEPT_PENDING_JOLLOF': ['ACCEPT_PENDING_JOLLOF', 'CANCELLED'],
'ACCEPT_PENDING_DELICACY': ['ACCEPT_PENDING_DELICACY', 'CANCELLED'],
'TO_PICKUP': ['TO_PICKUP', 'PICKED_UP_JOLLOF', 'PICKED_UP_DELICACY', 'CANCELLED'],
'PICKED_UP_JOLLOF': ['PICKED_UP_JOLLOF', 'CANCELLED'],
'PICKED_UP_DELICACY': ['PICKED_UP_DELICACY', 'CANCELLED'],
'TO_DROPOFF': ['TO_DROPOFF', 'DROPPED_OFF_JOLLOF', 'DROPPED_OFF_DELICACY', 'CANCELLED'],
'DROPPED_OFF_JOLLOF': ['DROPPED_OFF_JOLLOF', 'CANCELLED'],
'DROPPED_OFF_DELICACY': ['DROPPED_OFF_DELICACY', 'CANCELLED'],
}
def is_deliver_next_state(old_state, new_state):
'''
Returns boolean if new_state is a next state for old_state
'''
try:
state = deliver_states[old_state]
if new_state in state:
return True
else:
return False
except KeyError:
return False
|
class Synonym:
def __init__(self,
taxon_id,
name_id,
id='',
name_phrase='',
according_to_id='',
status='synonym',
reference_id='',
page_reference_id='',
link='',
remarks='',
needs_review=''):
self.id = id
self.taxon_id = taxon_id
self.name_id = name_id
self.name_phrase = name_phrase
self.according_to_id = according_to_id
self.status = status
self.reference_id = reference_id
self.page_reference_id = page_reference_id
self.link = link
self.remarks = remarks
self.needs_review = needs_review
def __str__(self):
return str(self.id) + '\t' + \
str(self.taxon_id) + '\t' + \
str(self.name_id) + '\t' + \
self.name_phrase + '\t' + \
str(self.according_to_id) + '\t' + \
self.status + '\t' + \
str(self.reference_id) + '\t' + \
str(self.page_reference_id) + '\t' + \
self.link + '\t' + \
self.remarks + '\n'
# def __repr__(self):
# return {
# 'id': self.id,
# 'taxon_id': self.taxon_id,
# 'name_id': self.name_id,
# 'name_phrase': self.name_phrase,
# 'according_to_id': self.according_to_id,
# 'status': self.status,
# 'reference_id': self.reference_id,
# 'page_reference_id': self.page_reference_id,
# 'link': self.link,
# 'remarks': self.remarks
# }
class Synonyms:
def __init__(self, output_tsv):
self.synonyms = []
self.output_tsv = output_tsv
def append(self, synonym):
if isinstance(synonym, Synonym):
self.synonyms.append(synonym)
else:
print('Error: synonym must be Synonym type')
def write_output(self, output_tsv=''):
if output_tsv == '' and self.output_tsv != '':
output_tsv = self.output_tsv
file = open(output_tsv, 'w')
if len(self.synonyms) > 0:
header = '\t'.join(self.synonyms[0].__dict__.keys()) + '\n'
file.write(header)
for synonym in self.synonyms:
row = '\t'.join(str(v) for v in synonym.__dict__.values()) + '\n'
file.write(row)
file.close()
|
# ----------------------------------------------------------------------
# CISCO-VPDN-MGMT-MIB
# Compiled MIB
# Do not modify this file directly
# Run ./noc mib make-cmib instead
# ----------------------------------------------------------------------
# Copyright (C) 2007-2020 The NOC Project
# See LICENSE for details
# ----------------------------------------------------------------------
# MIB Name
NAME = "CISCO-VPDN-MGMT-MIB"
# Metadata
LAST_UPDATED = "2009-06-16"
COMPILED = "2020-01-19"
# MIB Data: name -> oid
MIB = {
"CISCO-VPDN-MGMT-MIB::ciscoVpdnMgmtMIB": "1.3.6.1.4.1.9.10.24",
"CISCO-VPDN-MGMT-MIB::ciscoVpdnMgmtMIBNotifs": "1.3.6.1.4.1.9.10.24.0",
"CISCO-VPDN-MGMT-MIB::cvpdnNotifSessionID": "1.3.6.1.4.1.9.10.24.0.1",
"CISCO-VPDN-MGMT-MIB::cvpdnNotifSessionEvent": "1.3.6.1.4.1.9.10.24.0.2",
"CISCO-VPDN-MGMT-MIB::cvpdnNotifSession": "1.3.6.1.4.1.9.10.24.0.3",
"CISCO-VPDN-MGMT-MIB::ciscoVpdnMgmtMIBObjects": "1.3.6.1.4.1.9.10.24.1",
"CISCO-VPDN-MGMT-MIB::cvpdnSystemInfo": "1.3.6.1.4.1.9.10.24.1.1",
"CISCO-VPDN-MGMT-MIB::cvpdnTunnelTotal": "1.3.6.1.4.1.9.10.24.1.1.1",
"CISCO-VPDN-MGMT-MIB::cvpdnSessionTotal": "1.3.6.1.4.1.9.10.24.1.1.2",
"CISCO-VPDN-MGMT-MIB::cvpdnDeniedUsersTotal": "1.3.6.1.4.1.9.10.24.1.1.3",
"CISCO-VPDN-MGMT-MIB::cvpdnSystemTable": "1.3.6.1.4.1.9.10.24.1.1.4",
"CISCO-VPDN-MGMT-MIB::cvpdnSystemEntry": "1.3.6.1.4.1.9.10.24.1.1.4.1",
"CISCO-VPDN-MGMT-MIB::cvpdnSystemTunnelType": "1.3.6.1.4.1.9.10.24.1.1.4.1.1",
"CISCO-VPDN-MGMT-MIB::cvpdnSystemTunnelTotal": "1.3.6.1.4.1.9.10.24.1.1.4.1.2",
"CISCO-VPDN-MGMT-MIB::cvpdnSystemSessionTotal": "1.3.6.1.4.1.9.10.24.1.1.4.1.3",
"CISCO-VPDN-MGMT-MIB::cvpdnSystemDeniedUsersTotal": "1.3.6.1.4.1.9.10.24.1.1.4.1.4",
"CISCO-VPDN-MGMT-MIB::cvpdnSystemInitialConnReq": "1.3.6.1.4.1.9.10.24.1.1.4.1.5",
"CISCO-VPDN-MGMT-MIB::cvpdnSystemSuccessConnReq": "1.3.6.1.4.1.9.10.24.1.1.4.1.6",
"CISCO-VPDN-MGMT-MIB::cvpdnSystemFailedConnReq": "1.3.6.1.4.1.9.10.24.1.1.4.1.7",
"CISCO-VPDN-MGMT-MIB::cvpdnSystemNotifSessionEnabled": "1.3.6.1.4.1.9.10.24.1.1.5",
"CISCO-VPDN-MGMT-MIB::cvpdnSystemClearSessions": "1.3.6.1.4.1.9.10.24.1.1.6",
"CISCO-VPDN-MGMT-MIB::cvpdnTunnelInfo": "1.3.6.1.4.1.9.10.24.1.2",
"CISCO-VPDN-MGMT-MIB::cvpdnTunnelTable": "1.3.6.1.4.1.9.10.24.1.2.1",
"CISCO-VPDN-MGMT-MIB::cvpdnTunnelEntry": "1.3.6.1.4.1.9.10.24.1.2.1.1",
"CISCO-VPDN-MGMT-MIB::cvpdnTunnelTunnelId": "1.3.6.1.4.1.9.10.24.1.2.1.1.1",
"CISCO-VPDN-MGMT-MIB::cvpdnTunnelRemoteTunnelId": "1.3.6.1.4.1.9.10.24.1.2.1.1.2",
"CISCO-VPDN-MGMT-MIB::cvpdnTunnelLocalName": "1.3.6.1.4.1.9.10.24.1.2.1.1.3",
"CISCO-VPDN-MGMT-MIB::cvpdnTunnelRemoteName": "1.3.6.1.4.1.9.10.24.1.2.1.1.4",
"CISCO-VPDN-MGMT-MIB::cvpdnTunnelRemoteEndpointName": "1.3.6.1.4.1.9.10.24.1.2.1.1.5",
"CISCO-VPDN-MGMT-MIB::cvpdnTunnelLocalInitConnection": "1.3.6.1.4.1.9.10.24.1.2.1.1.6",
"CISCO-VPDN-MGMT-MIB::cvpdnTunnelOrigCause": "1.3.6.1.4.1.9.10.24.1.2.1.1.7",
"CISCO-VPDN-MGMT-MIB::cvpdnTunnelState": "1.3.6.1.4.1.9.10.24.1.2.1.1.8",
"CISCO-VPDN-MGMT-MIB::cvpdnTunnelActiveSessions": "1.3.6.1.4.1.9.10.24.1.2.1.1.9",
"CISCO-VPDN-MGMT-MIB::cvpdnTunnelDeniedUsers": "1.3.6.1.4.1.9.10.24.1.2.1.1.10",
"CISCO-VPDN-MGMT-MIB::cvpdnTunnelSoftshut": "1.3.6.1.4.1.9.10.24.1.2.1.1.12",
"CISCO-VPDN-MGMT-MIB::cvpdnTunnelNetworkServiceType": "1.3.6.1.4.1.9.10.24.1.2.1.1.13",
"CISCO-VPDN-MGMT-MIB::cvpdnTunnelLocalIpAddress": "1.3.6.1.4.1.9.10.24.1.2.1.1.14",
"CISCO-VPDN-MGMT-MIB::cvpdnTunnelSourceIpAddress": "1.3.6.1.4.1.9.10.24.1.2.1.1.15",
"CISCO-VPDN-MGMT-MIB::cvpdnTunnelRemoteIpAddress": "1.3.6.1.4.1.9.10.24.1.2.1.1.16",
"CISCO-VPDN-MGMT-MIB::cvpdnTunnelAttrTable": "1.3.6.1.4.1.9.10.24.1.2.2",
"CISCO-VPDN-MGMT-MIB::cvpdnTunnelAttrEntry": "1.3.6.1.4.1.9.10.24.1.2.2.1",
"CISCO-VPDN-MGMT-MIB::cvpdnTunnelAttrTunnelId": "1.3.6.1.4.1.9.10.24.1.2.2.1.1",
"CISCO-VPDN-MGMT-MIB::cvpdnTunnelAttrRemoteTunnelId": "1.3.6.1.4.1.9.10.24.1.2.2.1.2",
"CISCO-VPDN-MGMT-MIB::cvpdnTunnelAttrLocalName": "1.3.6.1.4.1.9.10.24.1.2.2.1.3",
"CISCO-VPDN-MGMT-MIB::cvpdnTunnelAttrRemoteName": "1.3.6.1.4.1.9.10.24.1.2.2.1.4",
"CISCO-VPDN-MGMT-MIB::cvpdnTunnelAttrRemoteEndpointName": "1.3.6.1.4.1.9.10.24.1.2.2.1.5",
"CISCO-VPDN-MGMT-MIB::cvpdnTunnelAttrLocalInitConnection": "1.3.6.1.4.1.9.10.24.1.2.2.1.6",
"CISCO-VPDN-MGMT-MIB::cvpdnTunnelAttrOrigCause": "1.3.6.1.4.1.9.10.24.1.2.2.1.7",
"CISCO-VPDN-MGMT-MIB::cvpdnTunnelAttrState": "1.3.6.1.4.1.9.10.24.1.2.2.1.8",
"CISCO-VPDN-MGMT-MIB::cvpdnTunnelAttrActiveSessions": "1.3.6.1.4.1.9.10.24.1.2.2.1.9",
"CISCO-VPDN-MGMT-MIB::cvpdnTunnelAttrDeniedUsers": "1.3.6.1.4.1.9.10.24.1.2.2.1.10",
"CISCO-VPDN-MGMT-MIB::cvpdnTunnelAttrSoftshut": "1.3.6.1.4.1.9.10.24.1.2.2.1.11",
"CISCO-VPDN-MGMT-MIB::cvpdnTunnelAttrNetworkServiceType": "1.3.6.1.4.1.9.10.24.1.2.2.1.12",
"CISCO-VPDN-MGMT-MIB::cvpdnTunnelAttrLocalIpAddress": "1.3.6.1.4.1.9.10.24.1.2.2.1.13",
"CISCO-VPDN-MGMT-MIB::cvpdnTunnelAttrSourceIpAddress": "1.3.6.1.4.1.9.10.24.1.2.2.1.14",
"CISCO-VPDN-MGMT-MIB::cvpdnTunnelAttrRemoteIpAddress": "1.3.6.1.4.1.9.10.24.1.2.2.1.15",
"CISCO-VPDN-MGMT-MIB::cvpdnTunnelAttrLocalInetAddressType": "1.3.6.1.4.1.9.10.24.1.2.2.1.16",
"CISCO-VPDN-MGMT-MIB::cvpdnTunnelAttrLocalInetAddress": "1.3.6.1.4.1.9.10.24.1.2.2.1.17",
"CISCO-VPDN-MGMT-MIB::cvpdnTunnelAttrSourceInetAddressType": "1.3.6.1.4.1.9.10.24.1.2.2.1.18",
"CISCO-VPDN-MGMT-MIB::cvpdnTunnelAttrSourceInetAddress": "1.3.6.1.4.1.9.10.24.1.2.2.1.19",
"CISCO-VPDN-MGMT-MIB::cvpdnTunnelAttrRemoteInetAddressType": "1.3.6.1.4.1.9.10.24.1.2.2.1.20",
"CISCO-VPDN-MGMT-MIB::cvpdnTunnelAttrRemoteInetAddress": "1.3.6.1.4.1.9.10.24.1.2.2.1.21",
"CISCO-VPDN-MGMT-MIB::cvpdnTunnelSessionInfo": "1.3.6.1.4.1.9.10.24.1.3",
"CISCO-VPDN-MGMT-MIB::cvpdnTunnelSessionTable": "1.3.6.1.4.1.9.10.24.1.3.1",
"CISCO-VPDN-MGMT-MIB::cvpdnTunnelSessionEntry": "1.3.6.1.4.1.9.10.24.1.3.1.1",
"CISCO-VPDN-MGMT-MIB::cvpdnTunnelSessionId": "1.3.6.1.4.1.9.10.24.1.3.1.1.1",
"CISCO-VPDN-MGMT-MIB::cvpdnTunnelSessionUserName": "1.3.6.1.4.1.9.10.24.1.3.1.1.2",
"CISCO-VPDN-MGMT-MIB::cvpdnTunnelSessionState": "1.3.6.1.4.1.9.10.24.1.3.1.1.3",
"CISCO-VPDN-MGMT-MIB::cvpdnTunnelSessionCallDuration": "1.3.6.1.4.1.9.10.24.1.3.1.1.4",
"CISCO-VPDN-MGMT-MIB::cvpdnTunnelSessionPacketsOut": "1.3.6.1.4.1.9.10.24.1.3.1.1.5",
"CISCO-VPDN-MGMT-MIB::cvpdnTunnelSessionBytesOut": "1.3.6.1.4.1.9.10.24.1.3.1.1.6",
"CISCO-VPDN-MGMT-MIB::cvpdnTunnelSessionPacketsIn": "1.3.6.1.4.1.9.10.24.1.3.1.1.7",
"CISCO-VPDN-MGMT-MIB::cvpdnTunnelSessionBytesIn": "1.3.6.1.4.1.9.10.24.1.3.1.1.8",
"CISCO-VPDN-MGMT-MIB::cvpdnTunnelSessionDeviceType": "1.3.6.1.4.1.9.10.24.1.3.1.1.9",
"CISCO-VPDN-MGMT-MIB::cvpdnTunnelSessionDeviceCallerId": "1.3.6.1.4.1.9.10.24.1.3.1.1.10",
"CISCO-VPDN-MGMT-MIB::cvpdnTunnelSessionDevicePhyId": "1.3.6.1.4.1.9.10.24.1.3.1.1.11",
"CISCO-VPDN-MGMT-MIB::cvpdnTunnelSessionMultilink": "1.3.6.1.4.1.9.10.24.1.3.1.1.12",
"CISCO-VPDN-MGMT-MIB::cvpdnTunnelSessionModemSlotIndex": "1.3.6.1.4.1.9.10.24.1.3.1.1.13",
"CISCO-VPDN-MGMT-MIB::cvpdnTunnelSessionModemPortIndex": "1.3.6.1.4.1.9.10.24.1.3.1.1.14",
"CISCO-VPDN-MGMT-MIB::cvpdnTunnelSessionDS1SlotIndex": "1.3.6.1.4.1.9.10.24.1.3.1.1.15",
"CISCO-VPDN-MGMT-MIB::cvpdnTunnelSessionDS1PortIndex": "1.3.6.1.4.1.9.10.24.1.3.1.1.16",
"CISCO-VPDN-MGMT-MIB::cvpdnTunnelSessionDS1ChannelIndex": "1.3.6.1.4.1.9.10.24.1.3.1.1.17",
"CISCO-VPDN-MGMT-MIB::cvpdnTunnelSessionModemCallStartTime": "1.3.6.1.4.1.9.10.24.1.3.1.1.18",
"CISCO-VPDN-MGMT-MIB::cvpdnTunnelSessionModemCallStartIndex": "1.3.6.1.4.1.9.10.24.1.3.1.1.19",
"CISCO-VPDN-MGMT-MIB::cvpdnSessionAttrTable": "1.3.6.1.4.1.9.10.24.1.3.2",
"CISCO-VPDN-MGMT-MIB::cvpdnSessionAttrEntry": "1.3.6.1.4.1.9.10.24.1.3.2.1",
"CISCO-VPDN-MGMT-MIB::cvpdnSessionAttrSessionId": "1.3.6.1.4.1.9.10.24.1.3.2.1.1",
"CISCO-VPDN-MGMT-MIB::cvpdnSessionAttrUserName": "1.3.6.1.4.1.9.10.24.1.3.2.1.2",
"CISCO-VPDN-MGMT-MIB::cvpdnSessionAttrState": "1.3.6.1.4.1.9.10.24.1.3.2.1.3",
"CISCO-VPDN-MGMT-MIB::cvpdnSessionAttrCallDuration": "1.3.6.1.4.1.9.10.24.1.3.2.1.4",
"CISCO-VPDN-MGMT-MIB::cvpdnSessionAttrPacketsOut": "1.3.6.1.4.1.9.10.24.1.3.2.1.5",
"CISCO-VPDN-MGMT-MIB::cvpdnSessionAttrBytesOut": "1.3.6.1.4.1.9.10.24.1.3.2.1.6",
"CISCO-VPDN-MGMT-MIB::cvpdnSessionAttrPacketsIn": "1.3.6.1.4.1.9.10.24.1.3.2.1.7",
"CISCO-VPDN-MGMT-MIB::cvpdnSessionAttrBytesIn": "1.3.6.1.4.1.9.10.24.1.3.2.1.8",
"CISCO-VPDN-MGMT-MIB::cvpdnSessionAttrDeviceType": "1.3.6.1.4.1.9.10.24.1.3.2.1.9",
"CISCO-VPDN-MGMT-MIB::cvpdnSessionAttrDeviceCallerId": "1.3.6.1.4.1.9.10.24.1.3.2.1.10",
"CISCO-VPDN-MGMT-MIB::cvpdnSessionAttrDevicePhyId": "1.3.6.1.4.1.9.10.24.1.3.2.1.11",
"CISCO-VPDN-MGMT-MIB::cvpdnSessionAttrMultilink": "1.3.6.1.4.1.9.10.24.1.3.2.1.12",
"CISCO-VPDN-MGMT-MIB::cvpdnSessionAttrModemSlotIndex": "1.3.6.1.4.1.9.10.24.1.3.2.1.13",
"CISCO-VPDN-MGMT-MIB::cvpdnSessionAttrModemPortIndex": "1.3.6.1.4.1.9.10.24.1.3.2.1.14",
"CISCO-VPDN-MGMT-MIB::cvpdnSessionAttrDS1SlotIndex": "1.3.6.1.4.1.9.10.24.1.3.2.1.15",
"CISCO-VPDN-MGMT-MIB::cvpdnSessionAttrDS1PortIndex": "1.3.6.1.4.1.9.10.24.1.3.2.1.16",
"CISCO-VPDN-MGMT-MIB::cvpdnSessionAttrDS1ChannelIndex": "1.3.6.1.4.1.9.10.24.1.3.2.1.17",
"CISCO-VPDN-MGMT-MIB::cvpdnSessionAttrModemCallStartTime": "1.3.6.1.4.1.9.10.24.1.3.2.1.18",
"CISCO-VPDN-MGMT-MIB::cvpdnSessionAttrModemCallStartIndex": "1.3.6.1.4.1.9.10.24.1.3.2.1.19",
"CISCO-VPDN-MGMT-MIB::cvpdnSessionAttrVirtualCircuitID": "1.3.6.1.4.1.9.10.24.1.3.2.1.20",
"CISCO-VPDN-MGMT-MIB::cvpdnSessionAttrSentPktsDropped": "1.3.6.1.4.1.9.10.24.1.3.2.1.21",
"CISCO-VPDN-MGMT-MIB::cvpdnSessionAttrRecvPktsDropped": "1.3.6.1.4.1.9.10.24.1.3.2.1.22",
"CISCO-VPDN-MGMT-MIB::cvpdnSessionAttrMultilinkBundle": "1.3.6.1.4.1.9.10.24.1.3.2.1.23",
"CISCO-VPDN-MGMT-MIB::cvpdnSessionAttrMultilinkIfIndex": "1.3.6.1.4.1.9.10.24.1.3.2.1.24",
"CISCO-VPDN-MGMT-MIB::cvpdnUserToFailHistInfo": "1.3.6.1.4.1.9.10.24.1.4",
"CISCO-VPDN-MGMT-MIB::cvpdnUserToFailHistInfoTable": "1.3.6.1.4.1.9.10.24.1.4.1",
"CISCO-VPDN-MGMT-MIB::cvpdnUserToFailHistInfoEntry": "1.3.6.1.4.1.9.10.24.1.4.1.1",
"CISCO-VPDN-MGMT-MIB::cvpdnUnameToFailHistUname": "1.3.6.1.4.1.9.10.24.1.4.1.1.1",
"CISCO-VPDN-MGMT-MIB::cvpdnUnameToFailHistTunnelId": "1.3.6.1.4.1.9.10.24.1.4.1.1.2",
"CISCO-VPDN-MGMT-MIB::cvpdnUnameToFailHistUserId": "1.3.6.1.4.1.9.10.24.1.4.1.1.3",
"CISCO-VPDN-MGMT-MIB::cvpdnUnameToFailHistLocalInitConn": "1.3.6.1.4.1.9.10.24.1.4.1.1.4",
"CISCO-VPDN-MGMT-MIB::cvpdnUnameToFailHistLocalName": "1.3.6.1.4.1.9.10.24.1.4.1.1.5",
"CISCO-VPDN-MGMT-MIB::cvpdnUnameToFailHistRemoteName": "1.3.6.1.4.1.9.10.24.1.4.1.1.6",
"CISCO-VPDN-MGMT-MIB::cvpdnUnameToFailHistSourceIp": "1.3.6.1.4.1.9.10.24.1.4.1.1.7",
"CISCO-VPDN-MGMT-MIB::cvpdnUnameToFailHistDestIp": "1.3.6.1.4.1.9.10.24.1.4.1.1.8",
"CISCO-VPDN-MGMT-MIB::cvpdnUnameToFailHistCount": "1.3.6.1.4.1.9.10.24.1.4.1.1.9",
"CISCO-VPDN-MGMT-MIB::cvpdnUnameToFailHistFailTime": "1.3.6.1.4.1.9.10.24.1.4.1.1.10",
"CISCO-VPDN-MGMT-MIB::cvpdnUnameToFailHistFailType": "1.3.6.1.4.1.9.10.24.1.4.1.1.11",
"CISCO-VPDN-MGMT-MIB::cvpdnUnameToFailHistFailReason": "1.3.6.1.4.1.9.10.24.1.4.1.1.12",
"CISCO-VPDN-MGMT-MIB::cvpdnUnameToFailHistSourceInetType": "1.3.6.1.4.1.9.10.24.1.4.1.1.13",
"CISCO-VPDN-MGMT-MIB::cvpdnUnameToFailHistSourceInetAddr": "1.3.6.1.4.1.9.10.24.1.4.1.1.14",
"CISCO-VPDN-MGMT-MIB::cvpdnUnameToFailHistDestInetType": "1.3.6.1.4.1.9.10.24.1.4.1.1.15",
"CISCO-VPDN-MGMT-MIB::cvpdnUnameToFailHistDestInetAddr": "1.3.6.1.4.1.9.10.24.1.4.1.1.16",
"CISCO-VPDN-MGMT-MIB::cvpdnTemplateInfo": "1.3.6.1.4.1.9.10.24.1.5",
"CISCO-VPDN-MGMT-MIB::cvpdnTemplateTable": "1.3.6.1.4.1.9.10.24.1.5.1",
"CISCO-VPDN-MGMT-MIB::cvpdnTemplateEntry": "1.3.6.1.4.1.9.10.24.1.5.1.1",
"CISCO-VPDN-MGMT-MIB::cvpdnTemplateName": "1.3.6.1.4.1.9.10.24.1.5.1.1.1",
"CISCO-VPDN-MGMT-MIB::cvpdnTemplateActiveSessions": "1.3.6.1.4.1.9.10.24.1.5.1.1.2",
"CISCO-VPDN-MGMT-MIB::cvpdnMultilinkInfo": "1.3.6.1.4.1.9.10.24.1.6",
"CISCO-VPDN-MGMT-MIB::cvpdnBundlesWithOneLink": "1.3.6.1.4.1.9.10.24.1.6.1",
"CISCO-VPDN-MGMT-MIB::cvpdnBundlesWithTwoLinks": "1.3.6.1.4.1.9.10.24.1.6.2",
"CISCO-VPDN-MGMT-MIB::cvpdnBundlesWithMoreThanTwoLinks": "1.3.6.1.4.1.9.10.24.1.6.3",
"CISCO-VPDN-MGMT-MIB::cvpdnBundleTable": "1.3.6.1.4.1.9.10.24.1.6.4",
"CISCO-VPDN-MGMT-MIB::cvpdnBundleEntry": "1.3.6.1.4.1.9.10.24.1.6.4.1",
"CISCO-VPDN-MGMT-MIB::cvpdnBundleName": "1.3.6.1.4.1.9.10.24.1.6.4.1.1",
"CISCO-VPDN-MGMT-MIB::cvpdnBundleLinkCount": "1.3.6.1.4.1.9.10.24.1.6.4.1.2",
"CISCO-VPDN-MGMT-MIB::cvpdnBundleEndpointType": "1.3.6.1.4.1.9.10.24.1.6.4.1.3",
"CISCO-VPDN-MGMT-MIB::cvpdnBundleEndpoint": "1.3.6.1.4.1.9.10.24.1.6.4.1.4",
"CISCO-VPDN-MGMT-MIB::cvpdnBundlePeerIpAddrType": "1.3.6.1.4.1.9.10.24.1.6.4.1.5",
"CISCO-VPDN-MGMT-MIB::cvpdnBundlePeerIpAddr": "1.3.6.1.4.1.9.10.24.1.6.4.1.6",
"CISCO-VPDN-MGMT-MIB::cvpdnBundleEndpointClass": "1.3.6.1.4.1.9.10.24.1.6.4.1.7",
"CISCO-VPDN-MGMT-MIB::cvpdnBundleLastChanged": "1.3.6.1.4.1.9.10.24.1.6.5",
"CISCO-VPDN-MGMT-MIB::cvpdnBundleChildTable": "1.3.6.1.4.1.9.10.24.1.6.6",
"CISCO-VPDN-MGMT-MIB::cvpdnBundleChildEntry": "1.3.6.1.4.1.9.10.24.1.6.6.1",
"CISCO-VPDN-MGMT-MIB::cvpdnBundleChildTunnelType": "1.3.6.1.4.1.9.10.24.1.6.6.1.1",
"CISCO-VPDN-MGMT-MIB::cvpdnBundleChildTunnelId": "1.3.6.1.4.1.9.10.24.1.6.6.1.2",
"CISCO-VPDN-MGMT-MIB::cvpdnBundleChildSessionId": "1.3.6.1.4.1.9.10.24.1.6.6.1.3",
"CISCO-VPDN-MGMT-MIB::ciscoVpdnMgmtMIBConformance": "1.3.6.1.4.1.9.10.24.3",
"CISCO-VPDN-MGMT-MIB::ciscoVpdnMgmtMIBCompliances": "1.3.6.1.4.1.9.10.24.3.1",
"CISCO-VPDN-MGMT-MIB::ciscoVpdnMgmtMIBGroups": "1.3.6.1.4.1.9.10.24.3.2",
}
DISPLAY_HINTS = {}
|
N = int(input())
positions = []
for x in range(N):
input_line = input().split()
positions.append([int(input_line[0]), int(input_line[1])])
sorted_positions = sorted(positions)
minRadius = 1000000
for x in range(len(sorted_positions)-1):
if sorted_positions[x][1] == 0 and sorted_positions[x-1][1] == 1:
distance = abs(sorted_positions[x-1][0] - sorted_positions[x][0])
if distance < minRadius:
minRadius = distance
if sorted_positions[x][1] == 0 and sorted_positions[x+1][1] == 1:
distance = abs(sorted_positions[x][0] - sorted_positions[x+1][0])
if distance < minRadius:
minRadius = distance
minRadius -= 1
visited = [False] * len(sorted_positions)
counter = 0
previous = 0
for x in range(0, len(sorted_positions)):
if x == 0:
if sorted_positions[x][1] == 1:
counter += 1
elif sorted_positions[x][1] == 1:
if abs(sorted_positions[x][0] - previous) <= minRadius:
pass
else:
counter += 1
elif sorted_positions[x][1] == 0:
pass
previous = sorted_positions[x][0]
print(counter)
|
# Implementation of a simple "Calculator" program
# The calculator consists of four functions: add, subtract, multiply and divide
def add(x, y):
"""
Function to add two numbers
Parameters
----------
x : int/float
First number to be added
y : int/float
Second number to be added
Returns
-------
sum : int/float
Sum of the two numbers
"""
return (x + y)
def subtract(x, y):
"""
Function to subtract two numbers
Parameters
----------
x : int/float
First number to be subtracted
y : int/float
Second number to be subtracted
Returns
-------
difference : int/float
Difference between the two numbers
"""
return (x - y)
def multiply(x, y):
"""
Function to multiply two numbers
Parameters
----------
x : int/float
First number to be multiplied
y : int/float
Second number to be multiplied
Returns
-------
product : int/float
Sum of the two numbers
"""
return (x * y)
def divide(x, y):
"""
Function to divide two numbers
Parameters
----------
x : int/float
First number to be divided
y : int/float
Second number to be divided
Returns
-------
quotient : int/float
Sum of the two numbers
"""
return (x / y)
|
"""Modules handling environment data.
For example: types for transitions/trajectories; methods to compute rollouts;
buffers to store transitions; helpers for these modules.
"""
|
# Payable-related constants
PAYABLE_FIRST_ROW = 20
PAYABLE_FIRST_COL = 2
PAYABLE_LAST_COL = 25
PAYABLE_SORT_BY = 3
PAYABLE_PAYPAL_ID_COL = 18
PAYABLE_FIELDS = [
'timestamp',
'requester',
'department',
'item',
'detail',
'event_date',
'payment_type',
'use_of_funds',
'notes',
'type',
'name',
'paypal',
'address',
'amount',
'driving_reimbursement'
]
PAYABLE_IGNORE_FIELDS = ('detail', 'notes')
# Receivable-related constants
RECEIVABLE_FIRST_ROW = 11
RECEIVABLE_FIRST_COL = 2
RECEIVABLE_LAST_COL = 25
RECEIVABLE_SORT_BY = 4
RECEIVABLE_FIELDS = [
'year',
'committed_date',
'timestamp',
'support_type',
'organization_type',
'budget_line_item',
'payee_name',
'payee_email',
'amount_requested',
'amount_committed',
'amount_gross',
'amount_net',
'transaction_id'
]
# Transaction-related constants
TRANSACTION_FIELDS = [
'status',
'type',
'timezone',
'timestamp',
'id',
'name',
'email',
'amount',
'fee_amount',
'net_amount',
'currency'
]
TRANSACTION_RESPONSE_KEYS = {
'L_STATUS': 'status',
'L_TYPE': 'type',
'L_TIMEZONE': 'timezone',
'L_TIMESTAMP': 'timestamp',
'L_TRANSACTIONID': 'id',
'L_NAME': 'name',
'L_EMAIL': 'email',
'L_AMT': 'amount',
'L_FEEAMT': 'fee_amount',
'L_NETAMT': 'net_amount',
'L_CURRENCYCODE': 'currency'
}
PAYABLE_TRANSACTION_MATCHES = (
('paypal', 'email'),
('amount', 'amount')
)
|
# -*- coding: utf-8 -*-
"""
Paraxial optical calculations
"""
|
operadores = ('+', '-', '*', '/', '%', '=', '>', '<', '>=', '<=', '!', '!=', '==', '&', '|', '++', '--', '+=', '-=',
'/=', '*=')
comentario = '//'
comentario_inicio = '/*'
comentario_fim = '*/'
aspas = '"'
aspasSimples = "'"
delimitadores = (';', '{', '}', '(', ')', '[', ']', comentario, comentario_inicio, comentario_fim, aspas, aspasSimples, ",")
palavras_reservadas = ('int', 'float', 'string', 'boolean', 'char', 'void', 'double', 'public', 'private', 'igor',
'vasco', 'return', 'if', 'else', 'for', 'while', 'break', 'continue', 'funcao', 'hame', 'true',
'false', 'switch', 'case', 'default', 'print')
|
class TestLinkController(object):
def test_create_shortlink_with_correct_request_body(self, client):
"""create_shortlink() with a correct request body
should respond with a success 200.
"""
form = {"provider": "tinyurl", "url": "http://example.com"}
response = client.post("/api/shortlinks", json=form)
assert response.status_code == 200
def test_create_shortlink_without_providing_access_token(self, client):
"""create_shortlink() if access_token is not provided to bitly,
should respond with an error 403.
"""
form = {"provider": "bitly", "url": "http://example.com"}
response = client.post("/api/shortlinks", json=form)
assert response.status_code == 403
def test_create_shortlink_endpoint_is_wrong(self, client):
"""create_shortlink() if endpoint is wrong,
should respond with an error 404.
"""
form = {"provider": "tinyurl", "url": "http://example.com"}
response = client.post("/api/shortlink", json=form)
assert response.status_code == 404
def test_create_shortlink_method_is_not_allowed(self, client):
"""create_shortlink() if method is not allowed,
should respond with an error 405.
"""
form = {"provider": "tinyurl", "url": "http://example.com"}
response = client.get("/api/shortlinks", json=form)
assert response.status_code == 405
def test_create_shortlink_provider_is_not_in_valid_format(self, client):
"""create_shortlink() if provider is not in valid format,
should respond with a validation error 400.
"""
form = {"provider": 1, "url": "http://example.com"}
response = client.post("/api/shortlinks", json=form)
assert response.status_code == 400
|
class pycacheNotFoundError(Exception):
def __init__(self, msg):
self.msg = msg
super().__init__(self.msg)
class installModulesFailedError(Exception):
def __init__(self):
self.msg = "The modules could not be installed! Some error occurred!"
super().__init__(self.msg)
|
# A python source file with exotic characters
# -*- coding: utf-8 -*-
upside_down = "ʎd˙ǝbɐɹǝʌoɔ"
surrogate = "db40,dd00: x󠄀"
|
# Auto-generated pytest file
class TestInit:
def test___init__(self):
fail()
class TestEnter:
def test___enter__(self):
fail()
class TestExit:
def test___exit__(self):
fail()
class TestGetSearchResultCount:
def test_get_search_result_count(self):
fail()
class TestGetSearchResultLinks:
def test_get_search_result_links(self):
fail()
class TestGetSpecialPageLinks:
def test_get_special_page_links(self):
fail()
class TestOpenIdLink:
def test_open_id_link(self):
fail()
class TestExtractSearchResultCount:
def test_extract_search_result_count(self):
fail()
class TestExtractSearchResultLinks:
def test_extract_search_result_links(self):
fail()
class TestExtractSpecialPageLinks:
def test_extract_special_page_links(self):
fail()
class TestTransformLinksToNoRedirectLinks:
def test_transform_links_to_no_redirect_links(self):
fail()
class TestIsSpecialPageIdExists:
def test_is_special_page_id_exists(self):
fail()
class TestLog:
def test_log(self):
fail()
class TestClose:
def test_close(self):
fail()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.