content
stringlengths 7
1.05M
|
---|
# -*- coding: utf-8 -*-
#
# Authors: Toni Ruottu, Finland 2014
# Tomi Jylhä-Ollila, Finland 2016-2019
#
# This file is part of Kunquat.
#
# CC0 1.0 Universal, http://creativecommons.org/publicdomain/zero/1.0/
#
# To the extent possible under law, Kunquat Affirmers have waived all
# copyright and related or neighboring rights to Kunquat.
#
class HitKeymapID:
pass
class KeyboardAction():
NOTE = 'note'
OCTAVE_DOWN = 'octave_down'
OCTAVE_UP = 'octave_up'
PLAY = 'play'
REST = 'rest'
SILENCE = 'silence'
def __init__(self, action_type):
super().__init__()
self.action_type = action_type
def __eq__(self, other):
return (self.action_type == other.action_type)
def __hash__(self):
return hash(self.action_type)
class KeyboardNoteAction(KeyboardAction):
def __init__(self, row, index):
super().__init__(KeyboardAction.NOTE)
self.row = row
self.index = index
def _get_fields(self):
return (self.action_type, self.row, self.index)
def __eq__(self, other):
if not isinstance(other, KeyboardNoteAction):
return False
return (self._get_fields() == other._get_fields())
def __hash__(self):
return hash(self._get_fields())
_hit_keymap = {
'is_hit_keymap': True,
'name': 'Hits',
'keymap': [
[0, 7, 1, 8, 2, 9, 3, 10, 4, 11, 5, 12, 6, 13,
14, 23, 15, 24, 16, 25, 17, 26, 18, 27, 19, 28, 20, 29, 21, 30, 22, 31],
[32, 39, 33, 40, 34, 41, 35, 42, 36, 43, 37, 44, 38, 45,
46, 55, 47, 56, 48, 57, 49, 58, 50, 59, 51, 60, 52, 61, 53, 62, 54, 63],
[64, 71, 65, 72, 66, 73, 67, 74, 68, 75, 69, 76, 70, 77,
78, 87, 79, 88, 80, 89, 81, 90, 82, 91, 83, 92, 84, 93, 85, 94, 86, 95],
[96, 103, 97, 104, 98, 105, 99, 106, 100, 107, 101, 108, 102, 109,
110, 119, 111, 120, 112, 121, 113, 122, 114, 123, 115, 124, 116, 125,
117, 126, 118, 127],
],
}
class KeymapManager():
def __init__(self):
self._session = None
self._updater = None
self._ui_model = None
def set_controller(self, controller):
self._session = controller.get_session()
self._updater = controller.get_updater()
self._share = controller.get_share()
def set_ui_model(self, ui_model):
self._ui_model = ui_model
def _are_keymap_actions_valid(self, actions):
ka = KeyboardAction
req_single_action_types = (
ka.OCTAVE_DOWN, ka.OCTAVE_UP, ka.PLAY, ka.REST, ka.SILENCE)
for action_type in req_single_action_types:
if ka(action_type) not in actions:
return False
note_actions = set(a for a in actions if a.action_type == ka.NOTE)
if len(note_actions) != 33:
return False
return True
def get_keyboard_row_sizes(self):
# The number of buttons provided for configuration on each row
# On a QWERTY layout, the leftmost buttons are: 1, Q, A, Z
return (11, 11, 11, 10)
def get_typewriter_row_sizes(self):
return (9, 10, 7, 7)
def get_typewriter_row_offsets(self):
return (1, 0, 1, 0)
def _is_row_layout_valid(self, locs):
row_sizes = self.get_keyboard_row_sizes()
used_locs = set()
for loc in locs:
if loc in used_locs:
return False
used_locs.add(loc)
row, index = loc
if not (0 <= row < len(row_sizes)):
return False
if not (0 <= index < row_sizes[row]):
return False
return True
def set_key_actions(self, actions):
assert self._is_row_layout_valid(actions.keys())
assert self._are_keymap_actions_valid(actions.values())
self._session.keyboard_key_actions = actions
action_locations = { act: loc for (loc, act) in actions.items() }
self._session.keyboard_action_locations = action_locations
def set_key_names(self, names):
assert self._is_row_layout_valid(names.keys())
self._session.keyboard_key_names = names
def set_scancode_locations(self, codes_to_locs):
assert self._is_row_layout_valid(codes_to_locs.values())
self._session.keyboard_scancode_locations = codes_to_locs
def set_key_id_locations(self, ids_to_locs):
assert self._is_row_layout_valid(ids_to_locs.values())
self._session.keyboard_id_locations = ids_to_locs
def get_scancode_location(self, code):
return self._session.keyboard_scancode_locations.get(code, None)
def get_key_id_location(self, key_id):
return self._session.keyboard_id_locations.get(key_id, None)
def get_key_action(self, location):
return self._session.keyboard_key_actions.get(location, None)
def get_key_name(self, location):
return self._session.keyboard_key_names.get(location, None)
def get_action_location(self, action):
if not isinstance(action, KeyboardAction):
assert action != KeyboardAction.NOTE
action = KeyboardAction(action)
return self._session.keyboard_action_locations.get(action, None)
def _get_keymap_ids(self):
notation_mgr = self._ui_model.get_notation_manager()
keymap_ids = notation_mgr.get_notation_ids()
keymap_ids.append(HitKeymapID)
return keymap_ids
def _get_some_keymap_id(self):
keymap_ids = self._get_keymap_ids()
if len(keymap_ids) < 2:
return HitKeymapID
some_id = sorted(keymap_ids)[1]
return some_id
def get_selected_keymap_id(self):
#keymap_ids = self.get_keymap_ids()
selected_id = self._session.get_selected_notation_id() or self._get_some_keymap_id()
return selected_id
def is_hit_keymap_active(self):
return self._session.is_hit_keymap_active()
def get_selected_keymap(self):
if self.is_hit_keymap_active():
return _hit_keymap
notation_mgr = self._ui_model.get_notation_manager()
notation = notation_mgr.get_selected_notation()
return notation.get_keymap()
def set_hit_keymap_active(self, active):
self._session.set_hit_keymap_active(active)
keymap_data = self.get_selected_keymap()
if keymap_data.get('is_hit_keymap', False):
base_octave = 0
else:
base_octave = keymap_data['base_octave']
typewriter_mgr = self._ui_model.get_typewriter_manager()
typewriter_mgr.set_octave(base_octave)
|
#num1=int(raw_input("Enter num #1:"))
#num2=int(raw_input("Enter num #2:"))
#total= num1 + num2
#print("The sum is: "+ str(total))
# need to be a string so computer can read it
# all strings can be integers but not all integers can be strings
# num = int(raw_input("Enter a number:"))
# if num>0:
# print("That's a postive num!")
# elif num<0:
# print("That's a negative num!")
# else:
# print("Zero is neither postive nor negative!")
# string = "hello"
# for letter in string:
# print(letter.upper())
#
# for i in range(5): repaeted executed depend on how may letters in the string so hello would be 5
# print(i)
#
# x=1
# while x <=5:
# print(x)
# x=x+1
# my_name= "B"
# friend1= "A"
# friend2= "J"
# friend3= "M"
# print(
# "My name is %s and my friends are %s, %s, and %s" %
# (my_name,friend1,friend2,friend3 )
# )
#
# name= "C"
# age= 19
# print("My name is "+ name + "and I'm " + str(age)+"years old.") one way
# print("My name is %s and I'm %s years old." %(name,age)) second way
# def greetAgent():
# print("B. James Bond.")
# greetAgent() always call the func
#
# def greetAgent(first_name, last_name):
# print("%s. %s. %s." % (last_name, first_name, last_name))
# One way
#
#
# def createAgentGreeting(first_name, last_name):
# return"%s. %s. %s." % (last_name, first_name, last_name)
#
# print(createAgentGreeting("Citlally", "G"))
# second way
word = "computerz"
print(word[:5]) # prints "compu"
print(word[:-1]) # prints "computer"
print(word[4:]) # prints "uterz"
print(word[-3:]) # prints "erz"
|
# -*- encoding: utf-8 -*-
# This is a package that contains a number of modules that are used to
# test import from the source files that have different encodings.
# This file (the __init__ module of the package), is encoded in utf-8
# and contains a list of strings from various unicode planes that are
# encoded differently to compare them to the same strings encoded
# differently in submodules. The following list, test_strings,
# contains a list of tuples. The first element of each tuple is the
# suffix that should be prepended with 'module_' to arrive at the
# encoded submodule name, the second item is the encoding and the last
# is the test string. The same string is assigned to the variable
# named 'test' inside the submodule. If the decoding of modules works
# correctly, from module_xyz import test should result in the same
# string as listed below in the 'xyz' entry.
# module, encoding, test string
test_strings = (
('iso_8859_1', 'iso-8859-1', "Les hommes ont oublié cette vérité, "
"dit le renard. Mais tu ne dois pas l'oublier. Tu deviens "
"responsable pour toujours de ce que tu as apprivoisé."),
('koi8_r', 'koi8-r', "Познание бесконечности требует бесконечного времени.")
)
|
class SinavroObject: pass
def init(self, val): self.value = val
gencls = lambda n: type(f'Sinavro{n.title()}', (SinavroObject,), {'__init__': init, 'type': n})
SinavroInt = gencls('int')
SinavroFloat = gencls('float')
SinavroString = gencls('string')
SinavroBool = gencls('bool')
SinavroArray = gencls('array')
|
'''
191. Number of 1 Bits
Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight).
For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, so the function should return 3.
'''
class Solution(object):
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
que=[]
offset = 2
while n!=0:
if n%offset == 1:
que.append(1)
n=n//2
return len(que)
if __name__ == '__main__':
solution = Solution()
t1=11
print(solution.hammingWeight(t1))
|
def lambda_handler(event):
try:
first_num = event["queryStringParameters"]["firstNum"]
except KeyError:
first_num = 0
try:
second_num = event["queryStringParameters"]["secondNum"]
except KeyError:
second_num = 0
try:
operation_type = event["queryStringParameters"]["operation"]
if operation_type == "add":
result = add(first_num, second_num)
elif operation_type == "subtract":
result = subtract(first_num, second_num)
elif operation_type == "subtract":
result = multiply(first_num, second_num)
else:
result = "No Operation"
except KeyError:
return "No Operation"
return result
def add(first_num, second_num):
result = int(first_num) + int(second_num)
print("The result of % s + % s = %s" % (first_num, second_num, result))
return {"body": result, "statusCode": 200}
def subtract(first_num, second_num):
result = int(first_num) - int(second_num)
print("The result of % s - % s = %s" % (first_num, second_num, result))
return {"body": result, "statusCode": 200}
def multiply(first_num, second_num):
result = int(first_num) * int(second_num)
print("The result of % s * % s = %s" % (first_num, second_num, result))
return {"body": result, "statusCode": 200}
|
input1 = int(input("Enter the first number: "))
input2 = int(input("Enter the second number: "))
input3 = int(input("Enter the third number: "))
input4 = int(input("Enter the fourth number: "))
input5 = int(input("Enter the fifth number: "))
tuple_num = []
tuple_num.append(input1)
tuple_num.append(input2)
tuple_num.append(input3)
tuple_num.append(input4)
tuple_num.append(input5)
print(tuple_num)
tuple_num.sort()
for a in tuple_num:
print(a * a) |
# Time: O(n!)
# Space: O(n)
class Solution(object):
def constructDistancedSequence(self, n):
"""
:type n: int
:rtype: List[int]
"""
def backtracking(n, i, result, lookup):
if i == len(result):
return True
if result[i]:
return backtracking(n, i+1, result, lookup)
for x in reversed(range(1, n+1)):
j = i if x == 1 else i+x
if lookup[x] or j >= len(result) or result[j]:
continue
result[i], result[j], lookup[x] = x, x, True
if backtracking(n, i+1, result, lookup):
return True
result[i], result[j], lookup[x] = 0, 0, False
return False
result, lookup = [0]*(2*n-1), [False]*(n+1)
backtracking(n, 0, result, lookup)
return result
|
#Longest Common Prefix in python
#Implementation of python program to find the longest common prefix amongst the given list of strings.
#If there is no common prefix then returning 0.
#define the function to evaluate the longest common prefix
def longestCommonPrefix(s):
p = '' #declare an empty string
for i in range(len(min(s, key=len))):
f = s[0][i]
for j in s[1:]:
if j[i] != f:
return p
p += f
return p #return the longest common prefix
n = int(input("Enter the number of names in list for input:"))
print("Enter the Strings:")
s = [input() for i in range(n)]
if(longestCommonPrefix(s)):
print("The Common Prefix is:" ,longestCommonPrefix(s))
else:
print("There is no common prefix for the given list of strings, hence the answer is:", 0) |
#!/usr/bin/env python
P = int(input())
for _ in range(P):
N, n, m = [int(i) for i in input().split()]
print(f"{N} {(n - m) * m + 1}")
|
def handler(event, context):
return {
"statusCode": 302,
"headers": {
"Location": "https://www.nhsx.nhs.uk/covid-19-response/data-and-covid-19/national-covid-19-chest-imaging-database-nccid/"
},
}
|
# Utwórz klasy do reprezentacji Produktu, Zamówienia, Jabłek i Ziemniaków.
# Stwórz po kilka obiektów typu jabłko i ziemniak i wypisz ich typ za pomocą funkcji wbudowanej type.
# Stwórz listę zawierającą 5 zamówień oraz słownik, w którym kluczami będą nazwy produktów
# a wartościami instancje klasy produkt.
class Product:
pass
class Order:
pass
class Apple:
pass
class Potato:
pass
if __name__ == '__main__':
green_apple = Apple()
red_apple = Apple()
fresh_apple = Apple()
print("green apple type:", type(green_apple))
print("red apple type:", type(red_apple))
print("fresh apple type:", type(fresh_apple))
old_potato = Potato()
young_potato = Potato()
print("old potato type:", type(old_potato))
print("young potato type:", type(young_potato))
# orders = [Order(), Order(), Order(), Order(), Order()]
orders = []
for _ in range(5):
orders.append(Order())
print(orders)
products = {
"Jabłko": Product(),
"Ziemniak": Product(),
"Marchew": Product(),
"Ciastka": Product(),
}
print(products)
|
def bin2dec(binNumber):
decNumber = 0
index = 1
binNumber = binNumber[::-1]
for i in binNumber:
number = int(i) * index
decNumber = decNumber + number
index = index * 2
return decNumber
print('ВВЕДИТЕ ДВОИЧНОЕ 8-БИТНОЕ ЧИСЛО')
binNumber = input('>')
if len(binNumber) != 8:
print('ВВЕДИТЕ ПРАВИЛЬНОЕ 8-БИТНОЕ ЧИСЛО')
elif not binNumber.isdigit():
print('ВВЕДИТЕ ПРАВИЛЬНОЕ 8-БИТНОЕ ЧИСЛО')
else:
print(bin2dec(binNumber)) |
__name__ = 'factory_djoy'
__version__ = '2.2.0'
__author__ = 'James Cooke'
__copyright__ = '2021, {}'.format(__author__)
__description__ = 'Factories for Django, creating valid model instances every time.'
__email__ = 'github@jamescooke.info'
|
def get_lorawan_maximum_payload_size(dr):
mac_payload_size_dic = {'0':59, '1':59, '2':59, '3':123, '4':230, '5':230, '6':230}
fhdr_size = 7 #in bytes. Assuming that FOpts length is zero
fport_size = 1 #in bytes
frm_payload_size = mac_payload_size_dic.get(str(dr)) - fhdr_size - fport_size
return frm_payload_size
def get_data_pointers(buff):
block_size = 51 # include 2 bytes for Checksum
n_block = math.ceil(len(buff)/block_size)
ptrs = list()
for i in range(n_block):
ptr_start = block_size*i
if i == n_block-1:
ptr_end = len(buff)-2
else:
ptr_end = block_size*(i+1)-2
#if check_fletcher16(buff[ptr_start:ptr_end+2]):
if mula(buff[ptr_start:ptr_end+2]):
print("LoPy4 - PROCESS - Checksum OK")
ptrs.append((ptr_start,ptr_end))
else:
print("LoPy4 - PROCESS - Checksum Error")
print(ptrs)
return ptrs
def mula(buff):
return True
def get_file_size(filename):
# https://docs.pycom.io/firmwareapi/micropython/uos/
# Returns file size in bytes
return os.stat(filename)[6]
def get_free_space(path):
# Returns available space in KiB
return os.getfree(path)
def file_exists_in_folder(filename, folder):
lowercase_ls = list(map(lambda x: x.lower(), os.listdir(folder)))
return filename.lower() in lowercase_ls
def save_text_file_sd(readings: list, index: int):
'''
Usage:
file_index = save_text_file_sd(decoded_data, file_index)
'''
if get_free_space(SD_MOUNT_POINT) < 2:
print("LoPy4 - SD - Too litle space available!")
filename = ('data%d' % index) + '.csv'
filepath = SD_MOUNT_POINT + '/' + filename
if file_exists_in_folder(filename, SD_MOUNT_POINT) and get_file_size(filename) > MAX_FILE_SIZE:
index += 1
filepath = SD_MOUNT_POINT + ('/data%d' % index) + '.csv'
print("LoPy4 - SD - Writing in", filepath)
with open(filepath, 'a') as f:
for reading in readings:
row = '%d;%d;%.1f\n' % reading
f.write(row)
f.flush()
os.sync()
return index
print("LoPy4 - Initializing communication values...")
m_dr = DATA_RATE
print("LoPy4 - LoRaWAN - Initial Data Rate: ", m_dr)
lorawan_mtu = get_lorawan_maximum_payload_size(m_dr)
print("LoPy4 - LoRaWAN - Initial Maximum Payload Size: %d bytes" % lorawan_mtu)
print("LoPy4 - Starting Loop...")
a = 1
while True:
print("*****************************")
print("LoPy4 - SERIAL_RX - Cleaning Serial Rx buffer")
n_bytes = uart.any()
buff = uart.read(n_bytes)
print("LoPy4 - SERIAL_RX - num bytes recv and dropped: %d" % n_bytes)
print("LoPy4 - Loop %d" % a)
a=a+1
print("LoPy4 - Going to sleep...")
time.sleep(3)
machine.sleep(50 * 1000) # 50 s
print("Wake up...")
# Se lee el mensaje serial proveniente desde el Arduino
start = time.ticks_ms()
recv_bytes = bytes()
n_bytes = 0
recv_len = -1
while True:
if time.ticks_diff(time.ticks_ms(), start) > 3000:
break
n_bytes = uart.any()
if n_bytes != 0:
recv_bytes = recv_bytes + uart.read(n_bytes)
recv_len = len(recv_bytes)
print("LoPy4 - SERIAL_RX - num bytes recv: %d" % n_bytes)
print("LoPy4 - SERIAL_RX - bytes recv: %s" % ubinascii.hexlify(recv_bytes))
print("LoPy4 - SERIAL_RX - total recv_bytes: %d" % recv_len)
if(recv_len != 0):
print("LoPy4 - SERIAL_RX - Dropping 1st byte (Dummy RX)")
recv_bytes = recv_bytes[1:] # Ahora sí son el mismo mensaje
print("LoPy4 - SERIAL_RX - actual recv msg (%d bytes): %s" % (recv_len, ubinascii.hexlify(recv_bytes)))
print("LoPy4 - DECODED : ", end='')
decoded_data = decode_payload(recv_bytes)
print(decoded_data)
file_index = save_text_file_sd(decoded_data, file_index)
# se obtiene el tamaño máximo disponible para un mensaje LoRaWAN
print("LoPy4 - LoRaWAN - Data Rate: ", m_dr)
lorawan_mtu = get_lorawan_maximum_payload_size(m_dr)
print("LoPy4 - LoRaWAN - Maximum Payload Size: %d bytes" % lorawan_mtu)
ptrs = get_data_pointers(recv_bytes)
block_size = 49 # bytes
blocks_per_mtu = lorawan_mtu//block_size # n° blocks per a LoRaWAN message
n_lorawan_messages = math.ceil(len(ptrs)/blocks_per_mtu)
n_blocks_in_full_lorawan_msg = blocks_per_mtu * (len(ptrs)//blocks_per_mtu)
print("LoPy4 - LoRaWAN - The current LoRaWAN MTU supports %d blocks" % blocks_per_mtu)
print("LoPy4 - LoRaWAN - The %d blocks are sent in multiple (%d) LoRaWAN messages" % (len(ptrs),n_lorawan_messages))
print("LoPy4 - LoRaWAN - blocks_per_mtu: %d" % blocks_per_mtu)
print("LoPy4 - LoRaWAN - len(ptrs): %d" % len(ptrs))
print("LoPy4 - LoRaWAN - n_blocks_in_full_lorawan_msg: %d" % n_blocks_in_full_lorawan_msg)
i = 0
while i < n_blocks_in_full_lorawan_msg:
aux = bytearray()
for _ in range(blocks_per_mtu):
aux += recv_bytes[ptrs[i][0]:ptrs[i][1]]
i += 1
try:
s.setblocking(True)
print("LoPy4 - LoRaWAN - Sending %d bytes" % len(aux))
s.send(aux)
s.setblocking(False)
except OSError as e:
if e.args[0] == 11:
s.setblocking(False)
print("LoPy4 - LoRaWAN_ERROR - It can probably be a duty cycle problem")
if n_blocks_in_full_lorawan_msg != len(ptrs):
aux = bytearray()
for i in range(n_blocks_in_full_lorawan_msg, len(ptrs)):
aux += recv_bytes[ptrs[i][0]:ptrs[i][1]]
try:
s.setblocking(True)
print("LoPy4 - LoRaWAN - Sending %d bytes" % len(aux))
s.send(aux)
s.setblocking(False)
except OSError as e:
if e.args[0] == 11:
s.setblocking(False)
print("LoPy4 - LoRaWAN_ERROR - It can probably be a duty cycle problem")
|
class CyclesMeshSettings:
pass
|
l = ["+", "-"]
def backRec(x):
for j in l:
x.append(j)
if consistent(x):
if solution(x):
solutionFound(x)
backRec(x)
x.pop()
def consistent(s):
return len(s) < n
def solution(s):
summ = list2[0]
if not len(s) == n - 1:
return False
for i in range(n - 1):
if s[i] == "-":
summ -= list2[i + 1]
else:
summ += list2[i + 1]
return summ > 0
def solutionFound(s):
print(s)
n = int(input("Give number"))
list2 = []
for i in range(n):
list2.append(int(input(str(i) + ":")))
backRec([])
|
"""
Triangle Challenge
Given the perimeter and the area of a triangle, devise a function that returns the length of the sides of all triangles that fit those specifications. The length of the sides must be integers. Sort results in ascending order.
triangle(perimeter, area) ➞ [[s1, s2, s3]]
Examples
triangle(12, 6) ➞ [[3, 4, 5]]
triangle(45, 97.42786) ➞ [[15, 15, 15]]
triangle(70, 210) ➞ [[17, 25, 28], [20, 21, 29]]
triangle(3, 0.43301) ➞ [[1, 1, 1]]
Notes
def triangle(p,a):
r=[]
s=p/2
for x in range(1,p//2+1):
for y in range(int(s-x+1),p//2+1):
z=p-x-y
if round((s*(s-x)*(s-y)*(s-z))**.5,5)==a:
new=sorted((x,y,z))
if new not in r:
r.append(new)
return sorted(r)
"""
def triangle(perimeter,area):
p,q=perimeter,[]
u = []
for a in range(1,p//2+1):
for b in range(p//2+1-a,p//2+1):
c= p - (a+b)
if round(((p/2)*(p/2-a)*(p/2-b)*(p/2-c))**0.5,3) == round(area,3):
u.append(a)
u.append(b)
u.append(c)
for i in range(len(u)//3):
if not sorted([u[3*i],u[3*i+1],u[3*i+2]]) in q:
q.append (sorted([u[3*i],u[3*i+1],u[3*i+2]]))
return q
##(p/2>a) and (p/2>b) and(p/2>c) and
#triangle(3, 0.43301) #, [[1, 1, 1]])
#triangle(201, 49.99937) #, [[1, 100, 100]])
#triangle(98, 420) #, [[24, 37, 37], [25, 34, 39], [29, 29, 40]])
#triangle(70, 210) #, [[17, 25, 28], [20, 21, 29]])
#triangle(30, 30) #, [[5, 12, 13]])
triangle(1792, 55440) #, [[170, 761, 861], [291, 626, 875]])
#triangle(150, 420) #, [[26, 51, 73]])
#triangle(864, 23760) #, [[132, 366, 366], [135, 352, 377]]) |
# block between mission & 6th and howard & 5th in SF.
# appears to have lots of buses.
# https://www.openstreetmap.org/way/88572932 -- Mission St
# https://www.openstreetmap.org/relation/3406710 -- 14X to Daly City
# https://www.openstreetmap.org/relation/3406709 -- 14X to Downtown
# https://www.openstreetmap.org/relation/3406708 -- 14R to Mission
# https://www.openstreetmap.org/relation/3000713 -- 14R to Downtown
# ... and many more bus route relations
z, x, y = (16, 10484, 25329)
# test that at least one is present in tiles up to z12
while z >= 12:
assert_has_feature(
z, x, y, 'roads',
{ 'is_bus_route': True })
z, x, y = (z-1, x/2, y/2)
# but that none are present in the parent tile at z11
assert_no_matching_feature(
z, x, y, 'roads',
{ 'is_bus_route': True })
|
class Zoo:
def __init__(self, name, locations):
self.name = name
self.stillActive = True
self.locations = locations
self.currentLocation = self.locations[1]
def changeLocation(self, direction):
neighborID = self.currentLocation.neighbors[direction]
self.currentLocation = self.locations[neighborID]
def exit(self):
if self.currentLocation.allowExit:
self.stillActive = False
class Location:
def __init__(self, id, name, animal, neighbors, allowExit):
self.id = id
self.name = name
self.animal = animal
self.neighbors = neighbors
self.allowExit = allowExit
class Animal:
def __init__(self, name, soundMade, foodEaten, shelterType):
self.name = name
self.soundMade = soundMade
self.foodEaten = foodEaten
self.shelterType = shelterType
def speak(self):
return 'The ' + self.name + ' sounds like: ' + self.soundMade
def diet(self):
return 'The ' + self.name + ' eats ' + self.foodEaten
def shelter(self):
return 'The ' + self.name + ' prefers: ' + self.shelterType
|
UNKNOWN = u''
def describe_track(track):
"""
Prepare a short human-readable Track description.
track (mopidy.models.Track): Track to source song data from.
"""
title = track.name or UNKNOWN
# Simple/regular case: normal song (e.g. from Spotify).
if track.artists:
artist = next(iter(track.artists)).name
elif track.album and track.album.artists: # Album-only artist case.
artist = next(iter(track.album.artists)).name
else:
artist = UNKNOWN
if track.album and track.album.name:
album = track.album.name
else:
album = UNKNOWN
return u';'.join([title, artist, album])
def describe_stream(raw_title):
"""
Attempt to parse given stream title in very rudimentary way.
"""
title = UNKNOWN
artist = UNKNOWN
album = UNKNOWN
# Very common separator.
if '-' in raw_title:
parts = raw_title.split('-')
artist = parts[0].strip()
title = parts[1].strip()
else:
# Just assume we only have track title.
title = raw_title
return u';'.join([title, artist, album])
|
# -*- coding: utf-8 -*-
class Tile(int):
TILES = '''
1s 2s 3s 4s 5s 6s 7s 8s 9s
1p 2p 3p 4p 5p 6p 7p 8p 9p
1m 2m 3m 4m 5m 6m 7m 8m 9m
ew sw ww nw
wd gd rd
'''.split()
def as_data(self):
return self.TILES[self // 4]
class TilesConverter(object):
@staticmethod
def to_one_line_string(tiles):
"""
Convert 136 tiles array to the one line string
Example of output 123s123p123m33z
"""
tiles = sorted(tiles)
man = [t for t in tiles if t < 36]
pin = [t for t in tiles if 36 <= t < 72]
pin = [t - 36 for t in pin]
sou = [t for t in tiles if 72 <= t < 108]
sou = [t - 72 for t in sou]
honors = [t for t in tiles if t >= 108]
honors = [t - 108 for t in honors]
sou = sou and ''.join([str((i // 4) + 1) for i in sou]) + 's' or ''
pin = pin and ''.join([str((i // 4) + 1) for i in pin]) + 'p' or ''
man = man and ''.join([str((i // 4) + 1) for i in man]) + 'm' or ''
honors = honors and ''.join([str((i // 4) + 1) for i in honors]) + 'z' or ''
return man + pin + sou + honors
@staticmethod
def to_34_array(tiles):
"""
Convert 136 array to the 34 tiles array
"""
results = [0] * 34
for tile in tiles:
tile //= 4
results[tile] += 1
return results
@staticmethod
def string_to_136_array(sou=None, pin=None, man=None, honors=None):
"""
Method to convert one line string tiles format to the 136 array
We need it to increase readability of our tests
"""
def _split_string(string, offset):
data = []
if not string:
return []
for i in string:
tile = offset + (int(i) - 1) * 4
data.append(tile)
return data
results = _split_string(man, 0)
results += _split_string(pin, 36)
results += _split_string(sou, 72)
results += _split_string(honors, 108)
return results
@staticmethod
def string_to_34_array(sou=None, pin=None, man=None, honors=None):
"""
Method to convert one line string tiles format to the 34 array
We need it to increase readability of our tests
"""
results = TilesConverter.string_to_136_array(sou, pin, man, honors)
results = TilesConverter.to_34_array(results)
return results
@staticmethod
def find_34_tile_in_136_array(tile34, tiles):
"""
Our shanten calculator will operate with 34 tiles format,
after calculations we need to find calculated 34 tile
in player's 136 tiles.
For example we had 0 tile from 34 array
in 136 array it can be present as 0, 1, 2, 3
"""
if tile34 > 33:
return None
tile = tile34 * 4
possible_tiles = [tile] + [tile + i for i in range(1, 4)]
found_tile = None
for possible_tile in possible_tiles:
if possible_tile in tiles:
found_tile = possible_tile
break
return found_tile
|
def test_get_news(sa_session, sa_backend, sa_child_news):
assert(sa_child_news == sa_backend.get_news(sa_child_news.id))
assert(sa_backend.get_news(None) is None)
def test_get_news_list(sa_session, sa_backend, sa_child_news):
assert(sa_child_news in sa_backend.get_news_list())
assert(sa_child_news in sa_backend.get_news_list(
owner=sa_child_news.owner))
assert(sa_child_news in sa_backend.get_news_list(
root_url=sa_child_news.root.url))
assert(sa_child_news in sa_backend.get_news_list(
owner=sa_child_news.owner,
root_url=sa_child_news.root.url
))
def test_news_exists(sa_session, sa_backend, sa_child_news):
assert(sa_backend.news_exists(sa_child_news.id))
sa_backend.delete_news(sa_child_news)
assert(not sa_backend.news_exists(sa_child_news.id))
def test_save_news(sa_session, sa_backend,
sa_schedule, sa_news_model, url_root, content_root):
news = sa_news_model.create_instance(
schedule=sa_schedule,
url=url_root,
title='title',
content=content_root,
summary='summary'
)
assert(news not in sa_backend.get_news_list(sa_schedule.owner, url_root))
sa_backend.save_news(news)
assert(news in sa_backend.get_news_list(sa_schedule.owner, url_root))
def test_delete_news(sa_session, sa_backend, sa_child_news):
assert(sa_backend.news_exists(sa_child_news.id))
sa_backend.delete_news(sa_child_news)
assert(not sa_backend.news_exists(sa_child_news.id))
def test_get_schedule(sa_session, sa_backend, sa_schedule):
assert(sa_schedule == sa_backend.get_schedule(sa_schedule.id))
def test_get_schedules(sa_session, sa_backend, sa_schedule,
sa_owner, url_root):
assert(sa_schedule in sa_backend.get_schedules(sa_owner, url_root))
|
# Implemented from: https://stackoverflow.com/questions/9501337/binary-search-algorithm-in-python
def binary_search(sequence, value):
lo, hi = 0, len(sequence) - 1
while lo <= hi:
mid = (lo + hi) // 2
if sequence[mid] < value:
lo = mid + 1
elif value < sequence[mid]:
hi = mid - 1
else:
return mid
return None
def dfs(graph, node, visited=[]):
if node not in visited:
visited.append(node)
for n in graph[node]:
dfs(graph, n, visited)
return visited
# Implemented from: https://pythoninwonderland.wordpress.com/2017/03/18/how-to-implement-breadth-first-search-in-python/
def bfs(graph, start):
# keep track of all visited nodes
explored = []
# keep track of nodes to be checked
queue = [start]
# keep looping until there are nodes still to be checked
while queue:
# pop shallowest node (first node) from queue
node = queue.pop(0)
if node not in explored:
# add node to list of checked nodes
explored.append(node)
neighbours = graph[node]
# add neighbours of node to queue
for neighbour in neighbours:
queue.append(neighbour)
return explored
|
'''
Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
Example:
Given array nums = [-1, 2, 1, -4], and target = 1.
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
'''
class Solution:
def threeSumClosest(self, nums: list, target: int) -> int:
nums.sort()
closest = 10**10
output = 0
for idx, x in enumerate(nums):
if idx > 0 and nums[idx - 1] == nums[idx]:
continue
l = idx + 1
r = len(nums) - 1
while l < r:
sums = x + nums[l] + nums[r]
subtraction = abs(sums - target)
if sums < target:
if subtraction < abs(closest):
closest = subtraction
output = sums
l += 1
elif sums > target:
if subtraction < abs(closest):
closest = subtraction
output = sums
r -= 1
else:
return target
return output
|
"""An extension for workspace rules."""
load("@bazel_skylib//lib:paths.bzl", "paths")
load("//:dependencies.bzl", "dependencies")
def _workspace_dependencies_impl(ctx):
platform = ctx.os.name if ctx.os.name != "mac os x" else "darwin"
for dependency in dependencies:
ctx.download(
executable = True,
output = dependency["name"],
sha256 = dependency["sha256"][platform],
url = dependency["url"][platform].format(version = dependency["version"]),
)
ctx.file("BUILD.bazel", 'exports_files(glob(["**/*"]))\n')
_workspace_dependencies = repository_rule(_workspace_dependencies_impl)
_WORKSPACE_DEPENDENCIES_REPOSITORY_NAME = "workspace_dependencies"
def workspace_dependencies():
"""A macro for wrapping the workspace_dependencies repository rule with a hardcoded name.
The workspace_dependencies repository rule should be called before any of the other rules in
this Bazel extension.
Hardcoding the target name is useful for consuming it internally. The targets produced by this
rule are only used within the workspace rules.
"""
_workspace_dependencies(
name = _WORKSPACE_DEPENDENCIES_REPOSITORY_NAME,
)
def _workspace_status_impl(ctx):
info_file_json = _convert_status(ctx, ctx.info_file)
version_file_json= _convert_status(ctx, ctx.version_file)
status_merger = ctx.actions.declare_file("status_merger.sh")
workspace_status = ctx.actions.declare_file("workspace_status.json")
ctx.actions.expand_template(
is_executable = True,
output = status_merger,
substitutions = {
"{info_file}": info_file_json.path,
"{version_file}": version_file_json.path,
"{workspace_status}": workspace_status.path,
"{jq}": ctx.executable._jq.path,
},
template = ctx.file._status_merger_tmpl,
)
ctx.actions.run(
executable = status_merger,
inputs = [
info_file_json,
version_file_json,
],
outputs = [workspace_status],
tools = [ctx.executable._jq],
)
return [DefaultInfo(files = depset([workspace_status]))]
def _convert_status(ctx, status_file):
status_file_basename = paths.basename(status_file.path)
status_file_json_name = paths.replace_extension(status_file_basename, ".json")
status_file_json = ctx.actions.declare_file(status_file_json_name)
status_converter = ctx.actions.declare_file("{}_converter.sh".format(status_file_basename))
ctx.actions.expand_template(
is_executable = True,
output = status_converter,
substitutions = {
"{input}": status_file.path,
"{output}": status_file_json.path,
"{jq}": ctx.executable._jq.path,
},
template = ctx.file._status_converter_tmpl,
)
ctx.actions.run(
executable = status_converter,
inputs = [status_file],
outputs = [status_file_json],
tools = [ctx.executable._jq],
)
return status_file_json
workspace_status = rule(
_workspace_status_impl,
attrs = {
"_status_converter_tmpl": attr.label(
allow_single_file = True,
default = "//:status_converter.tmpl.sh",
),
"_status_merger_tmpl": attr.label(
allow_single_file = True,
default = "//:status_merger.tmpl.sh",
),
"_jq": attr.label(
allow_single_file = True,
cfg = "host",
default = "@{}//:jq".format(_WORKSPACE_DEPENDENCIES_REPOSITORY_NAME),
executable = True,
),
},
)
def _yaml_loader(ctx):
# Check if the output file name has the .bzl extension.
out_ext = ctx.attr.out[len(ctx.attr.out)-4:]
if out_ext != ".bzl":
fail("Expected output file ({out}) to have .bzl extension".format(out = ctx.attr.out))
# Get the yq binary path.
yq = ctx.path(ctx.attr._yq)
# Get the YAML src absolute path and convert it to JSON.
src = ctx.path(ctx.attr.src)
res = ctx.execute([yq, "r", "--tojson", src])
if res.return_code != 0:
fail(res.stderr)
ctx.file("file.json", res.stdout)
# Convert the JSON file to the Starlark extension.
converter = ctx.path(ctx.attr._converter)
res = ctx.execute([_python3(ctx), converter, "file.json"])
if res.return_code != 0:
fail(res.stderr)
# Write the .bzl file with the YAML contents converted.
ctx.file(ctx.attr.out, res.stdout)
# An empty BUILD.bazel is only needed to indicate it's a Bazel package.
ctx.file("BUILD.bazel", "")
yaml_loader = repository_rule(
_yaml_loader,
doc = "A repository rule to load a YAML file into a Starlark dictionary",
attrs = {
"src": attr.label(
allow_single_file = True,
doc = "The YAML file to be loaded into a Starlark dictionary",
mandatory = True,
),
"out": attr.string(
doc = "The output file name",
mandatory = True,
),
"_yq": attr.label(
allow_single_file = True,
cfg = "host",
default = "@{}//:yq".format(_WORKSPACE_DEPENDENCIES_REPOSITORY_NAME),
executable = True,
),
"_converter": attr.label(
allow_single_file = True,
default = "//:json_bzl_converter.py",
),
},
)
def _python3(repository_ctx):
"""A helper function to get the Python 3 system interpreter if available. Otherwise, it fails.
"""
for option in ["python", "python3"]:
python = repository_ctx.which(option)
if python != None:
res = repository_ctx.execute([python, "--version"])
if res.return_code != 0:
fail(res.stderr)
version = res.stdout.strip() if res.stdout.strip() != "" else res.stderr.strip()
version = version.split(" ")
if len(version) != 2:
fail("Unable to parse Python output version: {}".format(version))
version = version[1]
major_version = version.split(".")[0]
if int(major_version) == 3:
return python
fail("Python 3 is required")
|
# -*- coding:UTF-8 -*-
'''
MIT License
Copyright (c) 2018 Robin Chen
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.
'''
'''
******************************************************************************
* 文 件:keyboard.py
* 概 述:识别单个机械按键的单击、连击(暂未限制连击次数)、长按、短按动作,并返回事件。
* 版 本:V0.10
* 作 者:Robin Chen
* 日 期:2018年7月26日
* 历 史: 日期 编辑 版本 记录
2018年7月26日 Robin Chen V0.10 创建文件
`
******************************************************************************'''
class KEYBOARD:
cont = 0
def __init__(self, _btnKey, _tmBtn, _btnDef = 1, even_djlong = None, even_lj = None, _pull = None):
self.btn = _btnKey
if _pull == "UP":
self.btn.init(_btnKey.IN, _btnKey.PULL_UP)
elif _pull == "DOWN":
self.btn.init(_btnKey.IN, _btnKey.PULL_DOWN)
else:
self.btn.init(_btnKey.IN)
self.btnDef = _btnDef
self.eve_btnLon = even_djlong
self.evn_Continuous_Clicks = even_lj
self.btnLabDown = 0 # 按钮扫描记次,按下状态
self.btnLabUp = 0 # 按钮扫描记次,弹起状态
self.Continuous_Clicks = 0 # 连续点击次数
self.clock = 10 # 定时器时钟,单位毫秒
_tmBtn.init(freq = (1000 / self.clock))
_tmBtn.callback(self.doBtnScan)
self.staLon = 1 # 长按标志字,1:长按计时,0:长按计次
self.tLon = 3000 # 计时或计次延时,单位毫秒
self.TIME_CONT_CLICKS = 50 # 连击时间间隔,按下和松开的状态保持时间长度,单位,次
'''*************************************************************************
* 功 能:按键扫描
* 说 明:定时器回调函数,用于识别当前按键是否动作,并判断其动作形式。
* 输入参数:
t : 定时器无参回调函数必备,否则调用不成功。
* 输出参数:None
* 返 回 值:True
**************************************************************************'''
# 扫描按键,定时中断调用函数
def doBtnScan(self, t):
global cont
self.btnLabUp = (self.btnLabUp * int(not(self.btn.value() ^ int(not(self.btnDef))))) + int(not(self.btn.value() ^ int(not(self.btnDef))))
btdown = self.btnLabDown
self.btnLabDown = (self.btnLabDown * int(not(self.btn.value() ^ self.btnDef))) + int(not(self.btn.value() ^ self.btnDef))
# 长按计时/计次
# t1:按键保持按下的时长
if (self.btnLabDown * self.clock) == self.tLon:
if self.staLon == 1:
if self.eve_btnLon != None:
self.eve_btnLon() # 按键长按事件,请勿在事件中执行过长时间的程序,否则会报定时器错误。
elif self.staLon == 0:
if self.eve_btnLon != None:
cont += 1
self.eve_btnLon(cont) # 按键长按事件,请勿在事件中执行过长时间的程序,否则会报定时器错误。
self.btnLabDown = 0
if self.btnLabUp > 5:
cont = 0
# 连续点击
if (btdown > 5 and btdown < self.TIME_CONT_CLICKS) and self.btnLabUp > 0:
self.Continuous_Clicks += 1
if (self.btnLabUp > self.TIME_CONT_CLICKS) and (self.Continuous_Clicks > 0) or (self.btnLabDown > self.TIME_CONT_CLICKS) and (self.Continuous_Clicks > 0):
if self.evn_Continuous_Clicks != None:
self.evn_Continuous_Clicks(self.Continuous_Clicks) # 连续点击事件,次数为1时为单击,请勿在事件中执行过长时间的程序,否则会报定时器错误。
self.Continuous_Clicks = 0
|
def print_lol(arr):
for row in arr:
if (isinstance(row, list)):
print_lol(row)
else:
print
row
|
class Source:
"""Source class to define News Source Objects"""
def __init__(self,id,name,description,url,category,country):
self.id = id
self.name = name
self.description = description
self.url = url
self.category = category
self.country = country
class Article:
"""Source class to define Article Objects from a news source"""
def __init__(self,author,article_title,article_description,article_url,image_url,published):
self.author = author
self.article_title = article_title
self.article_description = article_description
self.article_url = article_url
self.image_url = image_url
self.published = published
|
def cwinstart(callobj, *args, **kwargs):
print('cwinstart')
print(' args', repr(args))
for arg in args:
print(' ', arg)
print(' kwargs', len(kwargs))
for k, v in kwargs.items():
print(' ', k, v)
w = callobj(*args, **kwargs)
print(' callobj()->', w)
return w
def cwincall(req1, req2, *args, **kwargs):
print('cwincall')
print(' req1=', req1, 'req2=', req2)
print(' args', repr(args))
for arg in args:
print(' ', arg)
print('kwargs')
for k, v in kwargs.items():
print(' ', k, v)
return 'tomorrow'
|
#!/usr/bin/env python3
# Copyright (C) 2020-2021 The btclib developers
#
# This file is part of btclib. It is subject to the license terms in the
# LICENSE file found in the top-level directory of this distribution.
#
# No part of btclib including this file, may be copied, modified, propagated,
# or distributed except according to the terms contained in the LICENSE file.
"__init__ module for the btclib package."
name = "btclib"
__version__ = "2021.1"
__author__ = "The btclib developers"
__author_email__ = "devs@btclib.org"
__copyright__ = "Copyright (C) 2017-2021 The btclib developers"
__license__ = "MIT License"
|
for num in range(1,6):
#code inside for loop
if num == 4:
continue
#code inside for loop
print(num)
#code outside for loop
print("continue statement executed on num = 4")
|
def get_remain(cpf: str, start: int, upto: int) -> int:
total = 0
for count, num in enumerate(cpf[:upto]):
try:
total += int(num) * (start - count)
except ValueError:
return None
remain = (total * 10) % 11
remain = remain if remain != 10 else 0
return remain
def padronize_date(date: str) -> str:
day, month, year = map(lambda x: x.lstrip("0"), date.split("/"))
day = day if len(day) == 2 else f"0{day}"
month = month if len(month) == 2 else f"0{month}"
year = year if len(year) == 4 else f"{'0'*(4-len(year))}{year}"
return f"{day}/{month}/{year}"
def padronize_time(time: str) -> str:
hour, minute = map(lambda x: x.lstrip("0"), time.split(":"))
hour = hour if len(hour) == 2 else f"0{hour}"
minute = minute if len(minute) == 2 else f"0{minute}"
return f"{hour}:{minute}"
|
class Student:
def __init__(self, name, hours, qpoints):
self.name = name
self.hours = float(hours)
self.qpoints = float(qpoints)
def get_name(self):
return self.name
def get_hours(self):
return self.hours
def get_qpoints(self):
return self.qpoints
def gpa(self):
return self.qpoints / self.hours
def make_student(info_str):
# info_str is a tab-separated line: name hours qpoints
# returns a corresponding Student object
name, hours, qpoints = info_str.split('\t')
return Student(name, hours, qpoints)
def main():
# open the input file for reading
filename = input('Enter the name of the grade file: ')
infile = open(filename, 'r')
# set best to the record for the first student in the file
best = make_student(infile.readline())
# process subsequent lines of the file
for line in infile:
# turn the line into a student record
s = make_student(line)
# if this student is best so far, remember it.
if s.gpa() > best.gpa():
best = s
infile.close()
# print information about the best student
print('The best student is', best.get_name())
print('hours:', best.get_hours())
print('GPA:', best.gpa())
if __name__ == '__main__': main() |
class Solution:
def firstUniqChar(self, s):
table = {}
for ele in s:
table[ele] = table.get(ele, 0) + 1
# for i in range(len(s)):
# if table[s[i]] == 1:
# return i
for ele in s:
if table[ele] == 1:
return s.index(ele)
return -1
if __name__ == '__main__':
s = 'leetcode' # output 0
#s = 'loveleetcode' # output 2
#s = 'llee' # output -1
print(Solution().firstUniqChar(s)) |
#program to compute and print sum of two given integers (more than or equal to zero).
# If given integers or the sum have more than 80 digits, print "overflow".
print("Input first integer:")
x = int(input())
print("Input second integer:")
y = int(input())
if x >= 10 ** 80 or y >= 10 ** 80 or x + y >= 10 ** 80:
print("Overflow!")
else:
print("Sum of the two integers: ",x + y) |
# Crie um programa que leia nome, sexo e idade de várias pessoas, guardando os dados
# de cada pessoa em um dicionário e todos os dicionários em uma lista. No final, mostre:
# A) Quantas pessoas foram cadastradas B) A média de idade C) Uma lista com as mulheres
# D) Uma lista de pessoas com idade acima da média
dados = dict()
lista = list()
somaIdade = media = 0
while True:
dados['nome'] = str(input('Nome: '))
while True:
dados['sexo'] = str(input('Sexo [M/F]: ')).upper()
if dados['sexo'] in 'MF':
break
print('ERRO! Por favor, Digite apenas M ou F.')
if dados['sexo'] in 'N':
break
dados['idade'] = int(input('Idade: '))
somaIdade += dados['idade']
lista.append(dados.copy())
while True:
resp = str(input('Quer continuar? [S/N] ')).upper()
if resp in 'SN':
break
print('ERRO! Responda apenas S ou N.')
if resp in 'N':
break
media = somaIdade / len(lista)
print('-=' * 30)
print(f'A) A quantidade de pessoas cadastradas foi: {len(lista)}')
print(f'B) A média de idade é: {media:5.2f} anos.')
print('C) As mulheres cadastradas são: ', end='')
for p in lista:
if p['sexo'] == 'F':
print(f'{p["nome"]}; ', end='')
print()
print('D) As pessoas que estão acima da média de idade são: ')
for p in lista:
if p['idade'] >= media:
for k, v in p.items():
print(f'{k} = {v}; ', end='')
print()
print('<< ENCERRADO >>')
|
{
"targets": [
{
"target_name": "allofw",
"include_dirs": [
"<!@(pkg-config liballofw --cflags-only-I | sed s/-I//g)",
"<!(node -e \"require('nan')\")"
],
"libraries": [
"<!@(pkg-config liballofw --libs)",
"<!@(pkg-config glew --libs)",
],
"cflags!": [ "-fno-exceptions", "-fno-rtti" ],
"cflags_cc!": [ "-fno-exceptions", "-fno-rtti" ],
"cflags_cc": [
"-std=c++11"
],
'conditions': [
[ 'OS=="mac"', {
'xcode_settings': {
'OTHER_CPLUSPLUSFLAGS' : ['-std=c++11'],
'GCC_ENABLE_CPP_EXCEPTIONS': 'YES',
'GCC_ENABLE_CPP_RTTI': 'YES'
},
} ],
],
"sources": [
"src/allofw.cpp",
"src/node_graphics.cpp",
"src/node_sharedmemory.cpp",
"src/node_opengl.cpp",
"src/node_omnistereo.cpp",
"src/gl3binding/glbind.cpp"
]
}
]
}
|
TOKEN_PREALTA_CLIENTE = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJlbWFpbCI6InJhdWx0ckBnbWFpbC5jb20iLCJleHAiOjQ3MzM1MTA0MDAsIm93bmVyX25hbWUiOiJSYXVsIEVucmlxdWUgVG9ycmVzIFJleWVzIiwidHlwZSI6ImVtYWlsX2NvbmZpcm1hdGlvbl9uZXdfY2xpZW50In0.R-nXh1nXvlBABfEdV1g81mdIzJqMFLvFV7FAP7PQRCM'
TOKEN_PREALTA_CLIENTE_CADUCO = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyIjoibGF0aWVuZGl0YTJAZ2FtaWwuY29tIiwib3duZXJfbmFtZSI6IkFuZ2VsIEdhcmNpYSIsImV4cCI6MTU4NjU3ODg1MCwidHlwZSI6ImVtYWlsX2NvbmZpcm1hdGlvbl9uZXdfY2xpZW50In0.x66iQug11cjmkUHqmZq68gdbN3ffSVyD9MHagrspKRw'
TOKEN_PREALTA_USUARIO = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJlbWFpbCI6InJhdWx0ckBnbWFpbC5jb20iLCJleHAiOjQ3MzM1MTA0MDAsIm5hbWUiOiJSYXVsIEVucmlxdWUgVG9ycmVzIFJleWVzIiwic2NoZW1hX25hbWUiOiJtaXRpZW5kaXRhIiwidHlwZSI6ImVtYWlsX2NvbmZpcm1hdGlvbl9uZXdfdXNlciJ9.gcagbNxnNxIkgZbP0mu-9MudiFb9b6cKvttPF4EHH5E'
TOKEN_USUARIO_LOGIN = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJlbWFpbCI6InJhdWx0ckBnbWFpbC5jb20iLCJleHAiOjQ3MzM1MTA0MDAsInNjaGVtYV9uYW1lIjoibWl0aWVuZGl0YSIsInR5cGUiOiJ1c2VyX2xvZ2luIn0.vCdeH0iP94XBucXYtWZvEQq7CuEr-P80SdfIjN673qI'
|
"""
It converts Strings in the format
# to deactivate commands just comment them out by putting a # to the beginning of the line
# optional commands can be deactivated by putting a # to the lines' beginning and activated by removing # from the beginning
# replace 'example.com' with the hostname or ip address of the server the configuration structure 'servers/trufiwebsite' is for
host=example.com
# replace '22' with the port number the SSH server running on the server listens to and which the firewall allows to pass
port=22
# replace 'example' with the name of the UNIX server on the server to remote log in as
user=example
# optional but required when 'password' has been NOT set. Location to the ssh private key
private_key=./sshkey
# optional but required when 'private_key' has been set. Location to the ssh public key
public_key=./sshkey.pub
# optional but required when 'private_key' has been NOT set. The password to log into the server
password=GhSEs6G(%rfh&54§\"
# if both 'private_key' and 'password' are provided then the key authentication will be tried first.
# It's a general advise not to use password authentication and to deactivate it on the server explicitly.
# If you really can't use key authentication then please use password authentication under the following conditions:
# - contains at least 20 characters
# - contains lower- and uppercase letters, symbols, underscores, minus, special characters like & % ( ) | < > / [ ] =
# Pro Tipp: Use characters from other alphabetic systems like the Japanese or Arabic one as long as you stick to the UTF8 codepage´
to a python dictionary
{
"host": "example.com",
"port": "22",
"user": "example",
"private_key": "./sshkey",
"public_key": "./sshkey.pub",
"password": "GhSEs6G(%rfh&54§\""
}
"""
class ConfigParser():
def __init__(self, filepath, debug=False):
self.filepath = filepath
self.debug = debug
self.config = {}
sfile = open(filepath, "r")
filebuffer = sfile.read()
sfile.close()
for line in filebuffer.split("\n"):
if line.strip() == "":
continue
# 1. strip out the comment string starting with #
commentStarts = line.find("#")
if commentStarts == -1: commentStarts = len(line)-1
commandString = line[0:commentStarts+1].strip()
if commandString == "#": continue # means this is a comment line
#print(commandString)
# 2. parse the command
commandString = commandString.split("=")
# 3. map them to a dict (key-value pair consisting of all strings)
self.config[commandString[0].strip()] = commandString[1].strip()
|
SRM_TO_HEX = {
"0": "#FFFFFF",
"1": "#F3F993",
"2": "#F5F75C",
"3": "#F6F513",
"4": "#EAE615",
"5": "#E0D01B",
"6": "#D5BC26",
"7": "#CDAA37",
"8": "#C1963C",
"9": "#BE8C3A",
"10": "#BE823A",
"11": "#C17A37",
"12": "#BF7138",
"13": "#BC6733",
"14": "#B26033",
"15": "#A85839",
"16": "#985336",
"17": "#8D4C32",
"18": "#7C452D",
"19": "#6B3A1E",
"20": "#5D341A",
"21": "#4E2A0C",
"22": "#4A2727",
"23": "#361F1B",
"24": "#261716",
"25": "#231716",
"26": "#19100F",
"27": "#16100F",
"28": "#120D0C",
"29": "#100B0A",
"30": "#050B0A"
}
WATER_L_PER_GRAIN_KG = 2.5
MAIN_STYLES = {
"1": "LIGHT LAGER",
"2": "PILSNER",
"3": "EUROPEAN AMBER LAGER",
"4": "DARK LAGER",
"5": "BOCK",
"6": "LIGHT HYBRID BEER",
"7": "AMBER HYBRID BEER",
"8": "ENGLISH PALE ALE",
"9": "SCOTTISH AND IRISH ALE",
"10": "AMERICAN ALE",
"11": "ENGLISH BROWN ALE",
"12": "PORTER",
"13": "STOUT",
"14": "INDIA PALE ALE (IPA)",
"15": "GERMAN WHEAT AND RYE BEER",
"16": "BELGIAN AND FRENCH ALE",
"17": "SOUR ALE",
"18": "BELGIAN STRONG ALE",
"19": "STRONG ALE",
"20": "FRUIT BEER",
"21": "SPICE / HERB / VEGETABLE BEER",
"22": "SMOKE-FLAVORED AND WOOD-AGED BEER",
"23": "SPECIALTY BEER",
"24": "TRADITIONAL MEAD",
"25": "MELOMEL (FRUIT MEAD)",
"26": "OTHER MEAD",
"27": "STANDARD CIDER AND PERRY",
"28": "SPECIALTY CIDER AND PERRY"
}
|
# ------ [ API ] ------
API = '/api'
# ---------- [ BLOCKCHAIN ] ----------
API_BLOCKCHAIN = f'{API}/blockchain'
API_BLOCKCHAIN_LENGTH = f'{API_BLOCKCHAIN}/length'
API_BLOCKCHAIN_BLOCKS = f'{API_BLOCKCHAIN}/blocks'
# ---------- [ BROADCASTS ] ----------
API_BROADCASTS = f'{API}/broadcasts'
API_BROADCASTS_NEW_BLOCK = f'{API_BROADCASTS}/new_block'
API_BROADCASTS_NEW_TRANSACTION = f'{API_BROADCASTS}/new_transaction'
# ---------- [ TRANSACTIONS ] ----------
API_TRANSACTIONS = f'{API}/transactions'
API_TRANSACTIONS_PENDING = f'{API_TRANSACTIONS}/pending'
API_TRANSACTIONS_UTXO = f'{API_TRANSACTIONS}/UTXO'
# ---------- [ NODES ] ----------
API_NODES = f'{API}/nodes'
API_NODES_LIST = f'{API_NODES}/list'
API_NODES_INFO = f'{API_NODES}/info'
API_NODES_REGISTER = f'{API_NODES}/register'
# ------ [ WEB ] ------
WEB_HOME = '/'
WEB_SELECTOR = '/selector'
WEB_CHAT = '/chat'
WEB_CHAT_WITH_ADDRESS = f'{WEB_CHAT}/<address>'
|
#tables or h5py
libname="h5py" #tables"
#libname="tables"
def setlib(name):
global libname
libname = name
|
if __name__ == "__main__":
pages = [5, 4, 3, 2, 1, 4, 3, 5, 4, 3, 2, 1, 5]
faults = {3: 0, 4: 0}
for frames in faults:
memory = []
for page in pages:
out = None
if page not in memory:
if len(memory) == frames:
out = memory.pop(0)
memory.append(page)
faults[frames] += 1
print(f"In: {page} --> {memory} --> Out: {out}")
print(f"Marcos: {frames}, Fallas: {faults[frames]}\n")
if faults[4] > faults[3]:
print(f"La secuencia {pages} presenta anomalia de Belady")
|
a={'a':'hello','b':'1','c':'jayalatha','d':[1,2]}
d={}
val=list(a.values())
val.sort(key=len)
print(val)
for i in val:
for j in a:
if(i==a[j]):
d.update({j:a[j]})
print(d)
|
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 04 17:37:37 2015
@author: Kevin
"""
|
load("@io_bazel_rules_dotnet//dotnet:defs.bzl", "core_library", "core_resx", "core_xunit_test")
core_resx(
name = "core_resource",
src = ":src/Moq/Properties/Resources.resx",
identifier = "Moq.Properties.Resources.resources",
)
core_library(
name = "Moq.dll",
srcs = glob(["src/Moq/**/*.cs"]),
defines = [
"NETCORE",
],
keyfile = ":Moq.snk",
resources = [":core_resource"],
visibility = ["//visibility:public"],
nowarn = ["CS3027"],
deps = [
"@//ifluentinterface:IFluentInterface.dll",
"@TypeNameFormatter//:TypeNameFormatter.dll",
"@castle.core//:Castle.Core.dll",
"@core_sdk_stdlib//:libraryset",
],
)
core_xunit_test(
name = "Moq.Tests.dll",
srcs = glob(
["tests/Moq.Tests/**/*.cs"],
exclude = ["**/FSharpCompatibilityFixture.cs"],
),
defines = [
"NETCORE",
],
keyfile = ":Moq.snk",
nowarn = ["CS1701"],
visibility = ["//visibility:public"],
deps = [
":Moq.dll",
"@xunit.assert//:lib",
"@xunit.extensibility.core//:lib",
"@xunit.extensibility.execution//:lib",
],
)
|
# Time: O(n^2)
# Space: O(n)
# Given an array of unique integers, each integer is strictly greater than 1.
# We make a binary tree using these integers and each number may be used for
# any number of times.
# Each non-leaf node's value should be equal to the product of the values of
# it's children.
# How many binary trees can we make? Return the answer modulo 10 ** 9 + 7.
#
# Example 1:
#
# Input: A = [2, 4]
# Output: 3
# Explanation: We can make these trees: [2], [4], [4, 2, 2]
# Example 2:
#
# Input: A = [2, 4, 5, 10]
# Output: 7
# Explanation: We can make these trees:
# [2], [4], [5], [10], [4, 2, 2], [10, 2, 5], [10, 5, 2].
#
# Note:
# - 1 <= A.length <= 1000.
# - 2 <= A[i] <= 10 ^ 9.
try:
xrange # Python 2
except NameError:
xrange = range # Python 3
class Solution(object):
def numFactoredBinaryTrees(self, A):
"""
:type A: List[int]
:rtype: int
"""
M = 10**9 + 7
A.sort()
dp = {}
for i in xrange(len(A)):
dp[A[i]] = 1
for j in xrange(i):
if A[i] % A[j] == 0 and A[i] // A[j] in dp:
dp[A[i]] += dp[A[j]] * dp[A[i] // A[j]]
dp[A[i]] %= M
return sum(dp.values()) % M
|
def run():
animal = str(input('¿Cuál es tu animal favorito? '))
if animal.lower() == 'tortuga' or animal.lower() == 'tortugas':
print('También me gustan las tortugas.')
else:
print('Ese animal es genial, pero prefiero las tortugas.')
if __name__ == '__main__':
run() |
class reversor:
def __init__(self, value):
self.value = value
def __eq__(self, other):
return self.value == other.value
def __lt__(self, other):
"""
Inverted it to be able to sort in descending order.
"""
return self.value >= other.value
if __name__ == '__main__':
tuples = [(3, 'x'), (2, 'y'), (1, 'a'), (1, 'z')]
tuples.sort(key=lambda x: (x[0], x[1]))
assert tuples == [(1, 'a'), (1, 'z'), (2, 'y'),(3, 'x')], "Error 1: 0 asc, 1 asc"
tuples.sort(key=lambda x: (x[0], reversor(x[1])))
assert tuples == [(1, 'z'), (1, 'a'), (2, 'y'),(3, 'x')], "Error 2: 0 asc, 1 desc"
# The following approach works for a single char string.
tuples.sort(key=lambda x: (x[0], -ord(x[1])))
assert tuples == [(1, 'z'), (1, 'a'), (2, 'y'), (3, 'x')], "Error 3: 0 asc, 1 desc"
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Yue-Wen FANG'
__maintainer__ = "Yue-Wen FANG"
__email__ = 'fyuewen@gmail.com'
__license__ = 'Apache License 2.0'
__creation_date__= 'Dec. 25, 2018'
"""
This example shows the functionality
of positional arguments and keyword ONLY arguments.
The positional arguments correspond to tuple,
the keyword ONLY arguments correspond to dict.
"""
def add_function_01(x, *args): # you can use any other proper names instead of using args
""" positional arguments"""
print('x is', x)
for i in args:
print(i),
def add_function_02(x, *args, **kwargs): # you can use any other proper names instead of using args
""" positional arguments and keyword specific arguments """
print('x is', x)
print(args)
print('the type of args is', type(args))
print(kwargs.values())
print(kwargs.keys())
print('the type or kwargs is', type(kwargs))
if __name__ == "__main__":
add_function_01(1,2,3,45)
print("*************")
add_function_02(3, 1, 2, 3, 45, c=3, d=4)
print("*************")
|
"""
A unival tree (which stands for "universal value") is a tree where all nodes under it have the same value.
Given the root to a binary tree, count the number of unival subtrees.
For example, the following tree has 5 unival subtrees:
0
/ \
1 0
/ \
1 0
/ \
1 1
"""
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# O(n)
def count_univals2(root):
total_count, is_unival = helper(root)
return total_count
def helper(root):
if root == None:
return (0, True)
left_count, is_left_unival = helper(root.left)
right_count, is_right_unival = helper(root.right)
is_unival = True
if not is_left_unival or not is_right_unival:
is_unival = False
if root.left != None and root.left.data != root.data:
is_unival = False
if root.right != None and root.right.data != root.data:
is_unival = False
if is_unival:
return (left_count + right_count + 1, True)
else:
return (left_count + right_count, False)
def is_unival(root):
if root == None:
return True
if root.left != None and root.left.data != root.data:
return False
if root.right != None and root.right.data != root.data:
return False
if is_unival(root.left) and is_unival(root.right):
return True
return False
# O(n^2)
def count_univals(root):
if root == None:
return 0
total_count = count_univals(root.left) + count_univals(root.right)
if is_unival(root):
total_count += 1
return total_count
"""
5
/ \
4 5
/ \ \
4 4 5
"""
root = Node(5)
root.left = Node(4)
root.right = Node(5)
root.left.left = Node(4)
root.left.right = Node(4)
root.right.right = Node(5)
print(count_univals(root))
print(count_univals2(root)) |
# Iterations: Definite Loops
'''
Use the 'for' word
there is a iteration variable like 'i' or 'friend'
'''
# for i in [5, 4, 3, 2, 1] :
# print(i)
# print('Blastoff!')
# friends = ['matheus', 'wataru', 'mogli']
# for friend in friends :
# print('happy new year:', friend)
# print('Done!')
|
class formstruct():
name = str()
while True:
name = input("\n.bot >> enter your first name:")
if not name.isalpha():
print(".bot >> your first name must have alphabets only!")
continue
else:
name = name.upper()
break
city = str()
while True:
city = input("\n.bot >> enter your city:")
if not city.isalpha():
print(".bot >> a city name can have alphabets only!")
continue
else:
city = city.upper()
break
state = str()
while True:
state = input(".bot >> which sate do your reside in?")
if not state.isalpha():
print(".bot >> a state name can have alphabets only!")
continue
else:
state = state.upper()
break
pincode = str()
while True:
pincode = input(".bot >> pincode of your area?")
if not pincode.isnumeric():
print(".bot >> a pincode has numeric characters only")
continue
if not len(pincode)==6:
print(".bot >> invalid pincode , please make sure your pincode is of 6 digits")
continue
else:
break
mobilenumber = str()
while True:
mobilenumber = input(".bot >> provide us the mobile number we can contact you with?")
if not mobilenumber.isnumeric():
print(".bot >> a mobile number has numeric characters only")
continue
if not len(mobilenumber) == 10:
print(".bot >> invalid mobile number , please make sure your mobile number is of 10 digits")
continue
else:
break
aadhaarnumber = str()
while True:
aadhaarnumber = input(".bot >> enter your aadhaar number:")
if not aadhaarnumber.isnumeric():
print(".bot >> an aadhaar number has numeric characters only")
continue
if not len(aadhaarnumber) == 12:
print(".bot >> invalid aadhaar number , please make sure your aadhaar number is of 12 digits")
continue
else:
break
def __init__(self,val):
print("In Class Method")
self.val = val
print("The Value is: ", val)
|
#
# @lc app=leetcode id=719 lang=python3
#
# [719] Find K-th Smallest Pair Distance
#
# https://leetcode.com/problems/find-k-th-smallest-pair-distance/description/
#
# algorithms
# Hard (30.99%)
# Likes: 827
# Dislikes: 30
# Total Accepted: 29.9K
# Total Submissions: 96.4K
# Testcase Example: '[1,3,1]\n1'
#
# Given an integer array, return the k-th smallest distance among all the
# pairs. The distance of a pair (A, B) is defined as the absolute difference
# between A and B.
#
# Example 1:
#
# Input:
# nums = [1,3,1]
# k = 1
# Output: 0
# Explanation:
# Here are all the pairs:
# (1,3) -> 2
# (1,1) -> 0
# (3,1) -> 2
# Then the 1st smallest distance pair is (1,1), and its distance is 0.
#
#
#
# Note:
#
# 2 .
# 0 .
# 1 .
#
#
#
# @lc code=start
class Solution:
def smallestDistancePair(self, nums: List[int], k: int) -> int:
n = len(nums)
nums = sorted(nums)
low = 0
high = nums[n-1] - nums[0]
while low < high:
mid = int((low + high) / 2)
left, count = 0, 0
for right in range(n):
while nums[right] - nums[left] > mid:
left += 1
count += right - left
if count >= k:
high = mid
else:
low = mid + 1
return low
# @lc code=end
|
def chess_knight(start, moves):
def knight_can_move(from_pos, to_pos):
return set(map(lambda x: abs(ord(x[0]) - ord(x[1])), zip(from_pos, to_pos))) == {1, 2}
def knight_moves(pos):
return {f + r for f in 'abcdefgh' for r in '12345678' if knight_can_move(pos, f + r)}
# till task become consistent, hardcode
res = knight_moves(start)
if moves == 2:
res.update(*map(knight_moves, res))
return sorted(res) |
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 20 20:17:52 2018
@author: Administrator
最优分割
时间限制:C/C++语言 1000MS;其他语言 3000MS
内存限制:C/C++语言 65536KB;其他语言 589824KB
题目描述:
依次给出n个正整数A1,A2,… ,An,将这n个数分割成m段,每一段内的所有数的和记为这一段的权重, m段权重的最大值记为本次分割的权重。问所有分割方案中分割权重的最小值是多少?
输入
第一行依次给出正整数n,m,单空格切分;(n <= 10000, m <= 10000, m <= n)
第二行依次给出n个正整数单空格切分A1,A2,… ,An (Ai <= 10000)
输出
分割权重的最小值
样例输入
5 3
1 4 2 3 5
样例输出
5
Hint
分割成 1 4 | 2 3 | 5 的时候,3段的权重都是5,得到分割权重的最小值。
"""
n, m = map(int,input().split())
data = list(map(int,input().split()))
def split(data, m):
N = len(data)
if N == m:
return max(data)
low, high = max(data), sum(data)
while low <= high:
mid = (low + high) // 2
count, cum = 1, 0
for num in data:
if cum + num <= mid:
cum += num
else:
count += 1
cum = num
if count > m:
break
if count <= m:
high = mid - 1
else:
low = mid + 1
return low
print(split(data, m)) |
n = str(input())
if("0000000" in n):
print("YES")
elif("1111111" in n):
print("YES")
else:
print("NO")
|
list = ['a','b','c']
print(list)
|
#
# Copyright 2017 ABSA Group Limited
#
# 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.
#
# Enable Spline tracking.
# For Spark 2.3+ we recommend the codeless approach to enable Spline - by setting spark.sql.queryExecutionListeners
# (See: examples/README.md)
# Otherwise execute the following method to enable Spline manually.
sc._jvm.za.co.absa.spline.harvester \
.SparkLineageInitializer.enableLineageTracking(spark._jsparkSession)
# Execute a Spark job as usual:
spark.read \
.option("header", "true") \
.option("inferschema", "true") \
.csv("data/input/batch/wikidata.csv") \
.write \
.mode('overwrite') \
.csv("data/output/batch/python-sample.csv")
|
'''
Переменные настройки для parser.
'''
link_MireaSchedule = "https://www.mirea.ru/schedule/"
links_file = "links.txt"
first_september = [2021, 9, 1]
first_january = [2022, 1, 1]
semestr_start = [2021, 8, 30] # День отсчета начала семестра
block_tags = { # Список тегов, которые не будут обрабатыватся
"Колледж" : "Колледж", # Расписание колледжа
"З" : "З", # Заочники
"заоч" : "заоч", # Заочники
"зач" : "зач", # Зачеты
"Зач" : "зач", # Зачеты
"О-З" : "О-З" # Очно-заочники
}
special_tags = { # Теги, для которых предусмотрена специальная обработка
"ИТХТ_маг" : None,
"Экз" : "экз", # Расписание экзаменов
"сессия" : "экз",
"Маг" : "маг", # Магистратура
"маг" : "маг", # Магистратура
"МАГИ" : "маг",
"магистры" : "маг"
}
substitute_lessons = {
r"Физическая культура и спорт" : "Физ-ра",
r"Иностранный язык" : "Ин.яз.",
r"Специальные разделы дискретной математики" : "Дискретная математика",
r"Математический анализ" : "Мат. анализ",
r"Линейная алгебра и [(аналитическая геометрия), (АГ)]+" : "Лин. ал.",
r"Начертательная геометрия, инженерная и компьютерная графика" : "Инж. граф.",
r"Алгебраические модели в информационной безопасности" : "Алгебра",
r"день самостоятельной работы" : "",
r"День самостоятельных занятий" : "",
r"День" : "",
r"самостоятельных" : "",
r"занятий" : "",
r"Военная\nподготовка" : "Военная подготовка"
}
substitute_exams = {
r"Экзамен" : "Экз.",
r"Консультация" : "Конс.",
r"Зачёт" : "Зачет",
r"Зачет диф." : "Диф.зачет",
r"Зачёт диф." : "Диф.зачет",
r"Курсовая работа" : "К/р"
}
time_schedule = [
('9-00', '10-30'),
('10-40', '12-10'),
('12-40', '14-10'),
('14-20', '15-50'),
('16-20', '17-50'),
('18-00', '19-30')
]
|
##############################################################################
# Parte do livro Introdução à Programação com Python
# Autor: Nilo Ney Coutinho Menezes
# Editora Novatec (c) 2010-2017
# Primeira edição - Novembro/2010 - ISBN 978-85-7522-250-8
# Primeira reimpressão - Outubro/2011
# Segunda reimpressão - Novembro/2012
# Terceira reimpressão - Agosto/2013
# Segunda edição - Junho/2014 - ISBN 978-85-7522-408-3
# Primeira reimpressão - Segunda edição - Maio/2015
# Segunda reimpressão - Segunda edição - Janeiro/2016
# Terceira reimpressão - Segunda edição - Junho/2016
# Quarta reimpressão - Segunda edição - Março/2017
#
# Site: http://python.nilo.pro.br/
#
# Arquivo: exercicios\capitulo 07\exercicio-07-02.py
##############################################################################
primeira = input("Digite a primeira string: ")
segunda = input("Digite a segunda string: ")
terceira = ""
# Para cada letra na primeira string
for letra in primeira:
# Se a letra está na segunda string (comum a ambas)
# Para evitar repetidas, não deve estar na terceira.
if letra in segunda and letra not in terceira:
terceira+=letra
if terceira == "":
print("Caracteres comuns não encontrados.")
else:
print("Caracteres em comum: %s" % terceira)
|
""" Darshan Error classes and functions. """
class DarshanBaseError(Exception):
"""
Base exception class for Darshan errors in Python.
"""
pass
class DarshanVersionError(NotImplementedError):
"""
Raised when using a feature which is not provided by libdarshanutil.
"""
min_version = None
def __init__(self, min_version, msg="Feature"):
self.msg = msg
self.min_version = min_version
self.version = "0.0.0"
def __repr__(self):
return "DarshanVersionError('%s')" % str(self)
def __str__(self):
return "%s requires libdarshanutil >= %s, have %s" % (self.msg, self.min_version, self.version)
|
try:
width=float(input("Ieraksti savas istabas platumu (metros): "))
height=float(input("Ieraksti savas istabas augstumu (metros): "))
length=float(input("Ieraksti savas istabas garumu (metros): "))
capacity=round(width*height*length, 2)
print(f"Tavas istabas tilpums ir {capacity} m\u00b3.")
except ValueError:
print("Ievadiet vērtību ciparos! Komata vietā jālieto punkts.")
print("*"*30) |
file = open("input.txt", "r")
num_valid = 0
for line in file:
# policy = part before colon
policy = line.strip().split(":")[0]
# get min/max number allowed for given letter
min_max = policy.split(" ")[0]
letter = policy.split(" ")[1]
min = int(min_max.split("-")[0])
max = int(min_max.split("-")[1])
# password = part after colon
password = line.strip().split(":")[1]
# check if password contains between min and max of given letter
if password.count(letter) >= min and password.count(letter) <= max:
num_valid += 1
print("Number of valid passwords = ", num_valid) |
class Empleado(object):
"Clase para definir a un empleado"
def __init__(self, nombre, email):
self.nombre = nombre
self.email = email
def getNombre(self):
return self.nombre
jorge = Empleado("Jorge", "jorge@mail.com")
jorge.guapo = "Por supuesto"
# Probando hasattr, getattr, setattr
print(hasattr(jorge, 'guapo')) # True
print(getattr(jorge, 'guapo')) # Por supuesto
print(hasattr(jorge, 'listo')) # False
setattr(jorge, 'listo', 'Más que las monas')
print(getattr(jorge, 'listo')) # Mas que las monas |
# Problem code
def search(nums, target):
return search_helper(nums, target, 0, len(nums) - 1)
def search_helper(nums, target, left, right):
if left > right:
return -1
mid = (left + right) // 2
# right part is good
if nums[mid] <= nums[right]:
# we fall for it
if target >= nums[mid] and target <= nums[right]:
return binary_search(nums, target, mid, right)
# we don't fall for it
else:
return search_helper(nums, target, left, mid - 1)
# left part is good
if nums[mid] >= nums[left]:
# we fall for it
if target >= nums[left] and target <= nums[mid]:
return binary_search(nums, target, left, mid)
#we don't fall for it
else:
return search_helper(nums, target, mid + 1, right)
return -1
def binary_search(nums, target, left, right):
while left <= right:
mid = (left + right) // 2
if nums[mid] == target:
return mid
elif target > nums[mid]:
left = mid + 1
else:
right = mid - 1
return -1
|
#
# PySNMP MIB module CISCO-EMBEDDED-EVENT-MGR-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-EMBEDDED-EVENT-MGR-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:39:13 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsIntersection, SingleValueConstraint, ValueRangeConstraint, ConstraintsUnion, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "SingleValueConstraint", "ValueRangeConstraint", "ConstraintsUnion", "ValueSizeConstraint")
ciscoExperiment, = mibBuilder.importSymbols("CISCO-SMI", "ciscoExperiment")
SnmpAdminString, = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpAdminString")
ModuleCompliance, NotificationGroup, ObjectGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup", "ObjectGroup")
iso, Counter64, Unsigned32, Counter32, ModuleIdentity, Bits, IpAddress, NotificationType, MibScalar, MibTable, MibTableRow, MibTableColumn, ObjectIdentity, Integer32, TimeTicks, Gauge32, MibIdentifier = mibBuilder.importSymbols("SNMPv2-SMI", "iso", "Counter64", "Unsigned32", "Counter32", "ModuleIdentity", "Bits", "IpAddress", "NotificationType", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "ObjectIdentity", "Integer32", "TimeTicks", "Gauge32", "MibIdentifier")
TruthValue, TextualConvention, DisplayString, DateAndTime = mibBuilder.importSymbols("SNMPv2-TC", "TruthValue", "TextualConvention", "DisplayString", "DateAndTime")
cEventMgrMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 9, 10, 134))
cEventMgrMIB.setRevisions(('2006-11-07 00:00', '2003-04-16 00:00',))
if mibBuilder.loadTexts: cEventMgrMIB.setLastUpdated('200611070000Z')
if mibBuilder.loadTexts: cEventMgrMIB.setOrganization('Cisco Systems, Inc.')
cEventMgrMIBNotif = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 10, 134, 0))
cEventMgrMIBObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 10, 134, 1))
cEventMgrConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 10, 134, 3))
ceemEventMap = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 1))
ceemHistory = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 2))
ceemRegisteredPolicy = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 3))
class NotifySource(TextualConvention, Integer32):
status = 'current'
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2))
namedValues = NamedValues(("server", 1), ("policy", 2))
ceemEventMapTable = MibTable((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 1, 1), )
if mibBuilder.loadTexts: ceemEventMapTable.setStatus('current')
ceemEventMapEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 1, 1, 1), ).setIndexNames((0, "CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemEventIndex"))
if mibBuilder.loadTexts: ceemEventMapEntry.setStatus('current')
ceemEventIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 1, 1, 1, 1), Unsigned32())
if mibBuilder.loadTexts: ceemEventIndex.setStatus('current')
ceemEventName = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 1, 1, 1, 2), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 128))).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceemEventName.setStatus('current')
ceemEventDescrText = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 1, 1, 1, 3), SnmpAdminString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceemEventDescrText.setStatus('current')
ceemHistoryMaxEventEntries = MibScalar((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 2, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 50)).clone(10)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: ceemHistoryMaxEventEntries.setStatus('current')
ceemHistoryLastEventEntry = MibScalar((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 2, 2), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(1, 4294967295))).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceemHistoryLastEventEntry.setStatus('current')
ceemHistoryEventTable = MibTable((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 2, 3), )
if mibBuilder.loadTexts: ceemHistoryEventTable.setStatus('current')
ceemHistoryEventEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 2, 3, 1), ).setIndexNames((0, "CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemHistoryEventIndex"))
if mibBuilder.loadTexts: ceemHistoryEventEntry.setStatus('current')
ceemHistoryEventIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 2, 3, 1, 1), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(1, 4294967295)))
if mibBuilder.loadTexts: ceemHistoryEventIndex.setStatus('current')
ceemHistoryEventType1 = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 2, 3, 1, 2), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceemHistoryEventType1.setStatus('current')
ceemHistoryEventType2 = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 2, 3, 1, 3), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceemHistoryEventType2.setStatus('current')
ceemHistoryEventType3 = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 2, 3, 1, 4), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceemHistoryEventType3.setStatus('current')
ceemHistoryEventType4 = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 2, 3, 1, 5), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceemHistoryEventType4.setStatus('current')
ceemHistoryPolicyPath = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 2, 3, 1, 6), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceemHistoryPolicyPath.setStatus('current')
ceemHistoryPolicyName = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 2, 3, 1, 7), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceemHistoryPolicyName.setStatus('current')
ceemHistoryPolicyExitStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 2, 3, 1, 8), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-2147483648, 2147483647))).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceemHistoryPolicyExitStatus.setStatus('current')
ceemHistoryPolicyIntData1 = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 2, 3, 1, 9), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-2147483648, 2147483647))).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceemHistoryPolicyIntData1.setStatus('current')
ceemHistoryPolicyIntData2 = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 2, 3, 1, 10), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-2147483648, 2147483647))).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceemHistoryPolicyIntData2.setStatus('current')
ceemHistoryPolicyStrData = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 2, 3, 1, 11), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(0, 255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceemHistoryPolicyStrData.setStatus('current')
ceemHistoryNotifyType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 2, 3, 1, 12), NotifySource()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceemHistoryNotifyType.setStatus('current')
ceemHistoryEventType5 = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 2, 3, 1, 13), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceemHistoryEventType5.setStatus('current')
ceemHistoryEventType6 = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 2, 3, 1, 14), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceemHistoryEventType6.setStatus('current')
ceemHistoryEventType7 = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 2, 3, 1, 15), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceemHistoryEventType7.setStatus('current')
ceemHistoryEventType8 = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 2, 3, 1, 16), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceemHistoryEventType8.setStatus('current')
ceemRegisteredPolicyTable = MibTable((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 3, 1), )
if mibBuilder.loadTexts: ceemRegisteredPolicyTable.setStatus('current')
ceemRegisteredPolicyEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 3, 1, 1), ).setIndexNames((0, "CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemRegisteredPolicyIndex"))
if mibBuilder.loadTexts: ceemRegisteredPolicyEntry.setStatus('current')
ceemRegisteredPolicyIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 3, 1, 1, 1), Unsigned32())
if mibBuilder.loadTexts: ceemRegisteredPolicyIndex.setStatus('current')
ceemRegisteredPolicyName = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 3, 1, 1, 2), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceemRegisteredPolicyName.setStatus('current')
ceemRegisteredPolicyEventType1 = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 3, 1, 1, 3), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceemRegisteredPolicyEventType1.setStatus('current')
ceemRegisteredPolicyEventType2 = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 3, 1, 1, 4), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceemRegisteredPolicyEventType2.setStatus('current')
ceemRegisteredPolicyEventType3 = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 3, 1, 1, 5), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceemRegisteredPolicyEventType3.setStatus('current')
ceemRegisteredPolicyEventType4 = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 3, 1, 1, 6), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceemRegisteredPolicyEventType4.setStatus('current')
ceemRegisteredPolicyStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 3, 1, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceemRegisteredPolicyStatus.setStatus('current')
ceemRegisteredPolicyType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 3, 1, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("user", 1), ("system", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceemRegisteredPolicyType.setStatus('current')
ceemRegisteredPolicyNotifFlag = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 3, 1, 1, 9), TruthValue()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceemRegisteredPolicyNotifFlag.setStatus('current')
ceemRegisteredPolicyRegTime = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 3, 1, 1, 10), DateAndTime()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceemRegisteredPolicyRegTime.setStatus('current')
ceemRegisteredPolicyEnabledTime = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 3, 1, 1, 11), DateAndTime()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceemRegisteredPolicyEnabledTime.setStatus('current')
ceemRegisteredPolicyRunTime = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 3, 1, 1, 12), DateAndTime()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceemRegisteredPolicyRunTime.setStatus('current')
ceemRegisteredPolicyRunCount = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 3, 1, 1, 13), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceemRegisteredPolicyRunCount.setStatus('current')
ceemRegisteredPolicyEventType5 = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 3, 1, 1, 14), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceemRegisteredPolicyEventType5.setStatus('current')
ceemRegisteredPolicyEventType6 = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 3, 1, 1, 15), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceemRegisteredPolicyEventType6.setStatus('current')
ceemRegisteredPolicyEventType7 = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 3, 1, 1, 16), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceemRegisteredPolicyEventType7.setStatus('current')
ceemRegisteredPolicyEventType8 = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 10, 134, 1, 3, 1, 1, 17), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceemRegisteredPolicyEventType8.setStatus('current')
cEventMgrServerEvent = NotificationType((1, 3, 6, 1, 4, 1, 9, 10, 134, 0, 1)).setObjects(("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemHistoryEventType1"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemHistoryEventType2"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemHistoryEventType3"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemHistoryEventType4"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemHistoryPolicyPath"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemHistoryPolicyName"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemHistoryPolicyExitStatus"))
if mibBuilder.loadTexts: cEventMgrServerEvent.setStatus('current')
cEventMgrPolicyEvent = NotificationType((1, 3, 6, 1, 4, 1, 9, 10, 134, 0, 2)).setObjects(("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemHistoryEventType1"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemHistoryEventType2"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemHistoryEventType3"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemHistoryEventType4"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemHistoryPolicyPath"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemHistoryPolicyName"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemHistoryPolicyIntData1"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemHistoryPolicyIntData2"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemHistoryPolicyStrData"))
if mibBuilder.loadTexts: cEventMgrPolicyEvent.setStatus('current')
cEventMgrCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 10, 134, 3, 1))
cEventMgrGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 10, 134, 3, 2))
cEventMgrCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 9, 10, 134, 3, 1, 1)).setObjects(("CISCO-EMBEDDED-EVENT-MGR-MIB", "cEventMgrDescrGroup"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "cEventMgrNotificationsGroup"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "cEventMgrRegisteredPolicyGroup"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "cEventMgrHistoryGroup"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
cEventMgrCompliance = cEventMgrCompliance.setStatus('deprecated')
cEventMgrComplianceRev1 = ModuleCompliance((1, 3, 6, 1, 4, 1, 9, 10, 134, 3, 1, 2)).setObjects(("CISCO-EMBEDDED-EVENT-MGR-MIB", "cEventMgrDescrGroup"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "cEventMgrNotificationsGroup"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "cEventMgrRegisteredPolicyGroup"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "cEventMgrRegisteredPolicyGroupSup1"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "cEventMgrHistoryGroup"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "cEventMgrHistoryGroupSup1"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
cEventMgrComplianceRev1 = cEventMgrComplianceRev1.setStatus('current')
cEventMgrDescrGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 10, 134, 3, 2, 1)).setObjects(("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemEventName"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemEventDescrText"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
cEventMgrDescrGroup = cEventMgrDescrGroup.setStatus('current')
cEventMgrHistoryGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 10, 134, 3, 2, 2)).setObjects(("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemHistoryMaxEventEntries"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemHistoryLastEventEntry"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemHistoryEventType1"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemHistoryEventType2"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemHistoryEventType3"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemHistoryEventType4"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemHistoryPolicyPath"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemHistoryPolicyName"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemHistoryPolicyExitStatus"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemHistoryPolicyIntData1"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemHistoryPolicyIntData2"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemHistoryPolicyStrData"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemHistoryNotifyType"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
cEventMgrHistoryGroup = cEventMgrHistoryGroup.setStatus('current')
cEventMgrNotificationsGroup = NotificationGroup((1, 3, 6, 1, 4, 1, 9, 10, 134, 3, 2, 3)).setObjects(("CISCO-EMBEDDED-EVENT-MGR-MIB", "cEventMgrServerEvent"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "cEventMgrPolicyEvent"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
cEventMgrNotificationsGroup = cEventMgrNotificationsGroup.setStatus('current')
cEventMgrRegisteredPolicyGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 10, 134, 3, 2, 4)).setObjects(("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemRegisteredPolicyName"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemRegisteredPolicyEventType1"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemRegisteredPolicyEventType2"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemRegisteredPolicyEventType3"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemRegisteredPolicyEventType4"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemRegisteredPolicyStatus"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemRegisteredPolicyType"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemRegisteredPolicyNotifFlag"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemRegisteredPolicyRegTime"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemRegisteredPolicyEnabledTime"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemRegisteredPolicyRunTime"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemRegisteredPolicyRunCount"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
cEventMgrRegisteredPolicyGroup = cEventMgrRegisteredPolicyGroup.setStatus('current')
cEventMgrHistoryGroupSup1 = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 10, 134, 3, 2, 5)).setObjects(("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemHistoryEventType5"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemHistoryEventType6"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemHistoryEventType7"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemHistoryEventType8"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
cEventMgrHistoryGroupSup1 = cEventMgrHistoryGroupSup1.setStatus('current')
cEventMgrRegisteredPolicyGroupSup1 = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 10, 134, 3, 2, 6)).setObjects(("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemRegisteredPolicyEventType5"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemRegisteredPolicyEventType6"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemRegisteredPolicyEventType7"), ("CISCO-EMBEDDED-EVENT-MGR-MIB", "ceemRegisteredPolicyEventType8"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
cEventMgrRegisteredPolicyGroupSup1 = cEventMgrRegisteredPolicyGroupSup1.setStatus('current')
mibBuilder.exportSymbols("CISCO-EMBEDDED-EVENT-MGR-MIB", ceemEventDescrText=ceemEventDescrText, ceemHistoryEventType5=ceemHistoryEventType5, ceemRegisteredPolicyEventType4=ceemRegisteredPolicyEventType4, ceemEventName=ceemEventName, ceemHistoryPolicyIntData1=ceemHistoryPolicyIntData1, ceemRegisteredPolicyEntry=ceemRegisteredPolicyEntry, ceemHistoryPolicyExitStatus=ceemHistoryPolicyExitStatus, ceemRegisteredPolicyRunTime=ceemRegisteredPolicyRunTime, cEventMgrDescrGroup=cEventMgrDescrGroup, ceemHistory=ceemHistory, cEventMgrNotificationsGroup=cEventMgrNotificationsGroup, cEventMgrRegisteredPolicyGroup=cEventMgrRegisteredPolicyGroup, ceemRegisteredPolicyEventType3=ceemRegisteredPolicyEventType3, ceemRegisteredPolicyStatus=ceemRegisteredPolicyStatus, ceemEventIndex=ceemEventIndex, cEventMgrConformance=cEventMgrConformance, ceemRegisteredPolicyEventType6=ceemRegisteredPolicyEventType6, cEventMgrServerEvent=cEventMgrServerEvent, cEventMgrHistoryGroup=cEventMgrHistoryGroup, ceemHistoryPolicyStrData=ceemHistoryPolicyStrData, NotifySource=NotifySource, cEventMgrPolicyEvent=cEventMgrPolicyEvent, ceemRegisteredPolicyEventType8=ceemRegisteredPolicyEventType8, cEventMgrMIBNotif=cEventMgrMIBNotif, ceemHistoryEventType2=ceemHistoryEventType2, ceemEventMap=ceemEventMap, cEventMgrGroups=cEventMgrGroups, ceemHistoryEventType6=ceemHistoryEventType6, PYSNMP_MODULE_ID=cEventMgrMIB, ceemRegisteredPolicyRegTime=ceemRegisteredPolicyRegTime, cEventMgrRegisteredPolicyGroupSup1=cEventMgrRegisteredPolicyGroupSup1, cEventMgrMIB=cEventMgrMIB, ceemHistoryPolicyIntData2=ceemHistoryPolicyIntData2, ceemRegisteredPolicyEventType7=ceemRegisteredPolicyEventType7, ceemHistoryEventEntry=ceemHistoryEventEntry, ceemHistoryEventTable=ceemHistoryEventTable, cEventMgrMIBObjects=cEventMgrMIBObjects, ceemEventMapEntry=ceemEventMapEntry, ceemRegisteredPolicyName=ceemRegisteredPolicyName, ceemRegisteredPolicy=ceemRegisteredPolicy, ceemHistoryEventType3=ceemHistoryEventType3, ceemHistoryEventType8=ceemHistoryEventType8, ceemHistoryEventIndex=ceemHistoryEventIndex, cEventMgrCompliance=cEventMgrCompliance, ceemRegisteredPolicyNotifFlag=ceemRegisteredPolicyNotifFlag, ceemRegisteredPolicyRunCount=ceemRegisteredPolicyRunCount, ceemRegisteredPolicyEventType1=ceemRegisteredPolicyEventType1, ceemRegisteredPolicyIndex=ceemRegisteredPolicyIndex, ceemHistoryEventType1=ceemHistoryEventType1, ceemHistoryPolicyName=ceemHistoryPolicyName, ceemHistoryNotifyType=ceemHistoryNotifyType, ceemRegisteredPolicyEventType5=ceemRegisteredPolicyEventType5, ceemRegisteredPolicyType=ceemRegisteredPolicyType, ceemHistoryMaxEventEntries=ceemHistoryMaxEventEntries, ceemEventMapTable=ceemEventMapTable, ceemHistoryPolicyPath=ceemHistoryPolicyPath, cEventMgrHistoryGroupSup1=cEventMgrHistoryGroupSup1, ceemRegisteredPolicyEventType2=ceemRegisteredPolicyEventType2, ceemHistoryEventType4=ceemHistoryEventType4, ceemRegisteredPolicyTable=ceemRegisteredPolicyTable, ceemHistoryLastEventEntry=ceemHistoryLastEventEntry, cEventMgrCompliances=cEventMgrCompliances, ceemRegisteredPolicyEnabledTime=ceemRegisteredPolicyEnabledTime, ceemHistoryEventType7=ceemHistoryEventType7, cEventMgrComplianceRev1=cEventMgrComplianceRev1)
|
"""AyudaEnPython: https://www.facebook.com/groups/ayudapython
# ------------------------ REDACCION ORIGINAL ------------------------
1. Crear un programa que pida un número entero e imprimirlo, si no se
ingresa deberá preguntar otra vez por el número entero hasta que
ingrese un número positivo.
2. Crear una lista que almacene edades.
3. Con la lista anterior, contar cuantos son mayores de edad.
# --------------------------------------------------------------------
NOTA: Los ejercicios estan mal redactados, el instructor deberia tener
mas claridad e integrar lo enseñado con ejercicios bien diseñados.
"""
def ingresar_numero():
while True:
n = input("Ingrese un número entero: ")
try:
n = int(n)
if n >= 0:
return n
else:
print("El número debe ser positivo.")
except ValueError:
print("No es un número entero.")
print(ingresar_numero()) # 1
edades = [18, 13, 11, 19, 17, 15, 16, 14, 12, 10, 20] # 2
print(f"Mayores de edad: {len([e for e in edades if e >= 18])} personas") # 3 |
screen_resX=1920
screen_resY=1080
img_id=['1.JPG_HIGH_',
'2.JPG_HIGH_',
'7.JPG_HIGH_',
'12.JPG_HIGH_',
'13.JPG_HIGH_',
'15.JPG_HIGH_',
'19.JPG_HIGH_',
'25.JPG_HIGH_',
'27.JPG_HIGH_',
'29.JPG_HIGH_',
'41.JPG_HIGH_',
'42.JPG_HIGH_',
'43.JPG_HIGH_',
'44.JPG_HIGH_',
'48.JPG_HIGH_',
'49.JPG_HIGH_',
'51.JPG_HIGH_',
'54.JPG_HIGH_',
'55.JPG_HIGH_',
'59.JPG_HIGH_',
'61.JPG_HIGH_',
'64.JPG_HIGH_',
'67.JPG_HIGH_',
'74.JPG_HIGH_',
'76.JPG_HIGH_',
'77.JPG_HIGH_',
'84.JPG_HIGH_',
'87.JPG_HIGH_',
'88.JPG_HIGH_',
'91.JPG_HIGH_',
'94.JPG_HIGH_',
'95.JPG_HIGH_',
'100.JPG_HIGH_',
'101.JPG_HIGH_',
'112.JPG_HIGH_',
'113.JPG_HIGH_',
'3.JPG_LOW_',
'6.JPG_LOW_',
'10.JPG_LOW_',
'17.JPG_LOW_',
'21.JPG_LOW_',
'23.JPG_LOW_',
'28.JPG_LOW_',
'33.JPG_LOW_',
'35.JPG_LOW_',
'38.JPG_LOW_',
'39.JPG_LOW_',
'40.JPG_LOW_',
'46.JPG_LOW_',
'50.JPG_LOW_',
'52.JPG_LOW_',
'58.JPG_LOW_',
'60.JPG_LOW_',
'62.JPG_LOW_',
'63.JPG_LOW_',
'70.JPG_LOW_',
'72.JPG_LOW_',
'73.JPG_LOW_',
'75.JPG_LOW_',
'78.JPG_LOW_',
'80.JPG_LOW_',
'82.JPG_LOW_',
'89.JPG_LOW_',
'90.JPG_LOW_',
'92.JPG_LOW_',
'97.JPG_LOW_',
'99.JPG_LOW_',
'102.JPG_LOW_',
'103.JPG_LOW_',
'104.JPG_LOW_',
'105.JPG_LOW_',
'108.JPG_LOW_']
sub_id=[1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23,
25,
26,
28,
29,
30,
31]
BEHAVIORAL_FILE='C:/Users/presi/Desktop/PhD/Memory guided attention in '\
'cluttered scenes v.3/Behavioral Data/Memory/Preprocessed/Memory_all_dirty.csv'
DATA_PATH='C:/Users/presi/Desktop/PhD/Memory guided attention in '\
'cluttered scenes v.3/Eye Tracking Data/1. Associative Learning/Raw'
TRIALS_PATH='C:/Users/presi/Desktop/PhD/Memory guided attention in '\
'cluttered scenes v.3/Eye Tracking Data/'\
'1. Associative Learning/Learn_trials'
EVENTS_PATH='C:/Users/presi/Desktop/PhD/Memory guided attention in '\
'cluttered scenes v.3/Eye Tracking Data/'\
'1. Associative Learning/Learn_events'
COLLATION_PATH='C:/Users/presi/Desktop/PhD/Memory guided attention in '\
'cluttered scenes v.3/Eye Tracking Data/'\
'1. Associative Learning/Learn_collation'
DIR_ROUTE_PATH='C:/Users/presi/Desktop/PhD/Memory guided attention in '\
'cluttered scenes v.3/Eye Tracking Data/'\
'1. Associative Learning/Learn_direct_route'
IMG_PATH='C:/Users/presi/Desktop/PhD/Memory guided attention in '\
'cluttered scenes v.3/Tasks/Task2/Scenes'
RAW_SCANPATH='C:/Users/presi/Desktop/PhD/Memory guided attention in '\
'cluttered scenes v.3/Eye Tracking Data/1. Associative Learning/'\
'Learn_ visualizations/Raw_Scanpaths'
#IVT_SCANPATH='C:/Users/presi/Desktop/PhD/Memory guided attention in '\
#'cluttered scenes v.3/Eye Tracking Data/1. Associative Learning/'\
# 'Learn_visualizations/IVT_Scanpaths'
IVT_SCANPATH='E:/UCY PhD/Memory guided attention'\
' in cluttered scenes v.3/1. Associative Learning/'\
'Learn_visualizations/IVT_Scanpaths'
|
def create_matrix(rows_count):
matrix = []
for _ in range(rows_count):
matrix.append([int(x) for x in input().split(', ')])
return matrix
def get_square_sum(row, col, matrix):
square_sum = 0
for r in range(row, row + 2):
for c in range(col, col + 2):
square_sum += matrix[r][c]
return square_sum
def print_square(matrix, row, col):
for r in range(row, row + 2):
for c in range(col, col + 2):
print(matrix[r][c], end=' ')
print()
rows_count, cols_count = [int(x) for x in input().split(', ')]
matrix = create_matrix(rows_count)
best_pos = 0, 0
best_sum = get_square_sum(0, 0, matrix)
for r in range(rows_count - 1):
for c in range(cols_count - 1):
current_pos = r, c
current_sum = get_square_sum(r, c, matrix)
if current_sum > best_sum:
best_pos = current_pos
best_sum = current_sum
print_square(matrix, best_pos[0], best_pos[1])
print(best_sum)
|
#!/usr/bin/env python3
# Diodes
"1N4148"
"1N5817G"
"BAT43" # Zener
"1N457"
# bc junction of many transistors can also be used as dioded, i.e. 2SC1815, 2SA9012, etc. with very small leakage current (~1pA at -4V).
|
clientId = 'CLIENT_ID'
clientSecret = 'CLIENT_SECRET'
geniusToken = 'GENIUS_TOKEN'
bitrate = '320' |
'''
Created on Jun 15, 2016
@author: eze
'''
class NotFoundException(Exception):
'''
classdocs
'''
def __init__(self, element):
'''
Constructor
'''
self.elementNotFound = element
def __str__(self, *args, **kwargs):
return "NotFoundException(%s)" % self.elementNotFound
|
# Solution to the practise problem
# https://automatetheboringstuff.com/chapter6/
# Table Printer
def printTable(tableList):
"""Prints the list of list of strings with each column right justified"""
colWidth = 0
for row in tableList:
colWidth = max(colWidth, max([len(x) for x in row]))
colWidth += 1
printedTable = ''
tableList = [[row[i] for row in tableList] for i in range(len(tableList[0]))]
for row in tableList:
for item in row:
printedTable += item.rjust(colWidth, ' ')
printedTable += '\n'
print(printedTable)
tableData = [['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose']]
printTable(tableData) |
class Contact:
def __init__(self, first_name = None, last_name = None, mobile_phone = None):
self.first_name = first_name
self.last_name = last_name
self.mobile_phone = mobile_phone |
class Solution(object):
def shortestToChar(self, S, C):
"""
:type S: str
:type C: str
:rtype: List[int]
"""
pl = []
ret = [0] * len(S)
for i in range(0, len(S)):
if S[i] == C:
pl.append(i)
for i in range(0, len(S)):
minx = 10000000
for l in range(0, len(pl)):
minx = min(minx, abs(pl[l] - i))
ret[i] = minx
return ret
if __name__ == "__main__":
S = "loveleetcode"
C = 'e'
ret = Solution().shortestToChar(S, C)
print(ret) |
# Optional solution with tidy data representation (providing x and y)
monthly_victim_counts_melt = monthly_victim_counts.reset_index().melt(
id_vars="datetime", var_name="victim_type", value_name="count"
)
sns.relplot(
data=monthly_victim_counts_melt,
x="datetime",
y="count",
hue="victim_type",
kind="line",
palette="colorblind",
height=3, aspect=4,
) |
def findSmallest(arr):
smallest = arr[0]
smallest_index = 0
for i in range(1, len(arr)):
if arr[i] < smallest:
smallest = arr[i]
smallest_index = i
return smallest_index
def selection_sort(arr):
newarr = []
for i in range(len(arr)):
smallest_index = findSmallest(arr)
newarr.append(arr.pop(smallest_index))
return newarr
test_arr = [5, 3, 6, 1, 0, 0, 2, 10]
print(selection_sort(test_arr))
|
{
'Hello World':'Salve Mondo',
'Welcome to web2py':'Ciao da wek2py',
}
|
domain='https://monbot.hopto.org'
apm_id='admin'
apm_pw='New1234!'
apm_url='https://monbot.hopto.org:3000'
db_host='monbot.hopto.org'
db_user='izyrtm'
db_pw='new1234!'
db_datadbase='monbot' |
def norm(x, ord=None, axis=None):
# TODO(beam2d): Implement it
raise NotImplementedError
def cond(x, p=None):
# TODO(beam2d): Implement it
raise NotImplementedError
def det(a):
# TODO(beam2d): Implement it
raise NotImplementedError
def matrix_rank(M, tol=None):
# TODO(beam2d): Implement it
raise NotImplementedError
def slogdet(a):
# TODO(beam2d): Implement it
raise NotImplementedError
def trace(a, offset=0, axis1=0, axis2=1, dtype=None, out=None):
"""Returns the sum along the diagonals of an array.
It computes the sum along the diagonals at ``axis1`` and ``axis2``.
Args:
a (cupy.ndarray): Array to take trace.
offset (int): Index of diagonals. Zero indicates the main diagonal, a
positive value an upper diagonal, and a negative value a lower
diagonal.
axis1 (int): The first axis along which the trace is taken.
axis2 (int): The second axis along which the trace is taken.
dtype: Data type specifier of the output.
out (cupy.ndarray): Output array.
Returns:
cupy.ndarray: The trace of ``a`` along axes ``(axis1, axis2)``.
.. seealso:: :func:`numpy.trace`
"""
d = a.diagonal(offset, axis1, axis2)
return d.sum(-1, dtype, out, False)
|
def load():
with open("input") as f:
yield next(f).strip()
next(f)
for x in f:
yield x.strip().split(" -> ")
def pair_insertion():
data = list(load())
polymer, rules = list(data[0]), dict(data[1:])
for _ in range(10):
new_polymer = [polymer[0]]
for i in range(len(polymer) - 1):
pair = polymer[i] + polymer[i + 1]
new_polymer.extend((rules[pair], polymer[i + 1]))
polymer = new_polymer
histogram = {}
for e in polymer:
histogram[e] = histogram.get(e, 0) + 1
return max(histogram.values()) - min(histogram.values())
print(pair_insertion())
|
def compChooseWord(hand, wordList, n):
"""
Given a hand and a wordList, find the word that gives
the maximum value score, and return it.
This word should be calculated by considering all the words
in the wordList.
If no words in the wordList can be made from the hand, return None.
hand: dictionary (string -> int)
wordList: list (string)
returns: string or None
"""
maxScore = 0
bestWord = None
for word in wordList:
if isValidWord(word, hand, wordList) == True:
wordScore = getWordScore(word, n)
if wordScore > maxScore:
maxScore = wordScore
bestWord = word
return bestWord
def compPlayHand(hand, wordList, n):
"""
Allows the computer to play the given hand, following the same procedure
as playHand, except instead of the user choosing a word, the computer
chooses it.
1) The hand is displayed.
2) The computer chooses a word.
3) After every valid word: the word and the score for that word is
displayed, the remaining letters in the hand are displayed, and the
computer chooses another word.
4) The sum of the word scores is displayed when the hand finishes.
5) The hand finishes when the computer has exhausted its possible
choices (i.e. compChooseWord returns None).
"""
totalScore = 0
while calculateHandlen(hand) > 0:
print ('Current Hand: ' ),
displayHand(hand)
word = compChooseWord(hand, wordList, n)
if word == None:
print ('Total score: ' + str(totalScore) + ' points.')
break
else:
totalScore = getWordScore(word, n) + totalScore
print ('"' + str(word) + '"' + ' earned ' + str(getWordScore(word, n)) + ' points. Total: ' + str(totalScore) + ' points')
hand = updateHand(hand, word)
if calculateHandlen(hand) == 0:
print ('Total score: ' + str(totalScore) + ' points.')
else:
print (' ')
|
class Colors:
END = '\033[0m'
ERROR = '\033[91m[ERROR] '
INFO = '\033[94m[INFO] '
WARN = '\033[93m[WARN] '
def get_color(msg_type):
if msg_type == 'ERROR':
return Colors.ERROR
elif msg_type == 'INFO':
return Colors.INFO
elif msg_type == 'WARN':
return Colors.WARN
else:
return Colors.END
def get_msg(msg, msg_type=None):
color = get_color(msg_type)
msg = ''.join([color, msg, Colors.END])
return msg
def print_msg(msg, msg_type=None):
msg = get_msg(msg, msg_type)
print(msg)
|
def naive_string_matching(t, w, n, m):
for i in range(n - m + 1):
j = 0
while j < m and t[i + j + 1] == w[j + 1]:
j = j + 1
if j == m:
return True
return False |
# Leo colorizer control file for kivy mode.
# This file is in the public domain.
# Properties for kivy mode.
properties = {
"ignoreWhitespace": "false",
"lineComment": "#",
}
# Attributes dict for kivy_main ruleset.
kivy_main_attributes_dict = {
"default": "null",
"digit_re": "",
"escape": "",
"highlight_digits": "true",
"ignore_case": "true",
"no_word_sep": "",
}
# Dictionary of attributes dictionaries for kivy mode.
attributesDictDict = {
"kivy_main": kivy_main_attributes_dict,
}
# Keywords dict for kivy_main ruleset.
kivy_main_keywords_dict = {
"app": "keyword2",
"args": "keyword2",
"canvas": "keyword1",
"id": "keyword1",
"root": "keyword2",
"self": "keyword2",
"size": "keyword1",
"text": "keyword1",
"x": "keyword1",
"y": "keyword1",
}
# Dictionary of keywords dictionaries for kivy mode.
keywordsDictDict = {
"kivy_main": kivy_main_keywords_dict,
}
# Rules for kivy_main ruleset.
def kivy_rule0(colorer, s, i):
return colorer.match_eol_span(s, i, kind="comment1", seq="#",
at_line_start=False, at_whitespace_end=False, at_word_start=False,
delegate="", exclude_match=False)
def kivy_rule1(colorer, s, i):
return colorer.match_span(s, i, kind="literal1", begin="\"", end="\"",
at_line_start=False, at_whitespace_end=False, at_word_start=False,
delegate="kivy::literal_one",exclude_match=False,
no_escape=False, no_line_break=False, no_word_break=False)
def kivy_rule2(colorer, s, i):
return colorer.match_keywords(s, i)
# Rules dict for kivy_main ruleset.
rulesDict1 = {
"\"": [kivy_rule1,],
"#": [kivy_rule0,],
"0": [kivy_rule2,],
"1": [kivy_rule2,],
"2": [kivy_rule2,],
"3": [kivy_rule2,],
"4": [kivy_rule2,],
"5": [kivy_rule2,],
"6": [kivy_rule2,],
"7": [kivy_rule2,],
"8": [kivy_rule2,],
"9": [kivy_rule2,],
"@": [kivy_rule2,],
"A": [kivy_rule2,],
"B": [kivy_rule2,],
"C": [kivy_rule2,],
"D": [kivy_rule2,],
"E": [kivy_rule2,],
"F": [kivy_rule2,],
"G": [kivy_rule2,],
"H": [kivy_rule2,],
"I": [kivy_rule2,],
"J": [kivy_rule2,],
"K": [kivy_rule2,],
"L": [kivy_rule2,],
"M": [kivy_rule2,],
"N": [kivy_rule2,],
"O": [kivy_rule2,],
"P": [kivy_rule2,],
"Q": [kivy_rule2,],
"R": [kivy_rule2,],
"S": [kivy_rule2,],
"T": [kivy_rule2,],
"U": [kivy_rule2,],
"V": [kivy_rule2,],
"W": [kivy_rule2,],
"X": [kivy_rule2,],
"Y": [kivy_rule2,],
"Z": [kivy_rule2,],
"a": [kivy_rule2,],
"b": [kivy_rule2,],
"c": [kivy_rule2,],
"d": [kivy_rule2,],
"e": [kivy_rule2,],
"f": [kivy_rule2,],
"g": [kivy_rule2,],
"h": [kivy_rule2,],
"i": [kivy_rule2,],
"j": [kivy_rule2,],
"k": [kivy_rule2,],
"l": [kivy_rule2,],
"m": [kivy_rule2,],
"n": [kivy_rule2,],
"o": [kivy_rule2,],
"p": [kivy_rule2,],
"q": [kivy_rule2,],
"r": [kivy_rule2,],
"s": [kivy_rule2,],
"t": [kivy_rule2,],
"u": [kivy_rule2,],
"v": [kivy_rule2,],
"w": [kivy_rule2,],
"x": [kivy_rule2,],
"y": [kivy_rule2,],
"z": [kivy_rule2,],
}
# x.rulesDictDict for kivy mode.
rulesDictDict = {
"kivy_main": rulesDict1,
}
# Import dict for kivy mode.
importDict = {}
|
"""
Information on the Rozier Cipher can be found at:
https://www.dcode.fr/rozier-cipher
ROZIER.py
Written by: MrLukeKR
Updated: 16/10/2020
"""
# The Rozier cipher needs a string based key, which can be constant for ease
# or changed for each message, for better security
constant_key = "DCODE"
def encrypt(plaintext: str, key: str=constant_key):
"""
Encrypts a plaintext string using the Rozier cipher and a constant key.
Optionally, the function can accept a different key as a parameter.
"""
# Convert plaintext to upper case
plaintext = plaintext.upper()
# Initialise the ciphertext string to the empty string
ciphertext = ""
# Iterate over every letter in the plaintext string
for index, letter in enumerate(plaintext):
# Get the first and second letters of the key at index of letter,
# using modulus to allow for a key to be repeated
first_key = key[index % len(key)]
second_key = key[(index + 1) % len(key)]
# Get the position in the alphabet of the current plaintext letter.
# Negating the ASCII value of capital A allows us to convert from
# an ASCII code to alphabet position.
letter_position = ord(letter) - ord('A')
# Convert the first and second key values to ASCII codes
first_key_value = ord(first_key)
second_key_value = ord(second_key)
# Use the first and second key ASCII codes to determine the distance
# between the two letters. Negative values indicate that the ciphertext
# letter moves to the right of the current letter and positive values
# indicate a move to the left
key_distance = second_key_value - first_key_value
# Calculate the ciphertext letter by adding the original plaintext
# letter to the key distance derived from the two letters from the key.
# Modulus is applied to this to keep the letter within the bounds of
# the alphabet (numbers and special characters are not supported).
# This is added to the ASCII code for capital A to convert from
# alphabet space back into an ASCII code
cipher_letter_value = ord('A') + ((letter_position + key_distance) % 26)
# Convert the ASCII code to a character
cipher_letter = chr(cipher_letter_value)
# Add the character to the total ciphertext string
ciphertext += cipher_letter
return ciphertext
def decrypt(ciphertext: str, key: str=constant_key):
"""
Decrypts a ciphertext string using the Rozier cipher and a constant key.
Optionally, the function can accept a different key as a parameter.
"""
# Convert ciphertext to upper case
ciphertext = ciphertext.upper()
# Initialise the plaintext string to the empty string
plaintext = ""
# Iterate over every letter in the ciphertext string
for index, letter in enumerate(ciphertext):
# Get the first and second letters of the key at index of letter, using
# modulus to allow for a key to be repeated
first_key = key[index % len(key)]
second_key = key[(index + 1) % len(key)]
# Get the position in the alphabet of the current ciphertext letter.
# Negating the ASCII value of capital A allows us to convert from
# an ASCII code to alphabet position.
letter_position = ord(letter) - ord('A')
# Convert the first and second key values to ASCII codes
first_key_value = ord(first_key)
second_key_value = ord(second_key)
# Use the first and second key ASCII codes to determine the distance
# between the two letters. Negative values indicate that the plaintext
# letter moves to the right of the current letter and positive values
# indicate a move to the left
key_distance = second_key_value - first_key_value
# Calculate the plaintext letter by subtracting the key distance derived
# from the two letters from the key, from the original ciphertext letter
# position.
# Modulus is applied to this to keep the letter within the bounds of
# the alphabet (numbers and special characters are not supported).
# This is added to the ASCII code for capital A to convert from
# alphabet space back into an ASCII code
plain_letter_value = ord('A') + ((letter_position - key_distance) % 26)
# Convert the ASCII code to a character
plain_letter = chr(plain_letter_value)
# Add the character to the total plaintext string
plaintext += plain_letter
return plaintext
|
#!/usr/bin/env python3
# xml 资源
xml_w3_book = """
<?xml version="1.0" encoding="ISO-8859-1"?>
<bookstore>
<book>
<title lang="eng">Harry Potter</title>
<price>29.99</price>
</book>
<book>
<title lang="eng">Learning XML</title>
<price>39.95</price>
</book>
</bookstore>
"""
|
"""
Title: 0035 - Search Insert Position
Tags: Binary Search
Time: O(logn)
Space: O(1)
Source: https://leetcode.com/problems/search-insert-position/
Difficulty: Easy
"""
class Solution(object):
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
low = 0
high = len(nums) - 1
while low <= high:
mid = (low + high) / 2
if target == nums[mid]:
return mid
elif target < nums[mid]:
high = mid -1
else:
low = mid + 1
print(low, mid, high)
return low
|
"""Class static method test"""
class TestClass():
"""Test class"""
def __init__(self, a=1, b=2):
self.a = a
self.b = b
def add(self):
return self.a + self.b
@staticmethod
def static_add(a, b):
return 2 * a + 2 * b
def add2(self):
return self.static_add(self.a, self.b)
if __name__ == '__main__':
C = TestClass(a=1, b=2)
print(C.add())
print(C.add2())
|
# Quotes from: https://www.notion.so/Quotes-by-Naval-Ravikant-3edaf88cfc914b06a98b58b62b6dc222
dic = [\
"Read what you love until you love to read.",\
"True Wisdom Comes From Understanding, Not Memorization.",\
"Meditation is the art of doing nothing. You cannot do meditation. By definition, if you’re doing something, you’re not in meditation. Meditation is a state you’re in when you’re not doing anything – physically, mentally, or consciously. You’re just making no effort. You’re literally being completely still, physically and mentally, inside and out.",\
"You’re actually in deep meditation all the time. It’s just covered up by all the noise and all the thoughts and all the emotional things that are running through you. It’s always there underneath.",\
"Every psychedelic state that people encounter using so-called plant medicines can be arrived at just through pure meditation.",\
"You can meditate 24/7. Meditation is not a sit-down and close your eyes activity. Meditation is basically watching your own thoughts like you would watch anything else in the outside world and saying, ‘Why am I having that thought? Does that serve me anymore? Is this just conditioning from when I was 10 years?’",\
"Most smart people, over time, realize that possessions don’t make them happy.",\
"Anything you wanted in your life – whether it was a car, whether it was a girl, or whether it was money – when you got it, a year later, you were back to zero. Your brain had hedonically adapted to it, and you were looking for the next thing.",\
"If you’re smart, you should be able to figure out how to be happy. Otherwise, you’re not that smart.",\
"Just like fitness can be a choice, health can be a choice, nutrition can be a choice, and working hard and making money can be a choice, happiness can be a choice as well.",\
"Reality is neutral. Reality has no judgments. To a tree, there’s no concept of right or wrong or good or bad. You’re born, you have a whole set of sensory experiences… and then you die. How you choose to interpret that is up to you. And you do have that choice.",\
"In every moment, in everything that happens, you can look on the bright side of something… There are two ways of seeing almost everything.",\
"Desire to me is a contract that you make with yourself to be unhappy until you get what you want.",\
"Pick your one overwhelming desire – it’s okay to suffer over that one. But on all the other desires, let them go so you can be calm and peaceful and relaxed.",\
"Desire is suffering… every desire you have is an axis where you will suffer. So just don’t focus on more than one desire at a time. The universe is rigged in such a way that if you just want one thing, and you focus on that, you’ll get it, but everything else you gotta let go.",\
"In today’s day and age, many people think you get peace by resolving all your external problems, but there are unlimited external problems. The only way to actually get peace on the inside is by giving up the idea of having problems.",\
"To me, peace is happiness at rest, and happiness is peace in motion. You can convert peace to happiness anytime you want.",\
"A clear mind leads to better judgment and better outcomes. A happy, calm, and peaceful person will make better decisions. So if you want to operate at peak performance, you have to learn how to tame your mind.",\
"Look at your own experiences; your bliss from success never lasts, nor does your misery from failure."
"The way to survive in modern society is to be an ascetic; it is to retreat from society."
"You have society in your phone, society in your pocket, society in your ears… It’s socializing you and programming everyone. The only solution is to turn it off.",\
"In a first-world society, success and failure is much more about how you control, manage, and break addictions than it is about going out and doing something.",\
"A lot of what creates unhappiness in modern society is the struggle between what society wants and what the individual wants… Guilt is just society’s voice talking in your head.",\
"You’re better off following your genuine intellectual curiosity than chasing whatever’s hot right now.",\
"Retirement is when you stop sacrificing today for some imaginary tomorrow.",\
"Your real resume is just a cataloging of all your suffering."
"When you do things for their own sake, that’s when you create your best work. That’s when it’s art.",\
"The smaller the company you work for, the happier you’ll be."
"I value freedom above anything else. Freedom to do what I want, freedom from not doing what I don’t want to do, and freedom from my own reactions and emotions…things that may disturb my peace.",\
"I don’t care how rich you are. I don’t care whether you’re a top Wall Street banker. If somebody has to tell you when to be at work, what to wear and how to behave, you’re not a free person. You’re not actually rich.",\
"If you have to wear a tie to work, you’re not really free. If you have to be at your desk at a certain time, you’re not free.",\
"What you do, who you do it with, and how you do it is WAY more important than how hard you work."
"8 hours of input does not equate to the same output for every single person (your output is based on the quality of work you put in)."
"You HAVE to know how to learn anything you want to learn. There should be no book in the library that scares you."
"When you’re reading a book, and you’re not understanding a lot of what it’s saying, and there’s a lot of confusion in your mind about it, that confusion is similar to the burn you get in the gym when you’re working out, except you’re building mental, instead of physical, muscles.",\
"If you’re a perpetual learning machine, you will never be out of options on how to make money.",\
"Today in society, you get rewarded for creative work, for creating something brand new that society didn’t even know that it wanted that it doesn’t yet know how to get, other than through you.",\
"No matter how high your bar is, raise your bar… You can never be working with other people who are great enough. If there’s someone greater out there to work with, you should go work with them.",\
"Worry about working hard only AFTER you’ve picked the right thing to work on and the right people to work with."
"Specific knowledge is the stuff that feels like play to you but looks like work to others. It’s found by pursuing your innate talents, your genuine curiosity, and your passion."
"If you’re not 100% into it, then someone else who is 100% into it will outperform you.",\
"No one can compete with you on being you.",\
"Embrace accountability and take business risks under your own name."
"Busy is the death of productivity.",\
"You have to get bored before you can get creative… You can’t be creative on schedule.",\
"I need 4-5 hours of time by myself every day doing NOTHING. Because if I don’t have that time, I won’t be able to do ANYTHING.",\
"I believe everybody can be wealthy. It’s not a zero-sum game; it’s a positive-sum game.",\
"People who are living far below their means enjoy a freedom that people busy upgrading their lifestyle just can’t fathom."
"All the benefits in life come from compound interest, whether in relationships, life, your career, health, or learning."
"You’re not going to get rich renting out your time. Aim to have a job, career, or profession where your inputs don’t match your output."
"Successful people have a strong action bias."
"Productize yourself."
"Aim to become so good at something, that luck eventually finds you. Over time, it isn’t luck; it’s destiny."
"The 5 most important skills are reading, writing, arithmetic, persuasion, and computer programming."
"The number of iterations drives the learning curve."
"If you’re good with computers, if you’re good at basic math, if you’re good at writing, if you’re good at speaking, and if you like reading, you’re set for life.",\
"Get comfortable with frequent, small failures."
"If you’re willing to bleed a little bit every day, but in exchange, you win big later, you’ll be better off."
"Become the best in the world at what you do. Keep redefining what you do until this is true."
"Reject most advice but remember you have to listen to/read enough of it to know what to reject and what to accept."
"In entrepreneurship, you just have to be right ONCE. The good news is you can take as many shots on goal as you want."
"Know that your physical health, mental health, and your relationships will bring you more peace and happiness than any amount of money ever will."
"It’s good for everybody to realize that at this point in human history, you are basically no longer a citizen of your nation. Wherever you live, whoever you are, you have one foot in the internet. The internet is the real country.",\
"If all of your beliefs line up into one political party, you’re not a clear thinker. If all your beliefs are the same as your neighbors and your friends, you’re not a clear thinker; your beliefs are taken from other people. If you want to be a clear thinker, you cannot pay attention to politics; it will destroy your ability to think.",\
"Fair doesn’t exist in the world. If you’re going to obsess over fair, you’ll never get anywhere in life. You basically just have to do the best you can, with the cards you’re dealt.",\
"Pick three hobbies: One that makes you money, one that makes you fit, and one that keeps you creative.",\
"A lot of wisdom is just realizing the long-term consequences of your actions. The longer-term you’re willing to look, the wiser you’re going to seem to everybody around you.",\
# """llusion #1: The illusion of meaning
# We’re all going to die, and everything will turn to dust – how can anything have meaning?""",\
"IMHO the three big ones in life are wealth, health, and happiness. We pursue them in that order but their importance is in the reverse."
"You can have the mind or you can have the moment.",\
"Ego is false confidence, self-respect is true confidence."
"No one can compete with you on being you. Most of life is a search for who and what needs you the most."
"A rational person can find peace by cultivating indifference to things outside of their control.",\
"Success is the enemy of learning. It can deprive you of the time and the incentive to start over. Beginner’s mind also needs beginner’s time."
"Escape competition through authenticity.",\
"The heart decides, the head rationalizes."
"The fundamental delusion — there is something out there that will make you happy and fulfilled forever.",\
"All the benefits in life come from compound interest — money, relationships, habits — anything of importance.",\
"The compound interest from many quick small iterations is greater than the compound interest from a few slow big iterations. Compound interest operates in most intellectual and social domains."
"Relax. You’ll live longer *and* perform better."
"Twitter is television for intellectuals."
"If you can't decide, the answer is No."
"You don’t get rich by spending your time to save money. You get rich by saving your time to make money."
"Trade money for time, not time for money. You’re going to run out of time first."
"Seek wealth, not money or status. Wealth is having assets that earn while you sleep. Money is how we transfer time and wealth. Status is your place in the social hierarchy."
"Work as hard as you can. Even though who you work with and what you work on are more important than how hard you work.",\
"It is the mark of a charalatan to explain a simple concept in a complex way.",\
"Self-image is the prison. Other people are the guards."
"The greatest superpower is the ability to change yourself."
"We say 'peace of mind', but really what we want is peace from mind."
"A fit body, a calm mind, a house full of love. These things cannot be bought — they must be earned.",\
"Founders run every sprint as if they’re about to lose, but grind out the long race knowing that victory is inevitable."
"It's never been easier to start a company. It's never been harder to build one."
"An early exit for your startup is a mirage in the desert. If you thirst for it, it disappears.",\
"Read what you love until you love to read."
"Wealth creation is an evolutionarily recent positive-sum game. Status is an old zero-sum game. Those attacking wealth creation are often just seeking status."
"The reality is life is a single-player game. You’re born alone. You’re going to die alone. All of your interpretations are alone. All your memories are alone. You’re gone in three generations and nobody cares. Before you showed up, nobody cared. It’s all single-player."
"Become the best in the world at what you do. Keep redefining what you do until this is true."
"In an age of infinite leverage, judgement is the most important skill."
"Leverage is a force multiplier for your judgement."
"Once you’ve truly controlled your own fate, for better or for worse, you’ll never let anyone else tell you what to do."
"You will get rich by giving society what it wants but does not yet know how to get. At scale."
"People who try to look smart by pointing out obvious exceptions actually signal the opposite.",\
"The selfish reason to be ethical is that it attracts the other ethical people in the network.",\
"There are no get rich quick schemes. That’s just someone else getting rich off you.",\
"Specific knowledge is found by pursuing your genuine curiosity and passion rather than whatever is hot right now."
"Better to find a new audience than to write for the audience."
"Learn to sell. Learn to build. If you can do both, you will be unstoppable."
"A taste of freedom can make you unemployable."
"Your closest friends are the ones you can have a relationship with about nothing."
" 'Consensus' is just another way of saying 'average'."
"Morality and ethics automatically emerge when we realize the long term consequences of our actions.",\
"The best jobs are neither decreed nor degreed. They are creative expressions of continuous learners in free markets."
"The skills you really want can’t be taught, but they can be learned."
"Building technology means you don’t have to choose between practicing science, commerce, and art."
"Twitter is a much better resumé than LinkedIn."
"It is the mark of a charlatan to explain a simple concept in a complex way.",\
"Free education is abundant, all over the internet. It’s the desire to learn that’s scarce.",\
"The internet is the best school ever created. The best peers are on the Internet. The best books are on the Internet. The best teachers are on the Internet. The tools for learning are abundant. It’s the desire to learn that’s scarce."
"Teaching is more a way for the teacher to learn than for the student to learn."
"A busy mind accelerates the passage of subjective time."
"All the value in life, including in relationships, comes from compound interest."
"The first rule of handling conflict is don't hang around with people who are constantly engaging in conflict."
"If you want to be successful, surround yourself with people who are more successful than you are, but if you want to be happy, surround yourself with people who are less successful than you are."
"Pick an industry where you can play long term games with long term people."
"The most important trick to be happy is to realize that happiness is a choice that you make and a skill set that you develop. You choose to be happy, and then you work at it. It's just like building muscles."
"Don’t do things that you know are morally wrong. Not because someone is watching, but because you are. Self-esteem is just the reputation that you have with yourself. You’ll always know."
"If you create intersections, you’re going to have collisions."
"The right to debate should not be up for debate."
"Knowledge is discovered by all of us, each adding to the whole. Wisdom is rediscovered by each of us, one at a time."
"My 1 repeated learning in life: 'There Are No Adults' Everyone's making it up as they go along. Figure it out yourself, and do it."
"Making money through an early lucky trade is the worst way to win. The bad habits that it reinforces will lead to a lifetime of losses."
"Forty hour workweeks are a relic of the Industrial Age. Knowledge workers function like athletes — train and sprint, then rest and reassess.",\
"Information is everywhere but its meaning is created by the observer that interprets it. Meaning is relative and there is no objective, over-arching meaning.",\
"If you’re more passionate about founding a business than the business itself, you can fall into a ten year trap. Better to stay emotionally unattached and select the best opportunity that arises. Applies to relationships too.",\
"Smart money is just dumb money that’s been through a crash.",\
"The secret to public speaking is to speak as if you were alone.",\
"Notifications are just alarm clocks that someone else is setting for you."
"The best way, perhaps the only way, to change others is to become an example."
"Sophisticated foods are bittersweet (wine, beer, coffee, chocolate). Addictive relationships are cooperative and competitive. Work becomes flow at the limits of ability. The flavor of life is on the edge.",\
"I think the best way to prepare for the future 20 years is find something you love to do, to have a shot at being one of the best people in the world at it. Build an independent brand around it, with your name."
"Technology is not only the thing that moves the human race forward, but it’s the only thing that ever has. Without technology, we’re just monkeys playing in the dirt.",\
"Success is the enemy of learning. It can deprive you of the time and the incentive to start over. Beginner’s mind also needs beginner’s time.",\
"Don’t debate people in the media when you can debate them in the marketplace.",\
"Twitter is a way to broadcast messages to hundreds of millions of people to find the few dozen that you actually want to talk to."
"A contrarian isn’t one who always objects — that’s a confirmist of a different sort. A contrarian reasons independently, from the ground up, and resists pressure to conform.",\
"The real struggle isn’t proletariat vs bourgeois. It’s between high-status elites and wealthy elites. When their cooperation breaks, revolution.",\
"Branding requires accountability. To build a great personal brand (an eponymous one), you must take on the risk of being publicly wrong.",\
"If you're going to pick 3 cards in the hand you're dealt, take intelligence, drive, and most importantly, emotional self-discipline."
"Before you can lie to another, you must first lie to yourself.",\
"The tools for learning are abundant. It’s the desire to learn that’s scarce.",\
"This is such a short and precious life that it’s really important that you don’t spend it being unhappy.",\
"You make your own luck if you stay at it long enough.",\
"The power to make and break habits and learning how to do that is really important.",\
"Happiness is a choice and a skill and you can dedicate yourself to learning that skill and making that choice.",\
"We’re not really here for that long and we don’t really matter that much. And nothing that we do lasts. So eventually you will fade. Your works will fade. Your children will fade. Your thoughts will fade. This planet will fade. The sun will fade. It will all be gone.",\
"The first rule of handling conflict is don’t hang around people who are constantly engaging in conflict.",\
"The problem happens when we have multiple desires. When we have fuzzy desires. When we want to do ten different things and we’re not clear about which is the one we care about.",\
"People spend too much time doing and not enough time thinking about what they should be doing.",\
"The people who succeed are irrationally passionate about something.",\
"I don’t plan. I’m not a planner. I prefer to live in the moment and be free and to flow and to be happy.",\
"If you see a get rich quick scheme, that’s someone else trying to get rich off of you.",\
"If you try to micromanage yourself all you’re going to do is make yourself miserable.",\
"Social media has degenerated into a deafening cacophony of groups signaling and repeating their shared myths.",\
"If it entertains you now but will bore you someday, it’s a distraction. Keep looking.",\
"If the primary purpose of school was education, the Internet should obsolete it. But school is mainly about credentialing.",\
"Desire is a contract that you make with yourself to be unhappy until you get what you want.",\
"Technology is applied science. Science is the study of nature. Mathematics is the language of nature. Philosophy is the root of mathematics. All tightly interrelated.",\
"Be present above all else.",\
"Who you do business with is just as important as what you choose to do.",\
"If you can’t see yourself working with someone for life, don’t work with them for a day.",\
"Time is the ultimate currency and I should have been more tight fisted with it."
"Impatience is a virtue. Self-discipline is another form of self conflict. Find things that excite you."
"Earn with your mind, not your time.",\
"Humans are basically habit machines… I think learning how to break habits is actually a very important meta skill and can serve you in life almost better than anything else.",\
"The older the problem, the older the solution.",\
"Humans aren’t evolved to worry about everything happening outside of their immediate environment."
"It’s the mark of a charlatan to try and explain simple things in complex ways and it’s the mark of a genius to explain complicated things in simple ways.",\
"The Efficient Markets Hypothesis fails because humans are herd animals, not independent rational actors. Thus the best investors tend to be antisocial and contrarian.",\
"You’re never going to get rich renting out your time.",\
"Lots of literacy in modern society, but not enough numeracy.",\
"Above 'product-market fit', is 'founder-product-market fit'.",\
"Good copy is a poor substitute for good UI. Good marketing is a poor substitute for a good product."
"Software is gnawing on Venture Capital."
"Society has had multiple stores of value, as none is perfectly secure. Gold, oil, dollars, real estate, (some) bonds & equities. Crypto is the first that’s decentralized *and* digital.",\
"Crypto is a bet against the modern macroeconomic dogma, which is passed off as science, but is really a branch of politics — with rulers, winners, and losers.",\
"The overeducated are worse off than the undereducated, having traded common sense for the illusion of knowledge."
"Trade money for time, not time for money. You’re going to run out of time first."
"School, politics, sports, and games train us to compete against others. True rewards - wealth, knowledge, love, fitness, and equanimity - come from ignoring others and improving ourselves."
"If you eat, invest, and think according to what the ‘news’ advocates, you’ll end up nutritionally, financially and morally bankrupt.",\
"If you’re more passionate about founding a business than the business itself, you can fall into a ten year trap. Better to stay emotionally unattached and select the best opportunity that arises."
"Making money through an early lucky trade is the worst way to win. The bad habits that it reinforces will lead to a lifetime of losses."
"Your goal in life is to find out the people who need you the most, to find out the business that needs you the most, to find the project and the art that needs you the most. There is something out there just for you.",\
"Yoga cultivates Peace of Body. Meditation cultivates Peace of Mind."
"Judgement requires experience, but can be built faster by learning foundational skills."
"Tell your friends that you're a happy person. Then you'll be forced to conform to it. You'll have a consistency bias. You have to live up to it. Your friends will expect you to be a happy person."
"Clear thinkers appeal to their own authority.",\
"Think clearly from the ground up. Understand and explain from first principles. Ignore society and politics. Acknowledge what you have. Control your emotions.",\
"Cynicism is easy. Mimicry is easy. Optimistic contrarians are the rarest breed.",\
"If they can train you to do it, then eventually they will train a computer to do it.",\
"A great goal in life would be to not have to be in a given place at a given time... Being accountable for your output rather than your input. I would love to be paid purely for my judgment.",\
"If you’re desensitized to the fact that you’re going to die, consider it a different way. As far as you’re concerned, this world is going to end. Now what?",\
"Following your genuine intellectual curiosity is a better foundation for a career than following whatever is making money right now.",\
"Objectively, the world is improving. To the elites, it’s falling apart as their long-lived institutions are flattened by the Internet.",\
"One of the most damaging and widespread social beliefs is the idea that most adults are incapable of learning new skills.",\
"A personal metric: how much of the day is spent doing things out of obligation rather than out of interest?",\
"Caught in a funk? Use meditation, music, and exercise to reset your mood. Then choose a new path to commit emotional energy for rest of day.",\
"To be honest, speak without identity.",\
"A rational person can find peace by cultivating indifference to things outside of their control.",\
"Politics is sports writ large — pick a side, rally the tribe, exchange stories confirming bias, hurl insults and threats at the other side.",\
"People who live far below their means enjoy a freedom that people busy upgrading their lifestyles can’t fathom.",\
"We feel guilt when we no longer want to associate with old friends and colleagues who haven’t changed. The price, and marker, of growth.",\
"The most important trick to be happy is to realize that happiness is a choice that you make and a skill that you develop. You choose to be happy, and then you work at it. It’s just like building muscles.",\
"Don’t do things that you know are morally wrong. Not because someone is watching, but because you are. Self-esteem is just the reputation that you have with yourself.",\
"Anger is a hot coal that you hold in your hand while waiting to throw it at someone else. (Buddhist saying)",
"All the real benefits of life come from compound interest.",\
"Total honesty at all times. It’s almost always possible to be honest & positive.",\
"Truth is that which has predictive power.",\
"Watch every thought. Always ask, why am I having this thought?",\
"All greatness comes from suffering.",\
"Love is given, not received.",\
"Enlightenment is the space between your thoughts.",\
"Mathematics is the language of nature.",\
"Every moment has to be complete in and of itself.",\
"So I have no time for short-term things: dinners with people I won’t see again, tedious ceremonies to please tedious people, traveling to places that I wouldn’t go to on vacation.",\
"You can change it, you can accept it, or you can leave it. What is not a good option is to sit around wishing you would change it but not changing it, wishing you would leave it but not leaving it, and not accepting it. It’s that struggle, that aversion, that is responsible for most of our misery. The phrase that I use the most to myself in my head is one word: accept.",\
"I don’t have time is just saying it’s not a priority.",\
"Happiness is a state where nothing is missing.",\
"If you don’t love yourself who will?",\
"If being ethical were profitable everybody would do it.",\
"Someone who is using a lot of fancy words and big concepts probably doesn’t know what they’re talking about. The smartest people can explain things to a child; if you can’t do that, you don’t understand the concept.",\
"School, politics, sports, and games train us to compete against others. True rewards — wealth, knowledge, love, fitness, and equanimity — come from ignoring others and improving ourselves.",\
"Signaling virtue is a vice.",\
"Investing favors the dispassionate. Markets efficiently separate emotional investors from their money.",\
"Reality is neutral. Our reactions reflect back and create our world. Judge, and feel separate and lonely. Anger, and lose peace of mind. Cling, and live in anxiety. Fantasize, and miss the present. Desire, and suffer until you have it. Heaven and hell are right here, right now.",\
"Knowledge is a skyscraper. You can take a shortcut with a fragile foundation of memorization, or build slowly upon a steel frame of understanding.",\
"A busy mind accelerates the perceived passage of time. Buy more time by cultivating peace of mind.",\
"Politics is the exercise of power without merit.",\
"Politics and merit are opposite ends of a spectrum. More political organizations are less productive, have less inequality, and top performers opt out. More merit based organizations have higher productivity, more inequality, and higher odds of internal fracture.",\
# "Doctors won’t make you healthy.\nNutritionists won’t make you slim.\nTeachers won’t make you smart.\nGurus won’t make you calm.\nMentors won’t make you rich.\nTrainers won’t make you fit.\nUltimately, you have to take responsibility. Save yourself.",\
"You have to surrender, at least a little bit, to be the best version of yourself possible.",\
] |
# -*- coding: utf-8 -*-
def case_insensitive_string(string, available, default=None):
if string is None:
return default
_available = [each.lower() for each in available]
try:
index = _available.index(f"{string}".lower())
except ValueError:
raise ValueError(f"unrecognised input ('{string}') - must be in {available}")
else:
return available[index]
def listing_type(entry):
if entry is None:
return ""
available_listing_types = ["Sale", "Rent", "Share", "Sold", "NewHomes"]
_alt = [each.lower() for each in available_listing_types]
try:
index = _alt.index(str(entry).lower())
except ValueError:
raise ValueError("listing type must be one of: {}".format(
", ".join(available_listing_types)))
else:
return available_listing_types[index]
def property_types(entries):
if entries is None:
return [""]
available_property_types = [
"AcreageSemiRural", "ApartmentUnitFlat", "BlockOfUnits", "CarSpace",
"DevelopmentSite", "Duplex", "Farm", "NewHomeDesigns", "House",
"NewHouseLand", "NewLand", "NewApartments", "Penthouse",
"RetirementVillage", "Rural", "SemiDetached", "SpecialistFarm",
"Studio", "Terrace", "Townhouse", "VacantLand", "Villa"]
_lower_pt = [each.lower() for each in available_property_types]
if isinstance(entries, (str, unicode)):
entries = [entries]
validated_entries = []
for entry in entries:
try:
index = _lower_pt.index(str(entry).lower())
except IndexError:
raise ValueError(
"Unrecognised property type '{}'. Available types: {}".format(
entry, ", ".join(available_property_types)))
validated_entries.append(available_property_types[index])
return validated_entries
def listing_attributes(entries):
if entries is None:
return [""]
available_listing_attributes = ["HasPhotos", "HasPrice", "NotUpForAuction",
"NotUnderContract", "MarkedAsNew"]
_lower_la = [each.lower() for each in available_listing_attributes]
if isinstance(entries, (str, unicode)):
entries = [entries]
validated_entries = []
for entry in entries:
try:
index = _lower_la.index(str(entry).lower())
except IndexError:
raise ValueError(
"Unrecognised listing attribute {}. Available attributes: {}"\
.format(entry, ", ".join(available_listing_attributes)))
validated_entries.append(available_listing_attributes[index])
return validated_entries
def integer_range(entry, default_value=-1):
entry = entry or default_value
# Allow a single value to be given.
if isinstance(entry, int) or entry == default_value:
return (entry, entry)
if len(entry) > 2:
raise ValueError("only lower and upper range can be given, not a list")
return tuple(sorted(entry))
def city(string, **kwargs):
cities = ("Sydney", "Melbourne", "Brisbane", "Adelaide", "Canberra")
return case_insensitive_string(string, cities, **kwargs)
def advertiser_ids(entries):
if entries is None:
return [""]
if isinstance(entries, (str, unicode)):
entries = [entries]
return entries
|
begin_unit
comment|'# Copyright (c) 2014 The Johns Hopkins University/Applied Physics Laboratory'
nl|'\n'
comment|'# All Rights Reserved'
nl|'\n'
comment|'#'
nl|'\n'
comment|'# Licensed under the Apache License, Version 2.0 (the "License"); you may'
nl|'\n'
comment|'# not use this file except in compliance with the License. You may obtain'
nl|'\n'
comment|'# a copy of the License at'
nl|'\n'
comment|'#'
nl|'\n'
comment|'# http://www.apache.org/licenses/LICENSE-2.0'
nl|'\n'
comment|'#'
nl|'\n'
comment|'# Unless required by applicable law or agreed to in writing, software'
nl|'\n'
comment|'# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT'
nl|'\n'
comment|'# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the'
nl|'\n'
comment|'# License for the specific language governing permissions and limitations'
nl|'\n'
comment|'# under the License.'
nl|'\n'
nl|'\n'
name|'import'
name|'os'
newline|'\n'
nl|'\n'
name|'from'
name|'oslo_concurrency'
name|'import'
name|'processutils'
newline|'\n'
name|'from'
name|'oslo_log'
name|'import'
name|'log'
name|'as'
name|'logging'
newline|'\n'
name|'from'
name|'oslo_utils'
name|'import'
name|'excutils'
newline|'\n'
nl|'\n'
name|'from'
name|'nova'
op|'.'
name|'i18n'
name|'import'
name|'_LE'
newline|'\n'
name|'from'
name|'nova'
op|'.'
name|'virt'
op|'.'
name|'libvirt'
name|'import'
name|'utils'
newline|'\n'
nl|'\n'
nl|'\n'
DECL|variable|LOG
name|'LOG'
op|'='
name|'logging'
op|'.'
name|'getLogger'
op|'('
name|'__name__'
op|')'
newline|'\n'
nl|'\n'
DECL|variable|_dmcrypt_suffix
name|'_dmcrypt_suffix'
op|'='
string|"'-dmcrypt'"
newline|'\n'
nl|'\n'
nl|'\n'
DECL|function|volume_name
name|'def'
name|'volume_name'
op|'('
name|'base'
op|')'
op|':'
newline|'\n'
indent|' '
string|'"""Returns the suffixed dmcrypt volume name.\n\n This is to avoid collisions with similarly named device mapper names for\n LVM volumes\n """'
newline|'\n'
name|'return'
name|'base'
op|'+'
name|'_dmcrypt_suffix'
newline|'\n'
nl|'\n'
nl|'\n'
DECL|function|is_encrypted
dedent|''
name|'def'
name|'is_encrypted'
op|'('
name|'path'
op|')'
op|':'
newline|'\n'
indent|' '
string|'"""Returns true if the path corresponds to an encrypted disk."""'
newline|'\n'
name|'if'
name|'path'
op|'.'
name|'startswith'
op|'('
string|"'/dev/mapper'"
op|')'
op|':'
newline|'\n'
indent|' '
name|'return'
name|'path'
op|'.'
name|'rpartition'
op|'('
string|"'/'"
op|')'
op|'['
number|'2'
op|']'
op|'.'
name|'endswith'
op|'('
name|'_dmcrypt_suffix'
op|')'
newline|'\n'
dedent|''
name|'else'
op|':'
newline|'\n'
indent|' '
name|'return'
name|'False'
newline|'\n'
nl|'\n'
nl|'\n'
DECL|function|create_volume
dedent|''
dedent|''
name|'def'
name|'create_volume'
op|'('
name|'target'
op|','
name|'device'
op|','
name|'cipher'
op|','
name|'key_size'
op|','
name|'key'
op|')'
op|':'
newline|'\n'
indent|' '
string|'"""Sets up a dmcrypt mapping\n\n :param target: device mapper logical device name\n :param device: underlying block device\n :param cipher: encryption cipher string digestible by cryptsetup\n :param key_size: encryption key size\n :param key: encryption key as an array of unsigned bytes\n """'
newline|'\n'
name|'cmd'
op|'='
op|'('
string|"'cryptsetup'"
op|','
nl|'\n'
string|"'create'"
op|','
nl|'\n'
name|'target'
op|','
nl|'\n'
name|'device'
op|','
nl|'\n'
string|"'--cipher='"
op|'+'
name|'cipher'
op|','
nl|'\n'
string|"'--key-size='"
op|'+'
name|'str'
op|'('
name|'key_size'
op|')'
op|','
nl|'\n'
string|"'--key-file=-'"
op|')'
newline|'\n'
name|'key'
op|'='
string|"''"
op|'.'
name|'join'
op|'('
name|'map'
op|'('
name|'lambda'
name|'byte'
op|':'
string|'"%02x"'
op|'%'
name|'byte'
op|','
name|'key'
op|')'
op|')'
newline|'\n'
name|'try'
op|':'
newline|'\n'
indent|' '
name|'utils'
op|'.'
name|'execute'
op|'('
op|'*'
name|'cmd'
op|','
name|'process_input'
op|'='
name|'key'
op|','
name|'run_as_root'
op|'='
name|'True'
op|')'
newline|'\n'
dedent|''
name|'except'
name|'processutils'
op|'.'
name|'ProcessExecutionError'
name|'as'
name|'e'
op|':'
newline|'\n'
indent|' '
name|'with'
name|'excutils'
op|'.'
name|'save_and_reraise_exception'
op|'('
op|')'
op|':'
newline|'\n'
indent|' '
name|'LOG'
op|'.'
name|'error'
op|'('
name|'_LE'
op|'('
string|'"Could not start encryption for disk %(device)s: "'
nl|'\n'
string|'"%(exception)s"'
op|')'
op|','
op|'{'
string|"'device'"
op|':'
name|'device'
op|','
string|"'exception'"
op|':'
name|'e'
op|'}'
op|')'
newline|'\n'
nl|'\n'
nl|'\n'
DECL|function|delete_volume
dedent|''
dedent|''
dedent|''
name|'def'
name|'delete_volume'
op|'('
name|'target'
op|')'
op|':'
newline|'\n'
indent|' '
string|'"""Deletes a dmcrypt mapping\n\n :param target: name of the mapped logical device\n """'
newline|'\n'
name|'try'
op|':'
newline|'\n'
indent|' '
name|'utils'
op|'.'
name|'execute'
op|'('
string|"'cryptsetup'"
op|','
string|"'remove'"
op|','
name|'target'
op|','
name|'run_as_root'
op|'='
name|'True'
op|')'
newline|'\n'
dedent|''
name|'except'
name|'processutils'
op|'.'
name|'ProcessExecutionError'
name|'as'
name|'e'
op|':'
newline|'\n'
comment|'# cryptsetup returns 4 when attempting to destroy a non-existent'
nl|'\n'
comment|'# dm-crypt device. It indicates that the device is invalid, which'
nl|'\n'
comment|'# means that the device is invalid (i.e., it has already been'
nl|'\n'
comment|'# destroyed).'
nl|'\n'
indent|' '
name|'if'
name|'e'
op|'.'
name|'exit_code'
op|'=='
number|'4'
op|':'
newline|'\n'
indent|' '
name|'LOG'
op|'.'
name|'debug'
op|'('
string|'"Ignoring exit code 4, volume already destroyed"'
op|')'
newline|'\n'
dedent|''
name|'else'
op|':'
newline|'\n'
indent|' '
name|'with'
name|'excutils'
op|'.'
name|'save_and_reraise_exception'
op|'('
op|')'
op|':'
newline|'\n'
indent|' '
name|'LOG'
op|'.'
name|'error'
op|'('
name|'_LE'
op|'('
string|'"Could not disconnect encrypted volume "'
nl|'\n'
string|'"%(volume)s. If dm-crypt device is still active "'
nl|'\n'
string|'"it will have to be destroyed manually for "'
nl|'\n'
string|'"cleanup to succeed."'
op|')'
op|','
op|'{'
string|"'volume'"
op|':'
name|'target'
op|'}'
op|')'
newline|'\n'
nl|'\n'
nl|'\n'
DECL|function|list_volumes
dedent|''
dedent|''
dedent|''
dedent|''
name|'def'
name|'list_volumes'
op|'('
op|')'
op|':'
newline|'\n'
indent|' '
string|'"""Function enumerates encrypted volumes."""'
newline|'\n'
name|'return'
op|'['
name|'dmdev'
name|'for'
name|'dmdev'
name|'in'
name|'os'
op|'.'
name|'listdir'
op|'('
string|"'/dev/mapper'"
op|')'
nl|'\n'
name|'if'
name|'dmdev'
op|'.'
name|'endswith'
op|'('
string|"'-dmcrypt'"
op|')'
op|']'
newline|'\n'
dedent|''
endmarker|''
end_unit
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Time : 2019/5/5 12:39 AM
@Author : sweetcs
@Site :
@File : config.py
@Software: PyCharm
"""
DEBUG=True
HOST="0.0.0.0"
PORT=9292 |
# What should be printing the next snippet of code?
intNum = 10
negativeNum = -5
testString = "Hello "
testList = [1, 2, 3]
print(intNum * 5)
print(intNum - negativeNum)
print(testString + 'World')
print(testString * 2)
print(testString[-1])
print(testString[1:])
print(testList + testList)
# The sum of each three first numbers of each list should be resulted in the last element of each list
matrix = [
[1, 1, 1, 3],
[2, 2, 2, 7],
[3, 3, 3, 9],
[4, 4, 4, 13]
]
matrix[1][-1] = sum(matrix[1][:-1])
matrix[-1][-1] = sum(matrix[-1][:-1])
print(matrix)
# Reverse string str[::-1]
testString = "eoD hnoJ,01"
testString = testString[::-1]
print(testString)
n = 0
while n < 10:
if (n % 2) == 0:
print(n, 'even number')
else:
print(n, 'odd number')
n = n + 1
|
# THIS FILE IS GENERATED FROM NUMPY SETUP.PY
short_version = '1.9.0'
version = '1.9.0'
full_version = '1.9.0'
git_revision = '07601a64cdfeb1c0247bde1294ad6380413cab66'
release = True
if not release:
version = full_version
|
"""Given a string and a pattern, find all anagrams of the pattern in the given string.
Write a function to return a list of starting indices of the anagrams of the pattern
in the given string."""
"""Example: String="ppqp", Pattern="pq", Output = [1, 2] """
def find_string_anagrams(str1, pattern):
result_indexes = []
window_start, matched = 0, 0
char_frequency = {}
for char in pattern:
if char not in char_frequency:
char_frequency[char] = 0
char_frequency[char] += 1
for window_end in range(len(str1)):
right_char = str1[window_end]
if right_char in char_frequency:
char_frequency[right_char] -= 1
if char_frequency[right_char] == 0:
matched += 1
if matched == len(pattern):
result_indexes.append(window_start)
if window_end >= len(pattern) - 1:
left_char = str1[window_start]
window_start += 1
if left_char in char_frequency:
if char_frequency[left_char] == 0:
matched -= 1
char_frequency[left_char] += 1
return result_indexes
|
def table_pkey(table):
query = f"""SELECT KU.table_name as TABLENAME,column_name as PRIMARYKEYCOLUMN FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS TC
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KU ON TC.CONSTRAINT_TYPE = 'PRIMARY KEY' AND TC.CONSTRAINT_NAME = KU.CONSTRAINT_NAME
AND KU.table_name='{table}' ORDER BY KU.TABLE_NAME,KU.ORDINAL_POSITION LIMIT 1;"""
return query
def get_fkey_relations(db_name, table):
query = f"""SELECT TABLE_NAME, COLUMN_NAME, REFERENCED_TABLE_NAME, REFERENCED_COLUMN_NAME
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE REFERENCED_TABLE_SCHEMA = '{db_name}'
AND REFERENCED_TABLE_NAME = '{table}';"""
return query
def get_index_info(db_name):
query = f"""SELECT DISTINCT TABLE_NAME, COLUMN_NAME FROM INFORMATION_SCHEMA.STATISTICS WHERE TABLE_SCHEMA = '{db_name}';"""
return query
def get_table_columns_for_indexing(table):
query = f"select column_name FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '{table}';"
return query
def get_table_ref_idx(index_table, table, index_column, column):
sql = f"SELECT * FROM {index_table}, {table} WHERE {index_table}.{index_column} = {table}.{column} LIMIT 500;"
return sql |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
File: __init__.py.py
Author: Scott Yang(Scott)
Email: yangyingfa@skybility.com
Copyright: Copyright (c) 2021, Skybility Software Co.,Ltd. All rights reserved.
Description:
"""
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.