content
stringlengths 7
1.05M
|
|---|
# Vasya adores sport programming. He can't write programs but he loves to watch the contests' progress.
# Vasya even has a favorite coder and Vasya pays special attention to him.
# One day Vasya decided to collect the results of all contests where his favorite coder participated and track the
# progress of his coolness. For each contest where this coder participated, he wrote out a single non-negative number —
# the number of points his favorite coder earned in the contest. Vasya wrote out the points for the contest in the
# order, in which the contests run (naturally, no two contests ran simultaneously).
# Vasya considers a coder's performance in a contest amazing in two situations:
# he can break either his best or his worst performance record.
# First, it is amazing if during the contest the coder earns strictly more points that he earned on each past contest.
# Second, it is amazing if during the contest the coder earns strictly less points that he earned on each past contest.
# A coder's first contest isn't considered amazing. Now he wants to count the number of amazing performances the coder
# had throughout his whole history of participating in contests. But the list of earned points turned out long and
# Vasya can't code... That's why he asks you to help him.
# Input
# The first line contains the single integer n (1 ≤ n ≤ 1000) — the number of contests where the coder participated.
# The next line contains n space-separated non-negative integer numbers — they are the points which the coder has
# earned. The points are given in the chronological order. All points do not exceed 10000.
# Output
# Print the single number — the number of amazing performances the coder has had during his whole history of
# participating in the contests.
# Examples
# input
# 5
# 100 50 200 150 200
# output
# 2
# input
# 10
# 4664 6496 5814 7010 5762 5736 6944 4850 3698 7242
# output
# 4
# Note
# In the first sample the performances number 2 and 3 are amazing.
# In the second sample the performances number 2, 4, 9 and 10 are amazing.
n = int(input())
scores = list(map(int, input().split()))
mx = scores[0]
mn = scores[0]
c = 0
for i in range(1, n):
if scores[i] > mx:
mx = scores[i]
c += 1
elif scores[i] < mn:
mn = scores[i]
c += 1
print(c)
|
"""
@Author: huuuuusy
@GitHub: https://github.com/huuuuusy
系统: Ubuntu 18.04
IDE: VS Code 1.37
工具: python == 3.7.3
"""
"""
思路:
二分查找
结果:
执行用时 : 56 ms, 在所有 Python3 提交中击败了100%的用户
内存消耗 : 14.6 MB, 在所有 Python3 提交中击败了100%的用户
"""
class Solution:
def search(self, reader, target):
"""
:type reader: ArrayReader
:type target: int
:rtype: int
"""
# 按照数组最大的可能性设置左右边界
left = 0
right = 20000
while left < right:
mid = (left + right + 1) >> 1 # 右中位数
if reader.get(mid) == 2147483647: # 如果越界,则右边界收缩
right = mid - 1
elif reader.get(mid) > target: # 如果大于目标值,则右边界收缩
right = mid - 1
else:
left = mid
return left if reader.get(left) == target else -1 # 返回结果
|
'''
Python program to remove two duplicate numbers from a given number of list.
Sample Input:
([1,2,3,2,3,4,5])
([1,2,3,2,4,5])
([1,2,3,4,5])
Sample Output:
[1, 4, 5]
[1, 3, 4, 5]
[1, 2, 3, 4, 5]
'''
a = [10,20,30,20,10,50,60,40,80,50,40]
dup_items = set()
uniq_items = []
for x in a:
if x not in dup_items:
uniq_items.append(x)
dup_items.add(x)
print(dup_items)
|
# optimal performance
def copy_random_list(head):
if not head: return head
# copy each node and insert right after itself
curr = head
while curr:
node_new = RandomListNode(curr.label)
node_next = curr.next
curr.next = node_new
node_new.next = node_next
curr = node_next
# copy random reference
curr = head
while curr:
if curr.random:
curr.next.random = curr.random.next
curr = curr.next.next
# separate out new list
curr = head
dummy = RandomListNode(0)
head_new = dummy
while curr:
node_new = curr.next
node_next = node_new.next
curr.next = node_next
head_new.next = node_new
curr = node_next
head_new = node_new
return dummy.next
# O(n) time, O(1) space
# similar to clone graph approach, not good enough in interview
def copy_random_list_mapping(head):
if not head: return head
mapping = {} # original node => copied node
curr = head
while curr:
mapping[curr] = RandomListNode(curr.label)
curr = curr.next
curr = head
while curr:
mapping[node].next = mapping[node.next]
mapping[node].random = mapping[node.random]
curr = curr.next
return mapping[head]
# O(n) time and space
|
class CoinPaymentsProviderError(Exception):
pass
class TxInfoException(Exception):
pass
|
#!/usr/bin/env python
# vi: set ft=python sts=4 ts=4 sw=4 et:
######################################################################
#
# See COPYING file distributed along with the psignifit package for
# the copyright and license terms
#
######################################################################
__docformat__ = "restructuredtext"
class NosamplesError ( Exception ):
"""An exception that is raised whenever we try to use samples but there are none"""
def __init__ ( self, msg ):
self.msg = msg
def __str__(self):
return repr(self.msg)
class SamplingError ( Exception ):
"""An exception that is raised if some thing is wrong with the sampling"""
def __init__ ( self, msg ):
self.msg = msg
def __str__ ( self ):
return repr(self.msg)
|
current_number=0
while current_number <=5:
current_number +=1
print(current_number)
|
#!/usr/bin/python3
def add_sub(shellcode: bytes, add_or_sub: bool=True, to_num: int=1, decode: bool=False) -> bytes:
"""Perform a add or sub encoding scheme on `shellcode`.
:return: bytes object
"""
shellcode = bytearray(shellcode)
encoded_payload = bytearray()
calculated_num = (int(add_or_sub)*2-1) * to_num*(int(decode)*-2+1)
for byte in shellcode:
encoded_payload.append(byte + calculated_num)
return bytes(encoded_payload)
def right_left_rotation_bit(shellcode: bytes, right_or_left: bool=True, n: int=1) -> bytes:
# print(bin(byte<<n>>8<<8), bin(byte<<n), bin((byte<<n)-(byte<<n>>8<<8)), bin(byte>>8-n), bin((byte<<n)-(byte<<n>>8<<8) + (byte>>(8-n))))
# print(bin(byte), bin(byte<<(8-n)), bin(byte>>n<<8), bin(byte>>n), bin((byte<<(8-n)) - (byte>>n<<8) + (byte>>n)))
shellcode = bytearray(shellcode)
encoded_payload = bytearray()
for byte in shellcode:
if right_or_left:
encoded_payload.append((byte<<(8-n)) - (byte>>n<<8) + (byte>>n))
## right
else:
## left
encoded_payload.append((byte<<n)-(byte<<n>>8<<8) + (byte>>(8-n)))
return bytes(encoded_payload)
def rolling_rotation(shellcode: bytes, right_or_left: bool=True, decode: bool=False) -> bytes:
""" Perform a rolling xor encoding scheme on `shellcode`.
:param shellcode: bytes object; data to be [en,de]coded
:param decode: boolean, decrypt previously xor'd data
:return: bytes object
"""
shellcode = bytearray(shellcode)
if decode:
shellcode.reverse()
encoded_payload = bytearray()
for i, byte in enumerate(shellcode):
if i == len(shellcode) - 1:
encoded_payload.append(shellcode[i]) # last byte doesn't need xor'd, common to system call Ox80 generally
else:
encoded_payload.append(shellcode[i] ^ shellcode[i + 1])
encoded_payload.reverse()
else:
encoded_payload = bytearray([shellcode.pop(0)]) # first byte left as is in the ciphertext
for i, byte in enumerate(shellcode):
encoded_payload+=bytearray(right_left_rotation_bit( bytes(byte), right_or_left, int(encoded_payload[i])%8))
return bytes(encoded_payload)
def rolling_xor(shellcode: bytes, decode: bool=False) -> bytes:
""" Perform a rolling xor encoding scheme on `shellcode`.
:param shellcode: bytes object; data to be [en,de]coded
:param decode: boolean, decrypt previously xor'd data
:return: bytes object
"""
shellcode = bytearray(shellcode)
if decode:
shellcode.reverse()
encoded_payload = bytearray()
for i, byte in enumerate(shellcode):
if i == len(shellcode) - 1:
encoded_payload.append(shellcode[i]) # last byte doesn't need xor'd, common to system call Ox80 generally
else:
encoded_payload.append(shellcode[i] ^ shellcode[i + 1])
encoded_payload.reverse()
else:
encoded_payload = bytearray([shellcode.pop(0)]) # first byte left as is in the ciphertext
for i, byte in enumerate(shellcode):
encoded_payload.append(byte ^ encoded_payload[i])
return bytes(encoded_payload)
|
def tree(length):
if length>5:
t.forward(length)
t.right(20)
tree(length-15)
t.left(40)
tree(length-15)
t.right(20)
t.backward(length)
t.left(90)
t.color("green")
t.speed(1)
tree(90)
|
class Pessoa:
olhos = 2
def __init__(self, *filhos, nome=None, idade=36):
self.nome = nome
self.idade = idade
self.filhos = list(filhos)
def cumprimentar(self):
return f'Olá {id(self)}'
@staticmethod
#funciona como uma função da classe pessoa, não precisa receber atributo
def metodo_estatico():
return 42
@classmethod
def nome_e_atributos_de_classe(cls):
return f'{cls} - olhos {cls.olhos} '
if __name__=='__main__':
marilia = Pessoa(nome='Marilia', idade=12)
marilia.olhos=4
jose = Pessoa(marilia, nome='Jose2', idade=37)
print(Pessoa.cumprimentar(jose))
#print (jose.cumprimentar())
print(jose.nome)
print(jose.idade)
for filho in jose.filhos:
print(filho.nome)
print(filho.idade)
jose.sobrenome = 'Silva'
print(jose.sobrenome)
print(Pessoa.olhos)
print(marilia.olhos)
print(jose.olhos)
print(Pessoa.metodo_estatico())
print(Pessoa.nome_e_atributos_de_classe())
|
#!/usr/bin/env python
'''
https://leetcode.com/problems/find-the-duplicate-number/
Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one.
Input: [1,3,4,2,2]
Output: 2
Input: [3,1,3,4,2]
Output: 3
'''
def find_dup(ns):
if len(ns) <= 1:
return -1
slow, fast = ns[0], ns[ns[0]]
while slow != fast:
slow = ns[slow]
fast = ns[ns[fast]]
fast = 0
while fast != slow:
fast = ns[fast]
slow = ns[slow]
return slow
|
cases = int(input())
for a in range(cases):
tracks = int(input().split(" ")[0])
requests = input().split(" ")
last = int(requests[0])
total = 0
for i in requests[1:]:
next = int(i)
total += min(tracks - ((next - last - 1) % tracks + tracks) % tracks, ((next - last - 1) % tracks + tracks) % tracks)
last = next
print(total)
|
def alternating_sums(a):
even, odd = [], []
for i in range(len(a)):
if i % 2 == 0:
even.append(a[i])
else:
odd.append(a[i])
return [sum(even), sum(odd)]
def alternating_sums_short(a):
return [
sum(a[::2]), sum(a[1::2])
]
if __name__ == '__main__':
a = [50, 60, 60, 45, 70]
alternating_sums(a)
alternating_sums_short(a)
|
# [h] close all fonts
'''Close all open fonts.'''
all_fonts = AllFonts()
if len(all_fonts) > 0:
for font in all_fonts:
font.close()
|
"""Implementation for directed graph."""
class GraphNode:
def __init__(self, node_id):
self.id = node_id
self.data = None
self.adj = set()
class DirectedGraph:
"""Implements a directed graph.
Nodes have unique ids.
Attributes:
nodes: A map of id to node object.
"""
def __init__(self):
self.nodes = {}
def has_node(self, node_id):
return node_id in self.nodes
def get_node_ids(self):
node_ids = []
for node_id in self.nodes:
node_ids.append(node_id)
return node_ids
def get_adj_node_ids(self, node_id):
if node_id not in self.nodes:
raise IndexError('Node id does not exist.')
return list(self.nodes[node_id].adj)
def add_node_id(self, node_id):
"""Adds a new node id if it does not aleardy exist."""
if node_id not in self.nodes:
node = GraphNode(node_id)
self.nodes.update({node_id: node})
def add_edge(self, from_id, to_id):
"""Adds an edge: from_id --> to_id"""
if from_id == to_id:
raise ValueError('A node may not have a self edge.')
if (from_id not in self.nodes) or (to_id not in self.nodes):
raise IndexError('Node with given id does not exist.')
self.nodes[from_id].adj.add(to_id)
def adjacency_to_graph(self, adj_map):
"""Creates a graph from an adjacency map of node ids.
Overwrites any existing node id.
Args:
adj_map: A dictionary map from nodes to their adjacenet nodes.
Example: {1: [2, 3], 2: [3, 4]}
"""
for node_id, adj_list in adj_map.items():
self.add_node_id(node_id)
for adj_id in adj_list:
self.add_node_id(adj_id)
self.add_edge(node_id, adj_id)
def graph_to_adjacency(self):
"""Returns an adjacency map representation of the graph.
Example: The following graph
1 --> 2, 3
2 --> 3
will be shown as the following adjacency map:
{1: {2, 3}, 2: {3}, 3: {}}
"""
adj_map = {}
for node_id, node in self.nodes.items():
adj_map.update({node_id: list(node.adj)})
return adj_map
|
"""Top-level package for with-op script."""
__author__ = """Vince Broz"""
__email__ = 'vince@broz.cc'
__version__ = '1.1.1'
|
def adder(a:int, b:int) -> int:
while b:
_xor = a ^ b
_and = (a & b) << 1
a = _xor
b = _and
return a
if __name__ == "__main__":
bin_digits = 8
for i in range(2 ** bin_digits):
for ii in range(2 ** bin_digits):
true = i + ii
test = adder(i, ii)
if true != test:
print(f"Adding: {i:b} + {ii:b}")
print(f"\tTrue: {true:b}")
print(f"\tTest: {test:b}")
|
# calculate 10!
@profile
def factorial(num):
if num == 1:
return 1
else:
print("Calculating " + str(num) + "!")
return factorial(num -1) * num
@profile
def profiling_factorial():
value = 10
result = factorial(value)
print("10!= " + str(result))
if __name__ == "__main__":
profiling_factorial()
|
""" Holds utilities related with Earth plotting """
EARTH_PALETTE = {
"land_color": "#9fc164",
"ocean_color": "#b2d9ff",
"lake_color": "#e9eff9",
"dessert_color": "d8c596",
}
""" A color palette based on Earth colors """
|
# Problem: Reverse a doubly linked list
# Url: https://www.hackerrank.com/challenges/reverse-a-doubly-linked-list/problem
# Level: Easy
# Developer: Murillo Grübler
class DoublyLinkedListNode:
def __init__(self, node_data):
self.data = node_data
self.next = None
self.prev = None
class DoublyLinkedList:
def __init__(self):
self.head = None
self.tail = None
def insert_node(self, node_data):
node = DoublyLinkedListNode(node_data)
if not self.head:
self.head = node
else:
self.tail.next = node
node.prev = self.tail
self.tail = node
def print_doubly_linked_list(node):
while node:
print (str(node.data))
node = node.next
##################################################
#### Function to Reverse a doubly linked list ####
def reverse(head):
def reverseRecursion(node):
node.next, node.prev = node.prev, node.next
if node.prev is None:
return node
return reverseRecursion(node.prev)
if head is not None:
return reverseRecursion(head)
return None
##################################################
if __name__ == '__main__':
t = int(input())
for t_itr in range(t):
llist_count = int(input())
llist = DoublyLinkedList()
for _ in range(llist_count):
llist_item = int(input())
llist.insert_node(llist_item)
llist1 = reverse(llist.head)
print_doubly_linked_list(llist1)
|
BZX = Contract.from_abi("BZX", "0xc47812857a74425e2039b57891a3dfcf51602d5d", interface.IBZx.abi)
TOKEN_REGISTRY = Contract.from_abi("TOKEN_REGISTRY", "0x2fA30fB75E08f5533f0CF8EBcbb1445277684E85", TokenRegistry.abi)
list = TOKEN_REGISTRY.getTokens(0, 100)
for l in list:
iTokenTemp = Contract.from_abi("iTokenTemp", l[0], LoanTokenLogicStandard.abi)
globals()[iTokenTemp.symbol()] = iTokenTemp
underlyingTemp = Contract.from_abi("underlyingTemp", l[1], TestToken.abi)
globals()[underlyingTemp.symbol()] = underlyingTemp
CHI = Contract.from_abi("CHI", "0x0000000000004946c0e9F43F4Dee607b0eF1fA1c", TestToken.abi)
CHEF = Contract.from_abi("CHEF", "0x1FDCA2422668B961E162A8849dc0C2feaDb58915", MasterChef_BSC.abi)
HELPER = Contract.from_abi("HELPER", "0xE05999ACcb887D32c9bd186e8C9dfE0e1E7814dE", HelperImpl.abi)
BGOV = Contract.from_abi("PGOV", "0xf8E026dC4C0860771f691EcFFBbdfe2fa51c77CF", GovToken.abi)
CHEF = Contract.from_abi("CHEF", CHEF.address, interface.IMasterChef.abi)
SWEEP_FEES = Contract.from_abi("STAKING", "0x5c9b515f05a0E2a9B14C171E2675dDc1655D9A1c", FeeExtractAndDistribute_BSC.abi)
|
lowestPossible = 1
highestPossible = 999
num = 0
while True:
enemy = hero.findNearest(hero.findEnemies())
if enemy:
if enemy.type == "scout":
lowestPossible = num
elif enemy.type == "munchkin":
highestPossible = num
hero.attack(enemy)
else:
num = lowestPossible + Math.ceil((highestPossible - lowestPossible) / 2);
hero.say(num)
|
#!/usr/bin/env python
# coding: utf-8
# Utility functions
def get_image_size(model_prefix):
if 'caffenet' in model_prefix:
return 227
elif 'squeezenet' in model_prefix:
return 227
elif 'alexnet' in model_prefix:
return 227
elif 'googlenet' in model_prefix:
return 299
elif 'inception-v3' in model_prefix:
return 299
elif 'inception-v4' in model_prefix:
return 299
elif 'inception-resnet-v2' in model_prefix:
return 299
else:
return 224
|
# variable = a container for a value.
# Behaves as the value that it contains
first_name = "Bro"
last_name = "Code"
full_name = first_name +" "+ last_name
#name='Bro'
print("Hello "+full_name)
#print(type(name))
age = 21
age += 1
print("Your age is: "+str(age))
#print(age)
#print(type(age))
height = 250.5
print("Your height is: "+str(height)+"cm")
#print(height)
#print(type(height))
human = True
print("Are you a human: "+str(human))
#print(human)
#print(type(human))
|
#!/usr/bin/python
# Any system should have an sh capable of `command -v`
# REQUIRES: command -v sh
print("Oh, but it is!")
# CHECK: This should never be compared
|
__author__ = 'Liu'
__email__ = 'wisedoge@outlook.com'
# 一些惯用变量名的解释
|
#4. Faça um programa que peça dois números e imprima a soma deles.
print('VAMOS SOMAR')
#Informando numeros
num1 = int(input('Digite o 1º número: '))
num2 = int(input('Digite o 2º número: '))
#Declarando soma das variaveis
soma = num1 + num2
#imprimindo somas
print (f'A soma de {num1} + {num2} é igual a {soma}')
|
# CloudShell L1 resource autoload XML helper
#
# It should not be necessary to edit this file.
#
# - Generates the autoload XML resource format to return to CloudShell
# - Subresources are also represented with nested instances of this class
# - See example usage in <project>_l1_handler.py
class L1DriverResourceInfo:
def __init__(self, name, full_address, family, model, map_path=None, serial='-1'):
"""
:param name: str
:param full_address: str
:param family: str
:param model: str
:param map_path: str
:param serial: str
"""
self.name = name
self.address = full_address
self.family = family
self.model = model
self.serial = serial
self.map_path = map_path
self.subresources = []
self.attrname2typevaluetuple = {}
if False:
self.subresources.append(L1DriverResourceInfo(None, None, None, None))
def add_subresource(self, subresource):
"""
:param subresource: L1DriverResourceInfo
:return: None
"""
self.subresources.append(subresource)
def set_attribute(self, name, value, typename='String'):
"""
:param name: str
:param value: str
:param typename: str: String, Lookup,
:return: None
"""
self.attrname2typevaluetuple[name] = (typename, value)
def get_attribute(self, name):
"""
:param name: str
:return: str
"""
return self.attrname2typevaluetuple[name][1]
def to_string(self, tabs=''):
"""
:param tabs: str
:return: str
"""
def indent(t, s):
return t + (('\n' + t).join(s.split('\n'))).strip() + '\n'
return indent(tabs,
'''<ResourceInfo Name="{name}" Address="{address}" ResourceFamilyName="{family}" ResourceModelName="{model}" SerialNumber="{serial}">
<ChildResources>
{children} </ChildResources>
<ResourceAttributes>
{attributes} </ResourceAttributes>
{mapping}</ResourceInfo>'''.format(
name=self.name,
address=self.address,
family=self.family,
model=self.model,
serial=self.serial,
children=''.join([x.to_string(tabs=tabs + ' ') for x in self.subresources]),
attributes=''.join([''' <Attribute Name="{name}" Type="{type}" Value="{value}" />\n'''.format(name=attrname, type=type_value[0], value=type_value[1])
for attrname, type_value in self.attrname2typevaluetuple.iteritems()
]),
mapping=''' <ResourceMapping><IncomingMapping>''' + self.map_path + '''</IncomingMapping></ResourceMapping>\n''' if self.map_path else ''
))
|
class Solution:
def intToRoman(self, num):
symbols_list = [
["M", "M", "M"],
["C", "D", "M"],
["X", "L", "C"],
["I", "V", "X"]
]
pown_list = [1000, 100, 10, 1]
def digitToRoman(digit, symbols):
if digit < 4:
return symbols[0] * digit
elif digit == 4:
return symbols[0] + symbols[1]
elif digit < 9:
return symbols[1] + (symbols[0] * (digit - 5))
else:
return symbols[0] + symbols[2]
buffer = ""
for pown, symbols in zip(pown_list, symbols_list):
buffer += digitToRoman(num // pown, symbols)
num %= pown
return buffer
def test():
sol = Solution()
cases = [3, 4, 5, 9, 58, 1994]
for case in cases:
print(case)
print(sol.intToRoman(case))
if __name__ == '__main__':
test()
|
class Solution:
def mySqrt(self, x: int) -> int:
if x < 2: return x
result, value = x, x // 2
while result > value:
result, value = value, (value + x // value) // 2
return result
test = Solution().mySqrt
print(2, test(4))
print(2, test(8))
print(0, test(0))
print(1, test(1))
print(1, test(99999999))
# Implement int sqrt(int x).
# Compute and return the square root of x, where x is guaranteed to be a non-negative integer.
# Since the return type is an integer, the decimal digits are truncated and only the integer part of the value is returned.
# Example 1:
# Input: 4
# Output: 2
# Example 2:
# Input: 8
# Output: 2
# Explanation: The square root of 8 is 2.82842..., and since
# the decimal part is truncated, 2 is returned.
# 来源:力扣(LeetCode)
# 链接:https://leetcode-cn.com/problems/sqrtx
# 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
|
# Copyright 2015 Ufora Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""DefaultDict - dictionary with a default item
DefaultDict overrides a normal dict. When created, give it a lambda
function that takes a key and produces the 'zero' element for the dictionary
for that key.
"""
class DefaultDict(dict):
def __init__(self, defaultFunction):
dict.__init__(self)
self.defaultFunction = defaultFunction
def __getitem__(self, x):
if not self.has_key(x):
dict.__setitem__(self, x, self.defaultFunction(x))
return dict.__getitem__(self,x)
|
CLUSTERS_DB = 'complete_clusters.db'
SAMPLE2PROTEIN_DB = 'sample2protein.db'
SAMPLE2PATH = 'sample2path.tsv'
|
def funny(x):
if (x%2 == 1):
return x+1
else:
return funny(x-1)
print(funny(7))
print(funny(6))
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This package contains only the Brewery DB API key. It is necessary to provide
an alternate method for this key entry when using chalice so that secrets
aren't improperly shared.
"""
BREWERY_KEY = "<YOUR_BREWERY_DB_API_APP_KEY_HERE>"
S3_BUCKET = "<YOUR_S3_BUCKET>"
|
class TweetComplaint:
def __init__(self, complain_text, city, state, tweet_id, username, image_url):
self.complain_text = complain_text
self.tweet_id = tweet_id
self.username = username
self.city = city
self.state = state
self.image_url = image_url
self.status = "reported"
def __str__(self):
return self.complain_text +'\n'+ str(self.tweet_id) +'\n'+ self.username +'\n'+ self.city +'\n'+ self.state +'\n'+ self.image_url
def to_dict(self):
return {'category': '', 'city': self.city, 'state': self.state, 'image_url': self.image_url,
'status': self.status, 'text': self.complain_text, 'tweet_id': self.tweet_id, 'username': self.username}
|
class Solution:
def rob(self, num):
ls = [[0, 0]]
for e in num:
ls.append([max(ls[-1][0], ls[-1][1]), ls[-1][0] + e])
return max(ls[-1])
|
# -*- coding: utf-8 -*-
__version__ = '0.16.1.dev0'
PROJECT_NAME = "planemo"
PROJECT_USERAME = "galaxyproject"
RAW_CONTENT_URL = "https://raw.github.com/%s/%s/master/" % (
PROJECT_USERAME, PROJECT_NAME
)
|
"""This is the entry point of the program."""
def bubble_sort(list_of_numbers):
for i in range(len(list_of_numbers)-1,0,-1):
for j in range(i):
if list_of_numbers[j] > list_of_numbers[j+1]:
placeholder = list_of_numbers[j]
list_of_numbers[j] = list_of_numbers[j+1]
list_of_numbers[j+1] = placeholder
return list_of_numbers
if __name__ == '__main__':
print(bubble_sort([9, 1, 3, 11, 7, 2, 42, 111]))
|
spec = {
'name' : "ODL demo",
'external network name' : "exnet3",
'keypair' : "X220",
'controller' : "r720",
'dns' : "10.30.65.200",
'credentials' : { 'user' : "nic", 'password' : "nic", 'project' : "nic" },
# 'credentials' : { 'user' : "admin", 'password' : "admin", 'project' : "admin" },
# NOTE: network start/end range -
# a) must not include the gateway IP
# b) when assigning host IPs remember taht a DHCP server will be allocated from the range as well as the hosts
# Probably on the first or second available IP in the range....
'Networks' : [
{ 'name' : "odldemo" , "start": "192.168.50.2", "end": "192.168.50.254", "subnet" :" 192.168.50.0/24", "gateway": "192.168.50.1" },
{ 'name' : "odldemo2" , "start": "192.168.111.2", "end": "192.168.111.254", "subnet" :" 192.168.111.0/24", "gateway": "192.168.111.1" },
{ 'name' : "odldemo3" , "start": "172.16.0.2", "end": "172.16.0.254", "subnet" :" 172.16.0.0/24", "gateway": "172.16.0.1" },
],
# Hint: list explicity required external IPs first to avoid them being claimed by hosts that don't care...
'Hosts' : [
{ 'name' : "devstack-control" , 'image' : "trusty64" , 'flavor':"m1.xlarge" , 'net' : [ ("odldemo" , "192.168.50.20", "devstack-control"), ("odldemo2" , "192.168.111.10"), ("odldemo3" , "172.16.0.10") ] },
{ 'name' : "devstack-compute-1" , 'image' : "trusty64" , 'flavor':"m1.xlarge" , 'net' : [ ("odldemo" , "192.168.50.21","devstack-compute-1"), ("odldemo2" , "192.168.111.11"), ("odldemo3" , "172.16.0.11") ] },
# { 'name' : "devstack-compute-2" , 'image' : "trusty64" , 'flavor':"m1.xlarge" , 'net' : [ ("odldemo" , "192.168.50.22") ] },
# { 'name' : "devstack-compute-3" , 'image' : "trusty64" , 'flavor':"m1.xlarge" , 'net' : [ ("odldemo" , "192.168.50.23") ] },
{ 'name' : "kilo-controller" , 'image' : "Centos7" , 'flavor':"m1.xlarge" , 'net' : [ ("odldemo" , "192.168.50.60", "kilo-controller"), ("odldemo2" , "192.168.111.50"), ("odldemo3" , "172.16.0.50") ] },
{ 'name' : "kilo-compute-1" , 'image' : "Centos7" , 'flavor':"m1.xlarge" , 'net' : [ ("odldemo" , "192.168.50.61", "kilo-compute-1"), ("odldemo2" , "192.168.111.51"), ("odldemo3" , "172.16.0.51") ] },
{ 'name' : "kilo-compute-2" , 'image' : "Centos7" , 'flavor':"m1.xlarge" , 'net' : [ ("odldemo" , "192.168.50.62", "kilo-compute-2"), ("odldemo2" , "192.168.111.52"), ("odldemo3" , "172.16.0.52") ] },
]
}
|
#encoding:utf-8
subreddit = 'kratom'
t_channel = '@r_kratom'
def send_post(submission, r2t):
return r2t.send_simple(submission)
|
n = 5
count = 0
total = 0
startCount = n - 3
while True:
if count == n:
break
elif count < n:
x = int(input())
if count > startCount:
total = total + x
count = count + 1
print('')
print('Sum is %d.' % total)
|
JPEG_10918 = (
'SOF0', 'SOF1', 'SOF2', 'SOF3', 'SOF5',
'SOF6', 'SOF7', 'SOF9', 'SOF10',
'SOF11', 'SOF13', 'SOF14', 'SOF15',
)
JPEG_14495 = ('SOF55', 'LSE', )
JPEG_15444 = ('SOC', )
PARSE_SUPPORTED = {
'10918' : [
'Process 1',
'Process 2',
'Process 4',
'Process 14',
]
}
DECODE_SUPPORTED = {}
ENCODE_SUPPORTED = {}
ZIGZAG = [ 0, 1, 5, 6, 14, 15, 27, 28,
2, 4, 7, 13, 16, 26, 29, 42,
3, 8, 12, 17, 25, 30, 41, 43,
9, 11, 18, 24, 31, 40, 44, 53,
10, 19, 23, 32, 39, 45, 52, 54,
20, 22, 33, 38, 46, 51, 55, 60,
21, 34, 37, 47, 50, 56, 59, 61,
35, 36, 48, 49, 57, 58, 62, 63]
|
'''Crie um programa que tenha uma tupla com varias palavras (não usar acentos). Depois disso, voce deve mostrar, para cada palavra, quais são as suas vogais.'''
lista = ('Sao Paulo','Santos','Praia Grande','Peruibe','Cotia','Jundiai','Araraquara','Valinhos')
vogais = ('a','e','i','o','u')
for c in lista:
print(f'\n{c:.<30} = ',end='')
for letra in c:
if letra.lower() in 'aeiou':
print( letra,end=' ' )
|
def converte_formato_hora(hora: str):
# Classifica em AM ou PM
if hora[-2:] == "AM":
# se 12, retorna 00:[minutos]
if hora[:2] == "12":
return "00" + hora[2:-3]
# senão, retorna a hora menos AM
else:
return hora[:-3]
elif hora [-2:] == "PM":
# se 12m retorna a hora menos PM
if hora[:2] == "12":
return hora[:-3]
# senão, retorna a [hora mais 12]:[minutos]
else:
return str(int(hora[:2]) + 12) + hora[2:-3]
h = "10:17 PM"
print(converte_formato_hora(h))
|
# 递归
# Runtime: 32 ms, faster than 100.00% of Python3 online submissions for Invert Binary Tree.
# Memory Usage: 12.4 MB, less than 0.96% of Python3 online submissions for Invert Binary Tree.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def invertTree(self, root: 'TreeNode') -> 'TreeNode':
if root: root.left, root.right = self.invertTree(root.right), self.invertTree(root.left)
return root
|
class Solution:
def numberOfArithmeticSlices(self, A: List[int]) -> int:
count, currentSum = 0, 0
for i in range(2, len(A)):
if A[i] - A[i - 1] == A[i - 1] - A[i - 2]:
count += 1
else:
currentSum += ((count + 1) * count) // 2
count = 0
currentSum += ((count + 1) * count) // 2
return currentSum
|
#Add Key imports here!
TRAIN_URL = "https://raw.githubusercontent.com/karkir0003/DSGT-Bootcamp-Material/main/Udemy%20Material/Airline%20Satisfaction/train.csv"
def read_train_dataset():
"""
This function should read in the train.csv and return it
in whatever representation you like
"""
###YOUR CODE HERE####
raise NotImplementedError("Did not implement read_train_dataset() function")
#####################
def preprocess_dataset(dataset):
"""
Given the raw dataset read in from your read_train_dataset() function,
process the dataset accordingly
"""
###YOUR CODE HERE####
raise NotImplementedError("Did not implement read_train_dataset() function")
#####################
def train_model():
"""
Given your cleaned data, train your Machine Learning model on it and return the
model
MANDATORY FUNCTION TO IMPLEMENT
"""
####YOUR CODE HERE#####
raise NotImplementedError("Did not implement the train_model() function")
#######################
|
#!/usr/bin/env python
# encoding: utf-8
"""
candy.py
Created by Shengwei on 2014-07-22.
"""
# https://oj.leetcode.com/problems/candy/
# tags: hard, array, greedy, logic
"""
There are N children standing in a line. Each child is assigned a rating value.
You are giving candies to these children subjected to the following requirements:
Each child must have at least one candy.
Children with a higher rating get more candies than their neighbors.
What is the minimum candies you must give?
"""
# https://oj.leetcode.com/discuss/76/does-anyone-have-a-better-idea
# TODO: try alternative
class Solution:
# @param ratings, a list of integer
# @return an integer
def candy(self, ratings):
count = [1]
for index in xrange(1, len(ratings)):
# note: child gets the same rating can have fewer
# candies than the neighbors
# e.g., rating [1, 2, 2, 3] -> candies [1, 2, 1, 2]
if ratings[index] > ratings[index-1]:
count.append(count[-1] + 1)
else:
count.append(1)
for index in xrange(-2, -len(ratings)-1, -1):
if ratings[index] > ratings[index+1]:
count[index] = max(count[index], count[index+1] + 1)
return sum(count)
|
"""
Visualization styles.
"""
__author__ = "Alexander Urban"
__email__ = "aurban@atomistic.net"
__date__ = "2021-01-23"
__version__ = "0.1"
CPK = {
'H': 'white',
'C': 'black',
'N': 'blue',
'O': 'red',
'F': 'green',
'Cl': 'green',
'Br': '0x8b0000',
'I': '0x9400d3',
'He': 'cyan',
'Ne': 'cyan',
'Ar': 'cyan',
'Ce': 'cyan',
'Kr': 'cyan',
'P': 'orange',
'S': 'yellow',
'B': '0xffa07a',
'Li': 'violet',
'Na': 'violet',
'K': 'violet',
'Rb': 'violet',
'Cs': 'violet',
'Fr': 'violet',
'Be': '0x2e8b57',
'Mg': '0x2e8b57',
'Ca': '0x2e8b57',
'Sr': '0x2e8b57',
'Ba': '0x2e8b57',
'Ra': '0x2e8b57',
'Ti': '0x808080',
'Fe': '0xff8c00',
'default': '0xda70d6'
}
DEFAULT_COLORS = CPK.copy()
DEFAULT_COLORS.update({
'Li': '0x32cd32',
'Sc': '0x6b8e23',
'Ti': '0x48d1cc',
'V': '0xC71585',
'Cr': '0x87cefa',
'Mn': '0x8b008b',
'Co': '0x00008b',
'Ni': 'blue',
'Cu': '0x8b0000',
'Zn': '0xadd8e6',
'Pt': 'cyan',
'Ir': 'violet'
})
class AtomStyle(object):
def __init__(self, style, colors=DEFAULT_COLORS, **style_specs):
"""
Arguments:
style (str): line, cross, stick, sphere, cartoon, clicksphere
colors (dict): element specific colors
style_specs: other options for specific styles, such as sphere
scales or bond radii. See documentation for AtomStyleSpec
"""
self.styles = [style]
self.colors = colors
self.style_specs = [style_specs]
def add_style(self, style, **style_specs):
"""
Add another style to the representation.
Arguments:
style (str): line, cross, stick, sphere, cartoon, clicksphere
style_specs: other options for specific styles, such as sphere
scales or bond radii. See documentation for AtomStyleSpec
"""
self.styles.append(style)
self.style_specs.append(style_specs)
def apply(self, model, selection=None):
"""
Apply style to a structure model.
Arguments:
model (3Dmol.js Model): the structure model
selection (dict): AtomSelectionSpec
"""
if selection is not None:
sel = selection
else:
sel = {}
if 'default' in self.colors:
default_color = self.colors['default']
else:
default_color = None
style_dict = {}
for i, style in enumerate(self.styles):
style_dict[style] = self.style_specs[i]
if default_color is not None:
style_dict[style]['color'] = default_color
model.setStyle(sel, style_dict)
# Overwrite default styles with element-specific colors. Woud
# be great to make use of mode.setColorByElement() but I could
# not figure out how to use this method from Python.
for species in self.colors:
if species != 'default':
species_dict = style_dict.copy()
for style in species_dict:
species_dict[style].update({'color': self.colors[species]})
model.setStyle({'elem': species, **sel},
species_dict)
class StickStyle(AtomStyle):
def __init__(self, bond_radius=0.1, **kwargs):
super(StickStyle, self).__init__(
style='stick', radius=bond_radius, **kwargs)
class VanDerWaalsStyle(AtomStyle):
def __init__(self, sphere_scale=1.0, **kwargs):
super(VanDerWaalsStyle, self).__init__(
style='sphere', scale=sphere_scale, **kwargs)
class BallAndStickStyle(AtomStyle):
def __init__(self, sphere_scale=0.4, bond_radius=0.1, **kwargs):
super(BallAndStickStyle, self).__init__(
style='sphere', scale=sphere_scale, **kwargs)
self.add_style(style="stick", radius=bond_radius, **kwargs)
class UnitCellStyle(dict):
def __init__(self, linewidth=1.0, linecolor='black', showaxes=False,
showlabels=True):
style = dict(
box=dict(linewidth=linewidth, color=linecolor),
)
if not showaxes:
style['astyle'] = {'hidden': True}
style['bstyle'] = {'hidden': True}
style['cstyle'] = {'hidden': True}
if showaxes and showlabels:
style['alabel'] = "a"
style['blabel'] = "b"
style['clabel'] = "c"
super(UnitCellStyle, self).__init__(**style)
|
app_name = 'tulius.profile'
urlpatterns = [
]
|
# 判断整数的位数(0、一位数或多位数)
n = int(input('整数:'))
if n == 0: # 0
print('该值为零。')
elif n >= -9 and n <= 9: # 一位数
print('该值为一位数。')
else: # 多位数
print('该值为多位数。')
|
#
# PySNMP MIB module CISCO-WBX-MEETING-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-WBX-MEETING-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:04:58 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, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueRangeConstraint, ValueSizeConstraint, SingleValueConstraint, ConstraintsUnion, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "ValueSizeConstraint", "SingleValueConstraint", "ConstraintsUnion", "ConstraintsIntersection")
ciscoMgmt, = mibBuilder.importSymbols("CISCO-SMI", "ciscoMgmt")
InetAddressType, InetAddress = mibBuilder.importSymbols("INET-ADDRESS-MIB", "InetAddressType", "InetAddress")
SnmpAdminString, = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpAdminString")
ModuleCompliance, ObjectGroup, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "ObjectGroup", "NotificationGroup")
Counter64, NotificationType, IpAddress, Integer32, Counter32, Gauge32, MibIdentifier, ModuleIdentity, Bits, MibScalar, MibTable, MibTableRow, MibTableColumn, Unsigned32, TimeTicks, iso, ObjectIdentity = mibBuilder.importSymbols("SNMPv2-SMI", "Counter64", "NotificationType", "IpAddress", "Integer32", "Counter32", "Gauge32", "MibIdentifier", "ModuleIdentity", "Bits", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Unsigned32", "TimeTicks", "iso", "ObjectIdentity")
AutonomousType, TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "AutonomousType", "TextualConvention", "DisplayString")
ciscoWebExMeetingMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 9, 9, 809))
ciscoWebExMeetingMIB.setRevisions(('2013-05-29 00:00',))
if mibBuilder.loadTexts: ciscoWebExMeetingMIB.setLastUpdated('201305290000Z')
if mibBuilder.loadTexts: ciscoWebExMeetingMIB.setOrganization('Cisco Systems Inc.')
ciscoWebExMeetingMIBNotifs = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 809, 0))
ciscoWebExMeetingMIBObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 809, 1))
ciscoWebExMeetingMIBConform = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 809, 2))
class CiscoWebExCommSysResource(TextualConvention, Integer32):
status = 'current'
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4))
namedValues = NamedValues(("cpu", 0), ("memory", 1), ("swap", 2), ("fileDescriptor", 3), ("disk", 4))
class CiscoWebExCommSysResMonitoringStatus(TextualConvention, Integer32):
status = 'current'
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(0, 1))
namedValues = NamedValues(("closed", 0), ("open", 1))
ciscoWebExCommInfo = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 1))
ciscoWebExCommSystemResource = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2))
cwCommSystemVersion = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 1, 1), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(0, 255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cwCommSystemVersion.setStatus('current')
cwCommSystemObjectID = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 1, 2), AutonomousType()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cwCommSystemObjectID.setStatus('current')
cwCommCPUUsageObject = ObjectIdentity((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 1))
if mibBuilder.loadTexts: cwCommCPUUsageObject.setStatus('current')
cwCommCPUTotalUsage = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 1, 1), Gauge32().subtype(subtypeSpec=ValueRangeConstraint(0, 100))).setUnits('percent').setMaxAccess("readonly")
if mibBuilder.loadTexts: cwCommCPUTotalUsage.setStatus('current')
cwCommCPUUsageWindow = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 1, 2), Gauge32().subtype(subtypeSpec=ValueRangeConstraint(1, 60))).setUnits('Minute').setMaxAccess("readwrite")
if mibBuilder.loadTexts: cwCommCPUUsageWindow.setStatus('current')
cwCommCPUTotalNumber = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 1, 3), Gauge32().subtype(subtypeSpec=ValueRangeConstraint(0, 64))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cwCommCPUTotalNumber.setStatus('current')
cwCommCPUUsageTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 1, 4), )
if mibBuilder.loadTexts: cwCommCPUUsageTable.setStatus('current')
cwCommCPUUsageEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 1, 4, 1), ).setIndexNames((0, "CISCO-WBX-MEETING-MIB", "cwCommCPUIndex"))
if mibBuilder.loadTexts: cwCommCPUUsageEntry.setStatus('current')
cwCommCPUIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 1, 4, 1, 1), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(1, 128)))
if mibBuilder.loadTexts: cwCommCPUIndex.setStatus('current')
cwCommCPUName = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 1, 4, 1, 2), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cwCommCPUName.setStatus('current')
cwCommCPUUsage = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 1, 4, 1, 3), Gauge32().subtype(subtypeSpec=ValueRangeConstraint(0, 100))).setUnits('percent').setMaxAccess("readonly")
if mibBuilder.loadTexts: cwCommCPUUsage.setStatus('current')
cwCommCPUUsageUser = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 1, 4, 1, 4), Gauge32().subtype(subtypeSpec=ValueRangeConstraint(0, 4294967295))).setUnits('KHz').setMaxAccess("readonly")
if mibBuilder.loadTexts: cwCommCPUUsageUser.setStatus('current')
cwCommCPUUsageNice = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 1, 4, 1, 5), Gauge32().subtype(subtypeSpec=ValueRangeConstraint(0, 4294967295))).setUnits('KHz').setMaxAccess("readonly")
if mibBuilder.loadTexts: cwCommCPUUsageNice.setStatus('current')
cwCommCPUUsageSystem = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 1, 4, 1, 6), Gauge32().subtype(subtypeSpec=ValueRangeConstraint(0, 4294967295))).setUnits('KHz').setMaxAccess("readonly")
if mibBuilder.loadTexts: cwCommCPUUsageSystem.setStatus('current')
cwCommCPUUsageIdle = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 1, 4, 1, 7), Gauge32().subtype(subtypeSpec=ValueRangeConstraint(0, 4294967295))).setUnits('KHz').setMaxAccess("readonly")
if mibBuilder.loadTexts: cwCommCPUUsageIdle.setStatus('current')
cwCommCPUUsageIOWait = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 1, 4, 1, 8), Gauge32().subtype(subtypeSpec=ValueRangeConstraint(0, 4294967295))).setUnits('KHz').setMaxAccess("readonly")
if mibBuilder.loadTexts: cwCommCPUUsageIOWait.setStatus('current')
cwCommCPUUsageIRQ = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 1, 4, 1, 9), Gauge32().subtype(subtypeSpec=ValueRangeConstraint(0, 4294967295))).setUnits('KHz').setMaxAccess("readonly")
if mibBuilder.loadTexts: cwCommCPUUsageIRQ.setStatus('current')
cwCommCPUUsageSoftIRQ = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 1, 4, 1, 10), Gauge32().subtype(subtypeSpec=ValueRangeConstraint(0, 4294967295))).setUnits('KHz').setMaxAccess("readonly")
if mibBuilder.loadTexts: cwCommCPUUsageSoftIRQ.setStatus('current')
cwCommCPUUsageSteal = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 1, 4, 1, 11), Gauge32().subtype(subtypeSpec=ValueRangeConstraint(0, 4294967295))).setUnits('KHz').setMaxAccess("readonly")
if mibBuilder.loadTexts: cwCommCPUUsageSteal.setStatus('current')
cwCommCPUUsageCapacitySubTotal = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 1, 4, 1, 12), Gauge32().subtype(subtypeSpec=ValueRangeConstraint(0, 4294967295))).setUnits('KHz').setMaxAccess("readonly")
if mibBuilder.loadTexts: cwCommCPUUsageCapacitySubTotal.setStatus('current')
cwCommCPUMonitoringStatus = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 1, 5), CiscoWebExCommSysResMonitoringStatus()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cwCommCPUMonitoringStatus.setStatus('current')
cwCommCPUCapacityTotal = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 1, 6), Gauge32().subtype(subtypeSpec=ValueRangeConstraint(0, 4294967295))).setUnits('KHz').setMaxAccess("readonly")
if mibBuilder.loadTexts: cwCommCPUCapacityTotal.setStatus('current')
cwCommMEMUsageObject = ObjectIdentity((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 2))
if mibBuilder.loadTexts: cwCommMEMUsageObject.setStatus('current')
cwCommMEMUsage = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 2, 1), Gauge32().subtype(subtypeSpec=ValueRangeConstraint(0, 100))).setUnits('percent').setMaxAccess("readonly")
if mibBuilder.loadTexts: cwCommMEMUsage.setStatus('current')
cwCommMEMMonitoringStatus = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 2, 2), CiscoWebExCommSysResMonitoringStatus()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cwCommMEMMonitoringStatus.setStatus('current')
cwCommMEMTotal = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 2, 3), Gauge32()).setUnits('MBytes').setMaxAccess("readonly")
if mibBuilder.loadTexts: cwCommMEMTotal.setStatus('current')
cwCommMEMSwapUsageObject = ObjectIdentity((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 3))
if mibBuilder.loadTexts: cwCommMEMSwapUsageObject.setStatus('current')
cwCommMEMSwapUsage = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 3, 1), Gauge32().subtype(subtypeSpec=ValueRangeConstraint(0, 100))).setUnits('percent').setMaxAccess("readonly")
if mibBuilder.loadTexts: cwCommMEMSwapUsage.setStatus('current')
cwCommMEMSwapMonitoringStatus = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 3, 2), CiscoWebExCommSysResMonitoringStatus()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cwCommMEMSwapMonitoringStatus.setStatus('current')
cwCommSysResourceNotificationObject = ObjectIdentity((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 4))
if mibBuilder.loadTexts: cwCommSysResourceNotificationObject.setStatus('current')
cwCommNotificationHostAddressType = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 4, 1), InetAddressType()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: cwCommNotificationHostAddressType.setStatus('current')
cwCommNotificationHostAddress = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 4, 2), InetAddress()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: cwCommNotificationHostAddress.setStatus('current')
cwCommNotificationResName = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 4, 3), CiscoWebExCommSysResource()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: cwCommNotificationResName.setStatus('current')
cwCommNotificationResValue = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 4, 4), Unsigned32()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: cwCommNotificationResValue.setStatus('current')
cwCommNotificationSeqNum = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 4, 5), Counter32()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: cwCommNotificationSeqNum.setStatus('current')
cwCommDiskUsageObject = ObjectIdentity((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 5))
if mibBuilder.loadTexts: cwCommDiskUsageObject.setStatus('current')
cwCommDiskUsageCount = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 5, 1), Gauge32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cwCommDiskUsageCount.setStatus('current')
cwCommDiskUsageTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 5, 2), )
if mibBuilder.loadTexts: cwCommDiskUsageTable.setStatus('current')
cwCommDiskUsageEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 5, 2, 1), ).setIndexNames((0, "CISCO-WBX-MEETING-MIB", "cwCommDiskUsageIndex"))
if mibBuilder.loadTexts: cwCommDiskUsageEntry.setStatus('current')
cwCommDiskUsageIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 5, 2, 1, 1), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(1, 128)))
if mibBuilder.loadTexts: cwCommDiskUsageIndex.setStatus('current')
cwCommDiskPartitionName = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 5, 2, 1, 2), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cwCommDiskPartitionName.setStatus('current')
cwCommDiskUsage = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 5, 2, 1, 3), Gauge32().subtype(subtypeSpec=ValueRangeConstraint(0, 100))).setUnits('percent').setMaxAccess("readonly")
if mibBuilder.loadTexts: cwCommDiskUsage.setStatus('current')
cwCommDiskTotal = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 5, 2, 1, 4), Gauge32().subtype(subtypeSpec=ValueRangeConstraint(0, 4294967295))).setUnits('KB').setMaxAccess("readonly")
if mibBuilder.loadTexts: cwCommDiskTotal.setStatus('current')
cwCommDiskMonitoringStatus = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 5, 3), CiscoWebExCommSysResMonitoringStatus()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cwCommDiskMonitoringStatus.setStatus('current')
cwCommSystemResourceUsageNormalEvent = NotificationType((1, 3, 6, 1, 4, 1, 9, 9, 809, 0, 1)).setObjects(("CISCO-WBX-MEETING-MIB", "cwCommNotificationHostAddressType"), ("CISCO-WBX-MEETING-MIB", "cwCommNotificationHostAddress"), ("CISCO-WBX-MEETING-MIB", "cwCommNotificationResName"), ("CISCO-WBX-MEETING-MIB", "cwCommNotificationResValue"), ("CISCO-WBX-MEETING-MIB", "cwCommNotificationSeqNum"))
if mibBuilder.loadTexts: cwCommSystemResourceUsageNormalEvent.setStatus('current')
cwCommSystemResourceUsageMinorEvent = NotificationType((1, 3, 6, 1, 4, 1, 9, 9, 809, 0, 2)).setObjects(("CISCO-WBX-MEETING-MIB", "cwCommNotificationHostAddressType"), ("CISCO-WBX-MEETING-MIB", "cwCommNotificationHostAddress"), ("CISCO-WBX-MEETING-MIB", "cwCommNotificationResName"), ("CISCO-WBX-MEETING-MIB", "cwCommNotificationResValue"), ("CISCO-WBX-MEETING-MIB", "cwCommNotificationSeqNum"))
if mibBuilder.loadTexts: cwCommSystemResourceUsageMinorEvent.setStatus('current')
cwCommSystemResourceUsageMajorEvent = NotificationType((1, 3, 6, 1, 4, 1, 9, 9, 809, 0, 3)).setObjects(("CISCO-WBX-MEETING-MIB", "cwCommNotificationHostAddressType"), ("CISCO-WBX-MEETING-MIB", "cwCommNotificationHostAddress"), ("CISCO-WBX-MEETING-MIB", "cwCommNotificationResName"), ("CISCO-WBX-MEETING-MIB", "cwCommNotificationResValue"), ("CISCO-WBX-MEETING-MIB", "cwCommNotificationSeqNum"))
if mibBuilder.loadTexts: cwCommSystemResourceUsageMajorEvent.setStatus('current')
cwCommMIBCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 809, 2, 1))
cwCommMIBCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 9, 9, 809, 2, 1, 1)).setObjects(("CISCO-WBX-MEETING-MIB", "ciscoWebExCommInfoGroup"), ("CISCO-WBX-MEETING-MIB", "ciscoWebExCommSystemResourceGroup"), ("CISCO-WBX-MEETING-MIB", "ciscoWebExMeetingMIBNotifsGroup"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
cwCommMIBCompliance = cwCommMIBCompliance.setStatus('current')
cwCommMIBGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 809, 2, 2))
ciscoWebExCommInfoGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 809, 2, 2, 1)).setObjects(("CISCO-WBX-MEETING-MIB", "cwCommSystemVersion"), ("CISCO-WBX-MEETING-MIB", "cwCommSystemObjectID"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoWebExCommInfoGroup = ciscoWebExCommInfoGroup.setStatus('current')
ciscoWebExCommSystemResourceGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 809, 2, 2, 2)).setObjects(("CISCO-WBX-MEETING-MIB", "cwCommCPUTotalUsage"), ("CISCO-WBX-MEETING-MIB", "cwCommCPUUsageWindow"), ("CISCO-WBX-MEETING-MIB", "cwCommCPUTotalNumber"), ("CISCO-WBX-MEETING-MIB", "cwCommCPUName"), ("CISCO-WBX-MEETING-MIB", "cwCommCPUUsage"), ("CISCO-WBX-MEETING-MIB", "cwCommCPUMonitoringStatus"), ("CISCO-WBX-MEETING-MIB", "cwCommCPUUsageUser"), ("CISCO-WBX-MEETING-MIB", "cwCommCPUUsageNice"), ("CISCO-WBX-MEETING-MIB", "cwCommCPUUsageSystem"), ("CISCO-WBX-MEETING-MIB", "cwCommCPUUsageIdle"), ("CISCO-WBX-MEETING-MIB", "cwCommCPUUsageIOWait"), ("CISCO-WBX-MEETING-MIB", "cwCommCPUUsageIRQ"), ("CISCO-WBX-MEETING-MIB", "cwCommCPUUsageSoftIRQ"), ("CISCO-WBX-MEETING-MIB", "cwCommCPUUsageSteal"), ("CISCO-WBX-MEETING-MIB", "cwCommCPUUsageCapacitySubTotal"), ("CISCO-WBX-MEETING-MIB", "cwCommCPUCapacityTotal"), ("CISCO-WBX-MEETING-MIB", "cwCommMEMUsage"), ("CISCO-WBX-MEETING-MIB", "cwCommMEMMonitoringStatus"), ("CISCO-WBX-MEETING-MIB", "cwCommMEMSwapUsage"), ("CISCO-WBX-MEETING-MIB", "cwCommMEMSwapMonitoringStatus"), ("CISCO-WBX-MEETING-MIB", "cwCommMEMTotal"), ("CISCO-WBX-MEETING-MIB", "cwCommNotificationHostAddressType"), ("CISCO-WBX-MEETING-MIB", "cwCommNotificationHostAddress"), ("CISCO-WBX-MEETING-MIB", "cwCommNotificationResName"), ("CISCO-WBX-MEETING-MIB", "cwCommNotificationResValue"), ("CISCO-WBX-MEETING-MIB", "cwCommNotificationSeqNum"), ("CISCO-WBX-MEETING-MIB", "cwCommDiskUsageCount"), ("CISCO-WBX-MEETING-MIB", "cwCommDiskPartitionName"), ("CISCO-WBX-MEETING-MIB", "cwCommDiskUsage"), ("CISCO-WBX-MEETING-MIB", "cwCommDiskTotal"), ("CISCO-WBX-MEETING-MIB", "cwCommDiskMonitoringStatus"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoWebExCommSystemResourceGroup = ciscoWebExCommSystemResourceGroup.setStatus('current')
ciscoWebExMeetingMIBNotifsGroup = NotificationGroup((1, 3, 6, 1, 4, 1, 9, 9, 809, 2, 2, 3)).setObjects(("CISCO-WBX-MEETING-MIB", "cwCommSystemResourceUsageNormalEvent"), ("CISCO-WBX-MEETING-MIB", "cwCommSystemResourceUsageMinorEvent"), ("CISCO-WBX-MEETING-MIB", "cwCommSystemResourceUsageMajorEvent"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoWebExMeetingMIBNotifsGroup = ciscoWebExMeetingMIBNotifsGroup.setStatus('current')
mibBuilder.exportSymbols("CISCO-WBX-MEETING-MIB", CiscoWebExCommSysResource=CiscoWebExCommSysResource, cwCommMEMUsage=cwCommMEMUsage, ciscoWebExCommInfo=ciscoWebExCommInfo, cwCommCPUUsageIRQ=cwCommCPUUsageIRQ, cwCommCPUUsageCapacitySubTotal=cwCommCPUUsageCapacitySubTotal, cwCommNotificationHostAddressType=cwCommNotificationHostAddressType, CiscoWebExCommSysResMonitoringStatus=CiscoWebExCommSysResMonitoringStatus, cwCommSystemResourceUsageNormalEvent=cwCommSystemResourceUsageNormalEvent, cwCommCPUUsageNice=cwCommCPUUsageNice, ciscoWebExMeetingMIBNotifs=ciscoWebExMeetingMIBNotifs, cwCommNotificationResValue=cwCommNotificationResValue, cwCommCPUUsageUser=cwCommCPUUsageUser, cwCommSystemVersion=cwCommSystemVersion, cwCommDiskPartitionName=cwCommDiskPartitionName, cwCommMEMMonitoringStatus=cwCommMEMMonitoringStatus, cwCommCPUUsageIdle=cwCommCPUUsageIdle, cwCommMIBCompliances=cwCommMIBCompliances, cwCommDiskUsageCount=cwCommDiskUsageCount, cwCommCPUCapacityTotal=cwCommCPUCapacityTotal, cwCommMIBGroups=cwCommMIBGroups, cwCommMEMTotal=cwCommMEMTotal, cwCommMEMSwapUsage=cwCommMEMSwapUsage, cwCommSystemResourceUsageMinorEvent=cwCommSystemResourceUsageMinorEvent, cwCommDiskMonitoringStatus=cwCommDiskMonitoringStatus, cwCommMEMSwapUsageObject=cwCommMEMSwapUsageObject, cwCommSystemObjectID=cwCommSystemObjectID, cwCommCPUUsageSystem=cwCommCPUUsageSystem, cwCommCPUUsageWindow=cwCommCPUUsageWindow, cwCommCPUIndex=cwCommCPUIndex, cwCommSystemResourceUsageMajorEvent=cwCommSystemResourceUsageMajorEvent, cwCommCPUUsageSoftIRQ=cwCommCPUUsageSoftIRQ, cwCommDiskUsageTable=cwCommDiskUsageTable, cwCommCPUUsageObject=cwCommCPUUsageObject, cwCommCPUUsageEntry=cwCommCPUUsageEntry, ciscoWebExMeetingMIB=ciscoWebExMeetingMIB, cwCommMEMUsageObject=cwCommMEMUsageObject, cwCommNotificationHostAddress=cwCommNotificationHostAddress, cwCommNotificationResName=cwCommNotificationResName, ciscoWebExMeetingMIBNotifsGroup=ciscoWebExMeetingMIBNotifsGroup, cwCommDiskTotal=cwCommDiskTotal, ciscoWebExCommSystemResourceGroup=ciscoWebExCommSystemResourceGroup, cwCommDiskUsageIndex=cwCommDiskUsageIndex, cwCommDiskUsage=cwCommDiskUsage, ciscoWebExCommSystemResource=ciscoWebExCommSystemResource, cwCommMEMSwapMonitoringStatus=cwCommMEMSwapMonitoringStatus, cwCommCPUMonitoringStatus=cwCommCPUMonitoringStatus, cwCommDiskUsageEntry=cwCommDiskUsageEntry, ciscoWebExMeetingMIBConform=ciscoWebExMeetingMIBConform, cwCommSysResourceNotificationObject=cwCommSysResourceNotificationObject, cwCommCPUTotalNumber=cwCommCPUTotalNumber, cwCommCPUUsageTable=cwCommCPUUsageTable, cwCommCPUUsageIOWait=cwCommCPUUsageIOWait, cwCommMIBCompliance=cwCommMIBCompliance, ciscoWebExCommInfoGroup=ciscoWebExCommInfoGroup, cwCommDiskUsageObject=cwCommDiskUsageObject, cwCommCPUUsageSteal=cwCommCPUUsageSteal, ciscoWebExMeetingMIBObjects=ciscoWebExMeetingMIBObjects, PYSNMP_MODULE_ID=ciscoWebExMeetingMIB, cwCommCPUUsage=cwCommCPUUsage, cwCommNotificationSeqNum=cwCommNotificationSeqNum, cwCommCPUTotalUsage=cwCommCPUTotalUsage, cwCommCPUName=cwCommCPUName)
|
# Column/Label Types
NULL = 'null'
CATEGORICAL = 'categorical'
TEXT = 'text'
NUMERICAL = 'numerical'
ENTITY = 'entity'
# Feature Types
ARRAY = 'array'
# backend
PYTORCH = "pytorch"
MXNET = "mxnet"
|
def main():
a,b,c,k = map(int,input().split())
ans = 0
ans += min(a, k)
ans -= max(0, k-a-b)
print(ans)
if __name__ == "__main__":
main()
|
def main():
# equilibrate then isolate cold finger
info('Equilibrate then isolate coldfinger')
close(name="C", description="Bone to Turbo")
sleep(1)
open(name="B", description="Bone to Diode Laser")
sleep(20)
close(name="B", description="Bone to Diode Laser")
|
#!/usr/bin/python3
""" Verifies which numbers from a list of postive integers are even,
using filter and lambda.
filter() constructs a list of elements which were successfully
evaluated, according with the lambda function, upon the elements
of an iterable (list, strings, etc.).
"""
__author__ = "@ivanleoncz"
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 11]
even = filter(lambda n: n % 2 == 0, numbers)
print("Positive Integers: ", numbers)
print("Who is even: ", list(even))
|
class AmrTypes:
dbpedia = {
"person": "dbo:Person",
"family": "dbo:Agent",
"animal": "dbo:Animal",
"language": "dbo:Language",
"nationality": "dbo:Country",
"ethnic-group": "dbo:EthnicGroup",
"regional-group": "dbo:EthnicGroup",
"religious-group": "dbo:Religious",
"political-movement": "dbo:PoliticalParty",
"organization": "dbo:Organisation",
"company": "dbo:Company",
"government-organization": "dbo:Organisation",
"military": "dbo:MilitaryPerson",
"criminal-organization": "dbo:Criminal",
"political-party": "dbo:PoliticalParty",
"market-sector": "owl:Thing",
"school": "dbo:School",
"university": "dbo:University",
"research-institute": "dbo:EducationalInstitution",
"team": "dbo:SportsTeam",
"league": "dbo:SportsSeason",
"location": "dbo:Place",
"city": "dbo:City",
"city-district": "dbo:AdministrativeRegion",
"county": "dbo:AdministrativeRegion",
"state": "dbo:AdministrativeRegion",
"province": "dbo:AdministrativeRegion",
"territory": "dbo:Place",
"country": "dbo:Country",
"local-region": "dbo:AdministrativeRegion",
"country-region": "dbo:AdministrativeRegion",
"world-region": "dbo:AdministrativeRegion",
"continent": "dbo:Continent",
"ocean": "dbo:BodyOfWater",
"sea": "dbo:Sea",
"lake": "dbo:Lake",
"river": "dbo:River",
"gulf": "dbo:NaturalPlace",
"bay": "dbo:NaturalPlace",
"strait": "owl:Thing",
"peninsula": "dbo:Place",
"mountain": "dbo:Mountain",
"volcano": "dbo:Volcano",
"valley": "dbo:Valley",
"canyon": "dbo:Place",
"island": "dbo:Island",
"desert": "dbo:NaturalPlace",
"forest": "dbo:NaturalPlace",
"moon": "dbo:Planet",
"planet": "dbo:Planet",
"star": "dbo:Star",
"constellation": "dbo:Constellation",
"facility": "dbo:Building",
"airport": "dbo:Airport",
"station": "dbo:Station",
"port": "dbo:Place",
"tunnel": "dbo:Tunnel",
"bridge": "dbo:Bridge",
"road": "dbo:Road",
"railway-line": "dbo:RailwayStation",
"canal": "dbo:Canal",
"building": "dbo:Building",
"theater": "dbo:Theatre",
"museum": "dbo:Museum",
"palace": "dbo:Building",
"hotel": "dbo:Hotel",
"worship-place": "dbo:Building",
"sports-facility": "dbo:Stadium",
"market": "dbo:Place",
"park": "dbo:Park",
"zoo": "dbo:Park",
"amusement-park": "dbo:AmusementParkAttraction",
"event": "dbo:Event",
"incident": "dbo:Event",
"natural-disaster": "dbo:NaturalEvent",
"earthquake": "dbo:NaturalEvent",
"war": "dbo:MilitaryConflict",
"conference": "dbo:Event",
"game": "dbo:Game",
"festival": "dbo:Festival",
"product": "owl:Thing",
"vehicle": "dbo:MeanOfTransportation",
"ship": "dbo:Ship",
"aircraft": "dbo:Aircraft",
"aircraft-type": "dbo:Aircraft",
"spaceship": "dbo:Spacecraft",
"car-make": "dbo:Automobile",
"work-of-art": "dbo:Work",
"picture": "dbo:Work",
"music": "dbo:MusicalWork",
"show": "dbo:TelevisionEpisode",
"broadcast-program": "dbo:TelevisionEpisode",
"publication": "dbo:WrittenWork",
"book": "dbo:Book",
"newspaper": "dbo:Newspaper",
"magazine": "dbo:Magazine",
"journal": "dbo:WrittenWork",
"natural-object": "owl:Thing",
"award": "dbo:Award",
"law": "owl:Thing",
"court-decision": "owl:Thing",
"treaty": "owl:Thing",
"music-key": "dbo:MusicalWork",
"musical-note": "dbo:MusicalWork",
"food-dish": "dbo:Food",
"writing-script": "dbo:Work",
"variable": "owl:Thing",
"program": "owl:Thing",
"molecular-physical-entity"
"small-molecule": "owl:Thing",
"protein": "dbo:Protein",
"protein-family": "dbo:Protein",
"protein-segment": "dbo:Protein",
"amino-acid": "owl:Thing",
"macro-molecular-complex": "owl:Thing",
"enzyme": "dbo:Enzyme",
"nucleic-acid": "owl:Thing",
"pathway": "owl:Thing",
"gene": "dbo:Gene",
"dna-sequence": "owl:Thing",
"cell": "owl:Thing",
"cell-line": "owl:Thing",
"species": "dbo:Species",
"taxon": "owl:Thing",
"disease": "dbo:Disease",
"medical-condition": "owl:Thing"
}
|
students = []
def get_students_titlecase():
students_titlecase = []
for student in students:
students_titlecase.append(student['name'].title())
return students_titlecase
def print_students_titlecase():
print(get_students_titlecase())
def add_student(name, student_id = 332):
student = {'name': name, 'student_id': student_id}
students.append(student)
def save_file(student):
try:
f = open('student.txt','a')
f.write(student + '\n')
f.close()
except Exception:
print('could not save file')
def read_file():
try:
f = open('student.txt', 'r')
for student in f.readlines():
add_student(student)
f.close()
except Exception:
print('Could not read file')
read_file()
print_students_titlecase()
student_name = input('enter student name: ')
student_id = input('enter student id: ')
add_student(student_name, student_id)
save_file(student_name)
|
# author: @s.gholami
# -----------------------------------------------------------------------
# read_matrix_input.py
# -----------------------------------------------------------------------
# Accept inputs from console
# Populate the list with the inputs to form a matrix
def equations_to_matrix() -> list:
"""
:return: augmented matrix formed from user input (user inputs = linear equations)
:rtype: list
"""
n = int(input("input number of rows "))
m = int(input("input number of columns "))
A = []
for row_space in range(n):
print("input row ", row_space + 1)
row = input().split()
if len(row) == m:
row_map = list(map(int, row)) # use map function convert string to integer
A.append(row_map)
else:
print("length must be the column size of A")
equations_to_matrix()
print(A)
return A
# main for function call.
if __name__ == "__main__": # __name__ = m_determinant
equations_to_matrix()
else:
print("read_matrix_input.py is being imported into another module ")
|
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
return num_islands(grid)
def num_islands(grid):
res = 0
R = len(grid)
C = len(grid[0])
def dfs(i, j):
if grid[i][j] == '1':
grid[i][j] = '0'
if i > 0:
dfs(i - 1, j)
if i < R - 1:
dfs(i + 1, j)
if j > 0:
dfs(i, j - 1)
if j < C - 1:
dfs(i, j + 1)
for i in range(R):
for j in range(C):
if grid[i][j] == '1':
res += 1
dfs(i, j)
return res
|
sample_rate = 16000
audio_duration = 10
audio_samples = sample_rate * audio_duration
audio_duration_flusense = 1
audio_samples_flusense = sample_rate * audio_duration_flusense
window_size = 512
overlap = 256
mel_bins = 64
device = 'cuda'
num_epochs = 30
gamma = 0.4
patience = 4
step = 10
random_seed = 36851234
split_ratio = 0.2
classes_num = 2
classes_num_flusense = 9
exclude = ['burp', 'vomit', 'hiccup', 'snore', 'wheeze']
valid_labels = ['cough', 'speech', 'etc', 'silence', 'sneeze', 'gasp', 'breathe', 'sniffle', 'throat-clearing']
flusense_weights = [63.38, 2.45, 1.0, 47.78, 13.49, 27.89, 24.93, 0.91, 128.05]
|
# 다음 큰 숫자
def solution(n):
cnt = bin(n).count('1')
while True:
n += 1
if bin(n).count('1') == cnt: return n
'''
정확성 테스트
테스트 1 〉 통과 (0.01ms, 10.2MB)
테스트 2 〉 통과 (0.00ms, 10.2MB)
테스트 3 〉 통과 (0.00ms, 10.2MB)
테스트 4 〉 통과 (0.00ms, 10.2MB)
테스트 5 〉 통과 (0.01ms, 10.2MB)
테스트 6 〉 통과 (0.00ms, 10.3MB)
테스트 7 〉 통과 (0.01ms, 10.2MB)
테스트 8 〉 통과 (0.00ms, 10.2MB)
테스트 9 〉 통과 (0.01ms, 10.2MB)
테스트 10 〉 통과 (0.01ms, 10.2MB)
테스트 11 〉 통과 (0.00ms, 10.2MB)
테스트 12 〉 통과 (0.00ms, 10.1MB)
테스트 13 〉 통과 (0.00ms, 10.2MB)
테스트 14 〉 통과 (0.00ms, 10.2MB)
효율성 테스트
테스트 1 〉 통과 (0.01ms, 10.2MB)
테스트 2 〉 통과 (0.00ms, 10.2MB)
테스트 3 〉 통과 (0.00ms, 10.2MB)
테스트 4 〉 통과 (0.00ms, 10.2MB)
테스트 5 〉 통과 (0.01ms, 10.2MB)
테스트 6 〉 통과 (0.00ms, 10.2MB)
채점 결과
정확성: 70.0
효율성: 30.0
합계: 100.0 / 100.0
'''
|
def minion_game(string):
# your code goes here
vowels = frozenset('AEIOU')
length = len(string)
kev_sc = 0
stu_sc = 0
for i in range(length):
if string[i] in vowels:
kev_sc += length - i
else:
stu_sc += length - i
if kev_sc > stu_sc:
print('Kevin', kev_sc)
elif kev_sc < stu_sc:
print('Stuart', stu_sc)
else:
print('Draw')
if __name__ == '__main__':
s = input()
minion_game(s)
|
"""
1 - Faça um programa que receba dois números e mostre qual deles é o maior.
"""
numero1 = int(input("Digite o primeiro número: "))
numero2 = int(input("Digite o segundo número: "))
if numero1 > numero2:
print(f"Entre os números {numero1} e {numero2} .O número maior é: {numero1}")
elif numero1 == numero2:
print(f"Entre os números {numero1} e {numero2} .O número maior é: {numero1}")
else:
print(f"Entre os números {numero1} e {numero2} .O número maior é: {numero2}")
|
class Message:
def __init__(self, to_channel):
self.to_channel = to_channel
self.timestamp = ""
self.text = ""
self.blocks = []
self.is_completed = False
def get_message(self):
return {
"ts": self.timestamp,
"channel": self.to_channel,
"text": self.text,
"blocks": self.blocks,
}
|
productions = {
(52, 1): [1,25,47,53,49 ],
(53, 2): [54, 57,59,62,64],
(53, 3): [54,57,59,62,64],
(53, 4): [54,57,59,62,64],
(53, 5): [54,57,59,62,64],
(53, 6): [54,57,59,62,64],
(54, 2): [2,55,47],
(54, 3): [0],
(54, 4): [0],
(54, 5): [0],
(54, 6): [0],
(55, 25): [25,56],
(56, 39): [0],
(56, 46): [46,25,56],
(56, 47): [0],
(57, 3): [3,25,40,26,47,58],
(57, 4): [0],
(57, 5): [0],
(57, 6): [0],
(58, 4): [0],
(58, 5): [0],
(58, 6): [0],
(58, 25): [25,40,26,47,58],
(59, 4): [4,55,39,61,47,60],
(59, 5): [0],
(59, 6): [0],
(60, 5): [0],
(60, 6): [0],
(60, 25): [55,39,61,47,60],
(61, 8): [8],
(61, 9): [9,34,26,50,26,35,10,8],
(62, 5): [5,25,63,47,53,47,62],
(62, 6): [0],
(63, 36): [36,55,39,8,37],
(63, 39): [0],
(64, 6): [6,66,65,7],
(65, 7): [0],
(65, 47): [47,66,65],
(66, 6): [64],
(66, 7): [0],
(66, 11): [11,25,69],
(66, 12): [12,25 ],
(66, 13): [13,77,14,66,71],
(66, 15): [0],
(66, 16): [16,77,17,66],
(66, 18): [18,66,19,77],
(66, 19): [0],
(66, 20): [20,36,72,74,37],
(66, 21): [21,36,75,76,37],
(66, 25): [25,67],
(66, 27): [27,25,38,77,28,77,17,66],
(66, 29): [29,77,10,84,7 ],
(66, 47): [0],
(67, 34): [68,38,77],
(67, 38): [68,38,77],
(67, 39): [39,66],
(68, 34): [34,77,35],
(68, 38): [0],
(69, 7): [0],
(69, 15): [0],
(69, 19): [0],
(69, 36): [36,77,70,37],
(69, 47): [0],
(70, 37): [0],
(70, 46): [46,77,70 ],
(71, 7): [0],
(71, 15): [15,66],
(71, 19): [0],
(71, 47): [0],
(72, 25): [25,73],
(73, 7): [0],
(73, 10): [0],
(73, 14): [0],
(73, 15): [0],
(73, 17): [0],
(73, 19): [0],
(73, 22): [0],
(73, 23): [0],
(73, 28): [0],
(73, 30): [0],
(73, 31): [0],
(73, 32): [0],
(73, 33): [0],
(73, 34): [34,77,35],
(73, 35): [0],
(73, 37): [0],
(73, 40): [0],
(73, 41): [0],
(73, 42): [0],
(73, 43): [0],
(73, 44): [0],
(73, 45): [0],
(73, 46): [0],
(73, 47): [0],
(74, 37): [0],
(74, 46): [46,72,74],
(75, 24): [77],
(75, 25): [77],
(75, 26): [77],
(75, 30): [77],
(75, 31): [77],
(75, 36): [77],
(75, 48): [48],
(76, 37): [0],
(76, 46): [46,75,76],
(77, 24): [79,78 ],
(77, 25): [79,78 ],
(77, 26): [79,78 ],
(77, 30): [79,78 ],
(77, 31): [79,78 ],
(77, 36): [79,78 ],
(78, 7): [0],
(78, 10): [0],
(78, 14): [0],
(78, 15): [0],
(78, 17): [0],
(78, 19): [0],
(78, 28): [0],
(78, 35): [0],
(78, 37): [0],
(78, 40): [40,79],
(78, 41): [41,79],
(78, 42): [42,79],
(78, 43): [43,79],
(78, 44): [44,79 ],
(78, 45): [45,79],
(78, 46): [0],
(78, 47): [0],
(79, 24): [81,80],
(79, 25): [81,80],
(79, 26): [81,80],
(79, 30): [30,81,80],
(79, 31): [31,81,80],
(79, 36): [81,80],
(80, 7): [0],
(80, 10): [0],
(80, 14): [0],
(80, 15): [0],
(80, 17): [0],
(80, 19): [0],
(80, 22): [22,81,80],
(80, 28): [0],
(80, 30): [30,81,80],
(80, 31): [31,81,80],
(80, 35): [0],
(80, 37): [0],
(80, 40): [0],
(80, 41): [0],
(80, 42): [0],
(80, 43): [0],
(80, 44): [0],
(80, 45): [0],
(80, 46): [0],
(80, 47): [0],
(81, 24): [83,82 ],
(81, 25): [83,82 ],
(81, 26): [83,82 ],
(81, 36): [83,82 ],
(82, 7): [0],
(82, 10): [0],
(82, 14): [0],
(82, 15): [0],
(82, 17): [0],
(82, 19): [0],
(82, 22): [0],
(82, 23): [23,83,82],
(82, 28): [0],
(82, 30): [0],
(82, 31): [0],
(82, 32): [32,83,82],
(82, 33): [33,83,82],
(82, 35): [0],
(82, 37): [0],
(82, 40): [0],
(82, 41): [0],
(82, 42): [0],
(82, 43): [0],
(82, 44): [0],
(82, 45): [0],
(82, 46): [0],
(82, 47): [0],
(83, 24): [24,83],
(83, 25): [72],
(83, 26): [26],
(83, 36): [36,77,37],
(84, 26): [26,86,39,66,85],
(85, 7): [0],
(85, 47): [47,84],
(86, 39): [0],
(86, 46): [46,26,86]
}
|
class CDI():
def __init__(self,v3,v2,v3SessionID,v3BaseURL,v2BaseURL,v2icSessionID):
print("Created CDI Class")
self._v3=v3
self._v2=v2
self._v3SessionID = v3SessionID
self._v3BaseURL = v3BaseURL
self._v2BaseURL = v2BaseURL
self._v2icSessionID = v2icSessionID
|
# Média Aritmética
n1 = float(input('Digite a primeira nota: '))
n2 = float(input('Digite a segunda nota: '))
m = (n1 + n2) / 2
print('== DADOS OBTIDOS ==')
print('Primeira nota: {:.1f}'.format(n1))
print('Segunda nota: {:.1f}'.format(n2))
print('A média alcançada foi de {:.1f}'.format(m))
|
"""
스택 자료구조 구현
"""
class Node:
def __init__(self, data):
self.data = data
self.next = None
class Stack:
def __init__(self):
self.head = None
def push(self, value):
new_head = Node(value)
new_head.next = self.head
self.head = new_head
def pop(self):
if self.is_empty():
return "Stack is empty!"
new_head = self.head.next
pop_data = self.head.data
self.head = new_head
return pop_data
def peek(self):
if self.is_empty():
return "Stack is empty!"
cur_node = self.head
return cur_node.data
def is_empty(self):
return self.head is None
stack = Stack()
stack.push(3)
print(stack.peek())
stack.push(0)
print(stack.peek())
print(stack.pop())
print(stack.peek())
print(stack.is_empty())
print(stack.pop())
print(stack.pop())
|
# Função para Fatorial
def fatorial(n, show=False):
'''
=> Cálucula o Fatorial de um número.
:param n:O número a ser cálculado
:param show: Mostra o fatoramento do número
:return: Retorna com o valor solicitado o Fatorial (n)
'''
f = 1
for c in range(n, 0, -1):
if show:
print(c, end=' ')
if c > 1:
print('! x ', end=' ')
else:
print('! = ', end=' ')
f *= c
return f
# Programa Principal
núm = int(input('Digite um número para ver o seu fatorial: '))
print(fatorial(núm, show=True))
print('=-=' * 20)
help(fatorial)
|
"""List all the extensions."""
names = [
"tourney",
"season",
"refresh",
"misc",
]
|
# ----------------------------------------------------------------------------
# MODES: serial
# CLASSES: nightly
#
# Test Case: multicolor.py
#
# Tests: Tests setting colors using the multiColor field in some of
# our plots.
# Plots - Boundary, Contour, FilledBoundary, Subset
# Operators - Transform
#
# Programmer: Brad Whitlock
# Date: Wed Apr 6 17:52:12 PST 2005
#
# Modifications:
#
# Mark C. Miller, Thu Jul 13 22:41:56 PDT 2006
# Added test of user-specified material colors
#
# Mark C. Miller, Wed Jan 20 07:37:11 PST 2010
# Added ability to swtich between Silo's HDF5 and PDB data.
# ----------------------------------------------------------------------------
def TestColorDefinitions(testname, colors):
s = ""
for c in colors:
s = s + str(c) + "\n"
TestText(testname, s)
def TestMultiColor(section, plotAtts, decreasingOpacity):
# Get the current colors.
m = plotAtts.GetMultiColor()
# Test what the image currently looks like.
Test("multicolor_%d_00" % section)
# Change the colors all at once. We should have red->blue
for i in range(len(m)):
t = float(i) / float(len(m) - 1)
c = int(t * 255.)
m[i] = (255-c, 0, c, 255)
plotAtts.SetMultiColor(m)
SetPlotOptions(plotAtts)
Test("multicolor_%d_01" % section)
TestColorDefinitions("multicolor_%d_02" % section, plotAtts.GetMultiColor())
# Change the colors another way. We should get green to blue
for i in range(len(m)):
t = float(i) / float(len(m) - 1)
c = int(t * 255.)
plotAtts.SetMultiColor(i, 0, 255-c, c)
SetPlotOptions(plotAtts)
Test("multicolor_%d_03" % section)
TestColorDefinitions("multicolor_%d_04" % section, plotAtts.GetMultiColor())
# Change the colors another way. We should get yellow to red but
# the redder it gets, the more transparent it should also get.
for i in range(len(m)):
t = float(i) / float(len(m) - 1)
c = int(t * 255.)
if decreasingOpacity:
plotAtts.SetMultiColor(i, (255, 255-c, 0, 255 - c))
else:
plotAtts.SetMultiColor(i, (255, 255-c, 0, c))
SetPlotOptions(plotAtts)
Test("multicolor_%d_05" % section)
TestColorDefinitions("multicolor_%d_06" % section, plotAtts.GetMultiColor())
def test1():
TestSection("Testing setting of multiColor in Boundary plot")
# Set up the plot
OpenDatabase(silo_data_path("rect2d.silo"))
AddPlot("Boundary", "mat1")
b = BoundaryAttributes()
b.lineWidth = 4
DrawPlots()
# Test the plot
TestMultiColor(0, b, 0)
# Delete the plots
DeleteAllPlots()
def test2():
TestSection("Testing setting of multiColor in Contour plot")
# Set up the plot
OpenDatabase(silo_data_path("noise.silo"))
AddPlot("Contour", "hardyglobal")
c = ContourAttributes()
c.contourNLevels = 20
SetPlotOptions(c)
DrawPlots()
# Set the view.
v = GetView3D()
v.viewNormal = (-0.400348, -0.676472, 0.618148)
v.focus = (0,0,0)
v.viewUp = (-0.916338, 0.300483, -0.264639)
v.parallelScale = 17.3205
v.imagePan = (0, 0.0397866)
v.imageZoom = 1.07998
SetView3D(v)
# Test the plot
TestMultiColor(1, c, 0)
# Delete the plots
DeleteAllPlots()
def test3():
TestSection("Testing setting of multiColor in FilledBoundary plot")
# Set up the plots. First we want globe so we can see something inside
# of the Subset plot to make sure that setting alpha works.
OpenDatabase(silo_data_path("globe.silo"))
AddPlot("Pseudocolor", "w")
p = PseudocolorAttributes()
p.legendFlag = 0
p.colorTableName = "xray"
SetPlotOptions(p)
OpenDatabase(silo_data_path("bigsil.silo"))
AddPlot("FilledBoundary", "mat")
f = FilledBoundaryAttributes()
f.legendFlag = 0
SetPlotOptions(f)
# Add an operator to globe to make it small.
SetActivePlots(0)
AddOperator("Transform", 0)
t = TransformAttributes()
t.doScale = 1
t.scaleX, t.scaleY, t.scaleZ = 0.04, 0.04, 0.04
t.doTranslate = 1
t.translateX, t.translateY, t.translateZ = 0.5, 0.5, 0.5
SetOperatorOptions(t)
SetActivePlots(1)
DrawPlots()
# Set the view.
v = GetView3D()
v.viewNormal = (-0.385083, -0.737931, -0.554229)
v.focus = (0.5, 0.5, 0.5)
v.viewUp = (-0.922871, 0.310902, 0.227267)
v.parallelScale = 0.866025
v.imagePan = (-0.0165315, 0.0489375)
v.imageZoom = 1.13247
SetView3D(v)
# Test the plot
TestMultiColor(2, f, 1)
# Delete the plots
DeleteAllPlots()
def test4():
TestSection("Testing setting of multiColor in Subset plot")
# Set up the plots. First we want globe so we can see something inside
# of the Subset plot to make sure that setting alpha works.
OpenDatabase(silo_data_path("globe.silo"))
AddPlot("Pseudocolor", "w")
p = PseudocolorAttributes()
p.legendFlag = 0
p.colorTableName = "xray"
SetPlotOptions(p)
OpenDatabase(silo_data_path("bigsil.silo"))
AddPlot("Subset", "domains")
s = SubsetAttributes()
s.legendFlag = 0
SetPlotOptions(s)
# Add an operator to globe to make it small.
SetActivePlots(0)
AddOperator("Transform", 0)
t = TransformAttributes()
t.doScale = 1
t.scaleX, t.scaleY, t.scaleZ = 0.04, 0.04, 0.04
t.doTranslate = 1
t.translateX, t.translateY, t.translateZ = 0.5, 0.5, 0.5
SetOperatorOptions(t)
SetActivePlots(1)
DrawPlots()
# Set the view.
v = GetView3D()
v.viewNormal = (-0.385083, -0.737931, -0.554229)
v.focus = (0.5, 0.5, 0.5)
v.viewUp = (-0.922871, 0.310902, 0.227267)
v.parallelScale = 0.866025
v.imagePan = (-0.0165315, 0.0489375)
v.imageZoom = 1.13247
SetView3D(v)
# Test the plot
TestMultiColor(3, s, 1)
# Delete the plots
DeleteAllPlots()
def test5():
TestSection("Testing user defined colors for FilledBoundary")
ResetView()
OpenDatabase(silo_data_path("globe_matcolors.silo"))
AddPlot("FilledBoundary","mat1")
AddOperator("Slice")
DrawPlots()
Test("multicolor_matcolors")
DeleteAllPlots()
def main():
test1()
test2()
test3()
test4()
test5()
# Run the tests
main()
Exit()
|
'''
Faça um programa que leia o nome de uma pessoa e mostre uma mensagem de boas-vindas.
'''
nome = input('Qual seu nome: ')
print('Olá {}! Seja bem vindo!'.format(nome))
|
def run_tests_count_tokens(config):
scenario = sp.test_scenario()
admin, [alice, bob] = get_addresses()
scenario.h1("Tests count token")
#-----------------------------------------------------
scenario.h2("Nothing is minted")
contract = create_new_contract(config, admin, scenario, [])
count = contract.count_tokens()
scenario.verify(count == 0)
#-----------------------------------------------------
scenario.h2("One token is minted")
contract = create_new_contract(config, admin, scenario, [alice])
count = contract.count_tokens()
scenario.verify(count == 1)
#-----------------------------------------------------
scenario.h2("Two token are minted")
contract = create_new_contract(config, admin, scenario, [alice])
count = contract.count_tokens()
scenario.verify(count == 1)
contract.mint(1).run(sender=admin, amount=sp.mutez(1000000))
count = contract.count_tokens()
scenario.verify(count == 2)
#-----------------------------------------------------
scenario.h2("Mint fails are not counted as tokens")
config.max_editions = 2
contract = create_new_contract(config, admin, scenario, [alice, bob])
count = contract.count_tokens()
scenario.verify(count == 2)
contract.mint(1).run(sender=admin, amount=sp.mutez(1000000), valid=False)
count = contract.count_tokens()
scenario.verify(count == 2)
|
gal_sgd = ['HP0370', 'HP0950', 'HP0371', 'HP0557', 'HP0202', 'HP0587', 'HP0618', 'HP1112', 'HP0255', 'HP0859', 'HP0089', 'HP0106', 'HP0738', 'HP0942', 'HP0976', 'HP1483', 'HP1280', 'HP1281', 'HP1282', 'HP0598', 'HP1505', 'HP0422', 'HP1399', 'HP1017', 'HP1189', 'HP0723', 'HP0034', 'HP1084', 'HP1229', 'HP0672', 'HP1406', 'HP1376', 'HP0558', 'HP0195', 'HP0561', 'HP1237', 'HP0919', 'HP1443', 'HP0291', 'HP0663', 'HP0349', 'HP0107', 'HP0290', 'HP0566', 'HP0215', 'HP0804', 'HP0029', 'HP0134', 'HP0321', 'HP0510', 'HP1013', 'HP1545', 'HP1510', 'HP1011', 'HP0266', 'HP0581', 'HP1232', 'HP1038', 'HP0283', 'HP0929', 'HP0400', 'HP1228', 'HP0831', 'HP1474', 'HP0216', 'HP0354', 'HP0642', 'HP1161', 'HP1087', 'HP0577', 'HP0683', 'HP0961', 'HP1532', 'HP0045', 'HP0183', 'HP0512', 'HP1491', 'HP0549', 'HP0509', 'HP0044', 'HP0858', 'HP0860', 'HP0409', 'HP0928', 'HP0802', 'HP1158', 'HP0822', 'HP1050', 'HP1279', 'HP1468', 'HP1275', 'HP0829', 'HP0230', 'HP0003', 'HP0867', 'HP0279', 'HP0043', 'HP0090', 'HP0086', 'HP0625', 'HP1020', 'HP0197', 'HP0957', 'HP1058', 'HP1394', 'HP0329', 'HP0198', 'HP1337', 'HP1355', 'HP0240', 'HP0005', 'HP0588', 'HP0590', 'HP0589', 'HP0591', 'HP1257', 'HP0293', 'HP0006', 'HP0493', 'HP1348', 'HP1111', 'HP1109', 'HP1108', 'HP1110', 'HP0075', 'HP0096', 'HP0397', 'HP0737', 'HP1016', 'HP0620', 'HP1380', 'HP1218', 'HP0742', 'HP0401', 'HP1357', 'HP0736', 'HP0652', 'HP1071', 'HP1475', 'HP1356', 'HP0002', 'HP1574', 'HP0105', 'HP0680', 'HP0364', 'HP0574', 'HP0857', 'HP0212', 'HP0624', 'HP1210', 'HP1249', 'HP0157', 'HP0832', 'HP0626', 'HP0098', 'HP1088', 'HP1533', 'HP0194', 'HP1458', 'HP0825', 'HP0824', 'HP1164', 'HP1277', 'HP1278', 'HP0196', 'HP1494', 'HP1375', 'HP0648', 'HP1155', 'HP0494', 'HP0623', 'HP1418', 'HP0740', 'HP1052', 'HP0777']
glu_sgd = ['HP0370', 'HP0950', 'HP0371', 'HP0557', 'HP0202', 'HP0587', 'HP0618', 'HP1112', 'HP0255', 'HP0859', 'HP0089', 'HP0106', 'HP0738', 'HP0942', 'HP0976', 'HP1483', 'HP1280', 'HP1281', 'HP1282', 'HP0598', 'HP1505', 'HP0422', 'HP1399', 'HP1017', 'HP1189', 'HP0723', 'HP0034', 'HP1084', 'HP1229', 'HP0672', 'HP1406', 'HP1376', 'HP0558', 'HP0195', 'HP0561', 'HP1237', 'HP0919', 'HP1443', 'HP0291', 'HP0663', 'HP0349', 'HP0107', 'HP0290', 'HP0566', 'HP0215', 'HP0804', 'HP0029', 'HP0134', 'HP0321', 'HP0510', 'HP1013', 'HP1545', 'HP1510', 'HP1011', 'HP0266', 'HP0581', 'HP1232', 'HP1038', 'HP0283', 'HP0929', 'HP0400', 'HP1228', 'HP0831', 'HP1474', 'HP0216', 'HP0354', 'HP0642', 'HP1161', 'HP1087', 'HP0577', 'HP0683', 'HP0961', 'HP0646', 'HP1532', 'HP0045', 'HP0183', 'HP0512', 'HP1491', 'HP0549', 'HP0509', 'HP0044', 'HP0858', 'HP0860', 'HP0409', 'HP0928', 'HP0802', 'HP1158', 'HP0822', 'HP1050', 'HP1279', 'HP1468', 'HP1275', 'HP0829', 'HP0230', 'HP0003', 'HP0867', 'HP0279', 'HP0043', 'HP0090', 'HP0086', 'HP0625', 'HP1020', 'HP0197', 'HP0957', 'HP1058', 'HP1394', 'HP0329', 'HP0198', 'HP1337', 'HP1355', 'HP0240', 'HP0005', 'HP0588', 'HP0590', 'HP0589', 'HP0591', 'HP1257', 'HP0293', 'HP0006', 'HP0493', 'HP1348', 'HP1111', 'HP1109', 'HP1108', 'HP1110', 'HP0075', 'HP0096', 'HP0397', 'HP0737', 'HP1016', 'HP0620', 'HP1380', 'HP1218', 'HP0742', 'HP0401', 'HP1357', 'HP0736', 'HP0652', 'HP1071', 'HP1475', 'HP1356', 'HP0002', 'HP1574', 'HP0105', 'HP0680', 'HP0364', 'HP0574', 'HP0857', 'HP0212', 'HP0624', 'HP1210', 'HP1249', 'HP0157', 'HP0832', 'HP0626', 'HP0098', 'HP1088', 'HP1533', 'HP0194', 'HP1458', 'HP0825', 'HP0824', 'HP1164', 'HP1277', 'HP1278', 'HP0196', 'HP1494', 'HP1375', 'HP0648', 'HP1155', 'HP0494', 'HP0623', 'HP1418', 'HP0360', 'HP0740', 'HP1052', 'HP0777']
sgd = ['HP0370', 'HP0950', 'HP0371', 'HP0557', 'HP0202', 'HP0587', 'HP0618', 'HP1112', 'HP0255', 'HP0859', 'HP0089', 'HP0106', 'HP0738', 'HP0942', 'HP0976', 'HP1483', 'HP1280', 'HP1281', 'HP1282', 'HP0598', 'HP1505', 'HP0422', 'HP1399', 'HP1017', 'HP1189', 'HP0723', 'HP0034', 'HP1084', 'HP1229', 'HP0672', 'HP1539', 'HP1227', 'HP1538', 'HP1540', 'HP1406', 'HP1376', 'HP0558', 'HP0195', 'HP0561', 'HP1237', 'HP0919', 'HP1443', 'HP0291', 'HP0663', 'HP0349', 'HP0147', 'HP0144', 'HP0145', 'HP0146', 'HP0107', 'HP0290', 'HP0566', 'HP0215', 'HP0804', 'HP0029', 'HP0134', 'HP0321', 'HP0510', 'HP1013', 'HP1545', 'HP1510', 'HP1011', 'HP0266', 'HP0581', 'HP1232', 'HP1038', 'HP0283', 'HP0929', 'HP0400', 'HP1228', 'HP0831', 'HP1474', 'HP0216', 'HP0354', 'HP0154', 'HP0176', 'HP1385', 'HP0642', 'HP1161', 'HP1087', 'HP0577', 'HP0683', 'HP0961', 'HP0646', 'HP1532', 'HP0045', 'HP0183', 'HP0512', 'HP1491', 'HP0549', 'HP0509', 'HP0044', 'HP0858', 'HP0860', 'HP0409', 'HP0928', 'HP0802', 'HP1158', 'HP0822', 'HP1050', 'HP1279', 'HP1468', 'HP1275', 'HP0829', 'HP0230', 'HP0003', 'HP0867', 'HP0279', 'HP0043', 'HP0090', 'HP0086', 'HP0625', 'HP1020', 'HP0197', 'HP0957', 'HP1058', 'HP1394', 'HP0329', 'HP0198', 'HP1337', 'HP1355', 'HP0240', 'HP0005', 'HP0588', 'HP0590', 'HP0589', 'HP0591', 'HP1257', 'HP0293', 'HP0006', 'HP0493', 'HP1348', 'HP1111', 'HP1109', 'HP1108', 'HP1110', 'HP0075', 'HP0096', 'HP0397', 'HP1166', 'HP1345', 'HP0974', 'HP0737', 'HP1016', 'HP0620', 'HP1380', 'HP0121', 'HP1218', 'HP0742', 'HP0401', 'HP1357', 'HP0736', 'HP0652', 'HP1071', 'HP1475', 'HP1356', 'HP0002', 'HP1574', 'HP0105', 'HP0680', 'HP0364', 'HP0574', 'HP0857', 'HP0212', 'HP0624', 'HP1210', 'HP1249', 'HP0157', 'HP0832', 'HP0389', 'HP0626', 'HP0098', 'HP1088', 'HP1533', 'HP0194', 'HP1458', 'HP0825', 'HP0824', 'HP1164', 'HP1277', 'HP1278', 'HP0196', 'HP1494', 'HP1375', 'HP0648', 'HP1155', 'HP0494', 'HP0623', 'HP1418', 'HP0360', 'HP0740', 'HP1052', 'HP0777']
m = len(glu_sgd)
n = len(gal_sgd)
w = len(sgd)
# Glucose and galactose comparision
print("\nGlucose and galactose comparision mismatch")
i = j = 0
while i < m and j < n:
if glu_sgd[i] != gal_sgd[j]:
print(glu_sgd[i])
i += 1
else:
i += 1
j += 1
# WT and Glucose comparision
print("\nWT and Glucose comparision mismatch")
i = j = 0
while i < w and j < m:
if sgd[i] != glu_sgd[j]:
print(glu_sgd[i])
i += 1
else:
i += 1
j += 1
|
# This is not for real use!
# This is normally generated by the build and install so should not be used for anything or filled in with real values.
# File generated from /opt/config
#
GLOBAL_INJECTED_AAI1_IP_ADDR = "10.0.1.1"
GLOBAL_INJECTED_AAI2_IP_ADDR = "10.0.1.2"
GLOBAL_INJECTED_APPC_IP_ADDR = "10.0.2.1"
GLOBAL_INJECTED_ARTIFACTS_VERSION = "1.2.0"
GLOBAL_INJECTED_CLAMP_IP_ADDR = "10.0.12.1"
GLOBAL_INJECTED_CLOUD_ENV = "openstack"
GLOBAL_INJECTED_DCAE_IP_ADDR = "10.0.4.1"
GLOBAL_INJECTED_DNS_IP_ADDR = "10.0.100.1"
GLOBAL_INJECTED_DOCKER_VERSION = "1.1-STAGING-latest"
GLOBAL_INJECTED_EXTERNAL_DNS = "8.8.8.8"
GLOBAL_INJECTED_GERRIT_BRANCH = "amsterdam"
GLOBAL_INJECTED_KEYSTONE = "http://10.12.25.2:5000"
GLOBAL_INJECTED_MR_IP_ADDR = "10.0.11.1"
GLOBAL_INJECTED_MSO_IP_ADDR = "10.0.5.1"
GLOBAL_INJECTED_NETWORK = "oam_onap_wbaL"
GLOBAL_INJECTED_NEXUS_DOCKER_REPO = "10.12.5.2:5000"
GLOBAL_INJECTED_NEXUS_PASSWORD = "anonymous"
GLOBAL_INJECTED_NEXUS_REPO = "https://nexus.onap.org/content/sites/raw"
GLOBAL_INJECTED_NEXUS_USERNAME = "username"
GLOBAL_INJECTED_OPENO_IP_ADDR = "10.0.14.1"
GLOBAL_INJECTED_OPENSTACK_PASSWORD = "password"
GLOBAL_INJECTED_OPENSTACK_TENANT_ID = "000007144004bacac1e39ff23105fff"
GLOBAL_INJECTED_OPENSTACK_USERNAME = "username"
GLOBAL_INJECTED_POLICY_IP_ADDR = "10.0.6.1"
GLOBAL_INJECTED_PORTAL_IP_ADDR = "10.0.9.1"
GLOBAL_INJECTED_PUBLIC_NET_ID = "971040b2-7059-49dc-b220-4fab50cb2ad4"
GLOBAL_INJECTED_REGION = "RegionOne"
GLOBAL_INJECTED_REMOTE_REPO = "http://gerrit.onap.org/r/testsuite/properties.git"
GLOBAL_INJECTED_SCRIPT_VERSION = "1.1.1"
GLOBAL_INJECTED_SDC_IP_ADDR = "10.0.3.1"
GLOBAL_INJECTED_SDNC_IP_ADDR = "10.0.7.1"
GLOBAL_INJECTED_SO_IP_ADDR = "10.0.5.1"
GLOBAL_INJECTED_VID_IP_ADDR = "10.0.8.1"
GLOBAL_INJECTED_VM_FLAVOR = "m1.medium"
GLOBAL_INJECTED_UBUNTU_1404_IMAGE = "ubuntu-14-04-cloud-amd64"
GLOBAL_INJECTED_UBUNTU_1604_IMAGE = "ubuntu-16-04-cloud-amd64"
GLOBAL_INJECTED_PROPERTIES={
"GLOBAL_INJECTED_AAI1_IP_ADDR" : "10.0.1.1",
"GLOBAL_INJECTED_AAI2_IP_ADDR" : "10.0.1.2",
"GLOBAL_INJECTED_APPC_IP_ADDR" : "10.0.2.1",
"GLOBAL_INJECTED_ARTIFACTS_VERSION" : "1.2.0",
"GLOBAL_INJECTED_CLAMP_IP_ADDR" : "10.0.12.1",
"GLOBAL_INJECTED_CLOUD_ENV" : "openstack",
"GLOBAL_INJECTED_DCAE_IP_ADDR" : "10.0.4.1",
"GLOBAL_INJECTED_DNS_IP_ADDR" : "10.0.100.1",
"GLOBAL_INJECTED_DOCKER_VERSION" : "1.1-STAGING-latest",
"GLOBAL_INJECTED_EXTERNAL_DNS" : "8.8.8.8",
"GLOBAL_INJECTED_GERRIT_BRANCH" : "amsterdam",
"GLOBAL_INJECTED_KEYSTONE" : "http://10.12.25.2:5000",
"GLOBAL_INJECTED_MR_IP_ADDR" : "10.0.11.1",
"GLOBAL_INJECTED_MSO_IP_ADDR" : "10.0.5.1",
"GLOBAL_INJECTED_NETWORK" : "oam_onap_wbaL",
"GLOBAL_INJECTED_NEXUS_DOCKER_REPO" : "10.12.5.2:5000",
"GLOBAL_INJECTED_NEXUS_PASSWORD" : "username",
"GLOBAL_INJECTED_NEXUS_REPO" : "https://nexus.onap.org/content/sites/raw",
"GLOBAL_INJECTED_NEXUS_USERNAME" : "username",
"GLOBAL_INJECTED_OPENO_IP_ADDR" : "10.0.14.1",
"GLOBAL_INJECTED_OPENSTACK_PASSWORD" : "password",
"GLOBAL_INJECTED_OPENSTACK_TENANT_ID" : "000007144004bacac1e39ff23105fff",
"GLOBAL_INJECTED_OPENSTACK_USERNAME" : "demo",
"GLOBAL_INJECTED_POLICY_IP_ADDR" : "10.0.6.1",
"GLOBAL_INJECTED_PORTAL_IP_ADDR" : "10.0.9.1",
"GLOBAL_INJECTED_PUBLIC_NET_ID" : "971040b2-7059-49dc-b220-4fab50cb2ad4",
"GLOBAL_INJECTED_REGION" : "RegionOne",
"GLOBAL_INJECTED_REMOTE_REPO" : "http://gerrit.onap.org/r/testsuite/properties.git",
"GLOBAL_INJECTED_SCRIPT_VERSION" : "1.1.1",
"GLOBAL_INJECTED_SDC_IP_ADDR" : "10.0.3.1",
"GLOBAL_INJECTED_SDNC_IP_ADDR" : "10.0.7.1",
"GLOBAL_INJECTED_SO_IP_ADDR" : "10.0.5.1",
"GLOBAL_INJECTED_VID_IP_ADDR" : "10.0.8.1",
"GLOBAL_INJECTED_VM_FLAVOR" : "m1.medium",
"GLOBAL_INJECTED_UBUNTU_1404_IMAGE" : "ubuntu-14-04-cloud-amd64",
"GLOBAL_INJECTED_UBUNTU_1604_IMAGE" : "ubuntu-16-04-cloud-amd64"}
|
###############################################################################
# Copyright (c) 2017-2020 Koren Lev (Cisco Systems), #
# Yaron Yogev (Cisco Systems), Ilia Abashin (Cisco Systems) and others #
# #
# All rights reserved. This program and the accompanying materials #
# are made available under the terms of the Apache License, Version 2.0 #
# which accompanies this distribution, and is available at #
# http://www.apache.org/licenses/LICENSE-2.0 #
###############################################################################
VEDGE_ID = "3858e121-d861-4348-9d64-a55fcd5bf60a"
VEDGE = {
"configurations": {
"tunnel_types": [
"vxlan"
],
"tunneling_ip": "192.168.2.1"
},
"host": "node-5.cisco.com",
"id": "3858e121-d861-4348-9d64-a55fcd5bf60a",
"tunnel_ports": {
"vxlan-c0a80203": {
},
"br-tun": {
}
},
"type": "vedge"
}
VEDGE_WITHOUT_CONFIGS = {
}
VEDGE_WITHOUT_TUNNEL_TYPES = {
"configuration": {
"tunnel_types": ""
}
}
NON_ICEHOUSE_CONFIGS = {
"distribution": "Mirantis",
"distribution_version": "8.0"
}
ICEHOUSE_CONFIGS = {
"distribution": "Canonical",
"distribution_version": "icehouse"
}
HOST = {
"host": "node-5.cisco.com",
"id": "node-5.cisco.com",
"ip_address": "192.168.0.4",
"name": "node-5.cisco.com"
}
OTEPS_WITHOUT_CONFIGURATIONS_IN_VEDGE_RESULTS = []
OTEPS_WITHOUT_TUNNEL_TYPES_IN_VEDGE_RESULTS = []
OTEPS_FOR_NON_ICEHOUSE_DISTRIBUTION_RESULTS = [
{
"host": "node-5.cisco.com",
"ip_address": "192.168.2.1",
"udp_port": 4789,
"id": "node-5.cisco.com-otep",
"name": "node-5.cisco.com-otep",
"overlay_type": "vxlan",
"ports": {
"vxlan-c0a80203": {
},
"br-tun": {
}
}
}
]
OTEPS_FOR_ICEHOUSE_DISTRIBUTION_RESULTS = [
{
"host": "node-5.cisco.com",
"ip_address": "192.168.0.4",
"id": "node-5.cisco.com-otep",
"name": "node-5.cisco.com-otep",
"overlay_type": "vxlan",
"ports": {
"vxlan-c0a80203": {
},
"br-tun": {
}
},
"udp_port": "67"
}
]
OTEPS = [
{
"host": "node-5.cisco.com",
"ip_address": "192.168.2.1",
"udp_port": 4789
}
]
OTEP_FOR_GETTING_VECONNECTOR = {
"host": "node-5.cisco.com",
"ip_address": "192.168.2.1",
"udp_port": 4789,
"id": "node-5.cisco.com-otep",
"name": "node-5.cisco.com-otep",
"overlay_type": "vxlan",
"ports": {
"vxlan-c0a80203": {
},
"br-tun": {
}
}
}
HOST_ID = "node-5.cisco.com"
IP_ADDRESS_SHOW_LINES = [
"2: br-mesh: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc "
"pfifo_fast state UP group default qlen 1000",
" link/ether 00:50:56:ac:28:9d brd ff:ff:ff:ff:ff:ff",
" inet 192.168.2.1/24 brd 192.168.2.255 scope global br-mesh",
" valid_lft forever preferred_lft forever",
" inet6 fe80::d4e1:8fff:fe33:ed6a/64 scope global mngtmpaddr dynamic",
" valid_lft 2591951sec preferred_lft 604751sec"
]
OTEP_WITH_CONNECTOR = {
"host": "node-5.cisco.com",
"ip_address": "192.168.2.1",
"udp_port": 4789,
"id": "node-5.cisco.com-otep",
"name": "node-5.cisco.com-otep",
"overlay_type": "vxlan",
"ports": {
"vxlan-c0a80203": {
},
"br-tun": {
}
},
"vconnector": "node-5.cisco.com-br-mesh"
}
|
class RedbotMotorActor(object):
# TODO(asydorchuk): load constants from the config file.
_MAXIMUM_FREQUENCY = 50
def __init__(self, gpio, power_pin, direction_pin_1, direction_pin_2):
self.gpio = gpio
self.power_pin = power_pin
self.direction_pin_1 = direction_pin_1
self.direction_pin_2 = direction_pin_2
self.gpio.setup(power_pin, self.gpio.OUT)
self.gpio.setup(direction_pin_1, self.gpio.OUT)
self.gpio.setup(direction_pin_2, self.gpio.OUT)
self.motor_controller = self.gpio.PWM(
self.power_pin, self._MAXIMUM_FREQUENCY)
def _setDirectionForward(self):
self.gpio.output(self.direction_pin_1, True)
self.gpio.output(self.direction_pin_2, False)
def _setDirectionBackward(self):
self.gpio.output(self.direction_pin_1, False)
self.gpio.output(self.direction_pin_2, True)
def start(self):
self.gpio.output(self.direction_pin_1, False)
self.gpio.output(self.direction_pin_2, False)
self.motor_controller.start(0.0)
self.relative_power = 0.0
def stop(self):
self.gpio.output(self.direction_pin_1, False)
self.gpio.output(self.direction_pin_2, False)
self.motor_controller.stop()
self.relative_power = 0.0
def setPower(self, relative_power):
if relative_power < 0:
self._setDirectionBackward()
else:
self._setDirectionForward()
power = int(100.0 * abs(relative_power))
self.motor_controller.ChangeDutyCycle(power)
self.relative_power = relative_power
|
#!/usr/bin/env python3
print("// addTable")
for a in range(0, 10):
print(" '{0}': {{".format(a))
for b in range(a, 10):
s = (a + b) % 10
c = (a + b) // 10
print(" '{0}': '{1}{2}',".format(b, s, c))
print(" },")
print()
print("// subTable")
for a in range(0, 10):
print(" '{0}': {{".format(a))
for b in range(0, 10):
d = (a - b) % 10
c = 0 if a >= b else 1
print(" '{0}': '{1}{2}',".format(b, d, c))
print(" },")
print()
print("// mulTable")
for a in range(0, 10):
print(" '{0}': {{".format(a))
for b in range(a, 10):
p = (a * b) % 10
c = (a * b) // 10
print(" '{0}': '{1}{2}',".format(b, p, c))
print(" },")
print()
print("// fullAdderTest")
for a in range(0, 10):
for b in range(0, 10):
for ci in range(0, 10):
s = (a + b + ci) % 10
co = (a + b + ci) // 10
print(" BadBignumTests.checkFullAdder('{0}', '{1}', '{2}', '{3}{4}');".format(
a, b, ci, s, co
))
print("// fullSubberTest")
for a in range(0, 10):
for b in range(0, 10):
for bi in range(0, 10):
d = (a - b - bi) % 10
bo = -((a - b - bi) // 10)
print(" BadBignumTests.checkFullSubber('{0}', '{1}', '{2}', '{3}{4}');".format(
a, b, bi, d, bo
))
print("// mulTest")
for a in range(0, 100):
for b in range(a, 100):
prod = a * b
print(" BadBignumTests.checkMul('{0}', '{1}', '{2}');".format(
a, b, prod
))
|
'''1) Um funcionário recebe um salário fixo mais 4% de comissão
sobre as vendas. Faça um programa que receba o salário fixo de um
funcionário e o valor de suas vendas, calcule e mostre a comissão e
o salário final do funcionário.'''
salario = float(input("Digite o valor do seu salario: "))
vendas = float(input("Digite o valor total de suas vendas: "))
salario_final = salario + (vendas * 0.04)
print(f"Seu salario final e R${salario_final}")
|
n, k = map(int, input().split())
dis = input().split()
m = n
while True:
m = str(m)
for d in dis:
if d in m:
break
else:
print(m)
exit()
m = int(m) + 1
|
def replay(adb):
adb.tap(1720, 1000)
def go_to_home(adb):
adb.tap(1961, 40)
def go_to_battle(adb):
adb.tap(1943, 928)
def go_to_event_battle(adb):
adb.tap(1900, 345)
def select_daily_event(adb):
adb.tap(313, 267)
def select_unit(adb):
adb.tap(1935, 935)
def sortie(adb):
adb.tap(1930, 947)
def stage_clear_ok(adb):
adb.tap(1958, 996)
|
player_1_position = 7
player_2_position = 10
player_1_score = 0
player_2_score = 0
def roll_die():
i = 1
while 1:
yield i
i += 1
if i > 100:
i = 1
roll = roll_die()
number_of_die_rolls = 0
# while (player_1_score < 1000 and player_2_score < 1000):
# for i in range(6):
while 1:
three_die_rolls = next(roll) + next(roll) + next(roll)
number_of_die_rolls += 3
if((player_1_position + three_die_rolls) % 10 == 0):
player_1_position = 10
else:
player_1_position = (player_1_position + three_die_rolls) % 10
player_1_score += player_1_position
print(f'p1 position: {player_1_position} p1 score: {player_1_score}')
if(player_1_score >= 1000):
print(f'player 1 wins!')
print(f'{number_of_die_rolls} * {player_2_score} = {number_of_die_rolls * player_2_score}')
break
three_die_rolls = next(roll) + next(roll) + next(roll)
number_of_die_rolls += 3
if((player_2_position + three_die_rolls) % 10 == 0):
player_2_position = 10
else:
player_2_position = (player_2_position + three_die_rolls) % 10
player_2_score += player_2_position
print(f'p2 position: {player_2_position} p2 score: {player_2_score}')
if(player_2_score >= 1000):
print(f'player 2 wins!')
print(f'{number_of_die_rolls} * {player_1_score} = {number_of_die_rolls * player_1_score}')
break
print(f'number of die rolls: {number_of_die_rolls}')
|
class RevasCalculations:
'''Functions related to calculations go there
'''
pass
|
"""
write a first program in python3
How to run the program in terminal
python3 filename.py
"""
print("HelloWorld in Python !!")
|
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']
print(list) # Prints complete list
print(list[0]) # Prints first element of the list
print(list[1:3]) # Prints elements starting from 2nd till 3rd
print(list[2:]) # Prints elements starting from 3rd element
print(tinylist * 2) # Prints list two times
print(list + tinylist) # Prints concatenated lists
|
# Crie um programa que leia duas notas de um aluno e calcule sua média,
# mostrando uma mensagem no final, de acordo coma média atingida.
# -Média abaixo de 5.0: REPROVADO.
# -Média entre 5.0 e 6.9: RECUPERAÇÃO
# -Média 7.0 ou superior: APROVADO
n1 = float(input('Nota 1: '))
n2 = float(input('Nota 2: '))
media = (n1 + n2) / 2
cores = '\033[m \033[33m \033[34m'.split()
print(f'A sua média foi de {media}')
if media < 5.0:
cornota = '\033[31m'
print(f'Média {cornota}{media}{cores[0]} abaixo de {cores[1]}5.0{cores[0]} : {cores[2]}REPROVADO')
elif media < 6.99:
cornota = '\033[33m'
print(f'Média{cornota} {media} {cores[0]}entre 5.0 e 6.9 : RECUPERAÇÃO')
else:
cornota = '\033[32m'
print(f'Média{cornota} {media} {cores[0]} igual ou superior a 7.0 : APROVADO')
|
class Node:
"""Node for bst."""
def __init__(self, val):
"""Instantiate node."""
self.val = val
self.right = None
self.left = None
def __repr__(self):
"""Represent node."""
return '<Node Val: {}'.format(self.val)
def __str__(self):
"""Node value."""
return self.val
class BST:
"""Binary search tree."""
def __init__(self):
"""Instatiate bst."""
self.root = None
def __repr__(self):
"""Represent root."""
return '<BST Root {}>'.format(self.root.val)
def __str__(self):
"""Root value."""
return self.root.val
def in_order(self, operation):
"""In order traversal."""
def _walk(node=None):
"""Traverse."""
if node is None:
return
if node.left is not None:
_walk(node.left)
operation(node)
if node.right is not None:
_walk(node.right)
_walk(self.root)
def pre_order(self, operation):
"""Pre order traversal."""
def _walk(node=None):
"""Traverse."""
if node is None:
return
operation(node)
if node.left is not None:
_walk(node.left)
if node.right is not None:
_walk(node.right)
_walk(self.root)
def post_order(self, operation):
"""Post order traversal."""
def _walk(node=None):
"""Traverse."""
if node is None:
return
if node.left is not None:
_walk(node.left)
if node.right is not None:
_walk(node.right)
operation(node)
_walk(self.root)
def insert(self, val):
"""Add value as node to bst."""
node = Node(val)
current = self.root
if self.root is None:
self.root = node
return node
while current:
if val >= current.val:
if current.right is not None:
current = current.right
else:
current.right = node
break
elif val < current.val:
if current.left is not None:
current = current.left
else:
current.left = node
break
return node
|
"""Output the number of labs required for a certain number of students."""
SEATS = 24
students = input('Enter the number of students: ')
while not students.isnumeric():
students = input(
"Numbers are usually numeric. Let's try this again.\n"
'Enter the number of students: '
)
students = int(students)
labs, remaining = divmod(students, SEATS)
labs += 1 if remaining else 0
plural = 'Labs' if students == 1 else 'Lab'
print(f'{plural} required: {labs}')
|
def solve(s):
word_list = s.split(' ')
name_capitalized = []
for word in word_list:
name_capitalized.append(word.capitalize())
word = ' '.join(name_capitalized)
return word
|
"""Subscribe to a specific queue
and consume the messages.
"""
class Subscriber:
def __init__(self, adapter):
"""Create a new subscriber with an Adapter instance.
:param BaseAdapter adapter: Connection Adapter
"""
self.adapter = adapter
def consume(self, worker):
"""Consume a queued message.
:param function worker: Worker to execute when consuming the message
"""
self.adapter.consume(worker)
|
#
# Copyright (c) 2019 Jonathan McGee <broken.source@etherealwake.com>
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#
"""Common Implementation of GCC-Compatible C/C++ Toolchain."""
load(
"@bazel_tools//tools/cpp:cc_toolchain_config_lib.bzl",
"action_config",
"artifact_name_pattern",
"feature",
"flag_group",
"flag_set",
"variable_with_value",
"with_feature_set",
)
load(
":common.bzl",
"ACTION_NAMES",
"ALL_COMPILE_ACTIONS",
"ALL_LINK_ACTIONS",
"CPP_COMPILE_ACTIONS",
"FEATURE_NAMES",
"PREPROCESSOR_ACTIONS",
"make_default_compile_flags_feature",
"make_default_link_flags_feature",
"make_linkstamps_feature",
"make_tool",
"make_user_compile_flags_feature",
"make_user_link_flags_feature",
)
load("//cc:rules.bzl", "cc_toolchain")
#
# GCC-Compatible Features
#
def gcc_archiver_flags_feature(ctx):
return feature(
name = FEATURE_NAMES.archiver_flags,
flag_sets = [flag_set(
actions = [ACTION_NAMES.cpp_link_static_library],
flag_groups = [flag_group(
flags = ["rcsD", "%{output_execpath}"],
), flag_group(
iterate_over = "libraries_to_link",
flag_groups = [flag_group(
expand_if_equal = variable_with_value(
"libraries_to_link.type",
"object_file",
),
flags = ["%{libraries_to_link.name}"],
), flag_group(
expand_if_equal = variable_with_value(
"libraries_to_link.type",
"object_file_group",
),
iterate_over = "libraries_to_link.object_files",
flags = ["%{libraries_to_link.object_files}"],
)],
)],
)],
)
def gcc_compiler_input_flags_feature(ctx):
return feature(
name = FEATURE_NAMES.compiler_input_flags,
flag_sets = [flag_set(
actions = ALL_COMPILE_ACTIONS,
flag_groups = [flag_group(flags = ["-c", "%{source_file}"])],
)],
)
def gcc_compiler_output_flags_feature(ctx):
return feature(
name = FEATURE_NAMES.compiler_output_flags,
flag_sets = [flag_set(
actions = ALL_COMPILE_ACTIONS,
flag_groups = [flag_group(flags = ["-o", "%{output_file}"])],
)],
)
def gcc_dependency_file_feature(ctx):
return feature(
name = FEATURE_NAMES.dependency_file,
enabled = True,
flag_sets = [flag_set(
actions = ALL_COMPILE_ACTIONS,
flag_groups = [flag_group(
expand_if_available = "dependency_file",
flags = ["-MD", "-MF", "%{dependency_file}"],
)],
)],
)
def gcc_fission_support(ctx):
return feature(
name = FEATURE_NAMES.fission_support,
flag_sets = [flag_set(
actions = ALL_LINK_ACTIONS,
flag_groups = [flag_group(
expand_if_available = "is_using_fission",
flags = ["-Wl,--gdb-index"],
)],
)],
)
def gcc_force_pic_flags_feature(ctx):
return feature(
name = FEATURE_NAMES.force_pic_flags,
flag_sets = [flag_set(
actions = [ACTION_NAMES.cpp_link_executable],
flag_groups = [flag_group(
expand_if_available = "force_pic",
flags = ["-pie"],
)],
)],
)
def gcc_fully_static_link(ctx):
return feature(
name = FEATURE_NAMES.fully_static_link,
flag_sets = [flag_set(
actions = ALL_LINK_ACTIONS,
flag_groups = [flag_group(flags = ["-static"])],
)],
)
def gcc_includes_feature(ctx):
return feature(
name = FEATURE_NAMES.includes,
enabled = True,
flag_sets = [flag_set(
actions = PREPROCESSOR_ACTIONS,
flag_groups = [flag_group(
expand_if_available = "includes",
iterate_over = "includes",
flags = ["-include", "%{includes}"],
)],
)],
)
def gcc_include_paths_feature(ctx):
return feature(
name = FEATURE_NAMES.include_paths,
enabled = True,
flag_sets = [flag_set(
actions = PREPROCESSOR_ACTIONS,
flag_groups = [flag_group(
iterate_over = "quote_include_paths",
flags = ["-iquote", "%{quote_include_paths}"],
), flag_group(
iterate_over = "include_paths",
flags = ["-I%{include_paths}"],
), flag_group(
iterate_over = "system_include_paths",
flags = ["-isystem", "%{system_include_paths}"],
)],
)],
)
def gcc_libraries_to_link_feature(ctx):
whole_archive = flag_group(
expand_if_true = "libraries_to_link.is_whole_archive",
flags = ["-Wl,--whole-archive"],
)
no_whole_archive = flag_group(
expand_if_true = "libraries_to_link.is_whole_archive",
flags = ["-Wl,--no-whole-archive"],
)
return feature(
name = FEATURE_NAMES.libraries_to_link,
flag_sets = [flag_set(
actions = ALL_LINK_ACTIONS,
flag_groups = [flag_group(
iterate_over = "libraries_to_link",
flag_groups = [flag_group(
expand_if_equal = variable_with_value(
"libraries_to_link.type",
"dynamic_library",
),
flags = ["-l%{libraries_to_link.name}"],
), flag_group(
expand_if_equal = variable_with_value(
"libraries_to_link.type",
"interface_library",
),
flags = ["%{libraries_to_link.name}"],
), flag_group(
expand_if_equal = variable_with_value(
"libraries_to_link.type",
"object_file",
),
flags = ["%{libraries_to_link.name}"],
), flag_group(
expand_if_equal = variable_with_value(
"libraries_to_link.type",
"object_file_group",
),
flag_groups = [
whole_archive,
flag_group(flags = ["-Wl,--start-lib"]),
flag_group(
iterate_over = "libraries_to_link.object_files",
flags = ["%{libraries_to_link.object_files}"],
),
flag_group(flags = ["-Wl,--end-lib"]),
no_whole_archive,
],
), flag_group(
expand_if_equal = variable_with_value(
"libraries_to_link.type",
"static_library",
),
flag_groups = [
whole_archive,
flag_group(flags = ["%{libraries_to_link.name}"]),
no_whole_archive,
],
), flag_group(
expand_if_equal = variable_with_value(
"libraries_to_link.type",
"versioned_dynamic_library",
),
flags = ["-l:%{libraries_to_link.name}"],
)],
)],
)],
)
def gcc_library_search_directories_feature(ctx):
return feature(
name = FEATURE_NAMES.library_search_directories,
flag_sets = [flag_set(
actions = ALL_LINK_ACTIONS,
flag_groups = [flag_group(
expand_if_available = "library_search_directories",
iterate_over = "library_search_directories",
flags = ["-L%{library_search_directories}"],
)],
)],
)
def gcc_linker_param_file_feature(ctx):
return feature(
name = FEATURE_NAMES.linker_param_file,
flag_sets = [flag_set(
actions = ALL_LINK_ACTIONS + [ACTION_NAMES.cpp_link_static_library],
flag_groups = [flag_group(
expand_if_available = "linker_param_file",
flags = ["@%{linker_param_file}"],
)],
)],
)
def gcc_output_execpath_flags_feature(ctx):
return feature(
name = FEATURE_NAMES.output_execpath_flags,
flag_sets = [flag_set(
actions = ALL_LINK_ACTIONS,
flag_groups = [flag_group(
flags = ["-o", "%{output_execpath}"],
)],
)],
)
def gcc_per_object_debug_info_feature(ctx):
return feature(
name = FEATURE_NAMES.per_object_debug_info,
enabled = True,
flag_sets = [flag_set(
actions = ALL_COMPILE_ACTIONS,
flag_groups = [flag_group(
expand_if_available = "per_object_debug_info_file",
flags = ["-gsplit-dwarf"],
)],
)],
)
def gcc_pic_feature(ctx):
return feature(
name = FEATURE_NAMES.pic,
enabled = True,
flag_sets = [flag_set(
actions = ALL_COMPILE_ACTIONS,
flag_groups = [flag_group(
expand_if_available = "pic",
flags = ["-fPIC"],
)],
)],
)
def gcc_preprocessor_defines_feature(ctx):
return feature(
name = FEATURE_NAMES.preprocessor_defines,
enabled = True,
flag_sets = [flag_set(
actions = PREPROCESSOR_ACTIONS,
flag_groups = [flag_group(
iterate_over = "preprocessor_defines",
flags = ["-D%{preprocessor_defines}"],
)],
)],
)
def gcc_random_seed_feature(ctx):
return feature(
name = FEATURE_NAMES.random_seed,
enabled = True,
flag_sets = [flag_set(
actions = CPP_COMPILE_ACTIONS,
flag_groups = [flag_group(flags = ["-frandom-seed=%{output_file}"])],
)],
)
def gcc_runtime_library_search_directories_feature(ctx):
origin = "-Wl,-rpath,$ORIGIN/"
return feature(
name = FEATURE_NAMES.runtime_library_search_directories,
flag_sets = [flag_set(
actions = ALL_LINK_ACTIONS,
flag_groups = [flag_group(
expand_if_available = "runtime_library_search_directories",
iterate_over = "runtime_library_search_directories",
flags = [origin + "%{runtime_library_search_directories}"],
)],
)],
)
def gcc_shared_flag_feature(ctx):
return feature(
name = FEATURE_NAMES.shared_flag,
flag_sets = [flag_set(
actions = [
ACTION_NAMES.cpp_link_dynamic_library,
ACTION_NAMES.cpp_link_nodeps_dynamic_library,
],
flag_groups = [flag_group(flags = ["-shared"])],
)],
)
def gcc_static_libgcc_feature(ctx):
return feature(
name = FEATURE_NAMES.static_libgcc,
enabled = True,
flag_sets = [flag_set(
actions = ALL_LINK_ACTIONS,
with_features = [with_feature_set(features = [
FEATURE_NAMES.static_link_cpp_runtimes,
])],
flag_groups = [flag_group(flags = ["-static-libgcc"])],
)],
)
def gcc_strip_debug_symbols_feature(ctx):
return feature(
name = FEATURE_NAMES.strip_debug_symbols,
flag_sets = [flag_set(
actions = ALL_LINK_ACTIONS,
flag_groups = [flag_group(
expand_if_available = "strip_debug_symbols",
flags = ["-Wl,-S"],
)],
)],
)
def gcc_strip_flag_set(ctx, **kwargs):
"""Generates list of `flag_set` for the `strip` executable."""
return [flag_set(
flag_groups = [flag_group(
flags = ctx.attr.stripopts,
), flag_group(
flags = ["%{stripopts}"],
iterate_over = "stripopts",
), flag_group(
flags = ["-o", "%{output_file}", "%{input_file}"],
)],
**kwargs
)]
def gcc_sysroot_feature(ctx):
return feature(
name = FEATURE_NAMES.sysroot,
flag_sets = [flag_set(
actions = ALL_COMPILE_ACTIONS + ALL_LINK_ACTIONS,
flag_groups = [flag_group(
expand_if_available = "sysroot",
flags = ["--sysroot=%{sysroot}"],
)],
)],
)
def gcc_unfiltered_compile_flags_feature(ctx):
return feature(
name = FEATURE_NAMES.unfiltered_compile_flags,
enabled = True,
flag_sets = [flag_set(
actions = ALL_COMPILE_ACTIONS,
flag_groups = [flag_group(flags = [
"-no-canonical-prefixes",
"-Wno-builtin-macro-redefined",
"-D__DATE__=\"redacted\"",
"-D__TIME__=\"redacted\"",
"-D__TIMESTAMP__=\"redacted\"",
])],
)],
)
#
# Core Rule Implementation
#
def gcc_cc_toolchain_config_impl(ctx, copts = [], linkopts = []):
# Generate List of Actions
action_configs = []
for action_name in ALL_COMPILE_ACTIONS:
action_configs.append(action_config(
action_name = action_name,
implies = [
FEATURE_NAMES.default_compile_flags,
FEATURE_NAMES.user_compile_flags,
FEATURE_NAMES.sysroot,
FEATURE_NAMES.unfiltered_compile_flags,
FEATURE_NAMES.compiler_input_flags,
FEATURE_NAMES.compiler_output_flags,
],
tools = make_tool(ctx, ctx.file.cctool),
))
for action_name in ALL_LINK_ACTIONS:
if action_name == ACTION_NAMES.cpp_link_executable:
implies = [FEATURE_NAMES.force_pic_flags]
else:
implies = [FEATURE_NAMES.shared_flag]
action_configs.append(action_config(
action_name = action_name,
implies = implies + [
FEATURE_NAMES.default_link_flags,
FEATURE_NAMES.strip_debug_symbols,
FEATURE_NAMES.linkstamps,
FEATURE_NAMES.output_execpath_flags,
FEATURE_NAMES.runtime_library_search_directories,
FEATURE_NAMES.library_search_directories,
FEATURE_NAMES.libraries_to_link,
FEATURE_NAMES.user_link_flags,
FEATURE_NAMES.linker_param_file,
FEATURE_NAMES.fission_support,
FEATURE_NAMES.sysroot,
],
tools = make_tool(ctx, ctx.file.linktool),
))
action_configs.append(action_config(
action_name = ACTION_NAMES.cpp_link_static_library,
implies = [
FEATURE_NAMES.archiver_flags,
FEATURE_NAMES.linker_param_file,
],
tools = make_tool(ctx, ctx.file.artool),
))
action_configs.append(action_config(
action_name = ACTION_NAMES.strip,
flag_sets = gcc_strip_flag_set(ctx),
tools = make_tool(ctx, ctx.file.strip),
))
# Construct List of Artifacts
artifact_name_patterns = [
artifact_name_pattern("alwayslink_static_library", "lib", ".lo"),
artifact_name_pattern("executable", None, None),
artifact_name_pattern("included_file_list", None, ".d"),
artifact_name_pattern("object_file", None, ".o"),
artifact_name_pattern("static_library", "lib", ".a"),
]
# Support List
features = [
feature(name = FEATURE_NAMES.dbg),
feature(name = FEATURE_NAMES.fastbuild),
feature(name = FEATURE_NAMES.opt),
feature(name = FEATURE_NAMES.no_legacy_features),
]
if FEATURE_NAMES.supports_dynamic_linker in ctx.features:
artifact_name_patterns.extend([
artifact_name_pattern("dynamic_library", "lib", ".so"),
artifact_name_pattern("interface_library", "lib", ".ifso"),
])
features.append(feature(
name = FEATURE_NAMES.supports_dynamic_linker,
enabled = True,
))
if FEATURE_NAMES.supports_pic in ctx.features:
artifact_name_patterns.extend([
artifact_name_pattern("pic_file", None, ".pic"),
artifact_name_pattern("pic_object_file", None, ".pic.o"),
])
features.append(feature(
name = FEATURE_NAMES.supports_pic,
enabled = True,
))
if FEATURE_NAMES.supports_start_end_lib in ctx.features:
features.append(feature(
name = FEATURE_NAMES.supports_start_end_lib,
enabled = True,
))
# Action Groups
features += [
# Compiler Flags
make_default_compile_flags_feature(ctx, copts),
gcc_dependency_file_feature(ctx),
gcc_pic_feature(ctx),
gcc_per_object_debug_info_feature(ctx),
gcc_preprocessor_defines_feature(ctx),
gcc_includes_feature(ctx),
gcc_include_paths_feature(ctx),
# Linker Flags
make_default_link_flags_feature(ctx, linkopts),
gcc_shared_flag_feature(ctx),
make_linkstamps_feature(ctx),
gcc_output_execpath_flags_feature(ctx),
gcc_runtime_library_search_directories_feature(ctx),
gcc_library_search_directories_feature(ctx),
gcc_archiver_flags_feature(ctx),
gcc_libraries_to_link_feature(ctx),
gcc_force_pic_flags_feature(ctx),
make_user_link_flags_feature(ctx),
gcc_static_libgcc_feature(ctx),
gcc_fission_support(ctx),
gcc_strip_debug_symbols_feature(ctx),
gcc_fully_static_link(ctx),
# Trailing Flags
make_user_compile_flags_feature(ctx),
gcc_sysroot_feature(ctx),
gcc_unfiltered_compile_flags_feature(ctx),
gcc_linker_param_file_feature(ctx),
gcc_compiler_input_flags_feature(ctx),
gcc_compiler_output_flags_feature(ctx),
]
# Additional Parameters
sysroot = ctx.file.sysroot
if sysroot:
sysroot = sysroot.path
# Construct CcToolchainConfigInfo
config = cc_common.create_cc_toolchain_config_info(
ctx = ctx,
abi_libc_version = "local",
abi_version = "local",
action_configs = action_configs,
artifact_name_patterns = artifact_name_patterns,
builtin_sysroot = sysroot,
cc_target_os = None,
compiler = ctx.attr.compiler,
cxx_builtin_include_directories = ctx.attr.builtin_include_directories,
features = features,
host_system_name = "local",
make_variables = [],
tool_paths = [],
target_cpu = ctx.attr.cpu,
target_libc = "local",
target_system_name = ctx.attr.target,
toolchain_identifier = ctx.attr.name,
)
# Write out CcToolchainConfigInfo to file (diagnostics)
pbtxt = ctx.actions.declare_file(ctx.attr.name + ".pbtxt")
ctx.actions.write(
output = pbtxt,
content = config.proto,
)
return [DefaultInfo(files = depset([pbtxt])), config]
gcc_cc_toolchain_config = rule(
attrs = {
"artool": attr.label(
allow_single_file = True,
cfg = "host",
executable = True,
mandatory = True,
),
"asmopts": attr.string_list(),
"builtin_include_directories": attr.string_list(),
"cctool": attr.label(
allow_single_file = True,
cfg = "host",
executable = True,
mandatory = True,
),
"compiler": attr.string(default = "gcc"),
"conlyopts": attr.string_list(
default = ["-std=c17"],
),
"copts": attr.string_list(),
"cpu": attr.string(default = "local"),
"cxxopts": attr.string_list(
default = ["-std=c++17"],
),
"linkopts": attr.string_list(),
"linktool": attr.label(
allow_single_file = True,
cfg = "host",
executable = True,
mandatory = True,
),
"modes": attr.string_list_dict(),
"objcopy": attr.label(
allow_single_file = True,
cfg = "host",
executable = True,
mandatory = True,
),
"strip": attr.label(
allow_single_file = True,
cfg = "host",
executable = True,
mandatory = True,
),
"stripopts": attr.string_list(
default = ["-S", "-p"],
),
"sysroot": attr.label(
allow_single_file = True,
cfg = "host",
),
"target": attr.string(default = "local"),
},
implementation = gcc_cc_toolchain_config_impl,
)
def gcc_toolchain(
name,
all_files,
compiler_files,
target_compatible_with,
exec_compatible_with = None,
objcopy_files = None,
strip_files = None,
target_files = None,
visibility = None,
**kwargs):
"""C/C++ Toolchain Macro for Generic Unix.
Targets:
{name}: Instance of `toolchain`.
{name}-toolchain: Instance of `cc_toolchain`.
"""
gcc_cc_toolchain_config(
name = name + "-config",
tags = ["manual"],
visibility = ["//visibility:private"],
**kwargs
)
if target_files:
native.filegroup(
name = name + "-files",
srcs = [all_files] + target_files,
tags = ["manual"],
visibility = ["//visibility:private"],
)
all_files = ":%s-files" % name
native.filegroup(
name = name + "-compiler-files",
srcs = [compiler_files] + target_files,
tags = ["manual"],
visibility = ["//visibility:private"],
)
compiler_files = ":%s-compiler-files" % name
cc_toolchain(
name = name + "-toolchain",
all_files = all_files,
ar_files = kwargs["artool"],
as_files = compiler_files,
compiler_files = compiler_files,
dwp_files = compiler_files,
libc_top = None,
linker_files = all_files,
objcopy_files = objcopy_files or kwargs["objcopy"],
strip_files = strip_files or kwargs["strip"],
supports_header_parsing = False,
supports_param_files = False,
toolchain_config = ":%s-config" % name,
tags = ["manual"],
visibility = visibility,
)
native.toolchain(
name = name,
exec_compatible_with = exec_compatible_with,
target_compatible_with = target_compatible_with,
toolchain = ":%s-toolchain" % name,
toolchain_type = "@bazel_tools//tools/cpp:toolchain_type",
visibility = visibility,
)
|
#!/usr/bin/python
print('Content-type: text/plain\n\n')
print('script cgi with GET')
|
#
# GeomProc: geometry processing library in python + numpy
#
# Copyright (c) 2008-2021 Oliver van Kaick <ovankaic@gmail.com>
# under the MIT License.
#
# See file LICENSE.txt for details on copyright licenses.
#
"""This module contains the write_options class of the GeomProc geometry
processing library.
"""
# Options for saving files
class write_options:
"""A class that holds options of what information to write when saving a file
Attributes
----------
write_vertex_normals : boolean
Save normal vectors stored at mesh vertices
write_vertex_colors : boolean
Save colors stored at mesh vertices
write_vertex_uvs : boolean
Save (u, v) texture coordinates stored at mesh vertices
write_face_normals : boolean
Save normal vectors stored at mesh faces
write_corner_normals : boolean
Save normal vectors stored at face corners
write_corner_uvs : boolean
Save (u, v) texture coordinates stored at face corners
texture_name : string
Filename of image referenced by texture coordinates
write_point_normals : boolean
Save normal vectors stored at points in point cloud
write_point_colors : boolean
Save colors stored at points in point cloud
Notes
-----
Not all options are accepted by every file format. The class
collects all the possible options supported by different file
formats. The structure is relevant to both meshes and point clouds.
"""
def __init__(self):
# Not all options are accepted by every file format
self.write_vertex_normals = False
self.write_vertex_colors = False
self.write_vertex_uvs = False
self.write_face_normals = False
self.write_corner_normals = False
self.write_corner_uvs = False
self.texture_name = ''
self.write_point_normals = False
self.write_point_colors = False
|
OLD_EXP_PER_HOUR = 10
OLD_TIME_TO_LVL_DELTA = 5
NEW_EXP_PER_HOUR = 10
NEW_TIME_TO_LVL_DELTA = 7
NEW_TIME_TO_LVL_MULTIPLIER = 1.02
def old_level_to_exp(level, exp):
total_exp = exp
for i in range(2, level + 1):
total_exp += i * OLD_TIME_TO_LVL_DELTA * OLD_EXP_PER_HOUR
return total_exp
def new_time_on_lvl(lvl):
return float(NEW_TIME_TO_LVL_DELTA * lvl * NEW_TIME_TO_LVL_MULTIPLIER ** lvl)
def exp_to_new_level(exp):
level = 1
while exp >= new_time_on_lvl(level + 1) * NEW_EXP_PER_HOUR:
exp -= new_time_on_lvl(level + 1) * NEW_EXP_PER_HOUR
level += 1
return level, exp
def old_to_new(level, exp):
raw_exp = old_level_to_exp(level, exp)
return exp_to_new_level(raw_exp)
|
#!/usr/bin/env python3
# probleme des 8 dames
def printGrid(grid):
for y in range(8):
print(8 - y, end=" |")
for x in range(8):
print(grid[x][y], "", end="")
print()
print("------------------")
print("X |A B C D E F G H")
grid = [[0] * 8 for _ in range(8)]
for j in range(8):
for i in range(8):
grid[i][j] = (i + j) % 10
printGrid(grid)
|
class Bicicleta:
def __init__(self, marca, aro, calibragem):
self.marca = marca;
self.aro = aro;
self.calibragem = calibragem;
def __str__(self):
string = "Marca: "+self.marca+"\nAro: "+str(self.aro)+"\nCalibragem: "+str(self.calibragem)
return string
def getMarca(self):
return self.marca
def getAro(self):
return self.aro
def getCalibragem(self):
return self.calibragem
def getPegadaCarbono(self):
pegCarb = 0
return pegCarb
|
class Node(object):
def __init__(self, nm, name, capacity = 15):
self.nm = nm
self.name = name
self.capacity = capacity
self.values = []
def consume(self, from_name, value):
"""
All subclass need to override this function to do
acturlly calculation
"""
pass
def data_income(self, from_name, value):
out_val = self.consume(from_name, value)
if out_val != None:
self.values.append(out_val)
while len(self.values) > self.capacity:
del self.values[0]
self.data_output(self.name, out_val)
def data_output(self, from_name, value):
if from_name in self.nm.output_wires:
wires = self.nm.output_wires[from_name]
for wired_node in wires:
wired_node.data_income(from_name, value)
def snapshot(self):
return [v for v in self.values]
|
class Encapsulation:
def __hide(self):
print("示例的隐藏方法")
def getname(self):
return self.__name
def setname(self,name):
if len(name)<3 or len(name)>8:
raise ValueError("长度不在范围内")
self.__name = name
name=property(getname,setname)
e = Encapsulation()
#e.name = "ha"
#print(e.name)
e._Encapsulation__hide()
|
#!/usr/bin/env python
# encoding: utf-8
"""
@author: su jian
@contact: 121116111@qq.com
@file: __init__.py.py
@time: 2017/8/16 17:43
"""
def func():
pass
class Main():
def __init__(self):
pass
if __name__ == '__main__':
pass
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.