content stringlengths 7 1.05M |
|---|
#common utilities for all module
def trap_exc_during_debug(*args):
# when app raises uncaught exception, print info
print(args) |
# Copyright 2011 Nicholas Bray
#
# 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.
def doNothing(node):
pass
class CFGDFS(object):
def __init__(self, pre=doNothing, post=doNothing):
self.pre = pre
self.post = post
self.processed = set()
def process(self, node):
if node not in self.processed:
self.processed.add(node)
self.pre(node)
for child in node.forward():
self.process(child)
self.post(node)
|
def optical_flow(img_stack):
"""
Given an image stack (N, H, W, C) calculate the optical flow
beginning from the center image (rounded down) towards either
end.
Returns the disparity maps stackes as (N, H, W, 2)
"""
pass
|
class Calculator(object):
def __init__(self, corpus, segment_size):
self.corpus = corpus
self.segment_size = segment_size
@staticmethod
def calc_proportion(matches, total):
"""
Simple float division placed into a static method to prevent Zero division error.
"""
if matches and total:
return float(matches) / float(total)
return 0.0
def get_relevant_words(self, position, inverse=False):
"""
Filter relevant words. I.e. checking if one letter word matches biphoneme
segment doesn't make sense nor does matching phoneme in the fifth position
with the words shorter than five characters.
"""
if inverse:
return [x[::-1] for x in self.corpus if len(x) >= position + self.segment_size]
return [x for x in self.corpus if len(x) >= position + self.segment_size]
def split_into_segments(self, word):
"""
If segment size is equal to one, return list of characters. Otherwise, return
appropriate segments.
"""
if self.segment_size == 1:
return list(word)
return (word[x:x+self.segment_size] for x in range(len(word)-self.segment_size+1))
def get_number_of_matches(self, segment, position, relevant_words):
"""
Find out number of matching segments in the set of relevant words.
"""
return len(filter(
lambda x: x[position:position+self.segment_size] == segment, relevant_words)
)
def get_probability_for_segments(self, word, inverse=False):
"""
Calculate probabilities for each segment.
"""
proportions = []
for position, segment in enumerate(self.split_into_segments(word)):
relevant_words = self.get_relevant_words(position, inverse=inverse)
matches = self.get_number_of_matches(segment, position, relevant_words)
if inverse:
segment = segment[::-1]
proportions.append([segment,self.calc_proportion(matches,len(relevant_words))])
if inverse:
proportions.reverse()
return proportions
def get_word_probability_by_segments(self, word, prob_type):
"""
Call the above method to calculate different probability types depending on
parameters passed. If 'combined probability' is asked for, this method calls
itself recursively to calculate 'regular probability' and 'inverse probability'
for each segment, and then returns the average of the two results.
"""
if prob_type == 1:
return self.get_probability_for_segments(word)
if prob_type == 2:
return self.get_probability_for_segments(word[::-1], inverse=True)
return [
[i[0],(i[1]+j[1])/2] for i,j in zip(
self.get_word_probability_by_segments(word, 1),
self.get_word_probability_by_segments(word, 2)
)
]
def get_probs(self, word, prob_type, averaged=False):
"""
Get probabilities for all segments of the word, sum them and average (if asked for).
Return list of two elements, where the first one is summed/averaged probability and
the second one is a list of probabilities by segments.
"""
by_segments = self.get_word_probability_by_segments(word, prob_type)
summed = sum(x[1] for x in by_segments)
if averaged and summed > 0:
return [summed / (len(word)-self.segment_size+1), by_segments]
return [summed, by_segments]
|
"""
ytsync.py
Synchronize YouTube playlists on a channel to local storage.
Downloads all videos using youtube-dl.
"""
|
def summation(number):
total = 0
for num in range(number + 1):
total += num
return total
if __name__ == "__main__":
print(summation(1000)) |
a = int(input('Informe um numero:'))
if a%2 == 0 :
print("Par!")
else:
print('Impar!') |
class Piece:
def __init__(self, board, square, white):
self.square = square
self.row = square[0]
self.col = square[1]
self.is_clicked = False #dk if i need this
self._white = white
self.pinned = False
#self.letter
def move(self):
pass
def check_move(self):
if self.is_clicked == True:
pass
def clicked(self):
self.is_clicked = True
#white is uppercase
#black loewrcase
#team
class Not_King(Piece):
def __init__(self, square, white):
#super().__init__(self, fname, lname)
super().__init__(square, white)
self.square = square
self.is_pinned = False
self.is_protected = False
def check_pinned(self):
pass
def check_protection(self):
pass
class King(Piece):
def move(self):
moves = [(-1, -1), (-1, 0), (-1, 1),
(0, -1), (0, 1),
(1, -1), (1, 0), (1, 1),]
pass
#check squares
class Knight(Not_King):
def move(self):
moves = [(-1, -2), (-1, 2), (1, 2), (1,-2),
(-2, -1), (-2, 1), (2, -1), (2, 1)]
#move
#check L shape 2,1
pass
class Pawn(Not_King):
def move(self):
pass
# check squares of board
def __init__(self, board, square, white):
super().__init__(board, square, white)
if self._white:
self.moves = [(-1,0)] #-1 row is going up one row
else:
self.moves = [(1,0)]
def move(self):
pass
def possible_moves(self):
if self._white: #white
#board
pass
else: #black
pass
#
|
print('please input the starting annual salary(annual_salary):')
annual_salary=float(input())
print('please input The portion of salary to be saved (portion_saved):')
portion_saved=float(input())
print("The cost of your dream home (total_cost):")
total_cost=float(input())
portion_down_payment=0.25
current_savings=0
number_of_months=0
savings=0
r=0.04
while(current_savings<total_cost*portion_down_payment):
current_savings=annual_salary/12*portion_saved+current_savings*(1+r/12)
number_of_months=number_of_months+1
print(number_of_months)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
mylist = [ "a", 2, 4.5 ]
myotherlist = mylist[ : ]
mylist[1] = "hello"
print(myotherlist)
mytext = "Hello world"
myothertext = mytext
mytext = "Hallo Welt!"
#print(myothertext)
print(mylist[ : ])
|
'''
Pig Latin: Rules
if word starts with a vowel, add 'ay' to end
if word does not start with a vowel, put first letter at the end, then add 'ay'
word -> ordway
apple -> appleay
'''
def pig_latin(word):
initial_letter = word[0]
if initial_letter in 'aeiou':
translated_word = word + 'ay'
else:
translated_word = word[1:] + initial_letter + 'ay'
return translated_word
print(pig_latin('word'))
print(pig_latin('apple')) |
class Queryable:
"""This superclass holds all common behaviors of a queryable route of
MBTA's API v3"""
@property
def list_route(self):
raise NotImplementedError
class SingularQueryable(Queryable):
def __init__(self, id):
self._id = id
def __eq__(self, other):
return self.id == other.id
@property
def id(self):
return self._id
@property
def id_route(self):
raise NotImplementedError
|
class Break:
def __init__(self, dbRow):
self.flinch = dbRow[0]
self.wound = dbRow[1]
self.sever = dbRow[2]
self.extract = dbRow[3]
self.name = dbRow[4]
def __repr__(self):
return f"{self.__dict__!r}" |
#coding: utf-8
"""
Faça um Programa que peça 2 números inteiros e um número real. Calcule e mostre:
A. o produto do dobro do primeiro com metade do segundo .
B. a soma do triplo do primeiro com o terceiro.
C. o terceiro elevado ao cubo.
"""
i1 = int(input("Digite o 1º número inteiro: "))
i2 = int(input("Digite o 2º número inteiro: "))
r1 = float(input("Digite o número real: "))
a = (i1*2)+(i2/2)
b = (i1*3)+r1
c = r1**3
print()
print("O produto do dobro do primeiro com metade do segundo é", str(a))
print(f"A soma do triplo do primeiro com o terceiro é {b:.2f}")
print(f"O terceiro elevado ao cubo é {c:.2f}")
input() |
cont = 0
qtde = 10
print('Gerador de PA')
print('-=' * 10)
primeiro = int(input('Primeiro termo: '))
r = int(input('Razão da PA: '))
termo = primeiro
while cont < qtde:
cont += 1
print('{} → '.format(termo), end='')
termo += r
if cont == qtde:
print('PAUSA')
mais = int(input('Quantos termos você quer mostrar a mais?'))
qtde += mais
print(f'Progressão finalizada com {qtde} termos mostrados.')
|
# -*- coding: utf-8 -*-
empty_dict = dict()
print(empty_dict)
d = {}
print(type(d))
#zbiory definuje sie set
e = set()
print(type(e))
# klucze nie moga sie w slowniku powtarzac
#w slowniku uporzadkowanie nie jest istotne, i nie jest uporzadkowane
pol_to_eng = {'jeden':'one', 'dwa':'two', 'trzy': 'three'}
name_to_digit = {'Jeden':1, 'dwa':2, 'trzy':3}
#%%
len(name_to_digit)
#dict = {'key1'='value1,'key2'='value2'...}
#%%
#dodawanie kolejnych danych, nie trzeba sie martwic na ktore miejsce, bo
#nie ma uporzadkowania
pol_to_eng['cztery'] = 'four'
#%%
pol_to_eng.clear()
#%%
pol_to_eng_copied = pol_to_eng.copy()
#%%
#wydobycie kluczy ze slownika
pol_to_eng.keys()
#przekonwertowanie kluczy slownika na liste
list(pol_to_eng.keys())
#%%
#wydobycie wartosci ze slownika
pol_to_eng.values()
#przekonwertowanie wartosci slownika na liste
list(pol_to_eng.values())
#%%
# dostaje liste tupli, nie moge zmienic pary "klucz - wartosc"
pol_to_eng.items()
list(pol_to_eng.items())
#%%
pol_to_eng['jeden']
#pol_to_eng['zero']
#%%
#drugi argument podaje to, co jezeli nie ma danego klucza w slowniku
pol_to_eng.get('zero', 'NaN')
#%%
# wartosc usuwana ze struktury
#pol_to_eng.pop('dwa')
pol_to_eng.popitem()
#%%
#aktualizacje danych ktore moga zmieniac sie w czasie
pol_to_eng.update({'jeden':1})
|
class WordDictionary:
def __init__(self, cache=True):
self.cache = cache
def train(self, data):
raise NotImplemented()
def predict(self, data):
raise NotImplemented()
def save(self, model_path):
raise NotImplemented()
def read(self, model_path):
raise NotImplemented()
|
'''
Exercise 2: Odd Or Even
Ask the user for a number. Depending on whether the number is even or odd,
print out an appropriate message to the user. Hint: how does an even / odd
number react differently when divided by 2?
Extras:
If the number is a multiple of 4, print out a different message.
Ask the user for two numbers: one number to check (call it num) and one
number to divide by (check). If check divides evenly into num, tell that
to the user. If not, print a different appropriate message.
'''
input_number = int(input('Please input a number (num):'))
input_check = int(input('Please input a check number (check):'))
result_message = "Your input is an even number." if input_number % 2 == 0 else "Your input is an odd number."
result_message += "\nYour input is a multiple of 4." if input_number % 4 == 0 else ""
number_divided = "divides" if input_number % input_check == 0 else "dose not divide"
result_message += "\nYour input number {yes_or_not} evenly by {check}".format(yes_or_not = number_divided, check = input_check)
print(result_message)
|
"Macros for loading dependencies and registering toolchains"
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
load("@bazel_tools//tools/build_defs/repo:utils.bzl", "maybe")
load("//lib/private:jq_toolchain.bzl", "JQ_PLATFORMS", "jq_host_alias_repo", "jq_platform_repo", "jq_toolchains_repo", _DEFAULT_JQ_VERSION = "DEFAULT_JQ_VERSION")
load("//lib/private:yq_toolchain.bzl", "YQ_PLATFORMS", "yq_host_alias_repo", "yq_platform_repo", "yq_toolchains_repo", _DEFAULT_YQ_VERSION = "DEFAULT_YQ_VERSION")
def aspect_bazel_lib_dependencies():
"Load dependencies required by aspect rules"
maybe(
http_archive,
name = "bazel_skylib",
sha256 = "c6966ec828da198c5d9adbaa94c05e3a1c7f21bd012a0b29ba8ddbccb2c93b0d",
urls = [
"https://github.com/bazelbuild/bazel-skylib/releases/download/1.1.1/bazel-skylib-1.1.1.tar.gz",
"https://mirror.bazel.build/github.com/bazelbuild/bazel-skylib/releases/download/1.1.1/bazel-skylib-1.1.1.tar.gz",
],
)
# Re-export the default versions
DEFAULT_JQ_VERSION = _DEFAULT_JQ_VERSION
DEFAULT_YQ_VERSION = _DEFAULT_YQ_VERSION
def register_jq_toolchains(name = "jq", version = DEFAULT_JQ_VERSION, register = True):
"""Registers jq toolchain and repositories
Args:
name: override the prefix for the generated toolchain repositories
version: the version of jq to execute (see https://github.com/stedolan/jq/releases)
register: whether to call through to native.register_toolchains.
Should be True for WORKSPACE users, but false when used under bzlmod extension
"""
for [platform, meta] in JQ_PLATFORMS.items():
jq_platform_repo(
name = "%s_%s" % (name, platform),
platform = platform,
version = version,
)
if register:
native.register_toolchains("@%s_toolchains//:%s_toolchain" % (name, platform))
jq_host_alias_repo(name = name)
jq_toolchains_repo(
name = "%s_toolchains" % name,
user_repository_name = name,
)
def register_yq_toolchains(name = "yq", version = DEFAULT_YQ_VERSION, register = True):
"""Registers yq toolchain and repositories
Args:
name: override the prefix for the generated toolchain repositories
version: the version of yq to execute (see https://github.com/mikefarah/yq/releases)
register: whether to call through to native.register_toolchains.
Should be True for WORKSPACE users, but false when used under bzlmod extension
"""
for [platform, meta] in YQ_PLATFORMS.items():
yq_platform_repo(
name = "%s_%s" % (name, platform),
platform = platform,
version = version,
)
if register:
native.register_toolchains("@%s_toolchains//:%s_toolchain" % (name, platform))
yq_host_alias_repo(name = name)
yq_toolchains_repo(
name = "%s_toolchains" % name,
user_repository_name = name,
)
|
# wwwhisper - web access control.
# Copyright (C) 2012-2018 Jan Wrobel <jan@mixedbit.org>
"""wwwhisper authentication and authorization.
The package defines model that associates users with locations that
each user can access and exposes API for checking and manipulating
permissions. It also provides REST API to login, logout a
user and to check if a currently logged in user can access a given
location.
"""
|
# Copyright 2017 Neural Networks and Deep Learning lab, MIPT
#
# 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.
"""
Description of the module agents.paraphraser:
The task of the module
To recognize whether two sentences are paraphrases or not. The module should give
a positive answer in the case if two sentences are paraphrases, and a negative answer in the other case.
Models architecture
All models use Siamese architecture. Word embeddings to models are provided by the pretrained fastText model.
A sentence level context is taken into account using LSTM or bi-LSTM layer. Most models use attention to identify
similar parts in sentences. Currently implemented types of attention include multiplicative attention [1] and various
types of multi-perspective matching [2]. After the attention layer the absolute value of the difference and element-wise
product of two vectors representing the sentences are calculated. These vectors are concatenated and input to dense
layer with a sigmoid activation performing final classification. The chosen model is trained k times, where k equals to
the '--bagging-folds-number' parameter corresponding to the number of data folds. Predictions of the model trained on
various data subsets are averaged at testing time (bagging). There is a possibility to choose few models for training
at once. Each of them will be trained and their predictions will be averaged at testing time (ensembling).
[1] Luong, M.-T., Pham, H., & Manning, C. D. (2015). Effective Approaches to Attention-based Neural Machine Translation.
EMNLP 2015. CoRR, abs/1508.04025
[2] Zhiguo Wang, Wael Hamza, & Radu Florian. Bilateral multi-perspective matching for natural language sentences.
CoRR, abs/1702.03814, 2017.
""" |
#!/usr/bin/env python
# Copyright (c) 2019 VMware, Inc. All Rights Reserved.
# SPDX-License-Identifier: BSD-2 License
# The full license information can be found in LICENSE.txt
# in the root directory of this project.
SERVER_CONSTANTS = (
REQUEST_QUEUE_SIZE, PACKET_SIZE, ALLOW_REUSE_ADDRESS
) = (
100, 1024, True
)
|
class Formatting:
"""Terminal formatting constants"""
SUCCESS = '\033[92m'
INFO = '\033[94m'
WARNING = '\033[93m'
END = '\033[0m'
|
class Stack:
def __init__(self, stack=[], lim=None):
self._stack = stack
self._lim = lim
def push(self, data):
if self._lim is not None and len(self._stack) == self._lim:
print("~~STACK OVERFLOW~~")
return
self._stack.append(int(data))
def pop(self):
if len(self._stack) == 0:
print("~~STACK UNDERFLOW~~")
return None
return self._stack.pop()
def __str__(self):
return str(self._stack)
if __name__ == '__main__':
stack = Stack(lim=10)
print("1. Push to stack")
print("2. Pop stack")
print("3. Print stack")
while True:
inp = input("Your choice: ")
if inp == "1":
stack.push(input(" Enter element: "))
elif inp == "2":
print(" Element removed:", stack.pop())
else:
print(stack)
|
### Code is based on PySimpleAutomata (https://github.com/Oneiroe/PySimpleAutomata/)
# MIT License
# Copyright (c) 2017 Alessio Cecconi
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
def _epsilon_closure(states, epsilon, transitions):
## add epsilon closure
new_states = states
while new_states:
curr_states = set()
for state in new_states:
curr_states.update(transitions.get(state, {}).get(epsilon, set()))
new_states = curr_states - states
states.update(curr_states)
def nfa_determinization(nfa: dict, any_input=None, epsilon=None) -> dict:
dfa = {
'initial_state': None,
'accepting_states': set(),
'transitions': dict()
}
initial_states = nfa['initial_states']
_epsilon_closure(initial_states, epsilon, nfa['transitions'])
initial_states = frozenset(initial_states)
dfa['initial_state'] = initial_states
if initial_states.intersection(nfa['accepting_states']):
dfa['accepting_states'].add(initial_states)
sets_states = set()
sets_queue = list()
sets_queue.append(initial_states)
sets_states.add(initial_states)
while sets_queue:
current_set = sets_queue.pop(0)
new_transitions = {}
for state in current_set:
old_transitions = nfa['transitions'].get(state, {})
for a in old_transitions.keys():
if a != epsilon:
new_transitions[a] = new_transitions.get(a, set()) | old_transitions[a]
for char, value in new_transitions.items():
next_set = value | new_transitions.get(any_input, set())
_epsilon_closure(next_set, epsilon, nfa['transitions'])
next_set = frozenset(next_set)
if next_set not in sets_states:
sets_states.add(next_set)
sets_queue.append(next_set)
if next_set.intersection(nfa['accepting_states']):
dfa['accepting_states'].add(next_set)
dfa['transitions'].setdefault(current_set, {})[char] = next_set
return dfa
def dfa_intersection_language(dfa_1: dict, dfa_2: dict, any_input=None) -> dict:
language = set()
boundary = [(dfa_1['initial_state'], dfa_2['initial_state'])]
while boundary:
(state_dfa_1, state_dfa_2) = boundary.pop()
if state_dfa_1 in dfa_1['accepting_states'] and state_dfa_2 in dfa_2['accepting_states']:
language.add((state_dfa_1, state_dfa_2))
if any_input in dfa_1['transitions'].get(state_dfa_1, {}):
characters = dfa_2['transitions'].get(state_dfa_2, {}).keys()
elif any_input in dfa_2['transitions'].get(state_dfa_2, {}):
characters = dfa_1['transitions'].get(state_dfa_1, {}).keys()
else:
characters = set(dfa_1['transitions'].get(state_dfa_1, {}).keys()).intersection(dfa_2['transitions'].get(state_dfa_2, {}).keys())
for a in characters:
next_state_1 = dfa_1['transitions'][state_dfa_1].get(a, dfa_1['transitions'][state_dfa_1].get(any_input, frozenset()))
next_state_2 = dfa_2['transitions'][state_dfa_2].get(a, dfa_2['transitions'][state_dfa_2].get(any_input, frozenset()))
boundary.append((next_state_1, next_state_2))
return language
|
def ab(b):
c=input("Term To Be Search:")
if c in b:
print ("Term Found")
else:
print ("Term Not Found")
a=[]
while True:
b=input("Enter Term(To terminate type Exit):")
if b=='Exit' or b=='exit':
break
else:
a.append(b)
ab(a)
|
n = int(input())
def weird(n):
string = str(n)
while n != 1:
if n%2 == 0:
n = n//2
string += ' ' + str(n)
else:
n = n*3 + 1
string += ' ' + str(n)
return string
print(weird(n)) |
PRICES = [0.01, 0.02, 0.05, 0.10, 0.20, 0.50, 1, 2]
QUESTIONS = [
"Voer het aantal 1 centen in:\n",
"Voer het aantal 2 centen in: \n",
"Voer het aantal 5 centen in: \n",
"Voer het aantal 10 centen in: \n",
"Voer het aantal 20 centen in: \n",
"Voer het aantal 50 centen in: \n",
"Voer het aantal 1 euro's in: \n",
"Voer het aantal 2 euro's in: \n"
]
if __name__ == '__main__':
munten = [int(input(question)) for question in QUESTIONS]
aantal_munten = sum(munten)
totale_waarde = sum(quantity * value for (quantity, value) in zip(munten, PRICES))
print("Totaal aantal munten: {}".format(aantal_munten))
print("Totale waarde van de munten: {} euro".format(totale_waarde)) |
spec = {
'name' : "The devil's work...",
'external network name' : "exnet3",
'keypair' : "openstack_rsa",
'controller' : "r720",
'dns' : "10.30.65.200",
'credentials' : { 'user' : "nic", 'password' : "nic", 'project' : "nic" },
'Networks' : [
{ 'name' : "merlynctl" , "start": "172.16.1.2", "end": "172.16.1.100", "subnet" :" 172.16.1.0/24", "gateway": "172.16.1.1" },
{ 'name' : "merlyn201" , "start": "192.168.1.201", "end": "192.168.1.202", "subnet" :" 192.168.1.0/24", "vlan": 201, "physical_network": "vlannet" },
{ 'name' : "merlyn202" , "start": "192.168.1.202", "end": "192.168.1.203", "subnet" :" 192.168.1.0/24", "vlan": 202, "physical_network": "vlannet" }
],
'Hosts' : [
{ 'name' : "monos" , 'image' : "centos7.2" , 'flavor':"m1.large" , 'net' : [ ("merlynctl","*","10.30.65.130")] },
{ 'name' : "m201" , 'image' : "centos7.2" , 'flavor':"m1.medium" , 'net' : [ ("merlynctl","*","10.30.65.131"),("merlyn201" , "192.168.1.201") ] },
{ 'name' : "m202" , 'image' : "centos7.2" , 'flavor':"m1.medium" , 'net' : [ ("merlynctl","*","10.30.65.132"),("merlyn202" , "192.168.1.202") ] },
]
}
|
# coding: utf-8
# fields names
BITMAP = 'bitmap'
COLS = 'cols'
DATA = 'data'
EXTERIOR = 'exterior'
INTERIOR = 'interior'
MULTICHANNEL_BITMAP = 'multichannel_bitmap'
ORIGIN = 'origin'
POINTS = 'points'
ROWS = 'rows'
TYPE = 'type'
NODES = 'nodes'
EDGES = 'edges'
ENABLED = 'enabled'
LABEL = 'label'
COLOR = 'color'
TEMPLATE = 'template'
LOCATION = 'location'
|
# Data taken from the MathML 2.0 reference
data = '''
"(" form="prefix" fence="true" stretchy="true" lspace="0em" rspace="0em"
")" form="postfix" fence="true" stretchy="true" lspace="0em" rspace="0em"
"[" form="prefix" fence="true" stretchy="true" lspace="0em" rspace="0em"
"]" form="postfix" fence="true" stretchy="true" lspace="0em" rspace="0em"
"{" form="prefix" fence="true" stretchy="true" lspace="0em" rspace="0em"
"}" form="postfix" fence="true" stretchy="true" lspace="0em" rspace="0em"
"”" form="postfix" fence="true" lspace="0em" rspace="0em"
"’" form="postfix" fence="true" lspace="0em" rspace="0em"
"⟨" form="prefix" fence="true" stretchy="true" lspace="0em" rspace="0em"
"&LeftBracketingBar;" form="prefix" fence="true" stretchy="true" lspace="0em" rspace="0em"
"⌈" form="prefix" fence="true" stretchy="true" lspace="0em" rspace="0em"
"⟦" form="prefix" fence="true" stretchy="true" lspace="0em" rspace="0em"
"&LeftDoubleBracketingBar;" form="prefix" fence="true" stretchy="true" lspace="0em" rspace="0em"
"⌊" form="prefix" fence="true" stretchy="true" lspace="0em" rspace="0em"
"“" form="prefix" fence="true" lspace="0em" rspace="0em"
"‘" form="prefix" fence="true" lspace="0em" rspace="0em"
"⟩" form="postfix" fence="true" stretchy="true" lspace="0em" rspace="0em"
"&RightBracketingBar;" form="postfix" fence="true" stretchy="true" lspace="0em" rspace="0em"
"⌉" form="postfix" fence="true" stretchy="true" lspace="0em" rspace="0em"
"⟧" form="postfix" fence="true" stretchy="true" lspace="0em" rspace="0em"
"&RightDoubleBracketingBar;" form="postfix" fence="true" stretchy="true" lspace="0em" rspace="0em"
"⌋" form="postfix" fence="true" stretchy="true" lspace="0em" rspace="0em"
"&LeftSkeleton;" form="prefix" fence="true" lspace="0em" rspace="0em"
"&RightSkeleton;" form="postfix" fence="true" lspace="0em" rspace="0em"
"⁣" form="infix" separator="true" lspace="0em" rspace="0em"
"," form="infix" separator="true" lspace="0em" rspace="verythickmathspace"
"─" form="infix" stretchy="true" minsize="0" lspace="0em" rspace="0em"
"|" form="infix" stretchy="true" minsize="0" lspace="0em" rspace="0em"
";" form="infix" separator="true" lspace="0em" rspace="thickmathspace"
";" form="postfix" separator="true" lspace="0em" rspace="0em"
":=" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"≔" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"∵" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"∴" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"❘" form="infix" stretchy="true" lspace="thickmathspace" rspace="thickmathspace"
"//" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"∷" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"&" form="prefix" lspace="0em" rspace="thickmathspace"
"&" form="postfix" lspace="thickmathspace" rspace="0em"
"*=" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"-=" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"+=" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"/=" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"->" form="infix" lspace="thickmathspace" rspace="thickmathspace"
":" form="infix" lspace="thickmathspace" rspace="thickmathspace"
".." form="postfix" lspace="mediummathspace" rspace="0em"
"..." form="postfix" lspace="mediummathspace" rspace="0em"
"∋" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"⫤" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"⊨" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"⊤" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"⊣" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"⊢" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"⇒" form="infix" stretchy="true" lspace="thickmathspace" rspace="thickmathspace"
"⥰" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"|" form="infix" stretchy="true" lspace="thickmathspace" rspace="thickmathspace"
"||" form="infix" lspace="mediummathspace" rspace="mediummathspace"
"⩔" form="infix" stretchy="true" lspace="mediummathspace" rspace="mediummathspace"
"&&" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"⩓" form="infix" stretchy="true" lspace="mediummathspace" rspace="mediummathspace"
"&" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"!" form="prefix" lspace="0em" rspace="thickmathspace"
"⫬" form="prefix" lspace="0em" rspace="thickmathspace"
"∃" form="prefix" lspace="0em" rspace="thickmathspace"
"∀" form="prefix" lspace="0em" rspace="thickmathspace"
"∄" form="prefix" lspace="0em" rspace="thickmathspace"
"∈" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"∉" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"∌" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"⊏̸" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"⋢" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"⊐̸" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"⋣" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"⊂⃒" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"⊈" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"⊃⃒" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"⊉" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"∋" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"⊏" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"⊑" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"⊐" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"⊒" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"⋐" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"⊆" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"⊃" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"⊇" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"⇐" form="infix" stretchy="true" lspace="thickmathspace" rspace="thickmathspace"
"⇔" form="infix" stretchy="true" lspace="thickmathspace" rspace="thickmathspace"
"⇒" form="infix" stretchy="true" lspace="thickmathspace" rspace="thickmathspace"
"⥐" form="infix" stretchy="true" lspace="thickmathspace" rspace="thickmathspace"
"⥞" form="infix" stretchy="true" lspace="thickmathspace" rspace="thickmathspace"
"↽" form="infix" stretchy="true" lspace="thickmathspace" rspace="thickmathspace"
"⥖" form="infix" stretchy="true" lspace="thickmathspace" rspace="thickmathspace"
"⥟" form="infix" stretchy="true" lspace="thickmathspace" rspace="thickmathspace"
"⇁" form="infix" stretchy="true" lspace="thickmathspace" rspace="thickmathspace"
"⥗" form="infix" stretchy="true" lspace="thickmathspace" rspace="thickmathspace"
"←" form="infix" stretchy="true" lspace="thickmathspace" rspace="thickmathspace"
"⇤" form="infix" stretchy="true" lspace="thickmathspace" rspace="thickmathspace"
"⇆" form="infix" stretchy="true" lspace="thickmathspace" rspace="thickmathspace"
"↔" form="infix" stretchy="true" lspace="thickmathspace" rspace="thickmathspace"
"⥎" form="infix" stretchy="true" lspace="thickmathspace" rspace="thickmathspace"
"↤" form="infix" stretchy="true" lspace="thickmathspace" rspace="thickmathspace"
"⥚" form="infix" stretchy="true" lspace="thickmathspace" rspace="thickmathspace"
"↼" form="infix" stretchy="true" lspace="thickmathspace" rspace="thickmathspace"
"⥒" form="infix" stretchy="true" lspace="thickmathspace" rspace="thickmathspace"
"↙" form="infix" stretchy="true" lspace="thickmathspace" rspace="thickmathspace"
"↘" form="infix" stretchy="true" lspace="thickmathspace" rspace="thickmathspace"
"→" form="infix" stretchy="true" lspace="thickmathspace" rspace="thickmathspace"
"⇥" form="infix" stretchy="true" lspace="thickmathspace" rspace="thickmathspace"
"⇄" form="infix" stretchy="true" lspace="thickmathspace" rspace="thickmathspace"
"↦" form="infix" stretchy="true" lspace="thickmathspace" rspace="thickmathspace"
"⥛" form="infix" stretchy="true" lspace="thickmathspace" rspace="thickmathspace"
"⇀" form="infix" stretchy="true" lspace="thickmathspace" rspace="thickmathspace"
"⥓" form="infix" stretchy="true" lspace="thickmathspace" rspace="thickmathspace"
"←" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"→" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"↖" form="infix" stretchy="true" lspace="thickmathspace" rspace="thickmathspace"
"↗" form="infix" stretchy="true" lspace="thickmathspace" rspace="thickmathspace"
"=" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"<" form="infix" lspace="thickmathspace" rspace="thickmathspace"
">" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"!=" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"==" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"<=" form="infix" lspace="thickmathspace" rspace="thickmathspace"
">=" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"≡" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"≍" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"≐" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"∥" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"⩵" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"≂" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"⇌" form="infix" stretchy="true" lspace="thickmathspace" rspace="thickmathspace"
"≥" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"⋛" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"≧" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"⪢" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"≷" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"⩾" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"≳" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"≎" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"≏" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"⊲" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"⧏" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"⊴" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"≤" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"⋚" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"≦" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"≶" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"⪡" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"⩽" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"≲" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"≫" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"≪" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"≢" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"≭" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"∦" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"≠" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"≂̸" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"≯" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"≱" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"≧̸" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"≫̸" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"≹" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"⩾̸" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"≵" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"≎̸" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"≏̸" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"⋪" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"⧏̸" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"⋬" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"≮" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"≰" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"&NotLessFullEqual;" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"≸" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"≪̸" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"⩽̸" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"≴" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"⪢̸" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"⪡̸" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"⊀" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"⪯̸" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"⋠" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"&NotPrecedesTilde;" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"⋫" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"⧐̸" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"⋭" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"⊁" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"⪰̸" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"⋡" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"≿̸" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"≁" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"≄" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"≇" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"≉" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"∤" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"≺" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"⪯" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"≼" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"≾" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"∷" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"∝" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"⇋" form="infix" stretchy="true" lspace="thickmathspace" rspace="thickmathspace"
"⊳" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"⧐" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"⊵" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"≻" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"⪰" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"≽" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"≿" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"∼" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"≃" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"≅" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"≈" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"⊥" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"∣" form="infix" lspace="thickmathspace" rspace="thickmathspace"
"⊔" form="infix" stretchy="true" lspace="mediummathspace" rspace="mediummathspace"
"⋃" form="infix" stretchy="true" lspace="mediummathspace" rspace="mediummathspace"
"⊎" form="infix" stretchy="true" lspace="mediummathspace" rspace="mediummathspace"
"-" form="infix" lspace="mediummathspace" rspace="mediummathspace"
"+" form="infix" lspace="mediummathspace" rspace="mediummathspace"
"⋂" form="infix" stretchy="true" lspace="mediummathspace" rspace="mediummathspace"
"∓" form="infix" lspace="mediummathspace" rspace="mediummathspace"
"±" form="infix" lspace="mediummathspace" rspace="mediummathspace"
"⊓" form="infix" stretchy="true" lspace="mediummathspace" rspace="mediummathspace"
"⋁" form="prefix" largeop="true" movablelimits="true" stretchy="true" lspace="0em" rspace="thinmathspace"
"⊖" form="prefix" largeop="true" movablelimits="true" lspace="0em" rspace="thinmathspace"
"⊕" form="prefix" largeop="true" movablelimits="true" lspace="0em" rspace="thinmathspace"
"∑" form="prefix" largeop="true" movablelimits="true" stretchy="true" lspace="0em" rspace="thinmathspace"
"⋃" form="prefix" largeop="true" movablelimits="true" stretchy="true" lspace="0em" rspace="thinmathspace"
"⊎" form="prefix" largeop="true" movablelimits="true" stretchy="true" lspace="0em" rspace="thinmathspace"
"lim" form="prefix" movablelimits="true" lspace="0em" rspace="thinmathspace"
"max" form="prefix" movablelimits="true" lspace="0em" rspace="thinmathspace"
"min" form="prefix" movablelimits="true" lspace="0em" rspace="thinmathspace"
"⊖" form="infix" lspace="thinmathspace" rspace="thinmathspace"
"⊕" form="infix" lspace="thinmathspace" rspace="thinmathspace"
"∲" form="prefix" largeop="true" stretchy="true" lspace="0em" rspace="0em"
"∮" form="prefix" largeop="true" stretchy="true" lspace="0em" rspace="0em"
"∳" form="prefix" largeop="true" stretchy="true" lspace="0em" rspace="0em"
"∯" form="prefix" largeop="true" stretchy="true" lspace="0em" rspace="0em"
"∫" form="prefix" largeop="true" stretchy="true" lspace="0em" rspace="0em"
"⋓" form="infix" lspace="thinmathspace" rspace="thinmathspace"
"⋒" form="infix" lspace="thinmathspace" rspace="thinmathspace"
"≀" form="infix" lspace="thinmathspace" rspace="thinmathspace"
"⋀" form="prefix" largeop="true" movablelimits="true" stretchy="true" lspace="0em" rspace="thinmathspace"
"⊗" form="prefix" largeop="true" movablelimits="true" lspace="0em" rspace="thinmathspace"
"∐" form="prefix" largeop="true" movablelimits="true" stretchy="true" lspace="0em" rspace="thinmathspace"
"∏" form="prefix" largeop="true" movablelimits="true" stretchy="true" lspace="0em" rspace="thinmathspace"
"⋂" form="prefix" largeop="true" movablelimits="true" stretchy="true" lspace="0em" rspace="thinmathspace"
"∐" form="infix" lspace="thinmathspace" rspace="thinmathspace"
"⋆" form="infix" lspace="thinmathspace" rspace="thinmathspace"
"⊙" form="prefix" largeop="true" movablelimits="true" lspace="0em" rspace="thinmathspace"
"*" form="infix" lspace="thinmathspace" rspace="thinmathspace"
"⁢" form="infix" lspace="0em" rspace="0em"
"·" form="infix" lspace="thinmathspace" rspace="thinmathspace"
"⊗" form="infix" lspace="thinmathspace" rspace="thinmathspace"
"⋁" form="infix" lspace="thinmathspace" rspace="thinmathspace"
"⋀" form="infix" lspace="thinmathspace" rspace="thinmathspace"
"⋄" form="infix" lspace="thinmathspace" rspace="thinmathspace"
"∖" form="infix" stretchy="true" lspace="thinmathspace" rspace="thinmathspace"
"/" form="infix" stretchy="true" lspace="thinmathspace" rspace="thinmathspace"
"-" form="prefix" lspace="0em" rspace="veryverythinmathspace"
"+" form="prefix" lspace="0em" rspace="veryverythinmathspace"
"∓" form="prefix" lspace="0em" rspace="veryverythinmathspace"
"±" form="prefix" lspace="0em" rspace="veryverythinmathspace"
"." form="infix" lspace="0em" rspace="0em"
"⨯" form="infix" lspace="verythinmathspace" rspace="verythinmathspace"
"**" form="infix" lspace="verythinmathspace" rspace="verythinmathspace"
"⊙" form="infix" lspace="verythinmathspace" rspace="verythinmathspace"
"∘" form="infix" lspace="verythinmathspace" rspace="verythinmathspace"
"□" form="prefix" lspace="0em" rspace="verythinmathspace"
"∇" form="prefix" lspace="0em" rspace="verythinmathspace"
"∂" form="prefix" lspace="0em" rspace="verythinmathspace"
"ⅅ" form="prefix" lspace="0em" rspace="verythinmathspace"
"ⅆ" form="prefix" lspace="0em" rspace="verythinmathspace"
"√" form="prefix" stretchy="true" lspace="0em" rspace="verythinmathspace"
"⇓" form="infix" stretchy="true" lspace="verythinmathspace" rspace="verythinmathspace"
"⟸" form="infix" stretchy="true" lspace="verythinmathspace" rspace="verythinmathspace"
"⟺" form="infix" stretchy="true" lspace="verythinmathspace" rspace="verythinmathspace"
"⟹" form="infix" stretchy="true" lspace="verythinmathspace" rspace="verythinmathspace"
"⇑" form="infix" stretchy="true" lspace="verythinmathspace" rspace="verythinmathspace"
"⇕" form="infix" stretchy="true" lspace="verythinmathspace" rspace="verythinmathspace"
"↓" form="infix" stretchy="true" lspace="verythinmathspace" rspace="verythinmathspace"
"⤓" form="infix" stretchy="true" lspace="verythinmathspace" rspace="verythinmathspace"
"⇵" form="infix" stretchy="true" lspace="verythinmathspace" rspace="verythinmathspace"
"↧" form="infix" stretchy="true" lspace="verythinmathspace" rspace="verythinmathspace"
"⥡" form="infix" stretchy="true" lspace="verythinmathspace" rspace="verythinmathspace"
"⇃" form="infix" stretchy="true" lspace="verythinmathspace" rspace="verythinmathspace"
"⥙" form="infix" stretchy="true" lspace="verythinmathspace" rspace="verythinmathspace"
"⥑" form="infix" stretchy="true" lspace="verythinmathspace" rspace="verythinmathspace"
"⥠" form="infix" stretchy="true" lspace="verythinmathspace" rspace="verythinmathspace"
"↿" form="infix" stretchy="true" lspace="verythinmathspace" rspace="verythinmathspace"
"⥘" form="infix" stretchy="true" lspace="verythinmathspace" rspace="verythinmathspace"
"⟵" form="infix" stretchy="true" lspace="verythinmathspace" rspace="verythinmathspace"
"⟷" form="infix" stretchy="true" lspace="verythinmathspace" rspace="verythinmathspace"
"⟶" form="infix" stretchy="true" lspace="verythinmathspace" rspace="verythinmathspace"
"⥯" form="infix" stretchy="true" lspace="verythinmathspace" rspace="verythinmathspace"
"⥝" form="infix" stretchy="true" lspace="verythinmathspace" rspace="verythinmathspace"
"⇂" form="infix" stretchy="true" lspace="verythinmathspace" rspace="verythinmathspace"
"⥕" form="infix" stretchy="true" lspace="verythinmathspace" rspace="verythinmathspace"
"⥏" form="infix" stretchy="true" lspace="verythinmathspace" rspace="verythinmathspace"
"⥜" form="infix" stretchy="true" lspace="verythinmathspace" rspace="verythinmathspace"
"↾" form="infix" stretchy="true" lspace="verythinmathspace" rspace="verythinmathspace"
"⥔" form="infix" stretchy="true" lspace="verythinmathspace" rspace="verythinmathspace"
"↓" form="infix" lspace="verythinmathspace" rspace="verythinmathspace"
"↑" form="infix" lspace="verythinmathspace" rspace="verythinmathspace"
"↑" form="infix" stretchy="true" lspace="verythinmathspace" rspace="verythinmathspace"
"⤒" form="infix" stretchy="true" lspace="verythinmathspace" rspace="verythinmathspace"
"⇅" form="infix" stretchy="true" lspace="verythinmathspace" rspace="verythinmathspace"
"↕" form="infix" stretchy="true" lspace="verythinmathspace" rspace="verythinmathspace"
"⥮" form="infix" stretchy="true" lspace="verythinmathspace" rspace="verythinmathspace"
"↥" form="infix" stretchy="true" lspace="verythinmathspace" rspace="verythinmathspace"
"^" form="infix" lspace="verythinmathspace" rspace="verythinmathspace"
"<>" form="infix" lspace="verythinmathspace" rspace="verythinmathspace"
"'" form="postfix" lspace="verythinmathspace" rspace="0em"
"!" form="postfix" lspace="verythinmathspace" rspace="0em"
"!!" form="postfix" lspace="verythinmathspace" rspace="0em"
"~" form="infix" lspace="verythinmathspace" rspace="verythinmathspace"
"@" form="infix" lspace="verythinmathspace" rspace="verythinmathspace"
"--" form="postfix" lspace="verythinmathspace" rspace="0em"
"--" form="prefix" lspace="0em" rspace="verythinmathspace"
"++" form="postfix" lspace="verythinmathspace" rspace="0em"
"++" form="prefix" lspace="0em" rspace="verythinmathspace"
"⁡" form="infix" lspace="0em" rspace="0em"
"?" form="infix" lspace="verythinmathspace" rspace="verythinmathspace"
"_" form="infix" lspace="verythinmathspace" rspace="verythinmathspace"
"˘" form="postfix" accent="true" lspace="0em" rspace="0em"
"¸" form="postfix" accent="true" lspace="0em" rspace="0em"
"`" form="postfix" accent="true" lspace="0em" rspace="0em"
"˙" form="postfix" accent="true" lspace="0em" rspace="0em"
"˝" form="postfix" accent="true" lspace="0em" rspace="0em"
"&DiacriticalLeftArrow;" form="postfix" accent="true" stretchy="true" lspace="0em" rspace="0em"
"&DiacriticalLeftRightArrow;" form="postfix" accent="true" stretchy="true" lspace="0em" rspace="0em"
"&DiacriticalLeftRightVector;" form="postfix" accent="true" stretchy="true" lspace="0em" rspace="0em"
"&DiacriticalLeftVector;" form="postfix" accent="true" stretchy="true" lspace="0em" rspace="0em"
"´" form="postfix" accent="true" lspace="0em" rspace="0em"
"&DiacriticalRightArrow;" form="postfix" accent="true" stretchy="true" lspace="0em" rspace="0em"
"&DiacriticalRightVector;" form="postfix" accent="true" stretchy="true" lspace="0em" rspace="0em"
"˜" form="postfix" accent="true" stretchy="true" lspace="0em" rspace="0em"
"¨" form="postfix" accent="true" lspace="0em" rspace="0em"
"̑" form="postfix" accent="true" lspace="0em" rspace="0em"
"ˇ" form="postfix" accent="true" stretchy="true" lspace="0em" rspace="0em"
"^" form="postfix" accent="true" stretchy="true" lspace="0em" rspace="0em"
"‾" form="postfix" accent="true" stretchy="true" lspace="0em" rspace="0em"
"⏞" form="postfix" accent="true" stretchy="true" lspace="0em" rspace="0em"
"⎴" form="postfix" accent="true" stretchy="true" lspace="0em" rspace="0em"
"⏜" form="postfix" accent="true" stretchy="true" lspace="0em" rspace="0em"
"⃛" form="postfix" accent="true" lspace="0em" rspace="0em"
"_" form="postfix" accent="true" stretchy="true" lspace="0em" rspace="0em"
"⏟" form="postfix" accent="true" stretchy="true" lspace="0em" rspace="0em"
"⎵" form="postfix" accent="true" stretchy="true" lspace="0em" rspace="0em"
"⏝" form="postfix" accent="true" stretchy="true" lspace="0em" rspace="0em"
'''
|
# -*- coding: utf-8 -*-
# User role
USER = 0
ADMIN = 1
USER_ROLE = {
ADMIN: 'admin',
USER: 'user',
}
# User status
INACTIVE = 0
ACTIVE = 1
USER_STATUS = {
INACTIVE: 'inactive',
ACTIVE: 'active',
}
# Project progress
PR_CHALLENGE = -1
PR_NEW = 0
PR_RESEARCHED = 10
PR_SKETCHED = 20
PR_PROTOTYPED = 30
PR_LAUNCHED = 40
PR_LIVE = 50
PROJECT_PROGRESS = {
PR_CHALLENGE: 'This is an idea or challenge description',
PR_NEW: 'A team has formed and started a project',
PR_RESEARCHED: 'Research has been done to define the scope',
PR_SKETCHED: 'Initial designs have been sketched and shared',
PR_PROTOTYPED: 'A prototype of the idea has been developed',
PR_LAUNCHED: 'The prototype has been deployed and presented',
PR_LIVE: 'This project is live and available to the public',
}
PROJECT_PROGRESS_PHASE = {
PR_NEW: 'Researching',
PR_RESEARCHED: 'Sketching',
PR_SKETCHED: 'Prototyping',
PR_PROTOTYPED: 'Launching',
PR_LAUNCHED: 'Promoting',
PR_LIVE: 'Supporting',
PR_CHALLENGE: 'Challenge',
}
def projectProgressList(All=True):
if not All:
return [(PR_CHALLENGE, PROJECT_PROGRESS[PR_CHALLENGE])]
pl = [(g, PROJECT_PROGRESS[g]) for g in PROJECT_PROGRESS]
return sorted(pl, key=lambda x: x[0])
|
"""
This script allows you to hijack http/https networks. Before you start use this commands on Kali machine
1. Enable ip forwarding: echo 1 > /proc/sys/net/ipv4/ip_forward
2. Activate your packets Queues
- If want to test on your machine: iptables -I OUTPUT -j NFQUEUE --queue-num 0;iptables -I INPUT -j NFQUEUE --queue-num 0
- If want to use another machine: iptables -I FORWARD -j NFQUEUE --queue-num 0
3. Enable SSLStriper: sslstrip
4. Enable prerouting: iptables -t nat -A PREROUTING -p tcp --destination-port 80 -j REDIRECT --to-port 10000
5. Enable your web_service: service apache2 start
"""
|
q = int(input())
e = str(input()).split()
indq = 0
mini = int(e[0])
for i in range(1, len(e)):
if int(e[i]) > mini:
mini = int(e[i])
elif int(e[i]) < mini:
indq = i + 1
break
print(indq)
|
__version__ = "1.8.0"
__all__ = ["epsonprinter","testpage"]
|
'''Classe Bola: Crie uma classe que modele uma bola:
Atributos: Cor, circunferência, material
Métodos: trocaCor e mostraCor
'''
class Bola:
def __init__(self, cor=None, circ=None, material=None):
self.cor = cor
self.circ = circ
self.material = material
def mostra_cor(self):
return self.cor
def troca_cor(self, nova_cor):
nova_cor = 'Azul'
self.cor = nova_cor
return self.cor
if __name__ == '__main__':
print('Bola:')
bola = Bola('Branca', 15.5, 'Couro')
print()
bola.mostra_cor()
print()
bola.troca_cor('Azul')
print()
bola.mostra_cor() |
class RequestExeption(Exception):
def __init__(self, request):
self.request = request
def badRequest(self):
self.message = "bad request url : %s" % self.request.url
return self
def __str__(self):
return self.message
|
class Solution:
def dieSimulator(self, n: int, rollMax: List[int]) -> int:
# dp[i][j]: how many choices we have with i dices and the last face is j
# again dp[i][j] means the number of distinct sequences that can be obtained when rolling i times and ending with j
MOD = 10 ** 9 + 7
dp = [[0] * 7 for i in range(n + 1)]
# dp[1][i]: roll once, end with i => only one possible sequence. so dp[1][i] = 1
for i in range(6):
dp[1][i] = 1
# total
dp[1][6] = 6
for i in range(2, n + 1):
total = 0
for j in range(6):
# if there is no constrains, the total sequences ending with j should be the total sequences from previous rolling
dp[i][j] = dp[i - 1][6]
# for axx1, only 111 is not allowed, so we need to remove 1 sequence from previous sum
if i - rollMax[j] == 1:
dp[i][j] -= 1
# for axx1, we need to remove the number of a11(211, 311, 411...)
if i - rollMax[j] >= 2:
reduction = dp[i - rollMax[j] - 1][6] - dp[i - rollMax[j] - 1][j]
dp[i][j] = ((dp[i][j] - reduction) % MOD + MOD) % MOD
total = (total + dp[i][j]) % MOD
dp[i][6] = total
return dp[n][6]
|
n1 = int(input('Digite um valor: '))
n2 = int(input('Digite um valor: '))
n3 = int(input('Digite um valor: '))
menor = n1
maior = n2
if n2 < n1 and n2 < 3:
menor = n2
if n3 < n1 and n3 < n2:
menor = n3
if n1 > n2 and n1 > n3:
maior = n1
if n3 > n1 and n3 > n2:
maior = n3
print(f'O maior valor digitado foi {maior}')
print(f'O menor valor digitado foi {menor}') |
# a = ['a1','aa1','a2','aaa1']
# a.sort()
# print(a)
# print(2346/10)
def repeat_to_length(string_to_expand, length):
return (string_to_expand * (int(length/len(string_to_expand))+1))[:length]
for i in range(200):
if i > 10:
strnum = str(i)
tens = int(strnum[0:-1])
last = strnum[-1]
print(strnum)
print(tens)
print(repeat_to_length("a",tens)+last)
|
'''
Given a binary string s (a string consisting only of '0's and '1's), we can split s into 3 non-empty strings s1, s2, s3 (s1+ s2+ s3 = s).
Return the number of ways s can be split such that the number of characters '1' is the same in s1, s2, and s3.
Since the answer may be too large, return it modulo 10^9 + 7.
Example 1:
Input: s = "10101"
Output: 4
Explanation: There are four ways to split s in 3 parts where each part contain the same number of letters '1'.
"1|010|1"
"1|01|01"
"10|10|1"
"10|1|01"
Example 2:
Input: s = "1001"
Output: 0
Example 3:
Input: s = "0000"
Output: 3
Explanation: There are three ways to split s in 3 parts.
"0|0|00"
"0|00|0"
"00|0|0"
Example 4:
Input: s = "100100010100110"
Output: 12
Constraints:
3 <= s.length <= 10^5
s[i] is '0' or '1'.
'''
class Solution:
def numWays(self, s: str) -> int:
length = len(s)
one_count = 0
split_range = {}
for i in range(length):
if s[i] == '1':
one_count += 1
if one_count % 3 != 0 or length < 3:
return 0
if one_count == 0:
return (length - 2) * (length - 1) // 2 % (10 ** 9 + 7)
for i in range(1, 3):
split_range[i * one_count // 3] = i - 1
one_count = 0
split_index = [[] for i in range(2)]
flag = False
tmp_count = 0
for i in range(length):
if s[i] == '1':
one_count += 1
if flag == True:
split_index[tmp_count].append(i)
flag = False
if s[i] == '1' and one_count in split_range:
tmp_count = split_range[one_count]
split_index[tmp_count].append(i)
flag = True
output = (split_index[0][1] - split_index[0][0]) * (split_index[1][1] - split_index[1][0])
return output % (10 ** 9 + 7) |
arr = [2,3,5,8,1,8,0,9,11, 23, 51]
num = 0
def searchElement(arr, num):
n = len(arr)
for i in range(n):
if arr[i] == num:
print("From if block")
return i
elif arr[n-1] == num:
print("From else if block")
return n-1
n-=1
print(searchElement(arr, num))
|
class MidiProtocol:
NON_REAL_TIME_HEADER = 0x7E
GENERAL_SYSTEM_INFORMATION = 0x06
DEVICE_IDENTITY_REQUEST = 0x01
@staticmethod
def device_identify_request(target=0x00):
TARGET_ID = target
SUB_ID_1 = MidiProtocol.GENERAL_SYSTEM_INFORMATION
SUB_ID_2 = MidiProtocol.DEVICE_IDENTITY_REQUEST
return [MidiProtocol.NON_REAL_TIME_HEADER, TARGET_ID, SUB_ID_1, SUB_ID_2]
@staticmethod
def device_identity_reply_decode(data):
'''
F0 7E 00 06 02 52 5A 00 00 00 32 2E 31 30 F7
F0 7E Universal Non Real Time Sys Ex header
id ID of target device (default = 7F = All devices)
06 Sub ID#1 = General System Information
02 Sub ID#2 = Device Identity message
mm Manufacturers System Exclusive ID code.
If mm = 00, then the message is extended by 2 bytes to accomodate the additional manufacturers ID code.
ff ff Device family code (14 bits, LSB first)
dd dd Device family member code (14 bits, LSB first)
ss ss ss ss Software revision level (the format is device specific)
F7 EOX
'''
# 7e id 06 02 mm ff ff dd dd ss ss ss ss EOX
return {
'id': data[1],
'manufacturer': data[4],
'device family code': data[5:7],
'device family member code': data[7:11],
}
|
"""Exceptions raised by flowpipe."""
class CycleError(Exception):
"""Raised when an action would result in a cycle in a graph."""
|
def get_chunks(start, value):
for each in range(start, 2000000001, value):
yield range(each, each+value)
def sum_xor_n(value):
mod_value = value&3
if mod_value == 3:
return 0
elif mod_value == 2:
return value+1
elif mod_value == 1:
return 1
elif mod_value == 0:
return value
else:
return None
def get_numbers_xor(start, end):
start_xor = sum_xor_n(start-1)
end_xor = sum_xor_n(end)
return start_xor^end_xor
def solution(start, length):
# Your code here
checkpoint = length-1
value = 0
for each_chunk in get_chunks(start, length):
if checkpoint < 0:
break
temp = get_numbers_xor(
each_chunk[0],
each_chunk[checkpoint])
if checkpoint == 0:
value ^= each_chunk[0]
else:
value ^= temp
checkpoint -= 1
return value
print(solution(0, 3))
print(solution(17, 4))
|
#! /usr/bin/python
# -*- coding: utf-8 -*-
VER_MAIN = '3'
VER_SUB = '5'
BUILD_SN = '160809'
|
#4-9 Cube Comprehension
numberscube = [value ** 3 for value in range(1, 11)]
print(numberscube) |
#coding:utf-8
while True:
l_c = input().split()
x1 = int(l_c[0])
y1 = int(l_c[1])
x2 = int(l_c[2])
y2 = int(l_c[3])
if x1+x2+y1+y2 == 0:
break
else:
if (x1 == x2 and y1 == y2):
print(0)
elif ((x2-x1) == -(y2-y1) or -(x2-x1) == -(y2-y1)):
print(1)
elif -(x2-x1) == (y2-y1) or (x2-x1) == (y2-y1):
print(1)
elif (x1 == x2 or y1 == y2):
print(1)
else:
print(2)
|
# Definition for a binary tree node.
# class Node(object):
# def __init__(self, val=" ", left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def expTree(self, s: str) -> 'Node':
def process_op():
op = op_stack.pop()
rhs = val_stack.pop()
lhs = val_stack.pop()
node = Node(val=op, left=lhs, right=rhs)
val_stack.append(node)
def priority(op):
if op in '+-':
return 1
elif op in '*/':
return 2
else:
return -1
val_stack = []
op_stack = []
for ch in s:
if ch.isdigit():
val_stack.append(Node(ch))
else:
if ch == '(':
op_stack.append('(')
elif ch == ')':
while op_stack[-1] != '(':
process_op()
op_stack.pop()
else:
cur_op = ch
while op_stack and priority(op_stack[-1]) >= priority(cur_op):
process_op()
op_stack.append(cur_op)
while op_stack:
process_op()
return val_stack[0]
|
# Practice problem 1 for chapter 4
# Function that takes an array and returns a comma-separated string
def make_string(array):
answer_string = ""
for i in array:
if array.index(i) == 0:
answer_string += str(i)
# Last index word finishes with "and" before it
elif array.index(i) == len(array) - 1:
answer_string += ", and " + str(i)
else:
answer_string += ", " + str(i)
print(answer_string)
# Test from book
my_arr = ["apple", "bananas", "tofu", "cats"]
answer = make_string(my_arr)
|
class RCListener:
def __iter__(self): raise NotImplementedError()
class Source:
def listener(self, *args, **kwargs):
raise NotImplementedError()
def query(self, start, end, *args, types=None, **kwargs):
raise NotImplementedError()
|
class DataGridEditingUnit(Enum, IComparable, IFormattable, IConvertible):
"""
Defines constants that specify whether editing is enabled on a cell level or on a row level.
enum DataGridEditingUnit,values: Cell (0),Row (1)
"""
def __eq__(self, *args):
""" x.__eq__(y) <==> x==yx.__eq__(y) <==> x==yx.__eq__(y) <==> x==y """
pass
def __format__(self, *args):
""" __format__(formattable: IFormattable,format: str) -> str """
pass
def __ge__(self, *args):
pass
def __gt__(self, *args):
pass
def __init__(self, *args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
def __le__(self, *args):
pass
def __lt__(self, *args):
pass
def __ne__(self, *args):
pass
def __reduce_ex__(self, *args):
pass
def __str__(self, *args):
pass
Cell = None
Row = None
value__ = None
|
for _ in range(int(input())):
n,q = [int(x) for x in input().split()]
a = [int(x) for x in input().split()]
for _ in range(q):
k = int(input())
sum = 0
# if(k == 0):k = 1
for i in range(0,n,k + 1):
sum += a[i]
print(sum) |
def front_back(s):
if len(s) > 1:
string = [s[-1]]
string.extend([i for i in s[1:-1]])
string.append(s[0])
return "".join(string)
else:
return s |
# twitter api data (replace yours here given are placeholder)
# if you have not yet, go for applying at: https://developer.twitter.com/
TWITTER_KEY=""
TWITTER_SECRET=""
TWITTER_APP_KEY=""
TWITTER_APP_SECRET=""
with open("twitter_keys.txt") as f:
for line in f:
tups=line.strip().split("=")
if tups[0] == "TWITTER_KEY":
TWITTER_KEY=tups[1]
elif tups[0] == "TWITTER_SECRET":
TWITTER_SECRET=tups[1]
elif tups[0] == "TWITTER_APP_KEY":
TWITTER_APP_KEY=tups[1]
elif tups[0] == "TWITTER_APP_SECRET":
TWITTER_APP_SECRET=tups[1] |
def maximum_subarray_1(coll):
n = len(coll)
max_result = 0
for i in xrange(1, n+1):
for j in range(n-i+1):
result = sum(coll[j: j+i])
if max_result < result:
max_result = result
return max_result
def maximum_subarray_2(coll):
n = len(coll)
max_result = 0
for i in xrange(n):
result = 0
for j in xrange(i, n):
result += coll[j]
if max_result < result:
max_result = result
return max_result
def maximum_subarray_3(coll):
if len(coll) == 0:
return 0
# return maximum of (1) maximum subarray of array excluding last one, and
# (2) maximum subarray including the final element
n = len(coll)
result = 0
sums_with_final = []
for i in xrange(n-1, -1, -1):
result += coll[i]
sums_with_final.append(result)
return max([maximum_subarray_3(coll[:-1])] + sums_with_final)
def maximum_subarray(coll):
return maximum_subarray_3(coll)
|
lines = []
for i in xrange(3):
line = Line()
line.xValues = xrange(5)
line.yValues = [(i+1 / 2.0) * pow(x, i+1)
for x in line.xValues]
line.label = "Line %d" % (i + 1)
lines.append(line)
plot = Plot()
plot.add(lines[0])
inset = Plot()
inset.add(lines[1])
inset.hideTickLabels()
inset.title = ("Inset in Yo Inset\n"
"So You Can Inset\n"
"While You Inset")
insideInset = Plot()
insideInset.hideTickLabels()
insideInset.add(lines[2])
inset.addInset(insideInset, width=0.4,
height=0.3, location="upper left")
plot.addInset(inset, width=0.4, height=0.4,
location="lower right")
plot.save("inset.png")
|
#!/usr/bin/env python3
# Corona-Info-App
# flexstring-Parser
# © 2020 Tobias Höpp.
#######################################
# DOCUMENTATION: flexstring (Funktion: flexstringParse(flexstring,configuration))
# Die funktion dient dem auswerten von flexstrings, also strings, die selbst variablen beinhalten, die konfiguriert werden können.
# Das ermöglicht z.B. das einfache Anpassen von Daten in sehr vielen Sprachen.
# Steuerzeichen: $, [ , ] {, }, \
# müssen mit einem \ escaped werden, wenn sie im text vorkommen sollen. Außnahme: \n benötigt kein escaping als einzig zulässiges steuerzeichen.
# Mögliche Variablen-Typen: Boolean, String, Int, Array, Enum
# NAME stellt im folgenden den Variablennamen dar. Dieser ist case-sensitiv (Groß-kleinschreibung) und muss mit gültigem Wert in der Konfiguration vorhanden sein.
# Der Variablenname darf KEINE Unterstriche enthalten.
# Boolean:
# Booleans werden durch
# $_NAME_{TEXT}{KONJUNKTION} oder $_NAME_{TEXT}
# dargestellt.
# $!_NAME_{TEXT}{KONJUNKTION} oder $!_NAME_{TEXT}
# negiert den Wert des booleans.
# TEXT, KONJUNKTION, sind hierbei wieder ein flexstring (können also selbst Variablen enthalten).
# TEXT oder KONJUNKTION wird angezeigt, wenn der Boolean den Wert True hat. (bzw. ggf. seine negation)
# Werden mehrere Booleans direkt hintereinander (ohne Zeichen dazwischen) aufgelistet, so handelt es sich um eine BooleanList.
# Eine BooleanList endet automatisch, wenn ein Boolean keine KONJUNCTION beinhaltet oder auf einen Boolean etas anderes als direkt ein Boolean folgt.
# Ist ein weiterer Boolean in der BooleanList True, so wird KONJUNKTION anstelle von TEXT angezeigt
# Der Wert der Variable NAME muss ein Boolean (Wahrheitswert), also True ^= 1 oder False ^= 0 sein.
# String, Int:
# Strings und Integer werden durch
# $_NAME_
# ohne (direkt) folgende Klammer dargestellt.
# Sie werden 1:1 abgedruckt.
# Hinweis: Die Variable eines Integers kann (theoretisch) gleichzeitig als enum verwendet werden. Davon ist jedoch abzuraten.
# Der Wert der Variable NAME muss ein Integer (Zahl) oder String (Text) sein.
# Array:
# Arrays werden durch
# $_NAME_[[{ANFANG}{ENDE-BEI-KONJUNKTION}{ENDE-LETZTES}]]
# dargestellt.
# ANFANG, ENDE-BEI-KONJUNKTION, ENDE-LETZTES sind dabei wieder flexstring (können also Variablen beinhalten).
# ANFANG wird vor jedem Element des Arrays, das vom Typ String sein muss, angezeigt.
# darauf folgt der eigentliche string
# ENDE-BEI-KONJUNKTION wird nach jedem Element des Arrays angezeigt, außer dem letzten Element. Dort wird ENDE-LETZTES verwendet.
# Der Wert der Variable NAME muss ein Array (Liste) von Strings sein.
# Enum:
# Enums werden durch
# $_NAME_[{ELEMENT0},{ELEMENT1},{ELEMENT2}]
# dargestellt.
# ELEMENT0, ELEMENT1 usw. sond dabei wieder flexstring (können also Variablen beinhalten).
# Auf das letzte Element darf kein Komma folgen. Sonst sind alle Elemente durch exakt ein Komma voneinander getrennt und von geschweiften Klammern umgeben.
# Der Wert der Variable NAME muss ein nicht-negativer Integer (oder Boolean: True = 1, False = 0) sein.
# Das Element, welches an der Position mit der Nummer des Integerwertes steht, wird angezeigt. Das erste Element hat die Nummer 0.
#######################################
def flexstringParse(s, conf):
try:
result = ""
pos = 0
conjunction = ""
noconjunction = ""
while pos < len(s):
if s[pos] == "$":
#Variable
#First check if negated
if s[pos+1] == "!":
pos += 1
negate = True
else:
negate = False
# Name der Variable ermitteln
if not s[pos+1] == "_":
return 0, "Syntax error: _ missing at position ", pos+1
pos +=2
p = pos
c = False
while p < len(s):
if s[p] == "_":
c = True
break
elif s[p] in ["\\", "[", "]", "{", "}", "$"]:
return 0, "Syntax error: unexpectet character '"+s[p]+"' in variable name at position", pos
p +=1
if not c:
return 0, "Syntax error: missing _ for end of variablename for variable", pos-1
if p == pos:
return 0, "Syntax error: missing variable name", pos-1
varName = s[pos:p]
if varName not in conf:
return 0, "Configuration Error: variable '"+varName+"' not found", pos
#Typ der Variable ermitteln:
pos = p+1
if pos < len(s)-1 and s[pos] == "{":
#Ist boolean
# get arguments
p1 = closingPosition(s[pos+1:],"{","}")
if p1 == 0:
return 0, "Syntax Error: could not find closing bracket for opening bracket", pos
p1 += pos+1
noconj = s[pos+1:p1]
#conjunction
if p1+1 < len(s) and s[p1+1] == "{":
p2 = closingPosition(s[p1+2:],"{","}")
if p2 == 0:
return 0, "Syntax Error: could not find closing bracket for opening bracket", p1+1
p2+=p1+2
conj = s[p1+2:p2]
p3 = p2
else:
conj = noconj
p3 = p1
#evaluate value:
if not (isinstance(conf[varName],bool) or (isinstance(conf[varName],int) and (conf[varName] ==1 or conf[varName] ==0))):
return 0, "Configuration Error: variable '"+varName+"' is supposed to be bool, but has value '"+str(conf[varName])+"'", 0
boolval = negate != conf[varName]
if boolval:
if conjunction != "":
# Füge vorangegangenen Boolean als ein
ok, res, ep = flexstringParse(conjunction, conf)
if not ok:
return 0, "Syntax Error while parsing boolStatement '"+conjunction+"': "+res+" at position "+str(ep)+".", pos
result += res
conjunction = conj
noconjunction = noconj
# noconjunction wird angezeigt, wenn auf den Boolean kein weiterer folgt. Sonnst wird conjunction angezeigt.
pos = p3
elif pos < len(s)-1 and s[pos] == "[":
# Vorangegangene Booleanliste beenden
conjunction = ""
if noconjunction != "":
# Füge vorangegangenen Boolean ein
ok, res, ep = flexstringParse(noconjunction, conf)
if not ok:
return 0, "Syntax Error while parsing boolStatement '"+noconjunction+"': "+res+" at position "+str(ep)+".", pos
result += res
noconjunction = ""
# Eigentliche Auswertung
if s[pos+1] == "[":
#Ist array
p1 = closingPosition(s[pos+2:],"[[","]]")
if p1 == 0:
return 0, "Syntax Error: could not find closing bracket for opening bracket", pos
p1 += pos+2 #position of first closing bracket
#Extract Arguments required to pass array:
#First
if s[pos+2] != "{":
return 0, "Syntax Error: could not find first argument to parse array", pos+1
p2 = closingPosition(s[pos+3:p1],"{","}")
if p2 == 0:
return 0, "Syntax Error: could not find closing bracket for opening bracket", pos+2
p2 += pos+3
ok, res, ep = flexstringParse(s[pos+3:p2],conf)
if not ok:
print(s[pos+4:p2])
return 0, res, ep+pos+4
arrBegin = res
#Second
if s[p2+1] != "{":
return 0, "Syntax Error: could not find second argument to parse array", p2+1
p3 = closingPosition(s[p2+2:p1],"{","}")
if p3 == 0:
return 0, "Syntax Error: could not find closing bracket for opening bracket", p2+1
p3 += p2+2
ok, res, ep = flexstringParse(s[p2+2:p3],conf)
if not ok:
return 0, res, ep+p2+2
arrCon = res
#Third
if s[p3+1] != "{":
return 0, "Syntax Error: could not find third argument to parse array", p3+1
p4 = closingPosition(s[p3+2:p1],"{","}")
if p4 == 0:
return 0, "Syntax Error: could not find closing bracket for opening bracket", p3+1
p4 += p3+2
ok, res, ep = flexstringParse(s[p3+2:p4],conf)
if not ok:
return 0, res, ep+p3+2
arrEnd = res
#check if that was all for the array:
if p4+1!=p1:
return 0, "Syntax Error: array does not end with third argument", p4+1
#Iterate over array
if not isinstance(conf[varName], list):
return 0, "Type Error: Variable '"+varName+"' is not an array.", pos
for i, v in enumerate(conf[varName]):
if not isinstance(v,str):
return 0, "Type Error: Array '"+varName+"' does not only contain strings", pos #TODO: Use exeption instead
result+=arrBegin
result+=v #TODO: IMPORTANT: escape string content of v
if i < len(conf[varName])-1:
result+=arrCon
else:
result+=arrEnd
#Set new position
pos = p1+1
else:
#Ist enum
p1 = closingPosition(s[pos+1:],"[","]")
if p1 == 0:
return 0, "Syntax Error: could not find closing bracket for opening bracket", pos
p1 += pos+1
if not (isinstance(conf[varName], int)):
return 0, "Type Error: Variable '"+varName+"' is not an int.", pos-1
p3 = pos
if conf[varName] < 0:
return 0, "Type Error: Variable '"+varName+"'is negativ.", pos-1
for i in range(conf[varName]+1):
p2 = p3 +1
if s[p2] == "]":
return 0, "Value Error: enum variable '"+varName+"' out of range with id '"+str(conf[varName])+"'", p2
if i != 0:
if s[p2] != ",":
return 0, "Syntax Error: expected ',' separating enum values. Found '"+s[p2]+"' instead.", p2
p2 +=1
if s[p2] != "{":
return 0, "Syntax Error: unexpectet character '"+s[p2]+"' in enum", p2
p3 = closingPosition(s[p2+1:p1],"{","}")
if p3 == 0:
return 0, "Syntax Error: could not find closing bracket for opening bracket", p2
p3 += p2+1
ok, res, ep = flexstringParse(s[p2+1:p3],conf)
if not ok:
return 0, res, ep+pos+4
result+=res
pos = p1+1
else:
# Vorangegangene Booleanliste beenden
conjunction = ""
if noconjunction != "":
# Füge vorangegangenen Boolean ein
ok, res, ep = flexstringParse(noconjunction, conf)
if not ok:
return 0, "Syntax Error while parsing boolStatement '"+noconjunction+"': "+res+" at position "+str(ep)+".", pos
result += res
noconjunction = ""
# Eigentliche Auswertung
if not (isinstance(conf[varName], int) or isinstance(conf[varName], str)):
return 0, "Type Error: Variable '"+varName+"' is not a string or int.", pos-1
if isinstance(conf[varName],int) or isinstance(conf[varName],float):
result += str(abs(conf[varName]))
else:
result += str(conf[varName])#TODO: IMPORTANT: escape string content of v
pos -= 1 #make pos point to the right position
elif s[pos] == "\\":
# Vorangegangene Booleanliste beenden
conjunction = ""
if noconjunction != "":
# Füge vorangegangenen Boolean ein
ok, res, ep = flexstringParse(noconjunction, conf)
if not ok:
return 0, "Syntax Error while parsing boolStatement '"+noconjunction+"': "+res+" at position "+str(ep)+".", pos
result += res
noconjunction = ""
# Eigentliche Auswertung
#skip escaped arguments
pos += 1
if s[pos] == "n":
# pass line endings
result += "\\"
result += s[pos]
elif s[pos] in ["{","}","[","]"]:
return 0, "unexpected character '"+s[pos]+"'. (If you want to actually have it displayed, try using a \\ (Backslash) in front of it.", pos
else:
# Vorangegangene Booleanliste beenden
conjunction = ""
if noconjunction != "":
# Füge vorangegangenen Boolean ein
ok, res, ep = flexstringParse(noconjunction, conf)
if not ok:
return 0, "Syntax Error while parsing boolStatement '"+noconjunction+"': "+res+" at position "+str(ep)+".", pos
result += res
noconjunction = ""
# Eigentliche Auswertung
result += s[pos]
pos +=1
# Vorangegangene Booleanliste beenden
conjunction = ""
if noconjunction != "":
# Füge vorangegangenen Boolean ein
ok, res, ep = flexstringParse(noconjunction, conf)
if not ok:
return 0, "Syntax Error while parsing boolStatement '"+noconjunction+"': "+res+" at position "+str(ep)+".", pos
result += res
noconjunction = ""
# Eigentliche Auswertung
return 1, result, None
except IndexError:
return 0, "Unexpected end of (sub)-string", len(s)
#TODO: das mal ordentlich machen
def closingPosition(s,opening,closing):
#INPUT:
# s: String starting right after opening bracket
# opening: opening bracket
# closing: closing bracket
if len(opening) != len(closing):
Exception("length of opening bracket '"+opening+"' does not match lenth of closing bracket '"+closing+"'")
l = len(closing)
p = 0
c = 1
while p < len(s)-l+1:
if s[p:p+l] == opening:
c +=1
elif s[p:p+l] == closing:
c -=1
elif s[p] == '\\':
# skip escaped character
p += 1
if len(s)-l+1 < p:
# Handle index range error
return 0
if c == 0:
break #p is now the position of the closing bracket
p +=1
# Break in case of syntax error:
if c != 0:
return 0
return p #Anfangsposition der schließenden Klammer
################################
# Function for variables list
class variableList():
variableList = dict
# Constructor
def __init__(self):
self.variableList = {}
def append(self, name, vartype, maxval=None):
if name not in self.variableList:
if vartype == "int":
self.variableList[name] = {"type":"int","max":maxval}
else:
self.variableList[name] = {"type":vartype}
elif self.variableList[name]["type"] != vartype:
if (self.variableList[name]["type"] == "bool" and vartype in ("str", "int")) or (self.variableList[name]["type"] == "int" and vartype == "str"):
return True
elif self.variableList[name]["type"] == "int" and vartype == "bool":
self.variableList[name] = {"type":"bool"}
elif self.variableList[name]["type"] == "str" and vartype == "bool":
self.variableList[name]["type"] = "bool"
elif self.variableList[name]["type"] == "str" and vartype == "int":
self.variableList[name] = {"type":"int","max":maxval}
return False
return True
# Validation of varlists
def validateVarList(subset, varlist):
for name in subset:
if name not in varlist:
return 0, "variable '"+name+"' is not defined"
if subset[name]["type"] == "bool":
if varlist[name]["type"] != "bool": #and not (varlist[name]["type"] == "int" and varlist[name]["max"] == 1):
return 0, "variable '"+name+"' is required to be of type '"+varlist[name]["type"]+"' but has type 'bool'"
elif subset[name]["type"] == "int":
#if varlist[name]["type"] == "bool":
# if not subset[name]["max"] != 1:
# return 0, "variable '"+name+"' can only have a maxvalue of 1"
if varlist[name]["type"] == "int":
#if varlist[name]["max"] < subset[name]["max"]:
# return 0, "variable '"+name+"' can only have a maxvalue of "+str(varlist[name]["max"])
# Do not check if the list is to long, as this will not cause any errors but might be unintentional
if not isinstance(varlist[name]["max"],int):
return 0, "JSON Syntax Error: '"+name+"'['max'] has to be a number, but is not."
if varlist[name]["max"] > subset[name]["max"]:
return 0, "variable '"+name+"' has to allow for values as high as "+str(varlist[name]["max"])+", but only allows for values as high as "+str(subset[name]["max"])
elif varlist[name]["type"] != "bool":
return 0, "variable '"+name+"' is required to be of type '"+varlist[name]["type"]+"' but has type 'int'"
elif subset[name]["type"] == "arr":
if varlist[name]["type"] != "arr":
return 0, "variable '"+name+"' is required to be of type '"+varlist[name]["type"]+"' but has type 'arr'"
elif subset[name]["type"] == "str":
if varlist[name]["type"] == "arr":
return 0, "variable '"+name+"' is required to be of type 'arr' but has type 'str'"
return 1, None
# Validation of configurations
def validateConfig(config,varlist):
if varlist == None:
return 1, None
for name in varlist:
if name not in config:
return 0, "variable '"+name+"' is required but not in configuration"
if varlist[name]["type"] == "bool" and not(isinstance(config[name], bool)):# or (isinstance(config[name], int) and 0<=config[name]<=1)):
return 0, "variable '"+name+"' is required to be bool"
elif varlist[name]["type"] == "int":
if not(isinstance(config[name], int)):
return 0, "variable '"+name+"' is required to be int"
if "max" in varlist[name]:
if config[name] > varlist[name]["max"] or config[name]<0:
return 0, "variable '"+name+"' must be int between 0 and "+str(varlist[name]["max"])
elif varlist[name]["type"] == "arr":
if not(isinstance(config[name], list)):
return 0, "variable '"+name+"' is required to be array"
for li in config[name]:
if not(isinstance(li, str)):
return 0, "array '"+name+"' must only contain strings"
elif varlist[name]["type"] == "float":
if not(isinstance(config[name], float)) and not(isinstance(config[name], int)):
return 0, "variable '"+name+"' is required to be float or int"
elif varlist[name]["type"] == "str":
if not(isinstance(config[name], str) or isinstance(config[name], int) or isinstance(config[name], float)):
return 0, "variable '"+name+"' is required to be string"
return 1, None
# check if varlist is mergable
def isMergable(varlist):
for name in varlist:
if varlist[name]["type"] == "str":
return False
elif varlist[name]["type"] == "int" and "maxval" in varlist[name]:
return False
return True
def mergeConfig(conf1, conf2):
if conf1.keys() != conf2.keys():
return False
conf = {}
for name in conf1:
if type(conf1[name]) != type(conf2[name]):
return False
if isinstance(conf1[name], bool):
conf[name] = conf1[name] or conf2[name]
# booleans werden verordert
elif isinstance(conf1[name], int) or isinstance(conf1[name], float):
if conf1[name] < conf2[name]:
conf[name] = conf1[name]
else:
conf[name] = conf2[name]
# bei integern/floats wird der kleinste Wert genommen. Soll der größte Wert genommen werden, negative Zahlen verwenden. Diese werden als Betrag angezeigt. #TODO
elif isinstance(conf1[name], list):
tmp = conf2[name].copy()
conf[name] = []
for li in conf1[name]:
conf[name].append(li)
if li in tmp:
tmp.remove(li)
# remove duplicats
for li in tmp:
conf[name].append(li)
# TODO: Alphabetically order?
else:
return False
return conf
################################################
# MODIFICATIONS FOR SYNTAX-CHECK:
# GENERAL changes: use flexstringSyntax instead of flexstringParse and remove everything that has "conf" in it
# For BOOLEAN: Add conj and nocony straight away and remove everything with conjunction and noconjunction
# For ENUM iteration
# while true instead of range and break if s[p2] == "]"
# define i as 0 and make it increment
# Add ok, res, ep = flexstringSyntax(s[p2+1:p3]) and following lines (until including line result += res) to while
# Add variableListAppend with type "int" and maxval i
# For ARRAY iteration:
# use range(2) instead of enumerate and check if i <1 and remove everything that has "v" in it
# add result += varName+"-Value" to result instead of v
# For STRING: use result += varName+"-Value"
################################################
# Function for syntax-check:
def flexstringSyntax(s):
vlist = variableList()
ok, res, ep = flexstringSyntaxCheck(s, vlist)
return ok, res, ep, vlist.variableList
def flexstringSyntaxCheck(s, vlist):
try:
result = ""
pos = 0
while pos < len(s):
if s[pos] == "$":
#Variable
#First check if negated
if s[pos+1] == "!":
pos += 1
negate = True
else:
negate = False
# Name der Variable ermitteln
if not s[pos+1] == "_":
return 0, "Syntax error: _ missing at position ", pos+1
pos +=2
p = pos
c = False
while p < len(s):
if s[p] == "_":
c = True
break
elif s[p] in ["\\", "[", "]", "{", "}", "$"]:
return 0, "Syntax error: unexpectet character '"+s[p]+"' in variable name at position", pos
p +=1
if not c:
return 0, "Syntax error: missing _ for end of variablename for variable", pos-1
if p == pos:
return 0, "Syntax error: missing variable name", pos-1
varName = s[pos:p]
#Typ der Variable ermitteln:
pos = p+1
if pos < len(s)-1 and s[pos] == "{":
#Ist boolean
if not vlist.append(varName,"bool"):
return 0, "Type Error: variable '"+variableList+"' already defined with incompatible type to type 'bool'", pos
# get arguments
p1 = closingPosition(s[pos+1:],"{","}")
if p1 == 0:
return 0, "Syntax Error: could not find closing bracket for opening bracket", pos
p1 += pos+1
noconj = s[pos+1:p1]
#conjunction
if p1+1 < len(s) and s[p1+1] == "{":
p2 = closingPosition(s[p1+2:],"{","}")
if p2 == 0:
return 0, "Syntax Error: could not find closing bracket for opening bracket", p1+1
p2+=p1+2
conj = s[p1+2:p2]
p3 = p2
else:
conj = noconj
p3 = p1
ok, res, ep = flexstringSyntaxCheck(conj,vlist)
if not ok:
return 0, "Syntax Error while parsing boolStatement '"+conj+"': "+res+" at position "+str(ep)+".", pos
result += res
ok, res, ep = flexstringSyntaxCheck(noconj,vlist)
if not ok:
return 0, "Syntax Error while parsing boolStatement '"+noconj+"': "+res+" at position "+str(ep)+".", pos
result += res
pos = p3
elif pos < len(s)-1 and s[pos] == "[":
if s[pos+1] == "[":
#Ist array
if not vlist.append(varName,"array"):
return 0, "Type Error: variable '"+variableList+"' already defined with incompatible type to type 'array'", pos
p1 = closingPosition(s[pos+2:],"[[","]]")
if p1 == 0:
return 0, "Syntax Error: could not find closing bracket for opening bracket", pos
p1 += pos+2 #position of first closing bracket
#Extract Arguments required to pass array:
#First
if s[pos+2] != "{":
return 0, "Syntax Error: could not find first argument to parse array", pos+1
p2 = closingPosition(s[pos+3:p1],"{","}")
if p2 == 0:
return 0, "Syntax Error: could not find closing bracket for opening bracket", pos+2
p2 += pos+3
ok, res, ep = flexstringSyntaxCheck(s[pos+3:p2],vlist)
if not ok:
print(s[pos+4:p2])
return 0, res, ep+pos+4
arrBegin = res
#Second
if s[p2+1] != "{":
return 0, "Syntax Error: could not find second argument to parse array", p2+1
p3 = closingPosition(s[p2+2:p1],"{","}")
if p3 == 0:
return 0, "Syntax Error: could not find closing bracket for opening bracket", p2+1
p3 += p2+2
ok, res, ep = flexstringSyntaxCheck(s[p2+2:p3],vlist)
if not ok:
return 0, res, ep+p2+2
arrCon = res
#Third
if s[p3+1] != "{":
return 0, "Syntax Error: could not find third argument to parse array", p3+1
p4 = closingPosition(s[p3+2:p1],"{","}")
if p4 == 0:
return 0, "Syntax Error: could not find closing bracket for opening bracket", p3+1
p4 += p3+2
ok, res, ep = flexstringSyntaxCheck(s[p3+2:p4],vlist)
if not ok:
return 0, res, ep+p3+2
arrEnd = res
#check if that was all for the array:
if p4+1!=p1:
return 0, "Syntax Error: array does not end with third argument", p4+1
#Iterate over array
for i in range(2):
result+=arrBegin
result+=varName+"-VALUE" #TODO: IMPORTANT: escape string content of v
if i < 1:
result+=arrCon
else:
result+=arrEnd
#Set new position
pos = p1+1
else:
#Ist enum
p1 = closingPosition(s[pos+1:],"[","]")
if p1 == 0:
return 0, "Syntax Error: could not find closing bracket for opening bracket", pos
p1 += pos+1
p3 = pos
i = 0
while True:
p2 = p3 +1
if s[p2] == "]":
break
if i != 0:
if s[p2] != ",":
return 0, "Syntax Error: expected ',' separating enum values. Found '"+s[p2]+"' instead.", p2
p2 +=1
i += 1
if s[p2] != "{":
return 0, "Syntax Error: unexpectet character '"+s[p2]+"' in enum", p2
p3 = closingPosition(s[p2+1:p1],"{","}")
if p3 == 0:
return 0, "Syntax Error: could not find closing bracket for opening bracket", p2
p3 += p2+1
ok, res, ep = flexstringSyntaxCheck(s[p2+1:p3],vlist)
if not ok:
return 0, res, ep+pos+4
result+=res
pos = p1+1
# Vartype setzen
if not vlist.append(varName,"int",maxval=i):
return 0, "Type Error: variable '"+variableList+"' already defined with incompatible type to type 'int'", pos
else:
if not vlist.append(varName,"str"):
return 0, "Type Error: variable '"+variableList+"' already defined with incompatible type to type 'str'", pos
result += varName+"-VALUE"#TODO: IMPORTANT: escape string content of v
pos -= 1 #make pos point to the right position
elif s[pos] == "\\":
#skip escaped arguments
pos += 1
if s[pos] == "n":
# pass line endings
result += "\\"
result += s[pos]
elif s[pos] in ["{","}","[","]"]:
return 0, "unexpected character '"+s[pos]+"'. (If you want to actually have it displayed, try using a \\ (Backslash) in front of it.", pos
else:
result += s[pos]
pos +=1
return 1, result, None
except IndexError:
return 0, "Unexpected end of (sub)-string", len(s)
############################################################
# Example:
"""
sampleConf = {
"supermärkte": True,
"schulen": True,
"kindergärten": False,
"plätze": ["Odeonsplatz", "Marienplatz"],
"schülerzahl": 20,
"personen": 5,
"haushal": 2,
"auswahl": 2
}
sampleString = "Maskenpflicht gilt in $_supermärkte_{Supermärkten}{Supermärkten und }$_schulen_{Schulen}{Schulen und }$_kindergärten_{Kindergärten} \n"
sampleString +="und weiterhin auf den Plätzen: \n$_plätze_[[{*_}{_,\n}{_\n}]] "
sampleString += "Schulen sind $_auswahl_[{geschlossen},{geöffnet},{für Klassen mit weniger als $_schülerzahl_ Schülern geöffnet}] \n"
sampleString += "Maximal $_personen_ Personen aus $_haushal_ Haushalten"
"""
#Try it out with:
#ok, res, epos, varlist = flexstringSyntax(sampleString)
#varlist2 = varlist.copy()
#varlist2["demos"] = {"type":"bool"}
#print(validateVarList(varlist2,varlist))
#print(flexstringSyntax(sampleString))
#print(flexstringParse(sampleString,sampleConf))
|
file = open('csv_data.txt', 'r')
lines = file.readlines()
file.close()
lines = [line.strip() for line in lines[1:]]
for line in lines:
person_data = line.split(',')
name = person_data[0].title()
age = person_data[1]
university = person_data[2].title()
degree = person_data[3].capitalize()
print(f'{name} is {age}, studying {degree} at {university}.')
|
"""Top-level package for BioCyc and BRENDA in Python."""
__author__ = """Yi Zhou"""
__email__ = 'zhou.zy.yi@gmail.com'
__version__ = '0.1.0'
|
"""
问题描述: 在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序。
示例:
4->2->1->3 => 1->2->3->4
"""
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def sortList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head or not head.next:
return head
pre = head
slow = head
fast = head
# 通过快慢指针获取前半段和后半段
while fast and fast.next:
pre = slow
slow = slow.next
fast = fast.next.next
# 注意在链表操作的时候,一定要把尾指针置为None
pre.next = None
h1 = self.sortList(head)
h2 = self.sortList(slow)
return self.merge(h1, h2)
def merge(self, h1, h2):
if not h1:
return h2
if not h2:
return h1
if h1.val < h2.val:
h1.next = self.merge(h1.next, h2)
return h1
else:
h2.next = self.merge(h1, h2.next)
return h2 |
def media(n1, n2):
m = (n1 + n2)/2
return m
print(media(n1=10, n2=5))
def juros(preco, juros):
res = preco * (1 + juros/100)
return res
print(juros(preco=10, juros=50))
|
"""Multiply two arbitrary-precision integers. - [EPI: 5.3]. """
def multiply(num1, num2):
sign = -1 if (num1[0] < 0) ^ (num2[0] < 0) else 1
num1[0], num2[0] = abs(num1[0]), abs(num2[0])
result = [0] * (len(num1) + len(num2))
for i in reversed(range(len(num1))):
for j in reversed(range(len(num2))):
result[i + j + 1] += num1[i] * num2[j]
result[i + j] += result[i + j + 1] // 10
result[i + j + 1] %= 10
# Remove the leading zeroes.
result = result[next((i for i, x in enumerate(result)
if x != 0), len(result)):] or [0]
return [sign * result[0]] + result[1:]
|
def test_session_interruption(ui, ui_interrupted_session):
ui_interrupted_session.click()
interrupted_test = ui.driver.find_element_by_css_selector('.item.test')
css_classes = interrupted_test.get_attribute('class')
assert 'success' not in css_classes
assert 'fail' not in css_classes
interrupted_test.click()
assert 'errors' not in ui.driver.current_url
[link] = ui.driver.find_elements_by_xpath("//*[contains(text(), 'Interruptions')]")
link.click()
error_boxes = ui.driver.find_elements_by_class_name('error-box')
assert len(error_boxes) == 1
[err] = error_boxes
assert 'interruption' in err.get_attribute('class')
|
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def sortedArrayToBST(self, nums):
return self.recurse(nums,0,len(nums)-1)
def recurse(self,nums,start,end):
if end<start:
return None
mid=int(start+(end-start)/2)
root=TreeNode(val=nums[mid],left=self.recurse(nums,start,mid-1),right=self.recurse(nums,mid+1,end))
return root
def forward(self,root):
if not root:
return
print(root.val)
self.forward(root.left)
self.forward(root.right)
if __name__ == '__main__':
sol=Solution()
nums = [-10, -3, 0, 5, 9]
root=sol.sortedArrayToBST(nums)
sol.forward(root) |
"""Helper function to save serializer"""
def save_serializer(serializer):
"""returns a particular response for when serializer passed is valid or not"""
serializer.save()
data = {
"status": "success",
"data": serializer.data
}
return data
|
Vivaldi = Goalkeeper('Juan Vivaldi', 83, 77, 72, 82)
Peillat = Outfield_Player('Gonzalo Peillat', 'DF', 70, 89, 78, 73, 79, 67)
Ortiz = Outfield_Player('Ignacio Ortiz', 'MF', 79, 78, 77, 80, 75, 81)
Rey = Outfield_Player('Matias Rey', 'MF', 81, 77, 74, 72, 87, 72)
Vila = Outfield_Player('Lucas Vila', 'FW', 87, 50, 80, 82, 74, 85)
ARG = Team('Argentina', Vivaldi, Peillat, Ortiz, Rey, Vila) |
def factorial(x):
'''calculo de factorial
con una funcion recursiva'''
if x == 1:
return 1
else:
return (x * factorial(x-1))
num = 928
print('el factorial de: ', num ,'is ', factorial(num))
|
# prompting user to enter the file name
fname = input('Enter file name: ')
d = dict()
# catching exceptions
try:
fhand = open(fname)
except:
print('File does not exist')
exit()
# reading the lines in the file
for line in fhand:
words = line.split()
# we only want email addresses
if len(words) < 2 or words[0] != 'From':
continue
else:
d[words[1]] = d.get(words[1], 0) + 1
print(d) |
# crie um programa que tenha uma tupla unica com nomes de produtos e sesus respectivos preços
# no final mostre uma listagem de preços organizando os dados em forma tabular
listagem = ('Lápis', 1.75, 'Borracha', 2, 'Caderno', 15.90, 'Estojo', 25, 'Pendrive', 25, 'Fan', 11.25, 'Livro', 34.90)
print('~'*40)
print(f'{"LISTAGEM DE PREÇOS":^40}')
for pos in range(0, len(listagem)):
if pos % 2 == 0:
print(f'{listagem[pos]:.<30}', end='')
else:
print(f'R${listagem[pos]:>8.2f}')
print('~'*40)
|
# Separando dígitos de um número
'''Faça um programa que leia um número de 0 a 9999
e mostre na tela cada um dos digitos separados
Ex: número: 1835; unidade: 4, dezena: 3, centena: 8, milhar: 1'''
n = int(input('Digite um número entre 0 e 9999: '))
u = n // 1 % 10
d = n // 10 % 10
c = n // 100 % 10
m = n // 1000 % 10
print('\033[37m''Analisando o número {}...\033[m'.format(n))
print('\033[1m''Unidade: {}'.format(u))
print('Dezena: {}'.format(d))
print('Centena: {}'.format(c))
print('Milhar: {}'.format(m))
|
'''
根据一棵树的前序遍历与中序遍历构造二叉树。
注意:
你可以假设树中没有重复的元素。
例如,给出
前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]
返回如下的二叉树:
3
/ \
9 20
/ \
15 7
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
'''
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
def myBuildTree(preorder_left,preorder_right,inorder_left,inorder_right):
if preorder_left > preorder_right:
return None
preorder_root = preorder_left
inorder_root = index[preorder[preorder_root]]
root = TreeNode(preorder[preorder_root])
size_left_subtree = inorder_root - inorder_left
root.left = myBuildTree(preorder_left + 1,preorder_left + size_left_subtree,inorder_left, inorder_root - 1)
root.right = myBuildTree(preorder_left + size_left_subtree + 1, preorder_right, inorder_root + 1, inorder_right)
return root
n = len(preorder)
index = {element: i for i,element in enumerate(inorder)}
return myBuildTree(0,n-1,0,n-1)
|
# Copyright 2014 Google Inc.
#
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'variables': {
'skia_warnings_as_errors': 0,
},
'targets': [
{
'target_name': 'libpng',
'type': 'none',
'conditions': [
[ 'skia_android_framework', {
'dependencies': [ 'android_deps.gyp:png' ],
'export_dependent_settings': [ 'android_deps.gyp:png' ],
},{
'dependencies': [ 'libpng.gyp:libpng_static' ],
'export_dependent_settings': [ 'libpng.gyp:libpng_static' ],
}]
]
},
{
'target_name': 'libpng_static',
'type': 'static_library',
'standalone_static_library': 1,
'include_dirs': [
'../third_party/libpng',
],
'dependencies': [
'zlib.gyp:zlib',
],
'export_dependent_settings': [
'zlib.gyp:zlib',
],
'direct_dependent_settings': {
'include_dirs': [
'../third_party/libpng',
],
},
'cflags': [
'-w',
'-fvisibility=hidden',
],
'sources': [
'../third_party/libpng/png.c',
'../third_party/libpng/pngerror.c',
'../third_party/libpng/pngget.c',
'../third_party/libpng/pngmem.c',
'../third_party/libpng/pngpread.c',
'../third_party/libpng/pngread.c',
'../third_party/libpng/pngrio.c',
'../third_party/libpng/pngrtran.c',
'../third_party/libpng/pngrutil.c',
'../third_party/libpng/pngset.c',
'../third_party/libpng/pngtrans.c',
'../third_party/libpng/pngwio.c',
'../third_party/libpng/pngwrite.c',
'../third_party/libpng/pngwtran.c',
'../third_party/libpng/pngwutil.c',
],
'conditions': [
[ '"x86" in skia_arch_type', {
'defines': [
'PNG_INTEL_SSE_OPT=1',
],
'sources': [
'../third_party/libpng/contrib/intel/intel_init.c',
'../third_party/libpng/contrib/intel/filter_sse2_intrinsics.c',
],
}],
[ '(("arm64" == skia_arch_type) or \
("arm" == skia_arch_type and arm_neon == 1)) and \
("ios" != skia_os)', {
'defines': [
'PNG_ARM_NEON_OPT=2',
'PNG_ARM_NEON_IMPLEMENTATION=1',
],
'sources': [
'../third_party/libpng/arm/arm_init.c',
'../third_party/libpng/arm/filter_neon_intrinsics.c',
],
}],
[ '"ios" == skia_os', {
'defines': [
'PNG_ARM_NEON_OPT=0',
],
}],
],
}
]
}
|
_base_ = "./common_base.py"
# -----------------------------------------------------------------------------
# base model cfg for gdrn
# -----------------------------------------------------------------------------
MODEL = dict(
DEVICE="cuda",
WEIGHTS="",
# PIXEL_MEAN = [103.530, 116.280, 123.675] # bgr
# PIXEL_STD = [57.375, 57.120, 58.395]
# PIXEL_MEAN = [123.675, 116.280, 103.530] # rgb
# PIXEL_STD = [58.395, 57.120, 57.375]
PIXEL_MEAN=[0, 0, 0], # to [0,1]
PIXEL_STD=[255.0, 255.0, 255.0],
LOAD_DETS_TEST=False,
CDPN=dict(
NAME="GDRN", # used module file name
TASK="rot",
USE_MTL=False, # uncertainty multi-task weighting
## backbone
BACKBONE=dict(
PRETRAINED="torchvision://resnet34",
ARCH="resnet",
NUM_LAYERS=34,
INPUT_CHANNEL=3,
INPUT_RES=256,
OUTPUT_RES=64,
FREEZE=False,
),
## rot head
ROT_HEAD=dict(
FREEZE=False,
ROT_CONCAT=False,
XYZ_BIN=64, # for classification xyz, the last one is bg
NUM_LAYERS=3,
NUM_FILTERS=256,
CONV_KERNEL_SIZE=3,
NORM="BN",
NUM_GN_GROUPS=32,
OUT_CONV_KERNEL_SIZE=1,
NUM_CLASSES=13,
ROT_CLASS_AWARE=False,
XYZ_LOSS_TYPE="L1", # L1 | CE_coor
XYZ_LOSS_MASK_GT="visib", # trunc | visib | obj
XYZ_LW=1.0,
MASK_CLASS_AWARE=False,
MASK_LOSS_TYPE="L1", # L1 | BCE | CE
MASK_LOSS_GT="trunc", # trunc | visib | gt
MASK_LW=1.0,
MASK_THR_TEST=0.5,
# for region classification, 0 is bg, [1, num_regions]
# num_regions <= 1: no region classification
NUM_REGIONS=8,
REGION_CLASS_AWARE=False,
REGION_LOSS_TYPE="CE", # CE
REGION_LOSS_MASK_GT="visib", # trunc | visib | obj
REGION_LW=1.0,
),
## for direct regression
PNP_NET=dict(
FREEZE=False,
R_ONLY=False,
LR_MULT=1.0,
# ConvPnPNet | SimplePointPnPNet | PointPnPNet | ResPointPnPNet
PNP_HEAD_CFG=dict(type="ConvPnPNet", norm="GN", num_gn_groups=32, drop_prob=0.0), # 0.25
# PNP_HEAD_CFG=dict(
# type="ConvPnPNet",
# norm="GN",
# num_gn_groups=32,
# spatial_pooltype="max", # max | mean | soft | topk
# spatial_topk=1,
# region_softpool=False,
# region_topk=8, # NOTE: default the same as NUM_REGIONS
# ),
WITH_2D_COORD=False, # using 2D XY coords
REGION_ATTENTION=False, # region attention
MASK_ATTENTION="none", # none | concat | mul
TRANS_WITH_BOX_INFO="none", # none | ltrb | wh # TODO
## for losses
# {allo/ego}_{quat/rot6d/log_quat/lie_vec}
ROT_TYPE="ego_rot6d",
TRANS_TYPE="centroid_z", # trans | centroid_z (SITE) | centroid_z_abs
Z_TYPE="REL", # REL | ABS | LOG | NEG_LOG (only valid for centroid_z)
# point matching loss
NUM_PM_POINTS=3000,
PM_LOSS_TYPE="L1", # L1 | Smooth_L1
PM_SMOOTH_L1_BETA=1.0,
PM_LOSS_SYM=False, # use symmetric PM loss
PM_NORM_BY_EXTENT=False, # 10. / extent.max(1, keepdim=True)[0]
# if False, the trans loss is in point matching loss
PM_R_ONLY=True, # only do R loss in PM
PM_DISENTANGLE_T=False, # disentangle R/T
PM_DISENTANGLE_Z=False, # disentangle R/xy/z
PM_T_USE_POINTS=False,
PM_LW=1.0,
ROT_LOSS_TYPE="angular", # angular | L2
ROT_LW=0.0,
CENTROID_LOSS_TYPE="L1",
CENTROID_LW=0.0,
Z_LOSS_TYPE="L1",
Z_LW=0.0,
TRANS_LOSS_TYPE="L1",
TRANS_LOSS_DISENTANGLE=True,
TRANS_LW=0.0,
# bind term loss: R^T@t
BIND_LOSS_TYPE="L1",
BIND_LW=0.0,
),
## trans head
TRANS_HEAD=dict(
ENABLED=False,
FREEZE=True,
LR_MULT=1.0,
NUM_LAYERS=3,
NUM_FILTERS=256,
NORM="BN",
NUM_GN_GROUPS=32,
CONV_KERNEL_SIZE=3,
OUT_CHANNEL=3,
TRANS_TYPE="centroid_z", # trans | centroid_z
Z_TYPE="REL", # REL | ABS | LOG | NEG_LOG
CENTROID_LOSS_TYPE="L1",
CENTROID_LW=0.0,
Z_LOSS_TYPE="L1",
Z_LW=0.0,
TRANS_LOSS_TYPE="L1",
TRANS_LW=0.0,
),
),
# some d2 keys but not used
KEYPOINT_ON=False,
LOAD_PROPOSALS=False,
)
TEST = dict(
EVAL_PERIOD=0,
VIS=False,
TEST_BBOX_TYPE="gt", # gt | est
USE_PNP=False, # use pnp or direct prediction
# ransac_pnp | net_iter_pnp (learned pnp init + iter pnp) | net_ransac_pnp (net init + ransac pnp)
# net_ransac_pnp_rot (net_init + ransanc pnp --> net t + pnp R)
PNP_TYPE="ransac_pnp",
PRECISE_BN=dict(ENABLED=False, NUM_ITER=200),
)
|
# -*- coding: utf-8 -*-
# dict key:原node, val:新node
# Definition for singly-linked list with a random pointer.
class RandomListNode(object):
def __init__(self, x):
self.label = x
self.next = None
self.random = None
class Solution(object):
def copyRandomList(self, head):
"""
:type head: RandomListNode
:rtype: RandomListNode
"""
if not head:
return None
dic = {}
# 最后缺个None,这里补上
dic[None] = None
curr = head
# copy node
while curr:
dic[curr] = RandomListNode(curr.label)
curr = curr.next
curr = head
# copy pointers
while curr:
dic[curr].next = dic[curr.next]
dic[curr].random = dic[curr.random]
curr = curr.next
return dic[head] |
#This app does your math
addition = input("Print your math sign, +, -, *, /: ")
if addition == "+":
a = int(input("First Number: "))
b = int(input("Seccond Number: "))
c = a + b
print(c)
elif addition == "-":
a = int(input("First Number: "))
b = int(input("Seccond Number: "))
c = a - b
print(c)
elif addition == "*":
a = int(input("First Number: "))
b = int(input("Seccond Number: "))
c = a * b
print(c)
elif addition == "/":
a = int(input("First Number: "))
b = int(input("Seccond Number: "))
c = a / b
print(c)
else:
print("That is not a valid operation. Please do +, -, *, /")
|
class Solution:
def sequentialDigits(self, low: int, high: int) -> List[int]:
sequence, base, result = '123456789', 10, []
for length in range(len(str(low)), len(str(high)) + 1):
for start in range(base - length):
number = int(sequence[start : start + length])
if low <= number <= high:
result.append(number)
return result |
# -*- coding: utf-8 -*-
def range(start, stop, step=1.):
"""Replacement for built-in range function.
:param start: Starting value.
:type start: number
:param stop: End value.
:type stop: number
:param step: Step size.
:type step: number
:returns: List of values from `start` to `stop` incremented by `size`.
:rtype: [float]
"""
start, stop, step = map(float, (start, stop, step))
result = [start]
current = start
while current < stop:
current += step
result.append(current)
return result
def up(a, b, x):
a, b, x = map(float, (a, b, x))
a = float(a)
b = float(b)
x = float(x)
if x < a:
return 0.0
if x < b:
return (x - a) / (b - a)
return 1.0
def down(a, b, x):
return 1. - up(a, b, x)
def tri(a, b, x):
a, b, x = map(float, (a, b, x))
m = (a + b) / 2.
first = (x - a) / (m - a)
second = (b - x) / (b - m)
return max(min(first, second), 0.)
def trap(a, b, c, d, x):
a, b, c, d, x = map(float, (a, b, c, d, x))
first = (x - a) / (b - a)
second = (d - x) / (d - c)
return max(min(first, 1., second), 0.)
def ltrap(a, b, x):
a, b, x = map(float, (a, b, x))
return max(min((b - x) / (b - a), 1.), 0.)
def rtrap(a, b, x):
a, b, x = map(float, (a, b, x))
return max(min((x - a) / (b - a), 1.), 0.)
def rect(a, b, x):
a, b, x = map(float, (a, b, x))
return 1. if a < x < b else 0
|
""" from https://github.com/keithito/tacotron """
"""
Defines the set of symbols used in text input to the model.
The default is a set of ASCII characters that works well for English or text that has been run through Unidecode. For other data, you can modify _characters. See TRAINING_DATA.md for details. """ # noqa: E501
_punctuation = "!'\",.:;? "
_math = "#%&*+-/[]()"
_special = "_@©°½—₩€$"
_accented = "áçéêëñöøćž"
_numbers = "0123456789"
_letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
# Export all symbols:
symbols = list(_punctuation + _math + _special + _accented + _numbers + _letters)
|
class Solution(object):
def largestRectangleArea1(self, heights):
"""
:type heights: List[int]
:rtype: int
"""
self.ans = float('-inf')
def recurse(heights, l, r):
if l > r:
return 0
min_idx = l
# index r is included when searching min
for i in range(l, r + 1):
if heights[min_idx] > heights[i]:
min_idx = i
print(l, r)
return max(
heights[min_idx] * (r - l + 1),
recurse(heights, l, min_idx - 1),
recurse(heights, min_idx + 1, r))
return recurse(heights, 0, len(heights) - 1)
def largestRectangleArea2(self, heights):
"""
:type heights: List[int]
:rtype: int
"""
self.ans = float('-inf')
def recurse(heights, l, r):
if l > r:
return 0
min_idx = l
# index r is included when searching min
for i in range(l, r + 1):
if heights[min_idx] > heights[i]:
min_idx = i
print(l, r)
# time limit exceeded
cur = heights[min_idx] * (r - l + 1)
left = recurse(heights, min_idx + 1, r)
right = recurse(heights, l, min_idx - 1)
return max(cur, left, right)
return recurse(heights, 0, len(heights) - 1)
def largestRectangleArea(self, height):
height.append(0)
stack, size = [], 0
for i in range(len(height)):
while stack and height[stack[-1]] > height[i]:
l = stack.pop()
h = height[l]
w = i if not stack else i-l
cand = h * w
print(cand)
size = max(size, cand)
stack.append(i)
return size
solver = Solution()
arr1 = [2,1,5,6,2,3]
arr2 = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67]
print("largestRectangleArea")
print(solver.largestRectangleArea(arr2))
# print("largestRectangleArea")
# print(solver.largestRectangleArea1(arr2))
#
# print("largestRectangleArea2")
# print(solver.largestRectangleArea2(arr2)) |
# 問題URL: https://atcoder.jp/contests/abc134/tasks/abc134_d
# 解答URL: https://atcoder.jp/contests/abc134/submissions/24158327
n = int(input())
a = [int(i) for i in input().split()]
b = [0] * n
for i in range(n, 0, -1):
b[i - 1] = (sum(b[i - 1::i]) % 2) ^ a[i - 1]
print(sum(b))
print(*[i + 1 for i, bi in enumerate(b) if bi])
|
class PaceMaker():
"""
Class for a server that distributes the anonymized and
hashed contact traces.
Attributes:
connected_peers = []: List of peers to communicate with.
trace_buffer = {area: hashed_events}: Temporarily stored hashed events.
"""
def receive_hashed_trace(self, area, trace):
"""
Receive sets of hashed events (a trace) from a confirmed ill peer.
Save to the trace buffer.
"""
pass
def distribute_traces(self):
"""
Distribute the events from the trace buffer to all peers.
"""
trace_packets = self.shuffle_and_pack_traces()
for peer in self.connected_peers():
for packet in trace_packets:
self.send_packet(peer, packet)
def shuffle_and_pack_traces(self):
"""
Shuffle the hashed events within the same area.
Put into packets for distribution.
"""
pass
def send_packet(self, peer, packet):
""" Connect to peer and send packet of events. """
pass
### Other functionality
# Connect to new peers
|
"""任意的参数列表
@see: https://docs.python.org/3/tutorial/controlflow.html#arbitrary-argument-lists
函数可以使用任意数量的参数来调用。这些参数将封装在一个元组中。
在可变数量的参数之前,可能会出现零个或多个普通参数。
"""
def test_function_arbitrary_arguments():
"""任意的参数列表"""
# 当出现 **name 的最后一个正式形参时,它将接收一个字典,其中包含除与正式形参对应的关键字参数外的所有关键字参数。
# 这可以与 *name 的形式参数结合使用,该形式参数接收一个包含形式参数列表之外的位置参数的元组。
# (*name 必须出现在 **name之前。)例如,如果我们这样定义一个函数:
def test_function(first_param, *arguments):
"""这个函数通过“arguments”元组和关键字字典接受它的参数。"""
assert first_param == 'first param'
assert arguments == ('second param', 'third param')
test_function('first param', 'second param', 'third param')
# 通常,这些可变参数将位于形参列表的最后,因为它们将获取传递给函数的所有剩余输入参数。
# 任何出现在*args形参之后的形式形参都是“仅关键字”参数,这意味着它们只能作为关键字而不是位置参数使用。
def concat(*args, sep='/'):
return sep.join(args)
assert concat('earth', 'mars', 'venus') == 'earth/mars/venus'
assert concat('earth', 'mars', 'venus', sep='.') == 'earth.mars.venus'
|
# -*- coding: utf-8 -*-
# @Author : LG
"""
执行用时:40 ms, 在所有 Python3 提交中击败了84.24% 的用户
内存消耗:14.2 MB, 在所有 Python3 提交中击败了5.03%
解题思路:
递归
"""
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def levelOrder(self, root: TreeNode) -> List[List[int]]:
result = []
def find(root, deep): # 使用deep记录当前深度
if root:
if deep > len(result)-1:
result.append([])
result[deep].append(root.val) # 添加到最终结果的对应深度列表中
find(root.left, deep+1) # 处理左子树
find(root.right, deep+1) # 右子树
find(root, 0)
return result |
while True:
try:
comprimento, eventos = [int(x) for x in input().split()]
except EOFError:
break
lucro, utilizado, estacionamento = 0, 0, {} # 'veic' : tamanho
for aux in range(0, eventos):
evento = input().split(' ')
if len(evento) == 3: # entrada veic
if comprimento >= (utilizado + int(evento[2])):
# ok estacionar
utilizado += int(evento[2])
estacionamento[evento[1]] = int(evento[2])
lucro += 10
elif len(evento) == 2: # saida veic
try:
veic_tam = estacionamento[evento[1]]
except:
veic_tam = 0
utilizado -= veic_tam
print(lucro)
|
class EmbeddedDocumentMixin:
_fields = {}
_db_name_map = {}
_dirty_fields = {}
def __init__(self, **kwargs):
self._values = {}
for name, value in kwargs.items():
if name in self._fields:
setattr(self, name, value)
self._make_clean()
def to_mongo(self):
data = {}
for field in self._fields.values():
value = field.to_mongo(
getattr(self, field.name, None))
if value is not None:
data[field.db_name] = value
return data
def to_dict(self, cls=dict):
dct = cls()
for name, field in self._fields.items():
dct[name] = getattr(self, name, None)
return dct
@classmethod
async def from_mongo(cls, dct, resolver):
kwargs = {}
for db_name, value in dct.items():
field_name = cls._db_name_map[db_name]
field = cls._fields[field_name]
value = await field.from_mongo(value, resolver)
kwargs[field_name] = value
return cls(**kwargs)
@property
def is_valid(self):
for field in self._fields.values():
if not field.validate(getattr(self, field.name, None)):
return False
return True
@property
def is_dirty(self):
return len(self._dirty_fields) > 0
def _make_clean(self):
self._dirty_fields = set()
@property
def _identity(self):
return getattr(self, self._db_name_map['_id'], None)
@_identity.setter
def _identity(self, value):
return setattr(self, self._db_name_map['_id'], value)
def __eq__(self, other):
for name in self._fields.keys():
if getattr(self, name, None) != getattr(other, name, None):
return False
return True
def __repr__(self):
name = self.__class__.__name__
args = ','.join([
name + '=' + repr(getattr(self, name, None))
for name, field in self._fields.items()])
return f"{name}({args})"
# return str(self.to_dict())
class DocumentMixin(EmbeddedDocumentMixin):
@classmethod
def qs(self, db):
raise Exception('This method is replaced by the metaclass')
def before_create(self):
pass
def before_update(self):
pass
|
with open("input.txt", "r") as input_file:
input = input_file.read().split("\n")
total = 0
group_answers = {}
for line in input:
if not line:
total += len(group_answers)
group_answers = {}
for char in line:
group_answers[char] = 1
total += len(group_answers)
print(total)
|
class Solution:
def calPoints(self, ops):
"""
:type ops: List[str]
:rtype: int
"""
opsstack = []
point = 0
for o in ops:
p = 0
if o == '+':
p = opsstack[-1] + opsstack[-2]
point += p
opsstack.append(p)
elif o == 'C':
p = opsstack[-1]
opsstack.pop()
point -= p
elif o == 'D':
p = opsstack[-1] * 2
point += p
opsstack.append(p)
else:
p = int(o)
point += p
opsstack.append(p)
return point
if __name__ == '__main__':
solution = Solution()
print(solution.calPoints(["5","2","C","D","+"]))
print(solution.calPoints(["5","-2","4","C","D","9","+","+"]))
else:
pass
|
# This file is implements of 'The elements of computer systesm'
# chap 6.Assembler
# author:gongqingkui AT 126.com
# date:2021-09-18
jumpTable = {
'null': '000',
'JGT': '001',
'JEQ': '010',
'JGE': '011',
'JLT': '100',
'JNE': '101',
'JLE': '110',
'JMP': '111'}
compTable = {
# a = 0 A
'0': '0101010', '1': '0111111', '-1': '0111010', 'D': '0001100',
'A': '0110000', '!D': '0001101', '!A': '0110001', '-D': '0001111',
'-A': '0110011', 'D+1': '0011111', 'A+1': '0110111', 'D-1': '0001110',
'A-1': '0110010', 'D+A': '0000010', 'D-A': '0010011', 'A-D': '0000111',
'D&A': '0000000', 'D|A': '0010101',
# a = 1 M
'M': '1110000', '!M': '1110001', '-M': '1110011', 'M+1': '1110111',
'M-1': '1110010', 'D+M': '1000010', 'D-M': '1010011', 'M-D': '1000111',
'D&M': '1000000', 'D|M': '1010101',
}
def destCode(amd=None):
return '%s%s%s' % ('1' if 'A' in amd else '0',
'1' if 'D' in amd else '0',
'1' if 'M' in amd else '0')
def compCode(c=None):
return compTable[c]
def jumpCode(j=None):
return jumpTable[j]
if __name__ == '__main__':
# D=M+A
print(destCode('D'), compCode('D-1'), jumpCode('null'))
# D;JLE
print(destCode('null'), compCode('D'), jumpCode('JLE'))
|
# -*- encoding: utf-8 -*-
'''
__author__ = "Larry_Pavanery
'''
class User(object):
def __init__(self, id, url_keys=[]):
self.id = id
self.url_keys = url_keys
|
#评价器
def create_critic_network(self, state_size, action_dim):
print("Now we build the model")
S = Input(shape=[state_size])
A = Input(shape=[action_dim], name='action2')
w1 = Dense(HIDDEN1_UNITS, activation='relu')(S)
a1 = Dense(HIDDEN2_UNITS, activation='linear')(A)
h1 = Dense(HIDDEN2_UNITS, activation='linear')(w1)
h2 = merge([h1, a1], mode='sum')
h3 = Dense(HIDDEN2_UNITS, activation='relu')(h2)
V = Dense(action_dim, activation='linear')(h3)
model = Model(input=[S, A], output=V)
adam = Adam(lr=self.LEARNING_RATE)
model.compile(loss='mse', optimizer=adam)
print("We finished building the model")
return model, A, S |
def vmax(lista):
n = 0
for c in range(len(lista)):
for i in range(len(lista)):
if lista[i] > lista[c]:
n = i
return n
freq = []
num = int(input())
lista = list(range(2, num + 1))
n = num
n_1 = 0
c = 0
while True:
print(n_1)
if n_1 <= len(lista) - 1:
if n % lista[n_1] == 0:
c += 1
n = n / lista[n_1]
else:
n_1 += 1
freq.append(c)
c = 0
n = num
else:
break
mais_fre = lista[vmax(freq)]
frequencia = max(freq)
print('mostFrequent: {}, frequency: {}'.format(mais_fre, frequencia)) |
mp = 'Today is a Great DAY'
print(mp.lower())
print(mp.upper())
print(mp.strip())
print(mp.startswith('w'))
print(mp.find('a'))
|
"""
Trie tree.
"""
class TrieNode:
def __init__(self, data: str):
self.data = data
self.children = [None] * 26
self.is_ending_char = False
class TrieTree:
def __init__(self):
self._root = TrieNode('/')
def insert(self, word: str) -> None:
p = self._root
a_index = ord('a')
for i in range(len(word)):
index = ord(word[i]) - a_index
if p.children[index] is None:
np = TrieNode(word[i])
p.children[index] = np
p = p.children[index]
p.is_ending_char = True
def find(self, pattern: str) -> bool:
p = self._root
a_index = ord('a')
for i in range(len(pattern)):
index = ord(pattern[i]) - a_index
if p.children[index] is None:
return False
p = p.children[index]
return p.is_ending_char
if __name__ == '__main__':
t = TrieTree()
text = ['work', 'audio', 'zodic', 'element', 'world']
for w in text:
t.insert(w)
print(t.find('work'), t.find('audi'), t.find('zodicx'), t.find('ele'), t.find('world'))
|
#!/usr/bin/env python3
class Node(object):
"""Node class for binary tree"""
def __init__(self, data=None):
self.left = None
self.right = None
self.data = data
class Tree(object):
"""Tree class for binary search"""
def __init__(self, data=None):
self.root = Node(data)
def insert(self, data):
self._add(data, self.root)
def _add(self, data, node):
if data < node.data:
if node.left:
self._add(data, node.left)
else:
node.left = Node(data)
else:
if node.right:
self._add(data, node.right)
else:
node.right = Node(data)
def traverseBFS(self, node):
queue = [node]
out = [] # output buffer
while len(queue) > 0:
currentNode = queue.pop(0)
out.append(currentNode.data)
if currentNode.left:
queue.append(currentNode.left)
if currentNode.right:
queue.append(currentNode.right)
return out
def inorder(self, node, buf=[]):
if node is not None:
self.inorder(node.left, buf)
buf.append(node.data)
self.inorder(node.right, buf)
def preorder(self, node, buf=[]):
if node is not None:
buf.append(node.data)
self.preorder(node.left, buf)
self.preorder(node.right, buf)
def postorder(self, node, buf=[]):
if node is not None:
self.postorder(node.left, buf)
self.postorder(node.right, buf)
buf.append(node.data)
def test(self):
d = self.traverseBFS(self.root)
assert(d == [1,0,5,7,10])
f = []
self.inorder(self.root, f)
assert(f == [0,1,5,7,10])
j = []
self.preorder(self.root, j)
assert(j == [1,0,5,7,10])
l = []
self.postorder(self.root, l)
assert(l == [0,10,7,5,1])
def main():
tree = Tree(1)
data = [5,7,10,0]
for i in data:
tree.insert(i)
tree.test()
if __name__ == '__main__':
main()
|
# Copyright 2017 The Switch Authors. All rights reserved.
# Licensed under the Apache License, Version 2, which is in the LICENSE file.
"""
This package implements a transport model for the transmission network.
The core modules in the package are build and dispatch.
"""
core_modules = [
'switch_model.transmission.transport.build',
'switch_model.transmission.transport.dispatch']
|
# Conversão de Tempo
tempo=int(input())
h=tempo//3600
m=(tempo%3600)//60
s=(tempo%3600)%60
print('{}:{}:{}'.format(h,m,s))
|
# Programa que le a altura de uma parede em metros
# e calcule a sua area e a quantidade de tinta necessaria
# para pinta-la, sabendo que cada litro de tinta, pinta uma area
# de 2m^2
larg = float(input('Digite a largura da parede: '))
alt = float(input('Digite a altura da parede: '))
area = larg * alt
tinta = area / 2
print('A parede tem {}{}{} metros quadrados e para pintar essa parede precisaremos'
' de {} litros de tintas' .format('\033[1;107m', area, '\033[m', tinta))
|
#----------* CHALLENGE 37 *----------
#Ask the user to enter their name and display each letter in their name on a separate line.
name = input("Enter your name: ")
for i in name:
print(i)
|
class Camera(object):
def __init__(self, macaddress, lastsnap='snaps/default.jpg'):
self.macaddress = macaddress
self.lastsnap = lastsnap |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.