content
stringlengths 7
1.05M
|
|---|
class Judge:
def __init__(self, trial, comparator):
self.trial = trial
self.comparator = comparator
def judge(self, inputs, default):
results = {input: self.trial(input) for input in inputs}
eligible = {input: result for input, result in results.items() if result is not None}
champion = default
for challenger in eligible.items():
champion = self.comparator(champion, challenger)
return champion
|
class Solution:
def rob(self, nums: List[int]) -> int:
if len(nums) == 0:
return 0
elif len(nums) == 1:
return nums[0]
elif len(nums) == 2:
return max(nums[0], nums[1])
scores = [0] * len(nums)
scores[0] = nums[0]
scores[1] = nums[1]
for i in range(2, len(nums)):
if i > 2:
m = max(scores[:i-2+1])
else:
m = scores[0]
scores[i] = max(m + nums[i], scores[i-1])
return scores[-1]
|
a = 50
print('\033[32m_\033[m'*a)
print('\033[1;32m{:=^{}}\033[m'.format('SISTEMA DE IDENTIFICAÇÃO DE PESOS', a))
print('\033[32m-\033[m'*a)
listafinal = list()
listainit = list()
tamanho = 0
maiorp = menorp = 0
continuar = 's'
while True:
if 's' in continuar:
listainit.append(str(input('\033[36mNome: ')))
listainit.append(int(input('Peso: \033[m')))
listafinal.append(listainit[:])
tamanho +=1
if tamanho == 1:
maiorp = listainit[-1]
menorp = listainit[-1]
elif menorp > listainit[-1]:
menorp = listainit[-1]
elif maiorp < listainit[-1]:
maiorp = listainit[-1]
listainit.clear()
elif 'n' in continuar:
break
elif 'sn' not in continuar:
print('\033[31mTente novamente!\033[m')
continuar = str(input('\033[35mQuer continuar? [S/N] \033[m')).lower().strip()[0]
print(f'\033[34mAo todo, você cadastrou {tamanho} pessoas.\033[m')
#print(f'\033[34mAo todo, você cadastrou {len(listafinal} pessoas.\033[m')
print(f'\033[34mO maior peso cadastrado foi de {maiorp}Kg. Peso de: ', end='')
for c in listafinal:
if c[1] == maiorp:
print(f'\033[35m{c[0]}\033[m', end=' ')
print('')
print(f'\033[34mO menor peso cadastrado foi de {menorp}Kg. Peso de: ', end='')
for c in listafinal:
if c[1] == menorp:
print(f'\033[35m{c[0]}\033[m', end=' ')
|
#exercicio 93 curso de python
lista_de_tarefa = []
desfeito = []
menu_0 = '''
|_______________________|
| [1] - Adicionar tarefa|
| [2] - Listar tarefas |
| [3] - Desfazer tarefa |
| [4] - Refazer tarefa |
| [5] - Sair
|_______________________|
Digite uma opção: '''
def adicionar(kwargs):
a = input('Qual tarefa: ')
kwargs.append(a)
return
def listar(lista):
for x in lista:
print(x)
def desfazer(kwargs, kwargs2):
try:
for x in kwargs:
t = x
kwargs2.append(t)
kwargs.pop()
return kwargs and kwargs2
except UnboundLocalError:
print('não tem valores a desfazer')
def refazer(kwargs, kwargs2):
try:
for x in kwargs2:
t = x
kwargs.append(t)
kwargs2.pop()
return kwargs and kwargs2
except UnboundLocalError:
print('não tem valores a refazer')
while True:
opc_menu = input(menu_0)
if opc_menu == '1':
adicionar(lista_de_tarefa)
elif opc_menu == '2':
listar(lista_de_tarefa)
elif opc_menu == '3':
desfazer(lista_de_tarefa, desfeito)
listar(lista_de_tarefa)
elif opc_menu == '4':
refazer(lista_de_tarefa, desfeito)
listar(lista_de_tarefa)
elif opc_menu == '5':
break
else:
print('Digite apenas as opções do menu!')
|
class BinarySearchTree:
class Node:
def __init__(self, value):
self.left = None
self.right = None
self.value = value
def __init__(self):
self.root = None
def add(self, value):
if self.root:
self._add(value, self.root)
else:
self.root = self.Node(value)
def _add(self, value, node):
if value < node.value:
if node.left:
self._add(value, node.left)
else:
node.left = self.Node(value)
if value > node.value:
if node.right:
self._add(value, node.right)
else:
node.right = self.Node(value)
def preorder_left(self):
return self._preorder_left(self.root)
def _preorder_left(self, node):
if node:
result = str(node.value)+'\n'
result += self._preorder_left(node.left)
result += self._preorder_left(node.right)
return result
else:
return ''
def main():
bst = BinarySearchTree()
for vertex in open('input.txt'):
bst.add(int(vertex))
open('output.txt', 'w').write(bst.preorder_left())
main()
|
# noinspection PyUnusedLocal
def fizz_buzz(number):
strings = []
numstring = str(number)
# fizz if divisible by 3 or has a 3 in it
if (number % 3 == 0) or ("3" in numstring):
strings.append("fizz")
# buzz if divisible by 5 or it has a 5 in it:
if (number % 5 == 0) or ("5" in numstring):
strings.append("buzz")
"""
Deluxe if div by 3 and contains a 3
or div by 5 and contains a 5
still fake deluxe if odd
"""
if (
(
(number % 3 == 0) and ("3" in numstring)
) or
(
(number % 5 == 0) and ("5" in numstring)
)
):
if number % 2 == 0:
strings.append("deluxe")
else:
strings.append("fake deluxe")
if len(strings) > 0:
return(" ".join(strings))
else:
return(numstring)
|
# program to find whether it contains an additive sequence or not.
class Solution(object):
# DFS: iterative implement.
def is_additive_number(self, num):
length = len(num)
for i in range(1, int(length/2+1)):
for j in range(1, int((length-i)/2 + 1)):
first, second, others = num[:i], num[i:i+j], num[i+j:]
if self.isValid(first, second, others):
return True
return False
def isValid(self, first, second, others):
if ((len(first) > 1 and first[0] == "0") or
(len(second) > 1 and second[0] == "0")):
return False
sum_str = str(int(first) + int(second))
if sum_str == others:
return True
elif others.startswith(sum_str):
return self.isValid(second, sum_str, others[len(sum_str):])
else:
return False
if __name__ == "__main__":
print(Solution().is_additive_number('66121830'))
print(Solution().is_additive_number('51123'))
print(Solution().is_additive_number('235813'))
|
# -*- coding:UTF-8 -*-
# Author:Tiny Snow
# Date: Tue, 30 Mar 2021, 17:09
# Project Euler # 085 Counting rectangles
#=============================================================Solution
def get_rectangles(m, n):
return m * (m + 1) * n * (n + 1) // 4
diff = 10000
area = 0
for m in range(1, int(2 * (2 ** 0.5) * 10 * 3) + 1):
for n in range(m, int(2 * (2 ** 0.5) * 10 * 3) + 1):
if abs(get_rectangles(m, n) - 2 * (10 ** 6)) < diff:
area = m * n
diff = abs(get_rectangles(m, n) - 2 * (10 ** 6))
print(area)
|
class Solution:
def backspaceCompare(self, S: str, T: str) -> bool:
s = []; t = []
for i in range(len(S)):
if S[i] == "#":
if len(s) > 0:
s.pop(-1)
else:
s.append(S[i])
for i in range(len(T)):
if T[i] == "#":
if len(t) > 0:
t.pop(-1)
else:
t.append(T[i])
return s == t
|
N = int(input())
before = input()
after = input()
if N % 2 == 0:
print("Deletion succeeded" if before == after else "Deletion failed")
else:
find = True
for i in range(len(before)):
if before[i] == after[i]:
find = False
break
print("Deletion succeeded" if find else "Deletion failed")
|
class Actor:
def __init__(self, sess, learning_rate,action_dim,action_bound):
self.sess = sess
self.action_dim = action_dim
self.action_bound = action_bound
self.learning_rate = learning_rate
# input current state, output action to be taken
self.a = self.build_neural_network(S, scope='eval_nn', trainable=True)
self.a_ = self.build_neural_network(S_, scope='target_nn', trainable=False)
self.eval_parameters = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='Actor/eval_nn')
self.target_parameters = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='Actor/target_nn')
def act(self, s):
s = s[np.newaxis, :]
return self.sess.run(self.a, feed_dict={s: state})[0]
def learn(self, state): # update parameters
self.sess.run(self.train_op, feed_dict={s: state})
if self.t_replace_counter % self.t_replace_iter == 0:
self.sess.run([tf.assign(t, e) for t, e in zip(self.target_parameters, self.eval_parameters)])
self.t_replace_counter += 1
def build_neural_network(self, s, scope, trainable):
init_weights = tf.random_normal_initializer(0., 0.1)
init_bias = tf.constant_initializer(0.01)
# three dense layer networks
nn = tf.layers.dense(s, 500, activation=tf.nn.relu,
kernel_initializer=init_weights, bias_initializer=init_bias, name='l1', trainable=trainable)
nn = tf.layers.dense(nn, 200, activation=tf.nn.relu,
kernel_initializer=init_weights, bias_initializer=init_bias, name='l2', trainable=trainable)
actions = tf.layers.dense(nn, self.action_dim, activation=tf.nn.tanh, kernel_initializer=init_weights,
bias_initializer=init_bias, name='a', trainable=trainable)
scaled_actions = tf.multiply(actions, self.action_bound, name='scaled_actions')
return scaled_actions
def add_gradient(self, a_gradients):
self.policy_gradients_and_vars = tf.gradients(ys=self.a, xs=self.eval_parameters, grad_ys=a_gradients)
opt = tf.train.RMSPropOptimizer(-self.learning_rate) # gradient ascent
self.train_op = opt.apply_gradients(zip(self.policy_gradients_and_vars, self.eval_parameters), global_step=GLOBAL_STEP)
|
"""
PlotPlayer Validators Subpackage contains various modules to support input and type validations.
Public Modules:
* type_validation - Contains methods to validating various types
"""
|
class ParserError(Exception):
pass
|
r = int(input())
w = [int(x) for x in input().split()]
c = [int(x) for x in input().split()]
m = [0]
for i in range(1, r + 1):
m.append(max([x[0] + m[i - x[1]] for x in zip(c, w) if x[1] <= i], default = 0))
print(m)
|
#
# オセロ(リバーシ) 6x6
#
N = 6 # 大きさ
EMPTY = 0 # 空
BLACK = 1 # 黒
WHITE = 2 # 白
STONE = ['□', '●', '○'] #石の文字
#
# board = [0] * (N*N)
#
def xy(p): # 1次元から2次元へ
return p % N, p // N #35の座標の出力(5,5)
def p(x, y): # 2次元から1次元へ
return x + y * N #35を出力
# リバーシの初期画面を生成する
def init_board():
board = [EMPTY] * (N*N)
c = N//2 #3
board[p(c, c)] = BLACK #p(3,3)
board[p(c-1, c-1)] = BLACK #p(2,2)
board[p(c, c-1)] = WHITE #p(3,2)
board[p(c-1, c)] = WHITE #p(2,3)
return board
# リバーシの画面を表示する
def show_board(board):
counts = [0, 0, 0]
for y in range(N):
for x in range(N):
stone = board[p(x, y)]
counts[stone] += 1
print(STONE[stone], end='') #表の表示
print()
print()
for pair in zip(STONE, counts):
print(pair, end=' ') #記号と石の数を表示
print()
# (x,y) が盤面上か判定する
def on_borad(x, y):
return 0 <= x < N and 0 <= y < N
# (x,y)から(dx,dy)方向をみて反転できるか調べる
def try_reverse(board, x, y, dx, dy, color):
if not on_borad(x, y) or board[p(x, y)] == EMPTY:
return False
if board[p(x, y)] == color:
return True
if try_reverse(board, x+dx, y+dy, dx, dy, color):
board[p(x, y)] = color
return True
return False
# 相手(反対)の色を返す
def opposite(color):
if color == BLACK:
return WHITE
return BLACK
# (x,y) が相手(反対)の色かどうか判定
def is_oposite(board, x, y, color):
return on_borad(x, y) and board[p(x, y)] == opposite(color)
DIR = [
(-1, -1), (0, -1), (1, -1),
(-1, 0), (1, 0),
(-1, 1), (0, 1), (1, 1),
]
def put_and_reverse(board, position, color):
if board[position] != EMPTY:
return False
board[position] = color
x, y = xy(position) #xy(position) 1次元を2次元にする。
turned = False
for dx, dy in DIR:
nx = x + dx
ny = y + dy
if is_oposite(board, nx, ny, color):
if try_reverse(board, nx, ny, dx, dy, color):
turned = True
if not turned:
board[position] = EMPTY
return turned
# プレイが継続できるか?
# つまり、まだ石を置けるところが残っているか調べる?
def can_play(board, color):
board = board[:] # コピーしてボードを変更しないようにする
for position in range(0, N*N):
if put_and_reverse(board, position, color):
return True
return False
def game(player1, player2):
board = init_board()
show_board(board)
on_gaming = True # ゲームが続行できるか?
while on_gaming:
on_gaming = False # いったん、ゲーム終了にする
if can_play(board, BLACK):
# player1 に黒を置かせる
position = player1(board[:], BLACK)
show_board(board)
# 黒が正しく置けたら、ゲーム続行
on_gaming = put_and_reverse(board, position, BLACK)
if can_play(board, WHITE):
# player1 に白を置かせる
position = player2(board[:], WHITE)
show_board(board)
# 白が置けたらゲーム続行
on_gaming = put_and_reverse(board, position, WHITE)
show_board(board) # 最後の結果を表示!
# AI 用のインターフェース
def A_I(board,color):
x = [35, 0, 5, 30, 2,33,23,12,17,18,3,32, 27, 19, 16, 8, 22, 13, 9, 26, 28, 7, 10, 25, 29, 6, 4, 31, 24, 1, 11, 34,14,15,20,21 ]
#重り 4 : 35, 0, 5, 30 順番は適当
#重り 3 : 2,33,23,12,17,18,3,32
#重り 2 : 27, 19, 16, 8, 22, 13, 9, 26
#重り 1 : 28, 7, 10, 25, 29, 6, 4, 31, 24, 1, 11, 34
for i in range(N*N):
if put_and_reverse(board, x[i], color):
return x[i]
return 0
#4 1 3 3 1 4
#1 1 2 2 1 1
#3 2 2 3
#3 2 2 3
#1 1 2 2 1 1
#4 1 3 3 1 4
|
# Greewald et al. 1998
Japanese_names = ["Hitaka", "Yokomichi", "Fukamachi", "Yamamoto", "Itsumatsu", "Yagimoto", "Kawabashi", "Tsukimoto", "Kushibashi", "Tanaka", "Kuzumaki", "Takasawa", "Fujimoto", "Sugimoto", "Fukuyama", "Samukawa", "Harashima", "Sakata", "Kamakura", "Namikawa", "Kitayama", "Nakamoto", "Minakami", "Morimoto", "Miyamatsu"]
Korean_names = ["Hwang", "Hyun", "Choung", "Maeng", "Chun", "Choe", "Kwon", "Sunwoo", "Whang", "Byun", "Sohn", "Kung", "Youn", "Chae", "Choi", "Chon", "Kwan", "Jung", "Kang", "Hwangbo", "Bhak", "Paik", "Chong", "Jang", "Yoon"]
Truncated_Japanese_names = ["Hitak", "Yoko", "Fukama", "Yamam", "Itsu", "Yagi", "Kawa", "Tsukim", "Kushi", "Tana", "Kuzu", "Taka", "Fuji", "Sugi", "Fuku", "Samu", "Hara", "Saka", "Kama", "Namikaw", "Kita", "Naka", "Minak", "Mori", "Miya"]
White_American_male_names = ["Adam", "Chip", "Harry", "Josh", "Roger", "Alan", "Frank", "Ian", "Justin", "Ryan", "Andrew", "Fred", "Jack", "Matthew", "Stephen", "Brad", "Greg", "Jed", "Paul", "Todd", "Brandon", "Hank", "Jonathan", "Peter", "Wilbur"]
Black_American_male_names = ["Alonzo", "Jamel", "Lerone", "Percell", "Theo", "Alphonse", "Jerome", "Leroy", "Rasaan", "Torrance", "Darnell", "Lamar", "Lionel", "Rashaun", "Tyree", "Deion", "Lamont", "Malik", "Terrence", "Tyrone", "Everol", "Lavon", "Marcellus", "Terryl", "Wardell"]
White_American_female_names = ["Amanda", "Courtney", "Heather", "Melanie", "Sara", "Amber", "Crystal", "Katie", "Meredith", "Shannon", "Betsy", "Donna", "Kristin", "Nancy", "Stephanie", "Bobbie-Sue", "Ellen", "Lauren", "Peggy", "Sue-Ellen", "Colleen", "Emily", "Megan", "Rachel", "Wendy"]
Black_American_female_names = ["Aiesha", "Lashelle", "Nichelle", "Shereen", "Temeka", "Ebony", "Latisha", "Shaniqua", "Tameisha", "Teretha", "Jasmine", "Latonya", "Shanise", "Tanisha", "Tia", "Lakisha", "Latoya", "Sharise", "Tashika", "Yolanda", "Lashandra", "Malika", "Shavonn", "Tawanda", "Yvette"]
Positive_words = ["caress", "freedom", "health", "love", "peace", "cheer", "friend", "heaven", "loyal", "pleasure", "diamond", "gentle", "honest", "lucky", "rainbow", "diploma", "gift", "honor", "miracle", "sunrise", "family", "happy", "laughter", "paradise", "vacation"]
Negative_words = ["abuse", "crash", "filth", "murder", "sickness", "accident", "death", "grief", "poison", "stink", "assault", "disaster", "hatred", "pollute", "tragedy", "bomb", "divorce", "jail", "poverty", "ugly", "cancer", "evil", "kill", "rotten", "vomit", "agony", "prison"]
# NOTE: according to Greenwald et al. 1998 () divorce and kill were only in experiment 1 while prison was only in experiments 2 and 3
Negative_words_1 = ["abuse", "crash", "filth", "murder", "sickness", "accident", "death", "grief", "poison", "stink", "assault", "disaster", "hatred", "pollute", "tragedy", "bomb", "divorce", "jail", "poverty", "ugly", "cancer", "evil", "kill", "rotten", "vomit", "agony"]
Negative_words_2_3 = ["abuse", "crash", "filth", "murder", "sickness", "accident", "death", "grief", "poison", "stink", "assault", "disaster", "hatred", "pollute", "tragedy", "bomb", "jail", "poverty", "ugly", "cancer", "evil", "rotten", "vomit", "agony", "prison"]
Flowers = ["aster", "clover", "hyacinth", "marigold", "poppy", "azalea", "crocus", "iris", "orchid", "rose", "bluebell", "daffodil", "lilac", "pansy", "tulip", "buttercup", "daisy", "lily", "peony", "violet", "carnation", "gladiola", "magnolia", "petunia", "zinnia"]
Insects = ["ant", "caterpillar", "flea", "locust", "spider", "bedbug", "centipede", "fly", "maggot", "tarantula", "bee", "cockroach", "gnat", "mosquito", "termite", "beetle", "cricket", "hornet", "moth", "wasp", "blackfly", "dragonfly", "horsefly", "roach", "weevil"]
Instruments = ["bagpipe", "cello", "guitar", "lute", "trombone", "banjo", "clarinet", "harmonica", "mandolin", "trumpet", "bassoon", "drum", "harp", "oboe", "tuba", "bell", "fiddle", "harpsichord", "piano", "viola", "bongo", "flute", "horn", "saxophone", "violin"]
Weapons = ["arrow", "club", "gun", "missile", "spear", "axe", "dagger", "harpoon", "pistol", "sword", "blade", "dynamite", "hatchet", "rifle", "tank", "bomb", "firearm", "knife", "shotgun", "teargas", "cannon", "grenade", "mace", "slingshot", "whip"]
# Perez 2010
Latino_immigrant_surnames = ["García", "Martínez", "Rodríguez", "López", "Hernández", "González", "Pérez", "Sánchez", "Díaz", "Ramírez"]
White_immigrant_surnames = ["Smith", "Johnson", "Williams", "Jones", "Brown", "Davis", "Miller", "Wilson", "Moore", "Taylor"]
Asian_immigrant_surnames = ["Nguyen", "Liu", "Tran", "Chen", "Wong", "Wu", "Wang", "Choi", "Chang", "Yang"]
Good_words = ["Honest", "Joy", "Love", "Peace", "Wonderful", "Honor", "Pleasure", "Glorious", "Laughter", "Happy"]
Bad_words = ["Agony", "Prison", "Terrible", "Horrible", "Nasty", "Evil", "Awful", "Failure", "Hurt", "Poverty"]
good_words = [w.lower() for w in Good_words]
bad_words = [w.lower() for w in Bad_words]
|
'''"Template" day module for AoC 2015'''
def run(args):
print(f'day0: {args}')
|
'''
@Author: Hata
@Date: 2020-07-26 03:41:32
@LastEditors: Hata
@LastEditTime: 2020-07-28 21:31:17
@FilePath: \LeetCode\116.py
@Description: https://leetcode-cn.com/problems/populating-next-right-pointers-in-each-node/
'''
class Solution:
def connect(self, root: 'Node') -> 'Node':
if root is None:
return root
node_queue = [root]
while node_queue:
curr = None
for _ in range(len(node_queue)):
node = node_queue.pop(0)
if curr is None:
curr = node
else:
curr.next = node
curr = curr.next
if curr.left:
node_queue.append(curr.left)
if curr.right:
node_queue.append(curr.right)
return root
|
#pegando numero
num = int(input('Digite um número qualquer: '))
numDob = num * 2
numTri = num * 3
numRaiz = num**(1/2) #Raiz quadrada é o mesmo que o numero elevado ao meio 1/2
print('O número digitado foi {}, seu dobro é {}, seu triplo é {}, e por fim sua raiz é {}'.format(num, numDob, numTri, numRaiz))
'''
A variavel num recebe um inteiro do usuário, numDob faz o número atual * 2,
O numTri faz o número atual * 3 e numRaiz faz a raiz do número atual (num elevado a 0,5)
E o resultado é printado no final
'''
|
name = "boost"
version = "1.61.0"
authors = [
"Beman Dawes",
"David Abrahams"
]
description = \
"""
Boost is a set of libraries for the C++ programming language that provide support for tasks and structures such
as linear algebra, pseudorandom number generation, multithreading, image processing, regular expressions,
and unit testing.
"""
requires = [
"cmake-3+",
"gcc-6+",
"python-2.7+"
]
variants = [
["platform-linux"]
]
tools = [
"boost"
]
build_system = "cmake"
with scope("config") as config:
config.build_thread_count = "logical_cores"
uuid = "boost-{version}".format(version=str(version))
def commands():
env.LD_LIBRARY_PATH.prepend("{root}/lib")
# Helper environment variables.
env.BOOST_INCLUDE_PATH.set("{root}/include")
env.BOOST_LIBRARY_PATH.set("{root}/lib")
|
class Solution:
# Iterative
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
if not root:
return None
stack = [root]
while len(stack) > 0:
currentNode = stack.pop()
currentNode.left, currentNode.right = currentNode.right, currentNode.left
if currentNode.left is not None:
stack.append(currentNode.left)
if currentNode.right is not None:
stack.append(currentNode.right)
return root
# Recursive
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
if not root:
return None
root.left, root.right = root.right, root.left
self.invertTree(root.left)
self.invertTree(root.right)
return root
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number.
# A number n is called deficient if the sum of its proper divisors is less than n and it is called abundant if this sum exceeds n.
# As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, the smallest number that can be written as the sum of two abundant numbers is 24. By mathematical analysis, it can be shown that all integers greater than 28123 can be written as the sum of two abundant numbers. However, this upper limit cannot be reduced any further by analysis even though it is known that the greatest number that cannot be expressed as the sum of two abundant numbers is less than this limit.
# Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers.
class Abundant():
def __init__(self):
self.abundants = []
def generateAbindantNumbers(self, maxValue):
for number in range(maxValue):
if number % 1000 == 0:
print('GEN: itt jarunk:', number)
total = 0
for divisor in range(1, (number/2)+1):
if number % divisor == 0:
total += divisor
if total > number:
self.abundants.append(number)
#print(self.abundants)
print('Count: ', len(self.abundants))
def sumOfToAbundant(self, maxValue):
total = 0
for number in range(maxValue):
if number % 1000 == 0:
print('SUM: itt jarunk:', number, total)
for i in self.abundants:
if number < i * 2:
total += number
break
if (number - i) in self.abundants:
break
print(total)
def main():
generator = Abundant()
maxval = 28124
generator.generateAbindantNumbers(maxval)
generator.sumOfToAbundant(maxval)
if __name__ == '__main__':
main()
|
def returnHazards(map):
hazards = []
for x_index, x in enumerate(map):
for y_index, y in enumerate(x):
if y == 'x':
hazards.append({"x":x_index,"y":y_index})
return hazards
|
'''
A good meal is a meal that contains exactly two different food items with a sum of deliciousness equal to a power of two.
You can pick any two different foods to make a good meal.
Given an array of integers deliciousness where deliciousness[i] is the deliciousness of the ith item of food,
return the number of different good meals you can make from this list modulo 109 + 7.
Note that items with different indices are considered different even if they have the same deliciousness value.
Example 1:
Input: deliciousness = [1,3,5,7,9]
Output: 4
Explanation: The good meals are (1,3), (1,7), (3,5) and, (7,9).
Their respective sums are 4, 8, 8, and 16, all of which are powers of 2.
Example 2:
Input: deliciousness = [1,1,1,3,3,3,7]
Output: 15
Explanation: The good meals are (1,1) with 3 ways, (1,3) with 9 ways, and (1,7) with 3 ways.
'''
class Solution(object):
def countPairs(self, deliciousness):
dp_table = collections.defaultdict(int)
res = 0
for elem in deliciousness:
for idx in range(22):
# if 2**idx - elem in dp:
res += dp_table[2**idx - elem]
dp_table[elem] += 1
return res % (10**9 + 7)
|
# Codechef June2020
# PRICECON
# https://www.codechef.com/problems/PRICECON
# Chef and Price Control
"""
Chef has N items in his shop (numbered 1 through N); for each valid i, the price of the i-th item is Pi. Since Chef has very loyal customers, all N items are guaranteed to be sold regardless of their price.
However, the government introduced a price ceiling K, which means that for each item i such that Pi>K, its price should be reduced from Pi to K.
Chef's revenue is the sum of prices of all the items he sells. Find the amount of revenue which Chef loses because of this price ceiling.
"""
test = int(input())
for t in range(test) :
n, k = list(map(int, input().strip().split()))
parr = list(map(int, input().strip().split()))
loss = 0
for p in parr :
if p > k :
loss += (p-k)
print(loss)
|
chislo = input()
chislo_na_schote_drevnih_shizov = ""
cifri_scheta_drevnih_shizov = "ноль, целковый, чекушка, порнушка, пердушка, засирушка, жучок, мудачок, хуй на воротничок, дурачок, ВСЕ".split(", ")
for i in chislo: chislo_na_schote_drevnih_shizov+=cifri_scheta_drevnih_shizov[int(i)]
print(chislo_na_schote_drevnih_shizov)
|
'''
Entrada de dados
'''
nome = input('qual o seu nome? ')
idade = input('qual a sua idade? ')
ano_nascimento = 2021-int(idade)
print()
print(f'{nome}, tem {idade} anos. '
f'{nome} nasceu em {ano_nascimento}.')
print(f'O usuário digitou {nome} e o tipo da variável é'
f' {type(nome)}')
|
# # set up logging
# from config import logging
# logger = logging.getLogger(__name__)
# import re
class Criterion:
"""A set of conditions for matching Actions against PRAW objects"""
def __init__(self, values):
# convert the dict to attributes
self.conditions = values
self.modifiers = dict()
# re-duplicate concatenated targets
# parse out modifiers
target_syntax = re.compile(r'^(?P<targets>[a-z0-9\_\+]+)(?P<modifiers>\([a-z0-9\_,]*\))?$')
for k, v in self.conditions.items():
parts = target_syntax.match(k)
# now split the targets and modifiers
# targets = []
# modifiers = []
# for target in targets:
# self.conditions[target] = v
# self.modifiers[target] = modifiers
def matches(self, item):
logger.debug("Checking item {}".format(item))
# Conditions are in self.__dict__
for condition, value in self.conditions.items():
logger.debug("- Checking `{}` for `{}`".format(condition, value))
# uhhhh... this is kinda scary
if not getattr(item, condition, None) == value:
return False
# for condition in self.conditions:
# if not condition.matches(item):
# return False
return True
class Action:
"""A sequence of steps to perform on and in response to reddit content"""
def __init__(self, values):
self.actions = values
def perform_on(self, item):
for action, argument in self.actions.items():
method = getattr(item, action, getattr(item.mod, action, None))
if method:
method(argument)
else:
raise AttributeError("No such method {} on {}".format(method, item))
class Rule:
"""A collection of conditions and response actions triggered on matching content"""
def __init__(self, values):
# TODO lowercase keys
logger.debug("Creating new rule...")
self.yaml = yaml.dump(values)
# Handle single/multiple criteria
self.criteria = []
if isinstance(values["criteria"], list):
for criterion in values["criteria"]:
self.criteria.append(Criterion(criterion))
elif isinstance(values["criteria"], dict):
self.criteria.append(Criterion(values["criteria"]))
# same for actions
self.actions = []
if isinstance(values["actions"], list):
for action in values["actions"]:
self.actions.append(Action(action))
elif isinstance(values["actions"], dict):
self.actions.append(Action(values["actions"]))
# TODO consolidate the above two blocks, cleverly
pprint.pprint(vars(self))
for c in self.criteria:
pprint.pprint(vars(c))
for a in self.actions:
pprint.pprint(vars(a))
def matches(self, item):
# for reference later?
self.matched = []
for criterion in self.criteria:
if criterion.matches(item):
self.matched.append(criterion)
if len(self.matched) > 0:
return True
def _perform_actions_on(self, item):
for action in self.actions:
action.perform_on(item)
def process(self, item):
if self.matches(item):
logger.debug("Matched {}".format(item))
self._perform_actions_on(item)
|
result = 0
boxIds = []
with open("input.txt", "r") as input:
for line in input:
line = line.strip()
boxIds.append(line)
count2 = 0
count3 = 0
for boxId in boxIds:
flag2 = True
flag3 = True
for c in set(boxId):
n = boxId.count(c)
if n == 2 and flag2:
count2 += 1
flag2 = False
elif n == 3 and flag3:
count3 += 1
flag3 = False
result = count2 * count3
with open("output1.txt", "w") as output:
output.write(str(result))
print(str(result))
|
#!/usr/bin/env python3
"""I’ll Use My Scale module"""
def np_shape(matrix):
"""calculates the shape of a numpy.ndarray"""
return matrix.shape
|
class Solution(object):
def XXX(self, n):
g5=5**0.5
b=(((1+g5)/2)**(n+1)-((1-g5)/2)**(n+1))/g5
return int(round(b))
|
# -*- coding: utf-8 -*-
"""036 - Analisando Triângulo
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1oQmCX-HLeaqxWxaz9zsjj-5Na35XtNXM
"""
print('*' * 54)
print('------- Condição de existência de um triângulo -------'.upper())
print('*' * 54)
r1 = float(input('Informe o comprimento da 1ª reta: '))
r2 = float(input('Informe o comprimento da 2ª reta: '))
r3 = float(input('Informe o comprimento da 3ª reta: '))
sit_1 = ((r2 - r3) < r1 < (r2 + r3))
sit_2 = ((r1 - r3) < r2 < (r1 + r3))
sit_3 = ((r1 - r2) < r3 < (r1 + r2))
if (sit_1 and sit_2 and sit_3):
print('PARABÉNS! É possível formar um triângulo com essas retas!')
else:
print('DESCULPA. Não é possível formar um triângulo com essas retas.')
|
"""Created by sgoswami on 7/18/17."""
"""Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be
segmented into a space-separated sequence of one or more dictionary words. You may assume the dictionary does not
contain duplicate words.
For example, given
s = "leetcode",
dict = ["leet", "code"].
Return true because "leetcode" can be segmented as "leet code"."""
class Solution(object):
def wordBreak(self, s, wordDict):
"""
:type s: str
:type wordDict: List[str]
:rtype: bool
"""
memo = [False for _ in range(len(s) + 1)]
memo[0] = True
for i in range(1, len(s) + 1):
for w in wordDict:
if memo[i - len(w)] and s[i - len(w):i] == w:
memo[i] = True
return memo[-1]
if __name__ == '__main__':
solution = Solution()
print(solution.wordBreak('applepieapple', ['apple', 'pie']))
|
names = []
addr = 0x148 + 0x4E4
while addr <= 0x148 + 0x7FC:
names.append('\t' + Name(Dword(addr)) + ' = ')
addr += 8
with open('names.txt', 'w') as f:
f.write('\n'.join(names))
|
# Defines sample_keymap_string and sample_keymap_bytes
# Python 2 type Python 3 type
# sample_keymap_string unicode str
# sample_keymap_bytes str bytes
# This sample keymap is the output of xkbcomp :0 [filename] on my
# system - it wasn't chosen for any other reason. Some of the tests
# may rely on its details.
sample_keymap_string = r"""
xkb_keymap {
xkb_keycodes "evdev+aliases(qwerty)" {
minimum = 8;
maximum = 255;
<ESC> = 9;
<AE01> = 10;
<AE02> = 11;
<AE03> = 12;
<AE04> = 13;
<AE05> = 14;
<AE06> = 15;
<AE07> = 16;
<AE08> = 17;
<AE09> = 18;
<AE10> = 19;
<AE11> = 20;
<AE12> = 21;
<BKSP> = 22;
<TAB> = 23;
<AD01> = 24;
<AD02> = 25;
<AD03> = 26;
<AD04> = 27;
<AD05> = 28;
<AD06> = 29;
<AD07> = 30;
<AD08> = 31;
<AD09> = 32;
<AD10> = 33;
<AD11> = 34;
<AD12> = 35;
<RTRN> = 36;
<LCTL> = 37;
<AC01> = 38;
<AC02> = 39;
<AC03> = 40;
<AC04> = 41;
<AC05> = 42;
<AC06> = 43;
<AC07> = 44;
<AC08> = 45;
<AC09> = 46;
<AC10> = 47;
<AC11> = 48;
<TLDE> = 49;
<LFSH> = 50;
<BKSL> = 51;
<AB01> = 52;
<AB02> = 53;
<AB03> = 54;
<AB04> = 55;
<AB05> = 56;
<AB06> = 57;
<AB07> = 58;
<AB08> = 59;
<AB09> = 60;
<AB10> = 61;
<RTSH> = 62;
<KPMU> = 63;
<LALT> = 64;
<SPCE> = 65;
<CAPS> = 66;
<FK01> = 67;
<FK02> = 68;
<FK03> = 69;
<FK04> = 70;
<FK05> = 71;
<FK06> = 72;
<FK07> = 73;
<FK08> = 74;
<FK09> = 75;
<FK10> = 76;
<NMLK> = 77;
<SCLK> = 78;
<KP7> = 79;
<KP8> = 80;
<KP9> = 81;
<KPSU> = 82;
<KP4> = 83;
<KP5> = 84;
<KP6> = 85;
<KPAD> = 86;
<KP1> = 87;
<KP2> = 88;
<KP3> = 89;
<KP0> = 90;
<KPDL> = 91;
<LVL3> = 92;
<LSGT> = 94;
<FK11> = 95;
<FK12> = 96;
<AB11> = 97;
<KATA> = 98;
<HIRA> = 99;
<HENK> = 100;
<HKTG> = 101;
<MUHE> = 102;
<JPCM> = 103;
<KPEN> = 104;
<RCTL> = 105;
<KPDV> = 106;
<PRSC> = 107;
<RALT> = 108;
<LNFD> = 109;
<HOME> = 110;
<UP> = 111;
<PGUP> = 112;
<LEFT> = 113;
<RGHT> = 114;
<END> = 115;
<DOWN> = 116;
<PGDN> = 117;
<INS> = 118;
<DELE> = 119;
<I120> = 120;
<MUTE> = 121;
<VOL-> = 122;
<VOL+> = 123;
<POWR> = 124;
<KPEQ> = 125;
<I126> = 126;
<PAUS> = 127;
<I128> = 128;
<I129> = 129;
<HNGL> = 130;
<HJCV> = 131;
<AE13> = 132;
<LWIN> = 133;
<RWIN> = 134;
<COMP> = 135;
<STOP> = 136;
<AGAI> = 137;
<PROP> = 138;
<UNDO> = 139;
<FRNT> = 140;
<COPY> = 141;
<OPEN> = 142;
<PAST> = 143;
<FIND> = 144;
<CUT> = 145;
<HELP> = 146;
<I147> = 147;
<I148> = 148;
<I149> = 149;
<I150> = 150;
<I151> = 151;
<I152> = 152;
<I153> = 153;
<I154> = 154;
<I155> = 155;
<I156> = 156;
<I157> = 157;
<I158> = 158;
<I159> = 159;
<I160> = 160;
<I161> = 161;
<I162> = 162;
<I163> = 163;
<I164> = 164;
<I165> = 165;
<I166> = 166;
<I167> = 167;
<I168> = 168;
<I169> = 169;
<I170> = 170;
<I171> = 171;
<I172> = 172;
<I173> = 173;
<I174> = 174;
<I175> = 175;
<I176> = 176;
<I177> = 177;
<I178> = 178;
<I179> = 179;
<I180> = 180;
<I181> = 181;
<I182> = 182;
<I183> = 183;
<I184> = 184;
<I185> = 185;
<I186> = 186;
<I187> = 187;
<I188> = 188;
<I189> = 189;
<I190> = 190;
<FK13> = 191;
<FK14> = 192;
<FK15> = 193;
<FK16> = 194;
<FK17> = 195;
<FK18> = 196;
<FK19> = 197;
<FK20> = 198;
<FK21> = 199;
<FK22> = 200;
<FK23> = 201;
<FK24> = 202;
<MDSW> = 203;
<ALT> = 204;
<META> = 205;
<SUPR> = 206;
<HYPR> = 207;
<I208> = 208;
<I209> = 209;
<I210> = 210;
<I211> = 211;
<I212> = 212;
<I213> = 213;
<I214> = 214;
<I215> = 215;
<I216> = 216;
<I217> = 217;
<I218> = 218;
<I219> = 219;
<I220> = 220;
<I221> = 221;
<I222> = 222;
<I223> = 223;
<I224> = 224;
<I225> = 225;
<I226> = 226;
<I227> = 227;
<I228> = 228;
<I229> = 229;
<I230> = 230;
<I231> = 231;
<I232> = 232;
<I233> = 233;
<I234> = 234;
<I235> = 235;
<I236> = 236;
<I237> = 237;
<I238> = 238;
<I239> = 239;
<I240> = 240;
<I241> = 241;
<I242> = 242;
<I243> = 243;
<I244> = 244;
<I245> = 245;
<I246> = 246;
<I247> = 247;
<I248> = 248;
<I249> = 249;
<I250> = 250;
<I251> = 251;
<I252> = 252;
<I253> = 253;
indicator 1 = "Caps Lock";
indicator 2 = "Num Lock";
indicator 3 = "Scroll Lock";
indicator 4 = "Compose";
indicator 5 = "Kana";
indicator 6 = "Sleep";
indicator 7 = "Suspend";
indicator 8 = "Mute";
indicator 9 = "Misc";
indicator 10 = "Mail";
indicator 11 = "Charging";
virtual indicator 12 = "Shift Lock";
virtual indicator 13 = "Group 2";
virtual indicator 14 = "Mouse Keys";
alias <AC12> = <BKSL>;
alias <MENU> = <COMP>;
alias <HZTG> = <TLDE>;
alias <LMTA> = <LWIN>;
alias <RMTA> = <RWIN>;
alias <ALGR> = <RALT>;
alias <KPPT> = <I129>;
alias <LatQ> = <AD01>;
alias <LatW> = <AD02>;
alias <LatE> = <AD03>;
alias <LatR> = <AD04>;
alias <LatT> = <AD05>;
alias <LatY> = <AD06>;
alias <LatU> = <AD07>;
alias <LatI> = <AD08>;
alias <LatO> = <AD09>;
alias <LatP> = <AD10>;
alias <LatA> = <AC01>;
alias <LatS> = <AC02>;
alias <LatD> = <AC03>;
alias <LatF> = <AC04>;
alias <LatG> = <AC05>;
alias <LatH> = <AC06>;
alias <LatJ> = <AC07>;
alias <LatK> = <AC08>;
alias <LatL> = <AC09>;
alias <LatZ> = <AB01>;
alias <LatX> = <AB02>;
alias <LatC> = <AB03>;
alias <LatV> = <AB04>;
alias <LatB> = <AB05>;
alias <LatN> = <AB06>;
alias <LatM> = <AB07>;
};
xkb_types "complete" {
virtual_modifiers NumLock,Alt,LevelThree,LAlt,RAlt,RControl,LControl,ScrollLock,LevelFive,AltGr,Meta,Super,Hyper;
type "ONE_LEVEL" {
modifiers= none;
level_name[Level1]= "Any";
};
type "TWO_LEVEL" {
modifiers= Shift;
map[Shift]= Level2;
level_name[Level1]= "Base";
level_name[Level2]= "Shift";
};
type "ALPHABETIC" {
modifiers= Shift+Lock;
map[Shift]= Level2;
map[Lock]= Level2;
level_name[Level1]= "Base";
level_name[Level2]= "Caps";
};
type "KEYPAD" {
modifiers= Shift+NumLock;
map[Shift]= Level2;
map[NumLock]= Level2;
level_name[Level1]= "Base";
level_name[Level2]= "Number";
};
type "SHIFT+ALT" {
modifiers= Shift+Alt;
map[Shift+Alt]= Level2;
level_name[Level1]= "Base";
level_name[Level2]= "Shift+Alt";
};
type "PC_SUPER_LEVEL2" {
modifiers= Mod4;
map[Mod4]= Level2;
level_name[Level1]= "Base";
level_name[Level2]= "Super";
};
type "PC_CONTROL_LEVEL2" {
modifiers= Control;
map[Control]= Level2;
level_name[Level1]= "Base";
level_name[Level2]= "Control";
};
type "PC_LCONTROL_LEVEL2" {
modifiers= LControl;
map[LControl]= Level2;
level_name[Level1]= "Base";
level_name[Level2]= "LControl";
};
type "PC_RCONTROL_LEVEL2" {
modifiers= RControl;
map[RControl]= Level2;
level_name[Level1]= "Base";
level_name[Level2]= "RControl";
};
type "PC_ALT_LEVEL2" {
modifiers= Alt;
map[Alt]= Level2;
level_name[Level1]= "Base";
level_name[Level2]= "Alt";
};
type "PC_LALT_LEVEL2" {
modifiers= LAlt;
map[LAlt]= Level2;
level_name[Level1]= "Base";
level_name[Level2]= "LAlt";
};
type "PC_RALT_LEVEL2" {
modifiers= RAlt;
map[RAlt]= Level2;
level_name[Level1]= "Base";
level_name[Level2]= "RAlt";
};
type "CTRL+ALT" {
modifiers= Shift+Control+Alt+LevelThree;
map[Shift]= Level2;
preserve[Shift]= Shift;
map[LevelThree]= Level3;
map[Shift+LevelThree]= Level4;
preserve[Shift+LevelThree]= Shift;
map[Control+Alt]= Level5;
level_name[Level1]= "Base";
level_name[Level2]= "Shift";
level_name[Level3]= "Alt Base";
level_name[Level4]= "Shift Alt";
level_name[Level5]= "Ctrl+Alt";
};
type "LOCAL_EIGHT_LEVEL" {
modifiers= Shift+Lock+Control+LevelThree;
map[Shift+Lock]= Level1;
map[Shift]= Level2;
map[Lock]= Level2;
map[LevelThree]= Level3;
map[Shift+Lock+LevelThree]= Level3;
map[Shift+LevelThree]= Level4;
map[Lock+LevelThree]= Level4;
map[Control]= Level5;
map[Shift+Lock+Control]= Level5;
map[Shift+Control]= Level6;
map[Lock+Control]= Level6;
map[Control+LevelThree]= Level7;
map[Shift+Lock+Control+LevelThree]= Level7;
map[Shift+Control+LevelThree]= Level8;
map[Lock+Control+LevelThree]= Level8;
level_name[Level1]= "Base";
level_name[Level2]= "Shift";
level_name[Level3]= "Level3";
level_name[Level4]= "Shift Level3";
level_name[Level5]= "Ctrl";
level_name[Level6]= "Shift Ctrl";
level_name[Level7]= "Level3 Ctrl";
level_name[Level8]= "Shift Level3 Ctrl";
};
type "THREE_LEVEL" {
modifiers= Shift+LevelThree;
map[Shift]= Level2;
map[LevelThree]= Level3;
map[Shift+LevelThree]= Level3;
level_name[Level1]= "Base";
level_name[Level2]= "Shift";
level_name[Level3]= "Level3";
};
type "EIGHT_LEVEL" {
modifiers= Shift+LevelThree+LevelFive;
map[Shift]= Level2;
map[LevelThree]= Level3;
map[Shift+LevelThree]= Level4;
map[LevelFive]= Level5;
map[Shift+LevelFive]= Level6;
map[LevelThree+LevelFive]= Level7;
map[Shift+LevelThree+LevelFive]= Level8;
level_name[Level1]= "Base";
level_name[Level2]= "Shift";
level_name[Level3]= "Alt Base";
level_name[Level4]= "Shift Alt";
level_name[Level5]= "X";
level_name[Level6]= "X Shift";
level_name[Level7]= "X Alt Base";
level_name[Level8]= "X Shift Alt";
};
type "EIGHT_LEVEL_ALPHABETIC" {
modifiers= Shift+Lock+LevelThree+LevelFive;
map[Shift]= Level2;
map[Lock]= Level2;
map[LevelThree]= Level3;
map[Shift+LevelThree]= Level4;
map[Lock+LevelThree]= Level4;
map[Shift+Lock+LevelThree]= Level3;
map[LevelFive]= Level5;
map[Shift+LevelFive]= Level6;
map[Lock+LevelFive]= Level6;
map[LevelThree+LevelFive]= Level7;
map[Shift+LevelThree+LevelFive]= Level8;
map[Lock+LevelThree+LevelFive]= Level8;
map[Shift+Lock+LevelThree+LevelFive]= Level7;
level_name[Level1]= "Base";
level_name[Level2]= "Shift";
level_name[Level3]= "Alt Base";
level_name[Level4]= "Shift Alt";
level_name[Level5]= "X";
level_name[Level6]= "X Shift";
level_name[Level7]= "X Alt Base";
level_name[Level8]= "X Shift Alt";
};
type "EIGHT_LEVEL_SEMIALPHABETIC" {
modifiers= Shift+Lock+LevelThree+LevelFive;
map[Shift]= Level2;
map[Lock]= Level2;
map[LevelThree]= Level3;
map[Shift+LevelThree]= Level4;
map[Lock+LevelThree]= Level3;
preserve[Lock+LevelThree]= Lock;
map[Shift+Lock+LevelThree]= Level4;
preserve[Shift+Lock+LevelThree]= Lock;
map[LevelFive]= Level5;
map[Shift+LevelFive]= Level6;
map[Lock+LevelFive]= Level6;
preserve[Lock+LevelFive]= Lock;
map[Shift+Lock+LevelFive]= Level6;
preserve[Shift+Lock+LevelFive]= Lock;
map[LevelThree+LevelFive]= Level7;
map[Shift+LevelThree+LevelFive]= Level8;
map[Lock+LevelThree+LevelFive]= Level7;
preserve[Lock+LevelThree+LevelFive]= Lock;
map[Shift+Lock+LevelThree+LevelFive]= Level8;
preserve[Shift+Lock+LevelThree+LevelFive]= Lock;
level_name[Level1]= "Base";
level_name[Level2]= "Shift";
level_name[Level3]= "Alt Base";
level_name[Level4]= "Shift Alt";
level_name[Level5]= "X";
level_name[Level6]= "X Shift";
level_name[Level7]= "X Alt Base";
level_name[Level8]= "X Shift Alt";
};
type "FOUR_LEVEL" {
modifiers= Shift+LevelThree;
map[Shift]= Level2;
map[LevelThree]= Level3;
map[Shift+LevelThree]= Level4;
level_name[Level1]= "Base";
level_name[Level2]= "Shift";
level_name[Level3]= "Alt Base";
level_name[Level4]= "Shift Alt";
};
type "FOUR_LEVEL_ALPHABETIC" {
modifiers= Shift+Lock+LevelThree;
map[Shift]= Level2;
map[Lock]= Level2;
map[LevelThree]= Level3;
map[Shift+LevelThree]= Level4;
map[Lock+LevelThree]= Level4;
map[Shift+Lock+LevelThree]= Level3;
level_name[Level1]= "Base";
level_name[Level2]= "Shift";
level_name[Level3]= "Alt Base";
level_name[Level4]= "Shift Alt";
};
type "FOUR_LEVEL_SEMIALPHABETIC" {
modifiers= Shift+Lock+LevelThree;
map[Shift]= Level2;
map[Lock]= Level2;
map[LevelThree]= Level3;
map[Shift+LevelThree]= Level4;
map[Lock+LevelThree]= Level3;
preserve[Lock+LevelThree]= Lock;
map[Shift+Lock+LevelThree]= Level4;
preserve[Shift+Lock+LevelThree]= Lock;
level_name[Level1]= "Base";
level_name[Level2]= "Shift";
level_name[Level3]= "Alt Base";
level_name[Level4]= "Shift Alt";
};
type "FOUR_LEVEL_MIXED_KEYPAD" {
modifiers= Shift+NumLock+LevelThree;
map[Shift+NumLock]= Level1;
map[NumLock]= Level2;
map[Shift]= Level2;
map[LevelThree]= Level3;
map[NumLock+LevelThree]= Level3;
map[Shift+LevelThree]= Level4;
map[Shift+NumLock+LevelThree]= Level4;
level_name[Level1]= "Base";
level_name[Level2]= "Number";
level_name[Level3]= "Alt Base";
level_name[Level4]= "Shift Alt";
};
type "FOUR_LEVEL_X" {
modifiers= Shift+Control+Alt+LevelThree;
map[LevelThree]= Level2;
map[Shift+LevelThree]= Level3;
map[Control+Alt]= Level4;
level_name[Level1]= "Base";
level_name[Level2]= "Alt Base";
level_name[Level3]= "Shift Alt";
level_name[Level4]= "Ctrl+Alt";
};
type "SEPARATE_CAPS_AND_SHIFT_ALPHABETIC" {
modifiers= Shift+Lock+LevelThree;
map[Shift]= Level2;
map[Lock]= Level4;
preserve[Lock]= Lock;
map[LevelThree]= Level3;
map[Shift+LevelThree]= Level4;
map[Lock+LevelThree]= Level3;
preserve[Lock+LevelThree]= Lock;
map[Shift+Lock+LevelThree]= Level3;
level_name[Level1]= "Base";
level_name[Level2]= "Shift";
level_name[Level3]= "AltGr Base";
level_name[Level4]= "Shift AltGr";
};
type "FOUR_LEVEL_PLUS_LOCK" {
modifiers= Shift+Lock+LevelThree;
map[Shift]= Level2;
map[LevelThree]= Level3;
map[Shift+LevelThree]= Level4;
map[Lock]= Level5;
map[Shift+Lock]= Level2;
map[Lock+LevelThree]= Level3;
map[Shift+Lock+LevelThree]= Level4;
level_name[Level1]= "Base";
level_name[Level2]= "Shift";
level_name[Level3]= "Alt Base";
level_name[Level4]= "Shift Alt";
level_name[Level5]= "Lock";
};
type "FOUR_LEVEL_KEYPAD" {
modifiers= Shift+NumLock+LevelThree;
map[Shift]= Level2;
map[NumLock]= Level2;
map[LevelThree]= Level3;
map[Shift+LevelThree]= Level4;
map[NumLock+LevelThree]= Level4;
map[Shift+NumLock+LevelThree]= Level3;
level_name[Level1]= "Base";
level_name[Level2]= "Number";
level_name[Level3]= "Alt Base";
level_name[Level4]= "Alt Number";
};
};
xkb_compatibility "complete" {
virtual_modifiers NumLock,Alt,LevelThree,LAlt,RAlt,RControl,LControl,ScrollLock,LevelFive,AltGr,Meta,Super,Hyper;
interpret.useModMapMods= AnyLevel;
interpret.repeat= False;
interpret.locking= False;
interpret ISO_Level2_Latch+Exactly(Shift) {
useModMapMods=level1;
action= LatchMods(modifiers=Shift,clearLocks,latchToLock);
};
interpret Shift_Lock+AnyOf(Shift+Lock) {
action= LockMods(modifiers=Shift);
};
interpret Num_Lock+AnyOf(all) {
virtualModifier= NumLock;
action= LockMods(modifiers=NumLock);
};
interpret ISO_Level3_Shift+AnyOf(all) {
virtualModifier= LevelThree;
useModMapMods=level1;
action= SetMods(modifiers=LevelThree,clearLocks);
};
interpret ISO_Level3_Latch+AnyOf(all) {
virtualModifier= LevelThree;
useModMapMods=level1;
action= LatchMods(modifiers=LevelThree,clearLocks,latchToLock);
};
interpret ISO_Level3_Lock+AnyOf(all) {
virtualModifier= LevelThree;
useModMapMods=level1;
action= LockMods(modifiers=LevelThree);
};
interpret Alt_L+AnyOf(all) {
virtualModifier= Alt;
action= SetMods(modifiers=modMapMods,clearLocks);
};
interpret Alt_R+AnyOf(all) {
virtualModifier= Alt;
action= SetMods(modifiers=modMapMods,clearLocks);
};
interpret Meta_L+AnyOf(all) {
virtualModifier= Meta;
action= SetMods(modifiers=modMapMods,clearLocks);
};
interpret Meta_R+AnyOf(all) {
virtualModifier= Meta;
action= SetMods(modifiers=modMapMods,clearLocks);
};
interpret Super_L+AnyOf(all) {
virtualModifier= Super;
action= SetMods(modifiers=modMapMods,clearLocks);
};
interpret Super_R+AnyOf(all) {
virtualModifier= Super;
action= SetMods(modifiers=modMapMods,clearLocks);
};
interpret Hyper_L+AnyOf(all) {
virtualModifier= Hyper;
action= SetMods(modifiers=modMapMods,clearLocks);
};
interpret Hyper_R+AnyOf(all) {
virtualModifier= Hyper;
action= SetMods(modifiers=modMapMods,clearLocks);
};
interpret Scroll_Lock+AnyOf(all) {
virtualModifier= ScrollLock;
action= LockMods(modifiers=modMapMods);
};
interpret ISO_Level5_Shift+AnyOf(all) {
virtualModifier= LevelFive;
useModMapMods=level1;
action= SetMods(modifiers=LevelFive,clearLocks);
};
interpret ISO_Level5_Latch+AnyOf(all) {
virtualModifier= LevelFive;
useModMapMods=level1;
action= LatchMods(modifiers=LevelFive,clearLocks,latchToLock);
};
interpret ISO_Level5_Lock+AnyOf(all) {
virtualModifier= LevelFive;
useModMapMods=level1;
action= LockMods(modifiers=LevelFive);
};
interpret Mode_switch+AnyOfOrNone(all) {
virtualModifier= AltGr;
useModMapMods=level1;
action= SetGroup(group=+1);
};
interpret ISO_Level3_Shift+AnyOfOrNone(all) {
action= SetMods(modifiers=LevelThree,clearLocks);
};
interpret ISO_Level3_Latch+AnyOfOrNone(all) {
action= LatchMods(modifiers=LevelThree,clearLocks,latchToLock);
};
interpret ISO_Level3_Lock+AnyOfOrNone(all) {
action= LockMods(modifiers=LevelThree);
};
interpret ISO_Group_Latch+AnyOfOrNone(all) {
virtualModifier= AltGr;
useModMapMods=level1;
action= LatchGroup(group=2);
};
interpret ISO_Next_Group+AnyOfOrNone(all) {
virtualModifier= AltGr;
useModMapMods=level1;
action= LockGroup(group=+1);
};
interpret ISO_Prev_Group+AnyOfOrNone(all) {
virtualModifier= AltGr;
useModMapMods=level1;
action= LockGroup(group=-1);
};
interpret ISO_First_Group+AnyOfOrNone(all) {
action= LockGroup(group=1);
};
interpret ISO_Last_Group+AnyOfOrNone(all) {
action= LockGroup(group=2);
};
interpret KP_1+AnyOfOrNone(all) {
repeat= True;
action= MovePtr(x=-1,y=+1);
};
interpret KP_End+AnyOfOrNone(all) {
repeat= True;
action= MovePtr(x=-1,y=+1);
};
interpret KP_2+AnyOfOrNone(all) {
repeat= True;
action= MovePtr(x=+0,y=+1);
};
interpret KP_Down+AnyOfOrNone(all) {
repeat= True;
action= MovePtr(x=+0,y=+1);
};
interpret KP_3+AnyOfOrNone(all) {
repeat= True;
action= MovePtr(x=+1,y=+1);
};
interpret KP_Next+AnyOfOrNone(all) {
repeat= True;
action= MovePtr(x=+1,y=+1);
};
interpret KP_4+AnyOfOrNone(all) {
repeat= True;
action= MovePtr(x=-1,y=+0);
};
interpret KP_Left+AnyOfOrNone(all) {
repeat= True;
action= MovePtr(x=-1,y=+0);
};
interpret KP_6+AnyOfOrNone(all) {
repeat= True;
action= MovePtr(x=+1,y=+0);
};
interpret KP_Right+AnyOfOrNone(all) {
repeat= True;
action= MovePtr(x=+1,y=+0);
};
interpret KP_7+AnyOfOrNone(all) {
repeat= True;
action= MovePtr(x=-1,y=-1);
};
interpret KP_Home+AnyOfOrNone(all) {
repeat= True;
action= MovePtr(x=-1,y=-1);
};
interpret KP_8+AnyOfOrNone(all) {
repeat= True;
action= MovePtr(x=+0,y=-1);
};
interpret KP_Up+AnyOfOrNone(all) {
repeat= True;
action= MovePtr(x=+0,y=-1);
};
interpret KP_9+AnyOfOrNone(all) {
repeat= True;
action= MovePtr(x=+1,y=-1);
};
interpret KP_Prior+AnyOfOrNone(all) {
repeat= True;
action= MovePtr(x=+1,y=-1);
};
interpret KP_5+AnyOfOrNone(all) {
repeat= True;
action= PtrBtn(button=default);
};
interpret KP_Begin+AnyOfOrNone(all) {
repeat= True;
action= PtrBtn(button=default);
};
interpret KP_F2+AnyOfOrNone(all) {
repeat= True;
action= SetPtrDflt(affect=button,button=1);
};
interpret KP_Divide+AnyOfOrNone(all) {
repeat= True;
action= SetPtrDflt(affect=button,button=1);
};
interpret KP_F3+AnyOfOrNone(all) {
repeat= True;
action= SetPtrDflt(affect=button,button=2);
};
interpret KP_Multiply+AnyOfOrNone(all) {
repeat= True;
action= SetPtrDflt(affect=button,button=2);
};
interpret KP_F4+AnyOfOrNone(all) {
repeat= True;
action= SetPtrDflt(affect=button,button=3);
};
interpret KP_Subtract+AnyOfOrNone(all) {
repeat= True;
action= SetPtrDflt(affect=button,button=3);
};
interpret KP_Separator+AnyOfOrNone(all) {
repeat= True;
action= PtrBtn(button=default,count=2);
};
interpret KP_Add+AnyOfOrNone(all) {
repeat= True;
action= PtrBtn(button=default,count=2);
};
interpret KP_0+AnyOfOrNone(all) {
repeat= True;
action= LockPtrBtn(button=default,affect=lock);
};
interpret KP_Insert+AnyOfOrNone(all) {
repeat= True;
action= LockPtrBtn(button=default,affect=lock);
};
interpret KP_Decimal+AnyOfOrNone(all) {
repeat= True;
action= LockPtrBtn(button=default,affect=unlock);
};
interpret KP_Delete+AnyOfOrNone(all) {
repeat= True;
action= LockPtrBtn(button=default,affect=unlock);
};
interpret F25+AnyOfOrNone(all) {
repeat= True;
action= SetPtrDflt(affect=button,button=1);
};
interpret F26+AnyOfOrNone(all) {
repeat= True;
action= SetPtrDflt(affect=button,button=2);
};
interpret F27+AnyOfOrNone(all) {
repeat= True;
action= MovePtr(x=-1,y=-1);
};
interpret F29+AnyOfOrNone(all) {
repeat= True;
action= MovePtr(x=+1,y=-1);
};
interpret F31+AnyOfOrNone(all) {
repeat= True;
action= PtrBtn(button=default);
};
interpret F33+AnyOfOrNone(all) {
repeat= True;
action= MovePtr(x=-1,y=+1);
};
interpret F35+AnyOfOrNone(all) {
repeat= True;
action= MovePtr(x=+1,y=+1);
};
interpret Pointer_Button_Dflt+AnyOfOrNone(all) {
action= PtrBtn(button=default);
};
interpret Pointer_Button1+AnyOfOrNone(all) {
action= PtrBtn(button=1);
};
interpret Pointer_Button2+AnyOfOrNone(all) {
action= PtrBtn(button=2);
};
interpret Pointer_Button3+AnyOfOrNone(all) {
action= PtrBtn(button=3);
};
interpret Pointer_DblClick_Dflt+AnyOfOrNone(all) {
action= PtrBtn(button=default,count=2);
};
interpret Pointer_DblClick1+AnyOfOrNone(all) {
action= PtrBtn(button=1,count=2);
};
interpret Pointer_DblClick2+AnyOfOrNone(all) {
action= PtrBtn(button=2,count=2);
};
interpret Pointer_DblClick3+AnyOfOrNone(all) {
action= PtrBtn(button=3,count=2);
};
interpret Pointer_Drag_Dflt+AnyOfOrNone(all) {
action= LockPtrBtn(button=default,affect=both);
};
interpret Pointer_Drag1+AnyOfOrNone(all) {
action= LockPtrBtn(button=1,affect=both);
};
interpret Pointer_Drag2+AnyOfOrNone(all) {
action= LockPtrBtn(button=2,affect=both);
};
interpret Pointer_Drag3+AnyOfOrNone(all) {
action= LockPtrBtn(button=3,affect=both);
};
interpret Pointer_EnableKeys+AnyOfOrNone(all) {
action= LockControls(controls=MouseKeys);
};
interpret Pointer_Accelerate+AnyOfOrNone(all) {
action= LockControls(controls=MouseKeysAccel);
};
interpret Pointer_DfltBtnNext+AnyOfOrNone(all) {
action= SetPtrDflt(affect=button,button=+1);
};
interpret Pointer_DfltBtnPrev+AnyOfOrNone(all) {
action= SetPtrDflt(affect=button,button=-1);
};
interpret AccessX_Enable+AnyOfOrNone(all) {
action= LockControls(controls=AccessXKeys);
};
interpret AccessX_Feedback_Enable+AnyOfOrNone(all) {
action= LockControls(controls=AccessXFeedback);
};
interpret RepeatKeys_Enable+AnyOfOrNone(all) {
action= LockControls(controls=RepeatKeys);
};
interpret SlowKeys_Enable+AnyOfOrNone(all) {
action= LockControls(controls=SlowKeys);
};
interpret BounceKeys_Enable+AnyOfOrNone(all) {
action= LockControls(controls=BounceKeys);
};
interpret StickyKeys_Enable+AnyOfOrNone(all) {
action= LockControls(controls=StickyKeys);
};
interpret MouseKeys_Enable+AnyOfOrNone(all) {
action= LockControls(controls=MouseKeys);
};
interpret MouseKeys_Accel_Enable+AnyOfOrNone(all) {
action= LockControls(controls=MouseKeysAccel);
};
interpret Overlay1_Enable+AnyOfOrNone(all) {
action= LockControls(controls=Overlay1);
};
interpret Overlay2_Enable+AnyOfOrNone(all) {
action= LockControls(controls=Overlay2);
};
interpret AudibleBell_Enable+AnyOfOrNone(all) {
action= LockControls(controls=AudibleBell);
};
interpret Terminate_Server+AnyOfOrNone(all) {
action= Terminate();
};
interpret Alt_L+AnyOfOrNone(all) {
action= SetMods(modifiers=Alt,clearLocks);
};
interpret Alt_R+AnyOfOrNone(all) {
action= SetMods(modifiers=Alt,clearLocks);
};
interpret Meta_L+AnyOfOrNone(all) {
action= SetMods(modifiers=Meta,clearLocks);
};
interpret Meta_R+AnyOfOrNone(all) {
action= SetMods(modifiers=Meta,clearLocks);
};
interpret Super_L+AnyOfOrNone(all) {
action= SetMods(modifiers=Super,clearLocks);
};
interpret Super_R+AnyOfOrNone(all) {
action= SetMods(modifiers=Super,clearLocks);
};
interpret Hyper_L+AnyOfOrNone(all) {
action= SetMods(modifiers=Hyper,clearLocks);
};
interpret Hyper_R+AnyOfOrNone(all) {
action= SetMods(modifiers=Hyper,clearLocks);
};
interpret Shift_L+AnyOfOrNone(all) {
action= SetMods(modifiers=Shift,clearLocks);
};
interpret XF86Switch_VT_1+AnyOfOrNone(all) {
repeat= True;
action= SwitchScreen(screen=1,!same);
};
interpret XF86Switch_VT_2+AnyOfOrNone(all) {
repeat= True;
action= SwitchScreen(screen=2,!same);
};
interpret XF86Switch_VT_3+AnyOfOrNone(all) {
repeat= True;
action= SwitchScreen(screen=3,!same);
};
interpret XF86Switch_VT_4+AnyOfOrNone(all) {
repeat= True;
action= SwitchScreen(screen=4,!same);
};
interpret XF86Switch_VT_5+AnyOfOrNone(all) {
repeat= True;
action= SwitchScreen(screen=5,!same);
};
interpret XF86Switch_VT_6+AnyOfOrNone(all) {
repeat= True;
action= SwitchScreen(screen=6,!same);
};
interpret XF86Switch_VT_7+AnyOfOrNone(all) {
repeat= True;
action= SwitchScreen(screen=7,!same);
};
interpret XF86Switch_VT_8+AnyOfOrNone(all) {
repeat= True;
action= SwitchScreen(screen=8,!same);
};
interpret XF86Switch_VT_9+AnyOfOrNone(all) {
repeat= True;
action= SwitchScreen(screen=9,!same);
};
interpret XF86Switch_VT_10+AnyOfOrNone(all) {
repeat= True;
action= SwitchScreen(screen=10,!same);
};
interpret XF86Switch_VT_11+AnyOfOrNone(all) {
repeat= True;
action= SwitchScreen(screen=11,!same);
};
interpret XF86Switch_VT_12+AnyOfOrNone(all) {
repeat= True;
action= SwitchScreen(screen=12,!same);
};
interpret XF86LogGrabInfo+AnyOfOrNone(all) {
repeat= True;
action= Private(type=0x86,data[0]=0x50,data[1]=0x72,data[2]=0x47,data[3]=0x72,data[4]=0x62,data[5]=0x73,data[6]=0x00);
};
interpret XF86LogWindowTree+AnyOfOrNone(all) {
repeat= True;
action= Private(type=0x86,data[0]=0x50,data[1]=0x72,data[2]=0x57,data[3]=0x69,data[4]=0x6e,data[5]=0x73,data[6]=0x00);
};
interpret XF86Next_VMode+AnyOfOrNone(all) {
repeat= True;
action= Private(type=0x86,data[0]=0x2b,data[1]=0x56,data[2]=0x4d,data[3]=0x6f,data[4]=0x64,data[5]=0x65,data[6]=0x00);
};
interpret XF86Prev_VMode+AnyOfOrNone(all) {
repeat= True;
action= Private(type=0x86,data[0]=0x2d,data[1]=0x56,data[2]=0x4d,data[3]=0x6f,data[4]=0x64,data[5]=0x65,data[6]=0x00);
};
interpret ISO_Level5_Shift+AnyOfOrNone(all) {
action= SetMods(modifiers=LevelFive,clearLocks);
};
interpret ISO_Level5_Latch+AnyOfOrNone(all) {
action= LatchMods(modifiers=LevelFive,clearLocks,latchToLock);
};
interpret ISO_Level5_Lock+AnyOfOrNone(all) {
action= LockMods(modifiers=LevelFive);
};
interpret Caps_Lock+AnyOfOrNone(all) {
action= LockMods(modifiers=Lock);
};
interpret Any+Exactly(Lock) {
action= LockMods(modifiers=Lock);
};
interpret Any+AnyOf(all) {
action= SetMods(modifiers=modMapMods,clearLocks);
};
group 2 = AltGr;
group 3 = AltGr;
group 4 = AltGr;
indicator "Caps Lock" {
!allowExplicit;
whichModState= locked;
modifiers= Lock;
};
indicator "Num Lock" {
!allowExplicit;
whichModState= locked;
modifiers= NumLock;
};
indicator "Scroll Lock" {
whichModState= locked;
modifiers= ScrollLock;
};
indicator "Shift Lock" {
!allowExplicit;
whichModState= locked;
modifiers= Shift;
};
indicator "Group 2" {
!allowExplicit;
groups= 0xfe;
};
indicator "Mouse Keys" {
indicatorDrivesKeyboard;
controls= mouseKeys;
};
};
xkb_symbols "pc+gb+us:2+inet(evdev)+compose(ralt)" {
name[group1]="English (UK)";
name[group2]="English (US)";
key <ESC> { [ Escape ] };
key <AE01> {
type[group1]= "FOUR_LEVEL",
symbols[Group1]= [ 1, exclam, onesuperior, exclamdown ],
symbols[Group2]= [ 1, exclam ]
};
key <AE02> {
type[group1]= "FOUR_LEVEL",
symbols[Group1]= [ 2, quotedbl, twosuperior, oneeighth ],
symbols[Group2]= [ 2, at ]
};
key <AE03> {
type[group1]= "FOUR_LEVEL",
symbols[Group1]= [ 3, sterling, threesuperior, sterling ],
symbols[Group2]= [ 3, numbersign ]
};
key <AE04> {
type[group1]= "FOUR_LEVEL",
symbols[Group1]= [ 4, dollar, EuroSign, onequarter ],
symbols[Group2]= [ 4, dollar ]
};
key <AE05> {
type[group1]= "FOUR_LEVEL",
symbols[Group1]= [ 5, percent, onehalf, threeeighths ],
symbols[Group2]= [ 5, percent ]
};
key <AE06> {
type[group1]= "FOUR_LEVEL",
symbols[Group1]= [ 6, asciicircum, threequarters, fiveeighths ],
symbols[Group2]= [ 6, asciicircum ]
};
key <AE07> {
type[group1]= "FOUR_LEVEL",
symbols[Group1]= [ 7, ampersand, braceleft, seveneighths ],
symbols[Group2]= [ 7, ampersand ]
};
key <AE08> {
type[group1]= "FOUR_LEVEL",
symbols[Group1]= [ 8, asterisk, bracketleft, trademark ],
symbols[Group2]= [ 8, asterisk ]
};
key <AE09> {
type[group1]= "FOUR_LEVEL",
symbols[Group1]= [ 9, parenleft, bracketright, plusminus ],
symbols[Group2]= [ 9, parenleft ]
};
key <AE10> {
type[group1]= "FOUR_LEVEL",
symbols[Group1]= [ 0, parenright, braceright, degree ],
symbols[Group2]= [ 0, parenright ]
};
key <AE11> {
type[group1]= "FOUR_LEVEL",
symbols[Group1]= [ minus, underscore, backslash, questiondown ],
symbols[Group2]= [ minus, underscore ]
};
key <AE12> {
type[group1]= "FOUR_LEVEL",
symbols[Group1]= [ equal, plus, dead_cedilla, dead_ogonek ],
symbols[Group2]= [ equal, plus ]
};
key <BKSP> { [ BackSpace, BackSpace ] };
key <TAB> { [ Tab, ISO_Left_Tab ] };
key <AD01> {
type[group1]= "FOUR_LEVEL_SEMIALPHABETIC",
type[group2]= "ALPHABETIC",
symbols[Group1]= [ q, Q, at, Greek_OMEGA ],
symbols[Group2]= [ q, Q ]
};
key <AD02> {
type[group1]= "FOUR_LEVEL_ALPHABETIC",
type[group2]= "ALPHABETIC",
symbols[Group1]= [ w, W, lstroke, Lstroke ],
symbols[Group2]= [ w, W ]
};
key <AD03> {
type[group1]= "FOUR_LEVEL_ALPHABETIC",
type[group2]= "ALPHABETIC",
symbols[Group1]= [ e, E, e, E ],
symbols[Group2]= [ e, E ]
};
key <AD04> {
type[group1]= "FOUR_LEVEL_SEMIALPHABETIC",
type[group2]= "ALPHABETIC",
symbols[Group1]= [ r, R, paragraph, registered ],
symbols[Group2]= [ r, R ]
};
key <AD05> {
type[group1]= "FOUR_LEVEL_ALPHABETIC",
type[group2]= "ALPHABETIC",
symbols[Group1]= [ t, T, tslash, Tslash ],
symbols[Group2]= [ t, T ]
};
key <AD06> {
type[group1]= "FOUR_LEVEL_SEMIALPHABETIC",
type[group2]= "ALPHABETIC",
symbols[Group1]= [ y, Y, leftarrow, yen ],
symbols[Group2]= [ y, Y ]
};
key <AD07> {
type[group1]= "FOUR_LEVEL_SEMIALPHABETIC",
type[group2]= "ALPHABETIC",
symbols[Group1]= [ u, U, downarrow, uparrow ],
symbols[Group2]= [ u, U ]
};
key <AD08> {
type[group1]= "FOUR_LEVEL_SEMIALPHABETIC",
type[group2]= "ALPHABETIC",
symbols[Group1]= [ i, I, rightarrow, idotless ],
symbols[Group2]= [ i, I ]
};
key <AD09> {
type[group1]= "FOUR_LEVEL_ALPHABETIC",
type[group2]= "ALPHABETIC",
symbols[Group1]= [ o, O, oslash, Oslash ],
symbols[Group2]= [ o, O ]
};
key <AD10> {
type[group1]= "FOUR_LEVEL_ALPHABETIC",
type[group2]= "ALPHABETIC",
symbols[Group1]= [ p, P, thorn, THORN ],
symbols[Group2]= [ p, P ]
};
key <AD11> {
type[group1]= "FOUR_LEVEL",
symbols[Group1]= [ bracketleft, braceleft, dead_diaeresis, dead_abovering ],
symbols[Group2]= [ bracketleft, braceleft ]
};
key <AD12> {
type[group1]= "FOUR_LEVEL",
symbols[Group1]= [ bracketright, braceright, dead_tilde, dead_macron ],
symbols[Group2]= [ bracketright, braceright ]
};
key <RTRN> { [ Return ] };
key <LCTL> { [ Control_L ] };
key <AC01> {
type[group1]= "FOUR_LEVEL_ALPHABETIC",
type[group2]= "ALPHABETIC",
symbols[Group1]= [ a, A, ae, AE ],
symbols[Group2]= [ a, A ]
};
key <AC02> {
type[group1]= "FOUR_LEVEL_SEMIALPHABETIC",
type[group2]= "ALPHABETIC",
symbols[Group1]= [ s, S, ssharp, section ],
symbols[Group2]= [ s, S ]
};
key <AC03> {
type[group1]= "FOUR_LEVEL_ALPHABETIC",
type[group2]= "ALPHABETIC",
symbols[Group1]= [ d, D, eth, ETH ],
symbols[Group2]= [ d, D ]
};
key <AC04> {
type[group1]= "FOUR_LEVEL_SEMIALPHABETIC",
type[group2]= "ALPHABETIC",
symbols[Group1]= [ f, F, dstroke, ordfeminine ],
symbols[Group2]= [ f, F ]
};
key <AC05> {
type[group1]= "FOUR_LEVEL_ALPHABETIC",
type[group2]= "ALPHABETIC",
symbols[Group1]= [ g, G, eng, ENG ],
symbols[Group2]= [ g, G ]
};
key <AC06> {
type[group1]= "FOUR_LEVEL_ALPHABETIC",
type[group2]= "ALPHABETIC",
symbols[Group1]= [ h, H, hstroke, Hstroke ],
symbols[Group2]= [ h, H ]
};
key <AC07> {
type[group1]= "FOUR_LEVEL_SEMIALPHABETIC",
type[group2]= "ALPHABETIC",
symbols[Group1]= [ j, J, dead_hook, dead_horn ],
symbols[Group2]= [ j, J ]
};
key <AC08> {
type[group1]= "FOUR_LEVEL_SEMIALPHABETIC",
type[group2]= "ALPHABETIC",
symbols[Group1]= [ k, K, kra, ampersand ],
symbols[Group2]= [ k, K ]
};
key <AC09> {
type[group1]= "FOUR_LEVEL_ALPHABETIC",
type[group2]= "ALPHABETIC",
symbols[Group1]= [ l, L, lstroke, Lstroke ],
symbols[Group2]= [ l, L ]
};
key <AC10> {
type[group1]= "FOUR_LEVEL",
symbols[Group1]= [ semicolon, colon, dead_acute, dead_doubleacute ],
symbols[Group2]= [ semicolon, colon ]
};
key <AC11> {
type[group1]= "FOUR_LEVEL",
symbols[Group1]= [ apostrophe, at, dead_circumflex, dead_caron ],
symbols[Group2]= [ apostrophe, quotedbl ]
};
key <TLDE> {
type[group1]= "FOUR_LEVEL",
symbols[Group1]= [ grave, notsign, bar, bar ],
symbols[Group2]= [ grave, asciitilde ]
};
key <LFSH> { [ Shift_L ] };
key <BKSL> {
type[group1]= "FOUR_LEVEL",
symbols[Group1]= [ numbersign, asciitilde, dead_grave, dead_breve ],
symbols[Group2]= [ backslash, bar ]
};
key <AB01> {
type[group1]= "FOUR_LEVEL_SEMIALPHABETIC",
type[group2]= "ALPHABETIC",
symbols[Group1]= [ z, Z, guillemotleft, less ],
symbols[Group2]= [ z, Z ]
};
key <AB02> {
type[group1]= "FOUR_LEVEL_SEMIALPHABETIC",
type[group2]= "ALPHABETIC",
symbols[Group1]= [ x, X, guillemotright, greater ],
symbols[Group2]= [ x, X ]
};
key <AB03> {
type[group1]= "FOUR_LEVEL_SEMIALPHABETIC",
type[group2]= "ALPHABETIC",
symbols[Group1]= [ c, C, cent, copyright ],
symbols[Group2]= [ c, C ]
};
key <AB04> {
type[group1]= "FOUR_LEVEL_SEMIALPHABETIC",
type[group2]= "ALPHABETIC",
symbols[Group1]= [ v, V, leftdoublequotemark, leftsinglequotemark ],
symbols[Group2]= [ v, V ]
};
key <AB05> {
type[group1]= "FOUR_LEVEL_SEMIALPHABETIC",
type[group2]= "ALPHABETIC",
symbols[Group1]= [ b, B, rightdoublequotemark, rightsinglequotemark ],
symbols[Group2]= [ b, B ]
};
key <AB06> {
type[group1]= "FOUR_LEVEL_ALPHABETIC",
type[group2]= "ALPHABETIC",
symbols[Group1]= [ n, N, n, N ],
symbols[Group2]= [ n, N ]
};
key <AB07> {
type[group1]= "FOUR_LEVEL_SEMIALPHABETIC",
type[group2]= "ALPHABETIC",
symbols[Group1]= [ m, M, mu, masculine ],
symbols[Group2]= [ m, M ]
};
key <AB08> {
type[group1]= "FOUR_LEVEL",
symbols[Group1]= [ comma, less, horizconnector, multiply ],
symbols[Group2]= [ comma, less ]
};
key <AB09> {
type[group1]= "FOUR_LEVEL",
symbols[Group1]= [ period, greater, periodcentered, division ],
symbols[Group2]= [ period, greater ]
};
key <AB10> {
type[group1]= "FOUR_LEVEL",
symbols[Group1]= [ slash, question, dead_belowdot, dead_abovedot ],
symbols[Group2]= [ slash, question ]
};
key <RTSH> { [ Shift_R ] };
key <KPMU> {
type= "CTRL+ALT",
symbols[Group1]= [ KP_Multiply, KP_Multiply, KP_Multiply, KP_Multiply, XF86ClearGrab ]
};
key <LALT> { [ Alt_L, Meta_L ] };
key <SPCE> { [ space ] };
key <CAPS> { [ Caps_Lock ] };
key <FK01> {
type= "CTRL+ALT",
symbols[Group1]= [ F1, F1, F1, F1, XF86Switch_VT_1 ]
};
key <FK02> {
type= "CTRL+ALT",
symbols[Group1]= [ F2, F2, F2, F2, XF86Switch_VT_2 ]
};
key <FK03> {
type= "CTRL+ALT",
symbols[Group1]= [ F3, F3, F3, F3, XF86Switch_VT_3 ]
};
key <FK04> {
type= "CTRL+ALT",
symbols[Group1]= [ F4, F4, F4, F4, XF86Switch_VT_4 ]
};
key <FK05> {
type= "CTRL+ALT",
symbols[Group1]= [ F5, F5, F5, F5, XF86Switch_VT_5 ]
};
key <FK06> {
type= "CTRL+ALT",
symbols[Group1]= [ F6, F6, F6, F6, XF86Switch_VT_6 ]
};
key <FK07> {
type= "CTRL+ALT",
symbols[Group1]= [ F7, F7, F7, F7, XF86Switch_VT_7 ]
};
key <FK08> {
type= "CTRL+ALT",
symbols[Group1]= [ F8, F8, F8, F8, XF86Switch_VT_8 ]
};
key <FK09> {
type= "CTRL+ALT",
symbols[Group1]= [ F9, F9, F9, F9, XF86Switch_VT_9 ]
};
key <FK10> {
type= "CTRL+ALT",
symbols[Group1]= [ F10, F10, F10, F10, XF86Switch_VT_10 ]
};
key <NMLK> { [ Num_Lock ] };
key <SCLK> { [ Scroll_Lock ] };
key <KP7> { [ KP_Home, KP_7 ] };
key <KP8> { [ KP_Up, KP_8 ] };
key <KP9> { [ KP_Prior, KP_9 ] };
key <KPSU> {
type= "CTRL+ALT",
symbols[Group1]= [ KP_Subtract, KP_Subtract, KP_Subtract, KP_Subtract, XF86Prev_VMode ]
};
key <KP4> { [ KP_Left, KP_4 ] };
key <KP5> { [ KP_Begin, KP_5 ] };
key <KP6> { [ KP_Right, KP_6 ] };
key <KPAD> {
type= "CTRL+ALT",
symbols[Group1]= [ KP_Add, KP_Add, KP_Add, KP_Add, XF86Next_VMode ]
};
key <KP1> { [ KP_End, KP_1 ] };
key <KP2> { [ KP_Down, KP_2 ] };
key <KP3> { [ KP_Next, KP_3 ] };
key <KP0> { [ KP_Insert, KP_0 ] };
key <KPDL> { [ KP_Delete, KP_Decimal ] };
key <LVL3> {
type= "ONE_LEVEL",
symbols[Group1]= [ ISO_Level3_Shift ]
};
key <LSGT> {
type= "FOUR_LEVEL",
symbols[Group1]= [ backslash, bar, bar, brokenbar ]
};
key <FK11> {
type= "CTRL+ALT",
symbols[Group1]= [ F11, F11, F11, F11, XF86Switch_VT_11 ]
};
key <FK12> {
type= "CTRL+ALT",
symbols[Group1]= [ F12, F12, F12, F12, XF86Switch_VT_12 ]
};
key <KATA> { [ Katakana ] };
key <HIRA> { [ Hiragana ] };
key <HENK> { [ Henkan_Mode ] };
key <HKTG> { [ Hiragana_Katakana ] };
key <MUHE> { [ Muhenkan ] };
key <KPEN> { [ KP_Enter ] };
key <RCTL> { [ Control_R ] };
key <KPDV> {
type= "CTRL+ALT",
symbols[Group1]= [ KP_Divide, KP_Divide, KP_Divide, KP_Divide, XF86Ungrab ]
};
key <PRSC> {
type= "PC_ALT_LEVEL2",
symbols[Group1]= [ Print, Sys_Req ]
};
key <RALT> {
type= "TWO_LEVEL",
symbols[Group1]= [ Multi_key, Multi_key ]
};
key <LNFD> { [ Linefeed ] };
key <HOME> { [ Home ] };
key <UP> { [ Up ] };
key <PGUP> { [ Prior ] };
key <LEFT> { [ Left ] };
key <RGHT> { [ Right ] };
key <END> { [ End ] };
key <DOWN> { [ Down ] };
key <PGDN> { [ Next ] };
key <INS> { [ Insert ] };
key <DELE> { [ Delete ] };
key <MUTE> { [ XF86AudioMute ] };
key <VOL-> { [ XF86AudioLowerVolume ] };
key <VOL+> { [ XF86AudioRaiseVolume ] };
key <POWR> { [ XF86PowerOff ] };
key <KPEQ> { [ KP_Equal ] };
key <I126> { [ plusminus ] };
key <PAUS> {
type= "PC_CONTROL_LEVEL2",
symbols[Group1]= [ Pause, Break ]
};
key <I128> { [ XF86LaunchA ] };
key <I129> { [ KP_Decimal, KP_Decimal ] };
key <HNGL> { [ Hangul ] };
key <HJCV> { [ Hangul_Hanja ] };
key <LWIN> { [ Super_L ] };
key <RWIN> { [ Super_R ] };
key <COMP> { [ Menu ] };
key <STOP> { [ Cancel ] };
key <AGAI> { [ Redo ] };
key <PROP> { [ SunProps ] };
key <UNDO> { [ Undo ] };
key <FRNT> { [ SunFront ] };
key <COPY> { [ XF86Copy ] };
key <OPEN> { [ XF86Open ] };
key <PAST> { [ XF86Paste ] };
key <FIND> { [ Find ] };
key <CUT> { [ XF86Cut ] };
key <HELP> { [ Help ] };
key <I147> { [ XF86MenuKB ] };
key <I148> { [ XF86Calculator ] };
key <I150> { [ XF86Sleep ] };
key <I151> { [ XF86WakeUp ] };
key <I152> { [ XF86Explorer ] };
key <I153> { [ XF86Send ] };
key <I155> { [ XF86Xfer ] };
key <I156> { [ XF86Launch1 ] };
key <I157> { [ XF86Launch2 ] };
key <I158> { [ XF86WWW ] };
key <I159> { [ XF86DOS ] };
key <I160> { [ XF86ScreenSaver ] };
key <I161> { [ XF86RotateWindows ] };
key <I162> { [ XF86TaskPane ] };
key <I163> { [ XF86Mail ] };
key <I164> { [ XF86Favorites ] };
key <I165> { [ XF86MyComputer ] };
key <I166> { [ XF86Back ] };
key <I167> { [ XF86Forward ] };
key <I169> { [ XF86Eject ] };
key <I170> { [ XF86Eject, XF86Eject ] };
key <I171> { [ XF86AudioNext ] };
key <I172> { [ XF86AudioPlay, XF86AudioPause ] };
key <I173> { [ XF86AudioPrev ] };
key <I174> { [ XF86AudioStop, XF86Eject ] };
key <I175> { [ XF86AudioRecord ] };
key <I176> { [ XF86AudioRewind ] };
key <I177> { [ XF86Phone ] };
key <I179> { [ XF86Tools ] };
key <I180> { [ XF86HomePage ] };
key <I181> { [ XF86Reload ] };
key <I182> { [ XF86Close ] };
key <I185> { [ XF86ScrollUp ] };
key <I186> { [ XF86ScrollDown ] };
key <I187> { [ parenleft ] };
key <I188> { [ parenright ] };
key <I189> { [ XF86New ] };
key <I190> { [ Redo ] };
key <FK13> { [ XF86Tools ] };
key <FK14> { [ XF86Launch5 ] };
key <FK15> { [ XF86Launch6 ] };
key <FK16> { [ XF86Launch7 ] };
key <FK17> { [ XF86Launch8 ] };
key <FK18> { [ XF86Launch9 ] };
key <FK20> { [ XF86AudioMicMute ] };
key <FK21> { [ XF86TouchpadToggle ] };
key <FK22> { [ XF86TouchpadOn ] };
key <FK23> { [ XF86TouchpadOff ] };
key <MDSW> { [ Mode_switch ] };
key <ALT> { [ NoSymbol, Alt_L ] };
key <META> { [ NoSymbol, Meta_L ] };
key <SUPR> { [ NoSymbol, Super_L ] };
key <HYPR> { [ NoSymbol, Hyper_L ] };
key <I208> { [ XF86AudioPlay ] };
key <I209> { [ XF86AudioPause ] };
key <I210> { [ XF86Launch3 ] };
key <I211> { [ XF86Launch4 ] };
key <I212> { [ XF86LaunchB ] };
key <I213> { [ XF86Suspend ] };
key <I214> { [ XF86Close ] };
key <I215> { [ XF86AudioPlay ] };
key <I216> { [ XF86AudioForward ] };
key <I218> { [ Print ] };
key <I220> { [ XF86WebCam ] };
key <I223> { [ XF86Mail ] };
key <I224> { [ XF86Messenger ] };
key <I225> { [ XF86Search ] };
key <I226> { [ XF86Go ] };
key <I227> { [ XF86Finance ] };
key <I228> { [ XF86Game ] };
key <I229> { [ XF86Shop ] };
key <I231> { [ Cancel ] };
key <I232> { [ XF86MonBrightnessDown ] };
key <I233> { [ XF86MonBrightnessUp ] };
key <I234> { [ XF86AudioMedia ] };
key <I235> { [ XF86Display ] };
key <I236> { [ XF86KbdLightOnOff ] };
key <I237> { [ XF86KbdBrightnessDown ] };
key <I238> { [ XF86KbdBrightnessUp ] };
key <I239> { [ XF86Send ] };
key <I240> { [ XF86Reply ] };
key <I241> { [ XF86MailForward ] };
key <I242> { [ XF86Save ] };
key <I243> { [ XF86Documents ] };
key <I244> { [ XF86Battery ] };
key <I245> { [ XF86Bluetooth ] };
key <I246> { [ XF86WLAN ] };
modifier_map Control { <LCTL> };
modifier_map Shift { <LFSH> };
modifier_map Shift { <RTSH> };
modifier_map Mod1 { <LALT> };
modifier_map Lock { <CAPS> };
modifier_map Mod2 { <NMLK> };
modifier_map Mod5 { <LVL3> };
modifier_map Control { <RCTL> };
modifier_map Mod4 { <LWIN> };
modifier_map Mod4 { <RWIN> };
modifier_map Mod5 { <MDSW> };
modifier_map Mod1 { <META> };
modifier_map Mod4 { <SUPR> };
modifier_map Mod4 { <HYPR> };
};
xkb_geometry "pc(pc105)" {
width= 470;
height= 180;
alias <AC00> = <CAPS>;
alias <AA00> = <LCTL>;
baseColor= "white";
labelColor= "black";
xfont= "-*-helvetica-medium-r-normal--*-120-*-*-*-*-iso8859-1";
description= "Generic 105";
shape "NORM" {
corner= 1,
{ [ 18, 18 ] },
{ [ 2, 1 ], [ 16, 16 ] }
};
shape "BKSP" {
corner= 1,
{ [ 38, 18 ] },
{ [ 2, 1 ], [ 36, 16 ] }
};
shape "TABK" {
corner= 1,
{ [ 28, 18 ] },
{ [ 2, 1 ], [ 26, 16 ] }
};
shape "BKSL" {
corner= 1,
{ [ 28, 18 ] },
{ [ 2, 1 ], [ 26, 16 ] }
};
shape "RTRN" {
corner= 1,
{ [ 0, 0 ], [ 28, 0 ], [ 28, 37 ], [ 5, 37 ],
[ 5, 18 ], [ 0, 18 ] },
{ [ 2, 1 ], [ 26, 1 ], [ 26, 35 ], [ 7, 35 ],
[ 7, 16 ], [ 2, 16 ] },
approx= { [ 5, 0 ], [ 28, 37 ] }
};
shape "CAPS" {
corner= 1,
{ [ 33, 18 ] },
{ [ 2, 1 ], [ 31, 16 ] }
};
shape "LFSH" {
corner= 1,
{ [ 25, 18 ] },
{ [ 2, 1 ], [ 23, 16 ] }
};
shape "RTSH" {
corner= 1,
{ [ 50, 18 ] },
{ [ 2, 1 ], [ 48, 16 ] }
};
shape "MODK" {
corner= 1,
{ [ 27, 18 ] },
{ [ 2, 1 ], [ 25, 16 ] }
};
shape "SMOD" {
corner= 1,
{ [ 23, 18 ] },
{ [ 2, 1 ], [ 21, 16 ] }
};
shape "SPCE" {
corner= 1,
{ [ 113, 18 ] },
{ [ 2, 1 ], [ 111, 16 ] }
};
shape "KP0" {
corner= 1,
{ [ 37, 18 ] },
{ [ 2, 1 ], [ 35, 16 ] }
};
shape "KPAD" {
corner= 1,
{ [ 18, 37 ] },
{ [ 2, 1 ], [ 16, 35 ] }
};
shape "LEDS" { { [ 75, 20 ] } };
shape "LED" { { [ 5, 1 ] } };
section "Function" {
key.color= "grey20";
priority= 7;
top= 22;
left= 19;
width= 351;
height= 19;
row {
top= 1;
left= 1;
keys {
{ <ESC>, "NORM", 1 },
{ <FK01>, "NORM", 20, color="white" },
{ <FK02>, "NORM", 1, color="white" },
{ <FK03>, "NORM", 1, color="white" },
{ <FK04>, "NORM", 1, color="white" },
{ <FK05>, "NORM", 11, color="white" },
{ <FK06>, "NORM", 1, color="white" },
{ <FK07>, "NORM", 1, color="white" },
{ <FK08>, "NORM", 1, color="white" },
{ <FK09>, "NORM", 11, color="white" },
{ <FK10>, "NORM", 1, color="white" },
{ <FK11>, "NORM", 1, color="white" },
{ <FK12>, "NORM", 1, color="white" },
{ <PRSC>, "NORM", 8, color="white" },
{ <SCLK>, "NORM", 1, color="white" },
{ <PAUS>, "NORM", 1, color="white" }
};
};
}; // End of "Function" section
section "Alpha" {
key.color= "white";
priority= 8;
top= 61;
left= 19;
width= 287;
height= 95;
row {
top= 1;
left= 1;
keys {
{ <TLDE>, "NORM", 1 }, { <AE01>, "NORM", 1 },
{ <AE02>, "NORM", 1 }, { <AE03>, "NORM", 1 },
{ <AE04>, "NORM", 1 }, { <AE05>, "NORM", 1 },
{ <AE06>, "NORM", 1 }, { <AE07>, "NORM", 1 },
{ <AE08>, "NORM", 1 }, { <AE09>, "NORM", 1 },
{ <AE10>, "NORM", 1 }, { <AE11>, "NORM", 1 },
{ <AE12>, "NORM", 1 },
{ <BKSP>, "BKSP", 1, color="grey20" }
};
};
row {
top= 20;
left= 1;
keys {
{ <TAB>, "TABK", 1, color="grey20" },
{ <AD01>, "NORM", 1 }, { <AD02>, "NORM", 1 },
{ <AD03>, "NORM", 1 }, { <AD04>, "NORM", 1 },
{ <AD05>, "NORM", 1 }, { <AD06>, "NORM", 1 },
{ <AD07>, "NORM", 1 }, { <AD08>, "NORM", 1 },
{ <AD09>, "NORM", 1 }, { <AD10>, "NORM", 1 },
{ <AD11>, "NORM", 1 }, { <AD12>, "NORM", 1 },
{ <RTRN>, "RTRN", 1, color="grey20" }
};
};
row {
top= 39;
left= 1;
keys {
{ <CAPS>, "CAPS", 1, color="grey20" },
{ <AC01>, "NORM", 1 }, { <AC02>, "NORM", 1 },
{ <AC03>, "NORM", 1 }, { <AC04>, "NORM", 1 },
{ <AC05>, "NORM", 1 }, { <AC06>, "NORM", 1 },
{ <AC07>, "NORM", 1 }, { <AC08>, "NORM", 1 },
{ <AC09>, "NORM", 1 }, { <AC10>, "NORM", 1 },
{ <AC11>, "NORM", 1 }, { <BKSL>, "NORM", 1 }
};
};
row {
top= 58;
left= 1;
keys {
{ <LFSH>, "LFSH", 1, color="grey20" },
{ <LSGT>, "NORM", 1 }, { <AB01>, "NORM", 1 },
{ <AB02>, "NORM", 1 }, { <AB03>, "NORM", 1 },
{ <AB04>, "NORM", 1 }, { <AB05>, "NORM", 1 },
{ <AB06>, "NORM", 1 }, { <AB07>, "NORM", 1 },
{ <AB08>, "NORM", 1 }, { <AB09>, "NORM", 1 },
{ <AB10>, "NORM", 1 },
{ <RTSH>, "RTSH", 1, color="grey20" }
};
};
row {
top= 77;
left= 1;
keys {
{ <LCTL>, "MODK", 1, color="grey20" },
{ <LWIN>, "SMOD", 1, color="grey20" },
{ <LALT>, "SMOD", 1, color="grey20" },
{ <SPCE>, "SPCE", 1 },
{ <RALT>, "SMOD", 1, color="grey20" },
{ <RWIN>, "SMOD", 1, color="grey20" },
{ <MENU>, "SMOD", 1, color="grey20" },
{ <RCTL>, "SMOD", 1, color="grey20" }
};
};
}; // End of "Alpha" section
section "Editing" {
key.color= "grey20";
priority= 9;
top= 61;
left= 312;
width= 58;
height= 95;
row {
top= 1;
left= 1;
keys {
{ <INS>, "NORM", 1 }, { <HOME>, "NORM", 1 },
{ <PGUP>, "NORM", 1 }
};
};
row {
top= 20;
left= 1;
keys {
{ <DELE>, "NORM", 1 }, { <END>, "NORM", 1 },
{ <PGDN>, "NORM", 1 }
};
};
row {
top= 58;
left= 20;
keys {
{ <UP>, "NORM", 1 }
};
};
row {
top= 77;
left= 1;
keys {
{ <LEFT>, "NORM", 1 }, { <DOWN>, "NORM", 1 },
{ <RGHT>, "NORM", 1 }
};
};
}; // End of "Editing" section
section "Keypad" {
key.color= "grey20";
priority= 10;
top= 61;
left= 376;
width= 77;
height= 95;
row {
top= 1;
left= 1;
keys {
{ <NMLK>, "NORM", 1 }, { <KPDV>, "NORM", 1 },
{ <KPMU>, "NORM", 1 }, { <KPSU>, "NORM", 1 }
};
};
row {
top= 20;
left= 1;
keys {
{ <KP7>, "NORM", 1, color="white" },
{ <KP8>, "NORM", 1, color="white" },
{ <KP9>, "NORM", 1, color="white" },
{ <KPAD>, "KPAD", 1 }
};
};
row {
top= 39;
left= 1;
keys {
{ <KP4>, "NORM", 1, color="white" },
{ <KP5>, "NORM", 1, color="white" },
{ <KP6>, "NORM", 1, color="white" }
};
};
row {
top= 58;
left= 1;
keys {
{ <KP1>, "NORM", 1, color="white" },
{ <KP2>, "NORM", 1, color="white" },
{ <KP3>, "NORM", 1, color="white" },
{ <KPEN>, "KPAD", 1 }
};
};
row {
top= 77;
left= 1;
keys {
{ <KP0>, "KP0", 1, color="white" },
{ <KPDL>, "NORM", 1, color="white" }
};
};
}; // End of "Keypad" section
solid "LedPanel" {
top= 22;
left= 377;
priority= 0;
color= "grey10";
shape= "LEDS";
};
indicator "Num Lock" {
top= 37;
left= 382;
priority= 1;
onColor= "green";
offColor= "green30";
shape= "LED";
};
indicator "Caps Lock" {
top= 37;
left= 407;
priority= 2;
onColor= "green";
offColor= "green30";
shape= "LED";
};
indicator "Scroll Lock" {
top= 37;
left= 433;
priority= 3;
onColor= "green";
offColor= "green30";
shape= "LED";
};
text "NumLockLabel" {
top= 25;
left= 378;
priority= 4;
width= 19.8;
height= 10;
XFont= "-*-helvetica-medium-r-normal--*-120-*-*-*-*-iso8859-1";
text= "Num\nLock";
};
text "CapsLockLabel" {
top= 25;
left= 403;
priority= 5;
width= 26.4;
height= 10;
XFont= "-*-helvetica-medium-r-normal--*-120-*-*-*-*-iso8859-1";
text= "Caps\nLock";
};
text "ScrollLockLabel" {
top= 25;
left= 428;
priority= 6;
width= 39.6;
height= 10;
XFont= "-*-helvetica-medium-r-normal--*-120-*-*-*-*-iso8859-1";
text= "Scroll\nLock";
};
};
};
"""
sample_keymap_bytes = sample_keymap_string.encode('ascii')
|
prenom = input("Votre prenom svp ")
langue = input("Votre langue: ") # Langue devait etre "francais" ou "anglais"
if langue == "francais":
print("Bonjour %s" % prenom)
elif langue == "anglais":
print("Hello %s" % prenom)
else:
print("ERREUR")
|
"""
Day 1 Solutions
"""
def part1(input_lines):
"""
The captcha requires you to review a sequence of digits (your puzzle input) and find
the sum of all digits that match the next digit in the list. The list is circular,
so the digit after the last digit is the first digit in the list.
For example:
- 1122 produces a sum of 3 (1 + 2) because the first digit (1) matches the second digit
and the third digit (2) matches the fourth digit.
- 1111 produces 4 because each digit (all 1) matches the next.
- 1234 produces 0 because no digit matches the next.
- 91212129 produces 9 because the only digit that matches the next one is the last digit, 9.
"""
captcha = input_lines[0]
captcha = captcha + captcha[0]
return sum([
int(captcha[i]) for i in range(1, len(captcha))
if captcha[i] == captcha[i - 1]
])
def part2(input_lines):
"""
Now, instead of considering the next digit, it wants you to consider the digit halfway around
the circular list. That is, if your list contains 10 items, only include a digit in your sum
if the digit 10/2 = 5 steps forward matches it. Fortunately, your list has an even number of elements.
For example:
- 1212 produces 6: the list contains 4 items, and all four digits match the digit 2 items ahead.
- 1221 produces 0, because every comparison is between a 1 and a 2.
- 123425 produces 4, because both 2s match each other, but no other digit has a match.
- 123123 produces 12.
- 12131415 produces 4.
"""
captcha = input_lines[0]
if len(captcha) % 2 != 0:
raise AssertionError("Day 1, Part 2 anticaptchas must have an even number of digits!")
offset = len(captcha) // 2
mod = len(captcha)
return sum([
int(captcha[i]) for i in range(len(captcha))
if captcha[i] == captcha[(i + offset) % mod]
])
|
"""Top-level package for deployer-fsm."""
__author__ = """Luke Smith"""
__email__ = 'lsmith@zenoscave.com'
__version__ = '0.1.5'
|
class Solution:
# @param A : list of list of integers
# @return an integer
def cnt(self, A, mid):
l = 0
r = len(A)-1
while l <= r:
m = (l+r)//2
if A[m] <= mid:
l = m+1
else:
r = m-1
return l
def findMedian(self, A):
l = 1
r = 1000000000
n = len(A)
m = len(A[0])
while l <= r:
mid = (l+r)//2
ct = 0
for i in range(n):
ct += self.cnt(A[i], mid)
if ct <= (n*m)//2:
l = mid+1
else:
r = mid-1
return l
|
# raider.io api configuration
RIO_MAX_PAGE = 5
# need to update in templates/stats_table.html
# need to update in templates/compositions.html
# need to update in templates/navbar.html
RIO_SEASON = "season-sl-3"
WCL_SEASON = 3
WCL_PARTITION = 1
# config
RAID_NAME = "Sepulcher of the First Ones"
# for heroic week, set this to 10
# after that in the season, set this at 16
MIN_KEY_LEVEL = 16
# to generate a tier list based on heroic week data
# have to manually toggle this
MAX_RAID_DIFFICULTY = "Mythic"
#MAX_RAID_DIFFICULTY = "Heroic"
|
__all__ = [
'plotting',
'misc',
'colors',
'tables',
'nodes',
'containers',
'values',
'basic',
'textures',
'drawing',
]
__version__ = '1.1.1'
|
'''
Q: Popular star patterns
Pattern 1:
*
**
***
****
*****
******
Pattern 2:
* * * * * *
* * * * *
* * * *
* * *
* *
*
Pattern 3:
*
***
*****
*******
*********
Pattern 4:
*
* *
* *
* *
* *
* * * * * *
Notes:
------
Usually the outer for loop determines the height of the pattern
Output screenshot: https://github.com/Ranjul-Arumadi/Coding-Problems/blob/main/Output%20Screenshots/patterns.jpg
'''
'''*-------------------------Solution in python-------------------------'''
#pattern 1
for i in range(0,7):
for j in range(i):
print('*', end="")
print()
#pattern 2
for i in range(6, 0, -1):
for j in range(i):
print('*', end=" ")
print()
#pattern 3
print('Enter tree height: ',end='')
height = int(input())
count=1
for i in range(height, 0, -1):
for j in range(i):
print(' ', end="")
for k in range(count):
print('*', end="")
count = count+2
print()
#pattern 4
print('Enter tree height: ',end='')
height = int(input())
count=1
lineOne = True
for i in range(height, 0, -1):
for j in range(i):
print(' ', end="")
print('*',end="")
if i==1:
for x in range(height-1):
print(' *',end='')
exit()
else:
if lineOne==False:
for k in range(count):
print(' ',end="")
print('*',end="")
count = count+2
print()
lineOne = False
|
# 27. Remove Element
# Python 3
# https://leetcode.com/problems/remove-element
def removeElement(nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
nums[:] = [num for num in nums if num != val]
return len(nums)
numbers, value = [3, 2, 2, 3], 3
print('Length: {} | Array: {}'.format(removeElement(numbers, value), numbers))
|
class Guild:
__slots__ = ('id', 'name', 'icon', 'owner', 'client_is_owner', 'permissions', 'region', 'afk_channel',
'afk_timeout', 'verification_level', 'roles', 'emojis', 'system_channel', 'features',
'mfa_level', 'created', 'large', 'member_count', 'voice_states', 'members', 'channels',
'max_members', 'vanity_url_code', 'description', 'banner',
'premium_tier', 'premium_subscription_count')
def __new__(cls):
raise Exception('Guilds should not be created manually.')
@classmethod
def _create_guild(cls, data: dict):
guild = object.__new__(cls)
guild.id = data.get('id')
guild.name = data.get('name')
guild.icon = data.get('icon')
guild.owner = data.get('owner_id')
guild.client_is_owner = data.get('owner')
guild.permissions = data.get('permissions')
guild.members = data.get('members')
guild.region = data.get('region')
guild.afk_channel = data.get('afk_channel_id')
guild.afk_timeout = data.get('afk_timeout')
guild.verification_level = data.get('verification_level')
guild.roles = data.get('roles')
guild.emojis = data.get('emojis')
guild.features = data.get('features')
guild.mfa_level = data.get('mfa_level')
guild.created = data.get('joined_at')
guild.large = data.get('large')
guild.member_count = data.get('member_count')
guild.voice_states = data.get('voice_states')
guild.channels = data.get('channels')
guild.max_members = data.get('max_members')
guild.vanity_url_code = data.get('vanity_code_url')
guild.description = data.get('description')
guild.banner = data.get('banner')
guild.premium_tier = data.get('premium_tier')
guild.premium_subscription_count = data.get('premium_subscription_count')
return guild
|
q_data = [
{"question": "Japan was part of the Allied Powers during World War I.", "correct_answer": "True",
"incorrect_answers": ["False"]}, {"category": "History", "type": "boolean", "difficulty": "easy",
"question": "The Tiananmen Square protests of 1989 were held in Hong Kong.",
"correct_answer": "False", "incorrect_answers": ["True"]},
{"category": "History", "type": "boolean", "difficulty": "medium",
"question": "In World War II, Hawker Typhoons served in the Pacific theater.", "correct_answer": "False",
"incorrect_answers": ["True"]}, {"category": "History", "type": "boolean", "difficulty": "medium",
"question": "The M41 Walker Bulldog remains in service in some countries to this day.",
"correct_answer": "True", "incorrect_answers": ["False"]},
{"category": "History", "type": "boolean", "difficulty": "hard",
"question": "The Kingdom of Prussia briefly held land in Estonia.", "correct_answer": "False",
"incorrect_answers": ["True"]}, {"category": "History", "type": "boolean", "difficulty": "medium",
"question": "Assyrian king Sennacherib's destruction of Babylon in 689 BCE was viewed as a triumph by other Assyrian citizens.",
"correct_answer": "False", "incorrect_answers": ["True"]},
{"category": "History", "type": "boolean", "difficulty": "medium",
"question": "Brezhnev was the 5th leader of the USSR.", "correct_answer": "True",
"incorrect_answers": ["False"]}, {"category": "History", "type": "boolean", "difficulty": "hard",
"question": "The fourth funnel of the RMS Titanic was fake designed to make the ship look more powerful and symmetrical.",
"correct_answer": "True", "incorrect_answers": ["False"]},
{"category": "History", "type": "boolean", "difficulty": "medium",
"question": "Theodore Roosevelt Jr. was the only General involved in the initial assault on D-Day.",
"correct_answer": "True", "incorrect_answers": ["False"]},
{"category": "History", "type": "boolean", "difficulty": "easy",
"question": "The United States of America declared their independence from the British Empire on July 4th, 1776.",
"correct_answer": "True", "incorrect_answers": ["False"]},
{"category": "History", "type": "boolean", "difficulty": "medium",
"question": "Abraham Lincoln was the first U.S. President to be born outside the borders of the thirteen original states. ",
"correct_answer": "True", "incorrect_answers": ["False"]},
{"category": "History", "type": "boolean", "difficulty": "medium",
"question": "United States President Ronald Reagan was the first president to appoint a woman to the Supreme Court. ",
"correct_answer": "True", "incorrect_answers": ["False"]},
{"category": "History", "type": "boolean", "difficulty": "hard",
"question": "The Battle of Trafalgar took place on October 23rd, 1805", "correct_answer": "False",
"incorrect_answers": ["True"]}, {"category": "History", "type": "boolean", "difficulty": "medium",
"question": "Martin Luther King Jr. and Anne Frank were born the same year. ",
"correct_answer": "True", "incorrect_answers": ["False"]},
{"category": "History", "type": "boolean", "difficulty": "easy",
"question": "Adolf Hitler was tried at the Nuremberg trials.", "correct_answer": "False",
"incorrect_answers": ["True"]}, {"category": "History", "type": "boolean", "difficulty": "medium",
"question": "Adolf Hitler was accepted into the Vienna Academy of Fine Arts.",
"correct_answer": "False", "incorrect_answers": ["True"]},
{"category": "History", "type": "boolean", "difficulty": "hard",
"question": "During the Winter War, the amount of Soviet Union soliders that died or went missing was five times more than Finland's.",
"correct_answer": "True", "incorrect_answers": ["False"]},
{"category": "History", "type": "boolean", "difficulty": "easy",
"question": "The United States of America was the first country to launch a man into space.",
"correct_answer": "False", "incorrect_answers": ["True"]},
{"category": "History", "type": "boolean", "difficulty": "medium",
"question": "Sir Issac Newton served as a Member of Parliament, but the only recorded time he spoke was to complain about a draft in the chambers.",
"correct_answer": "True", "incorrect_answers": ["False"]},
{"category": "History", "type": "boolean", "difficulty": "hard",
"question": "The man that shot Alexander Hamilton was named Aaron Burr.", "correct_answer": "True",
"incorrect_answers": ["False"]}]
|
# Python INTRO for TD Users
# Kike Ramírez
# May, 2018
# Understanding Tuples
# Tuples comparison
#case 1
a=(5,6)
b=(1,4)
if (a>b):print("a is bigger")
else: print("b is bigger")
#case 2
a=(5,6)
b=(5,4)
if (a>b):print("a is bigger")
else: print ("b is bigger")
#case 3
a=(5,6)
b=(6,4)
if (a>b):print("a is bigger")
else: print("b is bigger")
|
#GamePlay.py
#Richard Greenbaum, Karson Daecher, Max Melamed
"""This module contains the functions needed to support pentago gameplay.
A pentago gameboard is represented by a 6x6 2D array. Each location on the board is initialized to "" and is set
to 0 or 1 when the player or the AI respectively places a marble on that location. Each array in the gameboard
nested array represents a column of the board. Thus the gameboard can be viewed as the square in the 1st coordinate
quadrant with x and y coordinates ranging from 0...5. For example, the bottom right location on the gameboard can
be accessed with the command board[5][0]. The four squares on the board are indexed 1...4 with 1 as bottom left, 2 as
top left, 3 as bottom right, and 4 as top right. """
def new_board():
"""Returns an empty board"""
return [[" ", " ", " ", " ", " ", " "], [" ", " ", " ", " ", " ", " "], [" ", " ", " ", " ", " ", " "], [" ", " ", " ", " ", " ", " "],
[" ", " ", " ", " ", " ", " "], [" ", " ", " ", " ", " ", " "]]
def printBoard(board):
"""prints out the board in a legible format"""
print("\033[1m -----------------------------------\033[0m")
print("5 \033[1m| \033[0m" + returnMarble(str(board[0][5])) + " | " + returnMarble(str(board[1][5])) + " | " + returnMarble(str(board[2][5])) +
"\033[1m | \033[0m" + returnMarble(str(board[3][5])) + " | " + returnMarble(str(board[4][5])) + " | " + returnMarble(str(board[5][5])) +"\033[1m |\033[0m")
print(" \033[1m|\033[0m-----------------\033[1m|\033[0m-----------------\033[1m|\033[0m")
print("4 \033[1m| \033[0m" +returnMarble(str(board[0][4])) + " | " + returnMarble(str(board[1][4])) + " | " + returnMarble(str(board[2][4])) +
"\033[1m | \033[0m" + returnMarble(str(board[3][4])) + " | " + returnMarble(str(board[4][4])) + " | " + returnMarble(str(board[5][4]))+"\033[1m |\033[0m")
print(" \033[1m|\033[0m-----------------\033[1m|\033[0m-----------------\033[1m|\033[0m")
print("3 \033[1m| \033[0m" +returnMarble(str(board[0][3])) + " | " + returnMarble(str(board[1][3])) + " | " + returnMarble(str(board[2][3])) +
"\033[1m | \033[0m" + returnMarble(str(board[3][3])) + " | " + returnMarble(str(board[4][3])) + " | " + returnMarble(str(board[5][3]))+"\033[1m |\033[0m 2 | 4 ")
print("\033[1m |-----------------|-----------------|\033[0m --|-- ")
print("2 \033[1m| \033[0m" +returnMarble(str(board[0][2])) + " | " + returnMarble(str(board[1][2])) + " | " + returnMarble(str(board[2][2])) +
"\033[1m | \033[0m" + returnMarble(str(board[3][2])) + " | " + returnMarble(str(board[4][2])) + " | " + returnMarble(str(board[5][2]))+"\033[1m |\033[0m 1 | 3 ")
print(" \033[1m|\033[0m-----------------\033[1m|\033[0m-----------------\033[1m|\033[0m")
print("1 \033[1m| \033[0m" + returnMarble(str(board[0][1])) + " | " + returnMarble(str(board[1][1])) + " | " + returnMarble(str(board[2][1])) +
"\033[1m | \033[0m" + returnMarble(str(board[3][1])) + " | " + returnMarble(str(board[4][1])) + " | " + returnMarble(str(board[5][1]))+"\033[1m |\033[0m")
print(" \033[1m|\033[0m-----------------\033[1m|\033[0m-----------------\033[1m|\033[0m")
print("0 \033[1m| \033[0m" + returnMarble(str(board[0][0])) + " | " + returnMarble(str(board[1][0])) + " | " + returnMarble(str(board[2][0])) +
"\033[1m | \033[0m" + returnMarble(str(board[3][0])) + " | " + returnMarble(str(board[4][0])) + " | " + returnMarble(str(board[5][0]))+"\033[1m |\033[0m")
print("\033[1m -----------------------------------\033[0m")
print(" 0 1 2 3 4 5")
return
def returnMarble(number):
"""Returns a string, red X for AI and black X for human player"""
if (number =="1"):
return "\033[91mX\033[0m"
elif (number == "0"):
return "X"
else:
return number
def rotate(board, direction, square_index):
"""Returns a copy of the board with the indicated square rotated 90 degrees in the indicated direction
Parameter board: a valid pentago board
Parameter direction: the direction of rotation "R" or "L"
Parameter square_index: the index of the square to be rotated int 1...4
"""
if square_index == 1:
vertical_offset = 0
horizontal_offset = 0
if square_index == 2:
vertical_offset = 3
horizontal_offset = 0
if square_index == 3:
vertical_offset = 0
horizontal_offset = 3
if square_index == 4:
vertical_offset = 3
horizontal_offset = 3
if direction == "R":
temp1 = board[2 + horizontal_offset][1 + vertical_offset]
temp2 = board[1 + horizontal_offset][0 + vertical_offset]
board[2 + horizontal_offset][1 + vertical_offset] = board[1 + horizontal_offset][2 + vertical_offset]
board[1 + horizontal_offset][0 + vertical_offset] = temp1
temp1 = board[0 + horizontal_offset][1 + vertical_offset]
board[0 + horizontal_offset][1 + vertical_offset] = temp2
board[1 + horizontal_offset][2 + vertical_offset] = temp1
temp1 = board[2 + horizontal_offset][2 + vertical_offset]
temp2 = board[2 + horizontal_offset][0 + vertical_offset]
board[2 + horizontal_offset][2 + vertical_offset] = board[0 + horizontal_offset][2 + vertical_offset]
board[2 + horizontal_offset][0 + vertical_offset] = temp1
temp1 = board[0 + horizontal_offset][0 + vertical_offset]
board[0 + horizontal_offset][0 + vertical_offset] = temp2
board[0 + horizontal_offset][2 + vertical_offset] = temp1
if direction == "L":
temp1 = board[0 + horizontal_offset][1 + vertical_offset]
temp2 = board[1 + horizontal_offset][0 + vertical_offset]
board[0 + horizontal_offset][1 + vertical_offset] = board[1 + horizontal_offset][2 + vertical_offset]
board[1 + horizontal_offset][0 + vertical_offset] = temp1
temp1 = board[2 + horizontal_offset][1 + vertical_offset]
board[2 + horizontal_offset][1 + vertical_offset] = temp2
board[1 + horizontal_offset][2 + vertical_offset] = temp1
temp1 = board[0 + horizontal_offset][2 + vertical_offset]
temp2 = board[0 + horizontal_offset][0 + vertical_offset]
board[0 + horizontal_offset][2 + vertical_offset] = board[2 + horizontal_offset][2 + vertical_offset]
board[0 + horizontal_offset][0 + vertical_offset] = temp1
temp1 = board[2 + horizontal_offset][0 + vertical_offset]
board[2 + horizontal_offset][0 + vertical_offset] = temp2
board[2 + horizontal_offset][2 + vertical_offset] = temp1
return board
def take_action(board, action, player):
"""Takes a given action on a given board for a given player. Returns the new board.
Parameter board: a valid game board
Parameter action: an instance of type Action
Parameter player: either "Player" or "AI"
"""
if player == "Player":
set_value = 0
else:
set_value = 1
temp=board
temp[action.x_coordinate][action.y_coordinate] = set_value
return rotate(temp, action.direction, action.square_index)
class Action(object):
"""Each acton is composed of the location on the board for a marble to be placed, a square selection,
and the direction that that square should be rotated."""
def __init__(self, x_coordinate, y_coordinate, square_index, direction):
"""Creates an instance of class Action
Parameter x_coordinate: x coordinate of the location for the marble to be placed int 0...5
Parameter y_coordinate: y coordinate of the location for the marble to be placed int 0...5
Parameter square_index: the index of the square to be rotated int 1...4
Parameter direction: the direction of rotation "R" or "L"
"""
self.x_coordinate = x_coordinate
self.y_coordinate = y_coordinate
self.square_index = square_index
self.direction = direction
def equals(self, action):
"""method of class Action that determines if an action is equal to another action"""
assert(isinstance(action, Action))
if not(self.x_coordinate==action.x_coordinate):
return False
if not(self.y_coordinate==action.y_coordinate):
return False
if not(self.square_index==action.square_index):
return False
if not(self.direction==action.direction):
return False
return True
|
def func(s):
one = 0
zero = 0
for i in range(len(s)):
if i > 0 and s[i] == s[i-1] : continue
if s[i] == "1":
one += 1
else :
zero += 1
return min(one,zero)
s = input()
print(func(s))
|
# n points
def lerp_line(pt0, pt1, n):
pts = []
for i in range(n + 1):
t = i / float(n)
pt = pt0 * t + pt1 * (1.0 - t)
pts.append(pt)
return pts
def pole_to_lines(pt0, pt1, color=[0, 255, 0], n=20):
lines = []
pts = lerp_line(pt0, pt1, n)
for pt in pts:
lines.append([pt[0], pt[1], pt[2], color[0], color[1], color[2]])
return lines
def frame_to_lines(Tcw, n=5):
Twc = inv_T(Tcw)
p000 = np.array([0.0, 0.0, 0.0])
p100 = np.array([1.0, 0.0, 0.0])
p010 = np.array([0.0, 1.0, 0.0])
p001 = np.array([0.0, 0.0, 1.0])
p100 /= 10.0
p010 /= 10.0
p001 /= 10.0
xs = lerp_line(p000, p100, n)
ys = lerp_line(p000, p010, n)
zs = lerp_line(p000, p001, n)
wxs = [apply_T(Twc, p) for p in xs]
wys = [apply_T(Twc, p) for p in ys]
wzs = [apply_T(Twc, p) for p in zs]
lines = []
Ow = apply_T(Twc, p000)
lines.append([Ow[0], Ow[1], Ow[2], 255, 255, 255])
for p in wxs[1:]:
lines.append([p[0], p[1], p[2], 255, 0, 0])
for p in wys[1:]:
lines.append([p[0], p[1], p[2], 0, 255, 0])
for p in wzs[1:]:
lines.append([p[0], p[1], p[2], 0, 0, 255])
return lines
|
class MetaData:
'''
convert to dynamically adding attributes by passing in **kwargs and
setting each key value pair
attention will need to be given for when this class is used in other processes
to make sure they know the attributes that exists with each class
however, not necessary just now
'''
def __init__(self):
self.data_raw = None
self.file_type = None
self.metadata_type = None
self.origin_date = None
self.author = None
self.location = None
self.compression_alg = None
self.metadata_dict = None
self.metadata_dict_indexlst = None
def get_metadata_dict(self):
return self.metadata_dict
def get_file_type(self):
return self.file_type
def get_type_md(self):
return self.metadata_type
def get_origin_date(self):
return self.origin_date
def get_author(self):
return self.author
def get_compression_alg(self):
return self.compression_alg
def get_location_taken(self):
return self.location
|
# A non-empty zero-indexed array A consisting of N integers is given.
#
# A permutation is a sequence containing each element from 1 to N once, and
# only once.
#
# For example, array A such that:
# A = [4, 1, 3, 2]
# is a permutation, but array A such that:
# A = [4, 1, 3]
# is not a permutation, because value 2 is missing.
#
# The goal is to check whether array A is a permutation.
#
# Write a function:
# def solution(A)
# that, given a zero-indexed array A, returns 1 if array A is a permutation
# and 0 if it is not.
#
# For example, given array A such that:
# A = [4, 1, 3, 2]
# the function should return 1.
#
# Given array A such that:
# A = [4, 1, 3]
# the function should return 0.
#
# Assume that:
# * N is an integer within the range [1..100,000];
# * each element of array A is an integer within the range [1..1,000,000,000].
#
# Complexity:
# * expected worst-case time complexity is O(N);
# * expected worst-case space complexity is O(N), beyond input storage (not
# counting the storage required for input arguments).
def solution(A):
N = len(A)
if N == 1:
if A[0] == 1:
return 1
else:
return 0
count = {}
for i in range(N):
if A[i] not in count:
count[A[i]] = 0
count[A[i]] += 1
if count[A[i]] > 1:
return 0
# print(count)
values = count.keys()
# print(values)
if max(values) == N:
return 1
return 0
|
while(True):
jars = [int(x) for x in input().split()]
if sum(jars) == 0:
break
if sum(jars) == 13:
print("Never speak again.")
elif jars[0] > jars[1]:
print("To the convention.")
elif jars[1] > jars[0]:
print("Left beehind.")
elif jars[1] == jars[0]:
print("Undecided.")
|
DATE_PATTERNS = ["%d.%m.%Y", "%Y-%m-%d", "%y-%m-%d", "%Y-%m-%dT%H:%M:%S",
"%Y-%m-%d %H:%M:%S",
"%d.%m.%Y %H:%M"]
DEFAULT_DICT_SHARE = 70
SUPPORTED_FILE_TYPES = ['xls', 'xlsx', 'csv', 'xml', 'json', 'jsonl', 'yaml', 'tsv', 'sql', 'bson']
DEFAULT_OPTIONS = {'encoding' : 'utf8',
'delimiter' : ',',
'limit' : 1000
}
|
#9. Elabore um programa para mostrar a sequência dos N primeiro números da série de Fibonacci:
#1 1 2 3 5 8 13 21 34 55 89 ....
#Sempre o próximo elemento é a soma dos dois anteriores, assim, no exemplo o próximo é 144.
ult = 0
num = 1
while num <= 144:
print(num)
ult, num = num, ult
num += ult
|
'''
This solution was submitted by Team: eyeCoders_UOP
during ACES Coders v8 2020
Team lead: Rusiru Thushara thusharakart@gmail.com
The solution runs in O(n)
'''
def getline():return [float(x) for x in input().strip().split(' ')]
c,e,n,s0 = getline()
arr, lst = [], []
m = c/s0
for i in range(int(n)):
x,s = getline()
arr.append((x,s))
if x<c and s>=0:
m = max(m,(c-x)/s)
elif s<0:
lst.append((x,s))
count = 0
for x,s in lst:
if x+s*m <= c:
count+=1
print(round(m),count)
|
# TODO: Make this a relative path
local_url = "/home/garrison/Code/blogengine/output"
remote_url = "http://www.example.com"
site_title = "My Vanilla Blog"
site_description = "The really cool blog in which I write about stuff"
copy_rst = False
disqus_shortname = "mydisqusshortname"
|
in_code = 'abcdefghijklmnopqrstuvwxyz'
out_code = '9128645!@#$%^&*()/.,;:~|[]'
code = str.maketrans(in_code, out_code)
print('this is encrypted!'.translate(code))
|
# Question:5
countNumber = input("Enter the string ")
print ("Original string is : " + countNumber)
res = len(countNumber.split())
print ("Number of words in string is : " + str(res))
|
class Solution:
def isValid(self, s: str) -> bool:
while '[]' in s or '()' in s or '{}' in s:
s = s.replace('[]','').replace('()','').replace('{}','')
return len(s) == 0
"""
time: 10 min
time: O(n)
space: O(n)
errors:
lower case values/keys
Have to use stack because 3 charactors open/close
"""
class Solution:
def isValid(self, s: str) -> bool:
stk = []
mp = {")":"(", "}":"{", "]":"["}
for c in s:
if c in mp.values():
stk.append(c)
elif c in mp.keys():
test = stk.pop() if stk else '#'
if mp[c] != test:
return False
return len(stk) == 0
class Solution:
def isValid(self, s) -> bool:
stk = []
for c in s:
if c == '(':
stk.append(')')
elif c == '[':
stk.append(']')
elif c == '{':
stk.append('}')
elif not stk or stk.pop() != c:
return False
return not stk
|
class Solution:
def __init__(self):
self.result = None
def findMax(self, root):
if root == None:
return 0
# find max for left and right node
left = self.findMax(root.left)
right = self.findMax(root.right)
# can either go straight down i.e. from root to one of the children and downwards
maxStraight = max(max(left, right) + root.val, root.val)
# or can come to root from either of the child nodes and go to other child node
maxCurved = max(left + right + root.val, maxStraight)
# update the result
self.result = max(self.result, maxCurved)
# can only return max straight, since we're going upwards
return maxStraight
def maxPathSum(self, root):
if root == None:
return 0
self.result = float('-inf')
self.findMax(root)
return self.result
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def main():
root = TreeNode(5)
root.left = TreeNode(2)
root.right = TreeNode(7)
root.left.left = TreeNode(1)
root.left.right = TreeNode(3)
root.right.left = TreeNode(5)
root.right.right = TreeNode(9)
mySol = Solution()
print("The max path sum in the binary tree is " + str(mySol.maxPathSum(root)))
if __name__ == "__main__":
main()
|
class DatasetVO:
def __init__(self):
self._id = None
self._name = ""
self._folder = ""
self._description = ""
self._data_type = ""
self._size = 0
self._count = 0
@property
def count(self):
return self._count
@count.setter
def count(self, value):
if self._size and self._size > 0:
self._count = value
else:
self._count = 0
@property
def size(self):
return self._size
@size.setter
def size(self, value):
self._size = value
@property
def folder(self):
return self._folder
@folder.setter
def folder(self, value):
self._folder = value
@property
def id(self):
return self._id
@id.setter
def id(self, value):
self._id = value
@property
def name(self):
return self._name
@name.setter
def name(self, value):
self._name = value
@property
def description(self):
return self._description
@description.setter
def description(self, value):
self._description = value
@property
def data_type(self):
return self._data_type
@data_type.setter
def data_type(self, value):
self._data_type = value
|
valores = []
while True:
valores.append(int(input('Digite um valor: ')))
resp = str(input('Quer continuar? [S/N] '))
if resp in 'Nn':
break
print('-='*30)
print(f'Você digitou {len(valores)} elementos')
valores.sort(reverse=True)
print(f'Os valores em ordem decrescente são {valores} ')
if 5 in (valores):
print('O valor 5 está na lista! ')
else:
print('O número 5 não está na lista! ')
|
class TembaException(Exception):
def __str__(self):
return self.message
class TembaConnectionError(TembaException):
message = "Unable to connect to host"
class TembaBadRequestError(TembaException):
def __init__(self, errors):
self.errors = errors
def __str__(self):
msgs = []
if isinstance(self.errors, dict):
for field, field_errors in self.errors.items():
if isinstance(field_errors, str): # e.g. {"detail": "message..."}
msgs.append(field_errors)
else:
for error in field_errors: # e.g. {"field1": ["msg1...", "msg2..."]}
msgs.append(error)
elif isinstance(self.errors, list):
msgs = self.errors
return msgs[0] if len(msgs) == 1 else ". ".join(msgs)
class TembaTokenError(TembaException):
message = "Authentication with provided token failed"
class TembaNoSuchObjectError(TembaException):
message = "No such object exists"
class TembaRateExceededError(TembaException):
message = (
"You have exceeded the number of requests allowed per org in a given time window. "
"Please wait %d seconds before making further requests"
)
def __init__(self, retry_after):
self.retry_after = retry_after
def __str__(self):
return self.message % self.retry_after
class TembaHttpError(TembaException):
def __init__(self, caused_by):
self.caused_by = caused_by
def __str__(self):
return str(self.caused_by)
class TembaSerializationException(TembaException):
pass
class TembaMultipleResultsError(TembaException):
message = "Request for single object returned multiple objects"
|
DEFAULT_WINDOW_SIZE = 32
DEFAULT_THRESHOLD_MIN_BASIC = 45.39
DEFAULT_THRESHOLD_MAX_BASIC = 46.0
DEFAULT_THRESHOLD_MIN_ABS = 50.32
DEFAULT_THRESHOLD_MAX_ABS = 52.96
DEFAULT_THRESHOLD_MIN_WITHOUT_GC = 11.28
DEFAULT_THRESHOLD_MAX_WITHOUT_GC = 11.42
DEFAULT_MEAN_GC = 0.46354823199323626
DEFAULT_MAX_EVALUE = 0.00445
DEFAULT_PENALTY_BLACK = 2.2
DEFAULT_PENALTY_WHITE = 0.7
DEFAULT_BLACK_LIST = [
'VOG0496',
'VOG5264',
'VOG4730',
'VOG5818',
'VOG7281',
'VOG6063',
'VOG6030',
'VOG1710',
'VOG0996',
'VOG4524',
'VOG8021',
'VOG8536',
'VOG2368',
'VOG1850',
'VOG1031',
'VOG0985',
'VOG0274',
'VOG4344',
'VOG1844',
'VOG0088',
'VOG8607',
'VOG4615',
'VOG8992',
'VOG3235',
'VOG0092',
'VOG4155',
'VOG3532',
'VOG1045',
'VOG4149',
'VOG8062',
'VOG4562',
'VOG7442',
'VOG7446',
'VOG0419',
'VOG4319',
'VOG8429',
'VOG4409',
'VOG1422',
'VOG10018',
'VOG3101',
'VOG5441',
'VOG4469',
'VOG6988',
'VOG4678',
'VOG3722',
]
DEFAULT_WHITE_LIST = [
"VOG0568",
"VOG0569",
"VOG0565",
"VOG0566",
"VOG0567",
"VOG0562",
"VOG2703",
"VOG0968",
"VOG0700",
"VOG0701",
"VOG0703",
"VOG0704",
"VOG8223",
"VOG9502",
"VOG5046",
"VOG5260",
"VOG4643",
"VOG4645",
"VOG4647",
"VOG9348",
"VOG3606",
"VOG9762",
"VOG4736",
"VOG3424",
"VOG9962",
"VOG8568",
"VOG7616",
"VOG7615",
"VOG6418",
"VOG7437",
"VOG10916",
"VOG6520",
"VOG9667",
"VOG0825",
"VOG0824",
"VOG0827",
"VOG0559",
"VOG0557",
"VOG2779",
"VOG4545",
"VOG0953",
"VOG1159",
"VOG0602",
"VOG5254",
"VOG0044",
"VOG4652",
"VOG4659",
"VOG3309",
"VOG4438",
"VOG2545",
"VOG10850",
"VOG1942",
"VOG1319",
"VOG3891",
"VOG3890",
"VOG2388",
"VOG3892",
"VOG3894",
"VOG3897",
"VOG2166",
"VOG1837",
"VOG0541",
"VOG0947",
"VOG0945",
"VOG0723",
"VOG0720",
"VOG0727",
"VOG0724",
"VOG0725",
"VOG0837",
"VOG0835",
"VOG0832",
"VOG0833",
"VOG0830",
"VOG0831",
"VOG0838",
"VOG0839",
"VOG0618",
"VOG0614",
"VOG0615",
"VOG5060",
"VOG0583",
"VOG0051",
"VOG0054",
"VOG5660",
"VOG4829",
"VOG4828",
"VOG4820",
"VOG8497",
"VOG0588",
"VOG3622",
"VOG3396",
"VOG4757",
"VOG3401",
"VOG3406",
"VOG3409",
"VOG2119",
"VOG1956",
"VOG0536",
"VOG0534",
"VOG0539",
"VOG0283",
"VOG0843",
"VOG0842",
"VOG0847",
"VOG0848",
"VOG0198",
"VOG0195",
"VOG10933",
"VOG9374",
"VOG4630",
"VOG4632",
"VOG4633",
"VOG4634",
"VOG10054",
"VOG10059",
"VOG5621",
"VOG8445",
"VOG6866",
"VOG0524",
"VOG0526",
"VOG6440",
"VOG0840",
"VOG0298",
"VOG0299",
"VOG0292",
"VOG0296",
"VOG0850",
"VOG0855",
"VOG0186",
"VOG0181",
"VOG0189",
"VOG9547",
"VOG0275",
"VOG5357",
"VOG10608",
"VOG5734",
"VOG4609",
"VOG4606",
"VOG4600",
"VOG4602",
"VOG3379",
"VOG4171",
"VOG4994",
"VOG4999",
"VOG8520",
"VOG4771",
"VOG4772",
"VOG8855",
"VOG6876",
"VOG0519",
"VOG0518",
"VOG0514",
"VOG2644",
"VOG0641",
"VOG5994",
"VOG4618",
"VOG4619",
"VOG4612",
"VOG3699",
"VOG9474",
"VOG4986",
"VOG7882",
"VOG4763",
"VOG2341",
"VOG10969",
"VOG2124",
"VOG2125",
"VOG6600",
"VOG1900",
"VOG2015",
"VOG0650",
"VOG0651",
"VOG0655",
"VOG5023",
"VOG5027",
"VOG10898",
"VOG0254",
"VOG1309",
"VOG9583",
"VOG8509",
"VOG4573",
"VOG4572",
"VOG0952",
"VOG4888",
"VOG4799",
"VOG2337",
"VOG2336",
"VOG2339",
"VOG2338",
"VOG7693",
"VOG1912",
"VOG1915",
"VOG1047",
"VOG1049",
"VOG2790",
"VOG2793",
"VOG2086",
"VOG2795",
"VOG2794",
"VOG0790",
"VOG0796",
"VOG0799",
"VOG0221",
"VOG0227",
"VOG0226",
"VOG4364",
"VOG4361",
"VOG9227",
"VOG5942",
"VOG4563",
"VOG4564",
"VOG4565",
"VOG4566",
"VOG4567",
"VOG4568",
"VOG4890",
"VOG3327",
"VOG3328",
"VOG6138",
"VOG7440",
"VOG7686",
"VOG6001",
"VOG2788",
"VOG0800",
"VOG1320",
"VOG1329",
"VOG9609",
"VOG9857",
"VOG4555",
"VOG4557",
"VOG4556",
"VOG4550",
"VOG4553",
"VOG4552",
"VOG3798",
"VOG8306",
"VOG7238",
"VOG6545",
"VOG6495",
"VOG0939",
"VOG4559",
"VOG1887",
"VOG5029",
"VOG5092",
"VOG5096",
"VOG5095",
"VOG0753",
"VOG1333",
"VOG4544",
"VOG2791",
"VOG3498",
"VOG10343",
"VOG3304",
"VOG3652",
"VOG3651",
"VOG3477",
"VOG3478",
"VOG8337",
"VOG8336",
"VOG10230",
"VOG0251",
"VOG6153",
"VOG6154",
"VOG1433",
"VOG0327",
"VOG0322",
"VOG0321",
"VOG6203",
"VOG0528",
"VOG5084",
"VOG4672",
"VOG1348",
"VOG9470",
"VOG0696",
"VOG0697",
"VOG0695",
"VOG0692",
"VOG0691",
"VOG0698",
"VOG0107",
"VOG4684",
"VOG9305",
"VOG4593",
"VOG4596",
"VOG4599",
"VOG4598",
"VOG4845",
"VOG4841",
"VOG3480",
"VOG3648",
"VOG3649",
"VOG3644",
"VOG3313",
"VOG3461",
"VOG3462",
"VOG3468",
"VOG8923",
"VOG10227",
"VOG7569",
"VOG0356",
"VOG0355",
"VOG1350",
"VOG1352",
"VOG1353",
"VOG1356",
"VOG5155",
"VOG4693",
"VOG4690",
"VOG4691",
"VOG4694",
"VOG4699",
"VOG2165",
"VOG2163",
"VOG9315",
"VOG9317",
"VOG4589",
"VOG4586",
"VOG4581",
"VOG8134",
"VOG8354",
"VOG2215",
"VOG3298",
"VOG11077",
"VOG1637",
"VOG1638",
"VOG7483",
"VOG2186",
"VOG2188",
"VOG1183",
"VOG0582",
"VOG1298",
"VOG0584",
"VOG0585",
"VOG1563",
"VOG0901",
"VOG0764",
"VOG0765",
"VOG5443",
"VOG0010",
"VOG4002",
"VOG4005",
"VOG4862",
"VOG4865",
"VOG5996",
"VOG4716",
"VOG4713",
"VOG4711",
"VOG8340",
"VOG8904",
"VOG3287",
"VOG4605",
"VOG6163",
"VOG2154",
"VOG2153",
"VOG6181",
"VOG0801",
"VOG0577",
"VOG0574",
"VOG0573",
"VOG0572",
"VOG0571",
"VOG0977",
"VOG0976",
"VOG0152",
"VOG0397",
"VOG0204",
"VOG0021",
"VOG0025",
"VOG0026",
"VOG3616",
"VOG4705",
"VOG4701",
"VOG3434",
"VOG2792",
"VOG3721",
"VOG3549",
"VOG2142",
"VOG10904",
"VOG2149",
"VOG2096",
"VOG9438",
]
|
# @desc Add a short description or instruction here. This will show up at the top of the exercise.
def function_name(parameter): # give your function a name and parameter(s)
# have it do stuff
return # what does it return? This will be what the user types when they predict the result.
def main():
print(function_name(parameter1))
print(function_name(parameter2))
print(function_name(parameter3))
print(function_name(parameter4))
if __name__ == '__main__':
main()
|
s = input()
g1 = {}
for i in range(1, len(s)):
g1[s[i-1: i+1]] = g1.get(s[i-1: i+1], 0) + 1
s = input()
g2 = set()
for i in range(1, len(s)):
g2.add(s[i-1: i+1])
print(sum([g1[g] for g in frozenset(g1.keys()) & g2]))
|
"""Defines LidarObject class.
----------------------------------------------------------------------------------------------------------
This file is part of Sim-ATAV project and licensed under MIT license.
Copyright (c) 2018 Cumhur Erkan Tuncali, Georgios Fainekos, Danil Prokhorov, Hisahiro Ito, James Kapinski.
For questions please contact:
C. Erkan Tuncali (etuncali [at] asu.edu)
----------------------------------------------------------------------------------------------------------
"""
class LidarObject(object):
OBJECT_CAR = 0
OBJECT_PEDESTRIAN = 1
OBJECT_BIKE = 2
OBJECT_TRUCK = 3
"""LidarObject class defines features of the object detected by LIDAR."""
def __init__(self, lidar_cluster, object_class, relative_position):
self.lidar_cluster = lidar_cluster
self.object_class = object_class
self.relative_position = relative_position
|
# Code Demo for 13 Lecture
# Working with Python Strings
# CIS 135 - Code Demo File
# Lecture example showing string contatenation
firstName = "Peter"
lastName = "Parker"
print("\nString Contcatenation in Pyton uses the + operator")
print(f'First Name = {firstName}')
print(f'Last Name = {lastName}')
print("Peter Parker can be concatenated as 'firstName' + ' ' + 'lastName'")
print("Hello,", firstName + ' ' + lastName)
# Example slicing JJC
JJC = "Joliet Junior College"
print('\nJJC = "Joliet Junior College"')
print("\nExtract 'Joliet' from the variable JJC")
print(JJC[0:6]) # this returns the first six characters
print("\nExtract 'College' from the variable JJC")
print(JJC[-7:]) # this returns the final seven characters
print("\nExtract 'Junior' from the variable JJC")
print(JJC[7:-7]) # this returns the final seven characters
alphas = 'abcdefghi'
print(f'\nThe variable alphas = {alphas}')
print('alphas[1:3] extract characters ', alphas[4:8])
print('alphas[:3] = will extract characters ', alphas[:3])
print('alphas[-2:] = will extract characters ', alphas[-2:])
print('alphas[-3:-2] = will extract characters ', alphas[-3:-2])
this_string = " some text "
print(this_string.lstrip())
print(this_string.rstrip())
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/10/17 21:35
# @Author : jacson
# @FileName: file_from_pycharm.py
print("hello world!!!")
|
def percentual(qtde, total):
return (100 * qtde) / total
n = int(input())
c = r = s = 0
for i in range(n):
val, tipo = input().split()
qtde = int(val)
if tipo == 'C':
c += qtde
if tipo == 'R':
r += qtde
if tipo == 'S':
s += qtde
total = c + r + s
print('Total: {} cobaias'.format(total))
print('Total de coelhos: {}\nTotal de ratos: {}\nTotal de sapos: {}'.format(c, r, s))
print('Percentual de coelhos: {:.2f} %'.format(percentual(c, total)))
print('Percentual de ratos: {:.2f} %'.format(percentual(r, total)))
print('Percentual de sapos: {:.2f} %'.format(percentual(s, total)))
|
# See: http://django-suit.readthedocs.org/en/develop/
SUIT_CONFIG = {
# header
'ADMIN_NAME': 'Augeo',
# 'HEADER_DATE_FORMAT': 'l, j. F Y',
# 'HEADER_TIME_FORMAT': 'H:i',
}
|
def convert(my_str):
my_list = list(my_str.split(' '))
return my_list
values = {}
times = {}
weights = {}
ids = []
f = open('crime_scene.txt')
my_lines = f.readlines()
stripped_lines = [line.strip() for line in my_lines]
f.close()
N = int(stripped_lines[1])
w = int(convert(stripped_lines[0])[0])
t = int(convert(stripped_lines[0])[1])
if N != 1:
for n in range(2,N+2):
content = convert(stripped_lines[n])
values[content[0]] = content[3]
times[content[0]] = content[2]
weights[content[0]] = content[1]
ids.append(content[0])
else:
n = 2
content = convert(stripped_lines[n])
values[content[0]] = content[3]
times[content[0]] = content[2]
weights[content[0]] = content[1]
ids.append(content[0])
def list_sum(my_lst,wanted = None):
if wanted == None:
wanted = 0
if len(my_lst) == 0:
return wanted
wanted = wanted + int(my_lst[0])
return list_sum(my_lst[1:],wanted)
def my_weights(my_lst,wanted = None):
if wanted == None:
wanted = []
if len(my_lst) == 0:
return wanted
wanted.append(weights[my_lst[0]])
return my_weights(my_lst[1:],wanted)
def my_times(my_lst,wanted = None):
if wanted == None:
wanted = []
if len(my_lst) == 0:
return wanted
wanted.append(times[my_lst[0]])
return my_times(my_lst[1:],wanted)
def my_values(my_lst,wanted = None):
if wanted == None:
wanted = []
if len(my_lst) == 0:
return wanted
wanted.append(values[my_lst[0]])
return my_values(my_lst[1:],wanted)
def control1(my_lst): # output 1
if list_sum(my_weights(my_lst)) <= w:
return True
else:
return False
def control2(my_lst): # output 2
if list_sum(my_times(my_lst)) <= t:
return True
else:
return False
def control3(my_lst): # output 3
if list_sum(my_weights(my_lst)) <= w and list_sum(my_times(my_lst)) <= t:
return True
else:
return False
def creating_lst(my_lst,for_lst,wanted = None):
if wanted == None:
wanted = []
if len(for_lst) == 0:
return wanted
wanted.append([my_lst[-1]]+for_lst[0])
return creating_lst(my_lst,for_lst[1:],wanted)
def combinations(my_lst):
if my_lst:
sonuc = combinations(my_lst[:-1])
wanted = sonuc + creating_lst(my_lst,sonuc)
return wanted
else:
return [[]]
def comb_control1(my_lst,i = None,wanted = None): # output 1
if i == len(combinations(my_lst)):
return wanted
if i == None:
i = 0
if wanted == None:
wanted = []
if control1(combinations(my_lst)[i]):
wanted.append(combinations(my_lst)[i])
else:
pass
i += 1
return comb_control1(my_lst,i,wanted)
def comb_control2(my_lst,i = None,wanted = None): # output 2
if i == len(combinations(my_lst)):
return wanted
if i == None:
i = 0
if wanted == None:
wanted = []
if control2(combinations(my_lst)[i]):
wanted.append(combinations(my_lst)[i])
else:
pass
i += 1
return comb_control2(my_lst,i,wanted)
def comb_control3(my_lst,i = None,wanted = None): # output 3
if i == len(combinations(my_lst)):
return wanted
if i == None:
i = 0
if wanted == None:
wanted = []
if control3(combinations(my_lst)[i]):
wanted.append(combinations(my_lst)[i])
else:
pass
i += 1
return comb_control3(my_lst,i,wanted)
def biggest_subset(my_lst,max = None,wanted_lst = None):
if len(my_lst) == 0:
return wanted_lst
if max == None:
max = 0
if wanted_lst == None:
wanted_lst = []
if list_sum(my_values(my_lst[0])) > max:
max = list_sum(my_values(my_lst[0]))
wanted_lst = my_lst[0]
else:
pass
return biggest_subset(my_lst[1:],max,wanted_lst)
ideal_list1 = biggest_subset(comb_control1(ids))
ideal_list2 = biggest_subset(comb_control2(ids))
ideal_list3 = biggest_subset(comb_control3(ids))
sorted_output1 = [] # w
sorted_output2 = [] # t
sorted_output3 = [] # t and w
while ideal_list1:
my_min = ideal_list1[0]
for evidence in ideal_list1:
if int(evidence) < int(my_min):
my_min = evidence
sorted_output1.append(my_min)
ideal_list1.remove(my_min)
while ideal_list2:
my_min = ideal_list2[0]
for evidence in ideal_list2:
if int(evidence) < int(my_min):
my_min = evidence
sorted_output2.append(my_min)
ideal_list2.remove(my_min)
while ideal_list3:
my_min = ideal_list3[0]
for evidence in ideal_list3:
if int(evidence) < int(my_min):
my_min = evidence
sorted_output3.append(my_min)
ideal_list3.remove(my_min)
def _output1(my_lst):
f1 = open('solution_part1.txt','w+')
f1.write(str(list_sum(my_values(my_lst)))+'\n')
for evidence in my_lst:
f1.write(str(evidence)+' ')
f1.close()
def _output2(my_lst):
f2 = open('solution_part2.txt','w+')
f2.write(str(list_sum(my_values(my_lst)))+'\n')
for evidence in my_lst:
f2.write(str(evidence)+' ')
f2.close()
def _output3(my_lst):
f3 = open('solution_part3.txt','w+')
f3.write(str(list_sum(my_values(my_lst)))+'\n')
for evidence in my_lst:
f3.write(str(evidence)+' ')
f3.close()
_output1(sorted_output1)
_output2(sorted_output2)
_output3(sorted_output3)
|
class Command:
def exec(self, ob):
met = getattr(self, "on"+type(ob).__name__)
return met(ob)
def onNode(self, a):
pass
def onConnection(self, a):
pass
def onGenome(self, a):
pass
|
__all__ = ['interpolation_slicing_default_param']
def interpolation_slicing_default_param(key):
""" Returns the default parameters with the specified key. """
if key in default_parameters:
return default_parameters[key]
else:
raise ValueError('The parameter with key : ' + str(key) +
' does not exist in the defaults of curved_slicing parameters. ')
default_parameters = \
{
# geodesics method
'target_LOW_geodesics_method': 'exact_igl',
'target_HIGH_geodesics_method': 'exact_igl',
# union method for HIGH target
# if all are false, then default 'min' method is used
'target_HIGH_smooth_union': [False, [10.0]], # blend radius
'target_HIGH_chamfer_union': [False, [100.0]], # size
'target_HIGH_stairs_union': [False, [80.0, 3]], # size, n-1 number of peaks
'uneven_upper_targets_offset': 0,
}
|
FILTER_ACTION_ON_CHOICES = (
('entry', 'On Entry'),
('exit', 'On Exit'),
)
FILTER_ACTION_TYPE_CHOICES = (
('eml', 'Send Email Notification'),
('sms', 'Send SMS Notification'),
('slk', 'Send Slack Notification'),
('cus', 'Custom Action'),
('drv', 'Derive Stream Action'),
('rpt', 'Report Generation Action'),
('smry', 'Summary Report Generation Action'),
)
|
# countup.py
# http://asu-compmethodsphysics-phy494.github.io/ASU-PHY494//2017/01/19/03_Introduction_to_Python_2/#the-while-loop
tmax = 10.
t, dt = 0, 2.
while t <= tmax:
print("time " + str(t))
t += dt
print("Finished")
|
wordList = ['quail']
def isValidWord(word, hand, wordList):
"""
Returns True if word is in the wordList and is entirely
composed of letters in the hand. Otherwise, returns False.
Does not mutate hand or wordList.
word: string
hand: dictionary (string -> int)
wordList: list of lowercase strings
"""
if len(word) == 0:
return False
for letter in word:
if word.count(letter) > hand.get(letter, 0) or word not in wordList:
return False
return True
hand = {'a':1, 'q':1, 'l':2, 'm':1, 'u':1, 'i':1}
print(isValidWord('quail', hand, wordList))
|
def func1():
"""
## Create a QA Task
To reach the tasks and assignments repositories go to <a href="https://sdk-docs.dataloop.ai/en/latest/repositories.html#module-dtlpy.repositories.tasks" target="_blank">tasks</a> and <a href="https://sdk-docs.dataloop.ai/en/latest/repositories.html#module-dtlpy.repositories.assignments" target="_blank">assignments</a>.
To reach the tasks and assignments entities go to <a href="https://sdk-docs.dataloop.ai/en/latest/entities.html#module-dtlpy.entities.task" target="_blank">tasks</a> and <a href="https://sdk-docs.dataloop.ai/en/latest/entities.html#module-dtlpy.entities.assignment" target="_blank">assignments</a>.
In Dataloop there are two ways to create a QA task:
1. You can create a QA task from the annotation task. This will collect all completed Items and create a QA Task.
2. You can create a standalone QA task.
### QA task from the annotation task
#### prep
"""
def func2():
"""
#### 2. Create a QA Task
This action will collect all completed Items and create a QA Task under the annotation task.
<div style="background-color: lightblue; color: black; width: 50%; padding: 10px; border-radius: 15px 5px 5px 5px;"><b>Note</b><br>
Adding filters is <b>optional</b>. Learn all about filters <a href="https://dataloop.ai/docs/sdk-sort-filter" target="_blank">here</a>.</div>
"""
def func3():
"""
### A standalone QA task
#### prep
"""
def func4():
"""
#### 2. Add filter by directory
<div style="background-color: lightblue; color: black; width: 50%; padding: 10px; border-radius: 15px 5px 5px 5px;"><b>Note</b><br>
Adding filters is <b>optional</b>. Learn all about filters <a href="https://dataloop.ai/docs/sdk-sort-filter" target="_blank">here</a>.</div>
"""
def func5():
"""
### Create a QA Task
This action will collect all items on the folder and create a QA Task from them.
"""
|
# https://leetcode.com/problems/partition-array-into-three-parts-with-equal-sum/
# Easy (47.22%)
# Total Accepted: 2,951
# Total Submissions: 6,250
# beats 100.0% of python submissions
class Solution(object):
def canThreePartsEqualSum(self, A):
"""
:type A: List[int]
:rtype: bool
"""
s = sum(A)
if s % 3 != 0:
return False
target = s / 3
cur_s, p = 0, 0
for idx, n in enumerate(A):
cur_s += n
if cur_s == target:
cur_s = 0
p += 1
if p == 2:
return True if sum(A[idx+1:]) == target else False
return False
|
'''
Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Created on Apr 9, 2014
@author: dfleck
'''
class MessageCache(list):
'''
Holds a list of tuples (envelope, message)
'''
def __contains__(self, otherEnvelope):
#print("\n-- Message Cache Check -- ")
for value in self:
(envelope, message) = value
#print("MessageCache comparing: [%s][%s]" % (otherEnvelope['msgID'], envelope['msgID']))
if envelope['msgID'] == otherEnvelope['msgID']:
#print("Message Cache: TRUE\n -- ")
return True
#print("Message Cache: FALSE\n -- ")
return False
|
class Request:
def __init__(self):
self.timeout = 5000
def get_params(self):
return {}
def get_body(self):
return {}
|
a = ['a', 'b', 'c', 'd']
print("This is a list", a)
print("It is", len(a), "elements length.")
print("Let's check if element 'd' is in the list:", 'd' in a)
print("This should be the maximun value of the list", max(a))
print("This should be the minnimun value of the list", min(a))
print("This is a list, item by item: ", end=' ')
for item in a:
print(item, end=' ')
print("\r\nThis is the first element of the list: ", a[0])
a.remove('b')
print("This is the list after removing the 'b' ", a)
del a[0]
print("This is the list after removing the first element", a)
|
# Verifica palíndromo
# Faça uma função que recebe uma string e retorna True se ela for um palíndromo (é a mesma de trás para frente), ou False caso contrário. Por exemplo, a string 'roma é amor' é um palíndromo.
# Use fatiamento.
# Desafio 1: dá para fazer essa função com apenas 2 linhas de código.
# Desafio 2: resolva novamente sem usar fatiamento.
# O nome da sua função deve ser 'eh_palindromo'.
def eh_palindromo (text):
rev_text = text[::-1]
check = text == rev_text
return check
|
def soft_update_network(target, source, tau):
for target_param, source_param in zip(target.parameters(), source.parameters()):
target_param.data.copy_(
target_param.data * (1 - tau) + source_param.data * tau
)
def hard_update_network(target, source):
target.load_state_dict(source.state_dict())
|
class PropertyError(Exception):
"""Represents game property error."""
pass
|
words = {
'i': 520,
'am': 100,
'batman': 20,
'hello': 100
}
# iterate over keys
# for key in words.keys():
# print(key)
# for key in words:
# print(key)
# iterate over values
# words_keys = words.keys()
# print(words_keys)
# words_values = words.values()
# print(words_values)
# for value in words.values():
# print(value)
# print(list(map(str, words.values())))
# iterate over items
for key, value in words.items():
print(key, value)
|
SECRET = "very secret key"
DEBUG = False
LOG_FILE = "log"
LOG_FORMAT = '''
Message type: %(levelname)s
Location: %(pathname)s:%(lineno)d
Module: %(module)s
Function: %(funcName)s
Time: %(asctime)s
Message:
%(message)s
'''
SENDGRID_APIKEY = "BLAABLAA"
RECEIPTS_FOLDER = '/tmp/'
TMP_FOLDER = '/tmp/'
SQLALCHEMY_DATABASE_URI = 'sqlite:////tmp/dev.db'
SQLALCHEMY_TRACK_MODIFICATIONS = False
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
50个话题
9章
1.课程简介
2.数据结构相关话题
3.迭代器与生成器相关话题
4.字符串处理相关话题
5.文件I/O操作相关话题
6.数据编码与处理相关话题
7.类与对象相关话题
8.多线程与多进程相关话题
9.装饰器相关话题
"""
"""
第1章 课程简介
1-1 课程简介
1-2 在线编码工具WebIDE使用指南
第2章 数据结构与算法进阶训练
2-1 如何在列表, 字典, 集合中根据条件筛选数据
2-2 如何为元组中的每个元素命名, 提高程序可读性
2-3 如何统计序列中元素的出现频度
2-4 如何根据字典中值的大小, 对字典中的项排序
2-5 如何快速找到多个字典中的公共键(key)
2-6 如何让字典保持有序
2-7 如何实现用户的历史记录功能(最多n条)
第3章 对象迭代与反迭代技巧训练
3-1 如何实现可迭代对象和迭代器对象(1)
3-2 如何实现可迭代对象和迭代器对象(2)
3-3 如何使用生成器函数实现可迭代对象
3-4 如何进行反向迭代以及如何实现反向迭代
3-5 如何对迭代器做切片操作
3-6 如何在一个for语句中迭代多个可迭代对象
第4章 字符串处理技巧训练
4-1 如何拆分含有多种分隔符的字符串
4-2 如何判断字符串a是否以字符串b开头或结尾
4-3 如何调整字符串中文本的格式
4-4 如何将多个小字符串拼接成一个大的字符串
4-5 如何对字符串进行左, 右, 居中对齐
4-6 如何去掉字符串中不需要的字符
第5章 文件I/O高效处理技巧训练
5-1 如何读写文本文件
5-2 如何处理二进制文件
5-3 如何设置文件的缓冲
5-4 如何将文件映射到内存
5-5 如何访问文件的状态
5-6 如何使用临时文件
第6章 csv,json,xml,excel高效解析与构建技巧训练
6-1 如何读写csv数据
6-2 如何读写json数据
6-3 如何解析简单的xml文档
6-4 如何构建xml文档
6-5 如何读写excel文件
第7章 类与对象深度技术进阶训练
7-1 如何派生内置不可变类型并修改实例化行为
7-2 如何为创建大量实例节省内存
7-3 如何让对象支持上下文管理
7-4 如何创建可管理的对象属性
7-5 如何让类支持比较操作
7-6 如何使用描述符对实例属性做类型检查
7-7 如何在环状数据结构中管理内存
7-8 如何通过实例方法名字的字符串调用方法
第8章 多线程编程核心技术应用进阶训练
8-1 如何使用多线程
8-2 如何线程间通信
8-3 如何在线程间进行事件通知
8-4 如何使用线程本地数据
8-5 如何使用线程池
8-6 如何使用多进程
第9章 装饰器使用技巧进阶训练
9-1 如何使用函数装饰器
9-2 如何为被装饰的函数保存元数据
9-3 如何定义带参数的装饰器
9-4 如何实现属性可修改的函数装饰器
9-5 如何在类中定义装饰器
"""
"""
6-1 如何读写csv数据
实际案例:
http://table.finance.yahoo.com/table.csv?s=000001.sz我们可以通过雅虎网站获取了中国股市(深市)数据集,它以csv数据格式存储:
Date,Open,High,Low,Close,Volume,Adj Close
2016-06-30,8.69,8.74,8.66,8.70,36220400,8.70
2016-06-29,8.63,8.69,8.62,8.69,36961100,8.69
2016-06-28,8.58,8.64,8.56,8.63,33651900,8.63
请将平安银行这支股票,在2016奶奶中成交量超过50000000的纪录存储到另一个csv文件中
解决方案:
使用标准库中的csv模块,可以使用其中reader和writer完成csv文件读写
"""
'''
urllib.request.urlretrieve("http://table.finance.yahoo.com/table.csv?s=000001.sz",'pingan.csv')
cat pingan.csv | less
'''
"""
# 使用二进制打开
# 有问题,其实csv文件不是二进制文件
rf = open(file_name,'rb')
reader = csv.reader(rf)
print(reader)
for row in reader:
print(row)
"""
'''
file = 'test.csv'
file_name = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + \
'\\' + 'docs' + '\\' + 'csv' + '\\' + file
file_copy = 'pingan_copy.csv'
file_name_copy = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + \
'\\' + 'docs' + '\\' + 'csv' + '\\' + file_copy
with open(file_name,"rt",encoding="utf-8") as csvfile:
reader = csv.reader(csvfile)
rows = [row for row in reader]
print(rows)
wf = open(file_name_copy,'w')
writer = csv.writer(wf)
writer.writerow(['Date','Open','High','Low','Close','Volume','Adj Close'])
writer.writerow(['Date','Open','High','Low','Close','Volume','Adj Close'])
wf.flush()
print("-----最好的方法-----")
print("python2和python3的csv.reader.next的方法有所区别")
file_copy_2 = 'pingan2.csv'
file_name_copy2 = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + \
'\\' + 'docs' + '\\' + 'csv' + '\\' + file_copy_2
with open(file_name,'r') as rf:
reader = csv.reader(rf)
with open(file_name_copy2,'w') as wf:
writer = csv.writer(wf)
headers = next(reader)
writer.writerow(headers)
for row in reader:
#if row[0] < '2016-01-01':
#break
if int(row[5]) > 36961100:
writer.writerow(row)
print("end")
'''
'''
6-2 如何读写json数据
实际案例:
在web应用中常用JSON(JavaScript Object Notation)格式传输数据,例如我们利用Baidu语音识别服务做语音识别,将本地音频数据post到Baidu语音识别服务器,服务器响应结果为json字符串
{"corpus_no":"6303355448008565863","err_msg":"success.","err_no":0,"result":["你好 ,"],"sn":"418359718861467614305"}
在python中如何读写json数据?
解决方案:
使用标准库中的json模块,其中loads,dumps函数可以完成json数据的读写
'''
'''
#coding:utf-8
import requests
import json
# 录音
from record import Record
record = Record(channels=1)
audioData = record.record(2)
# 获取token
from secret import API_KEY,SECRET_KEY
authUrl = "https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials&client_id=" + API_KEY + "&client_secret=" + SECRET_KEY
response = requests.get(authUrl)
res = json.loads(response.content)
token = res['access_token']
# 语音识别
cuid = 'xxxxxxxxxxx'
srvUrl = 'http://vop.baidu.com/server_api' + '?cuid=' + cuid + '&token=' + token
httpHeader = {
'Content-Type':'audio/wav; rate = 8000',
}
response = requests.post(srvUrl,headers=httpHeader,data=audioData)
res = json.loads(response.content)
text = res['result'][0]
print(u'\n识别结果:')
print(text)
'''
'''
# dumps将python对象转换为json的字符串
l = [1,2,'abc',{'name': 'Bob','age':13}]
print(json.dumps(l))
d = {'b':None,'a':5,'c':'abc'}
print(json.dumps(d))
# 将逗号后的空格和冒号后的空格删除,将空格压缩掉
print(json.dumps(l,separators=[',', ':']))
# 对输出的字典中的键进行排序
print(json.dumps(d,sort_keys=True))
# 把json字符串转换为python对象
l2 = json.loads('[1,2,"abc",{"name": "Bob","age":13}]')
print(type(l2))
d2 = json.loads('{"b":null,"a":5,"c":"abc"}')
print(type(d2))
'''
'''
file = 'demo.json'
file_name = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + \
'\\' + 'docs' + '\\' + 'json' + '\\' + file
l = [1,2,'abc',{'name': 'Bob','age':13}]
# 将json写入文件当中,dump和load同理
with open(file_name,'w') as f:
json.dump(l,f)
'''
'''
6-3 如何解析简单的xml文档
实际案例:
xml是一种十分常用的标记性语言,可提供统一的方法来描述应用程序的结构化数据:
<?xml version="1.0"?>
<data>
<country name="Liechtenstein">
<rank updated="yes">2</rank>
<year>2008</year>
<gdppc>141100</gdppc>
<neighbor name="Austria" direction="E"/>
<neighbor name="Switzerland" direction="W"/>
</country>
</data>
python中如何解析xml文档?
解决方案:
使用标准库中的xml.etree.ElementTree,其中的parse函数可以解析xml文档
from xml.etree.ElementTree import parse
import os
file = 'demo.xml'
file_name = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + \
'\\' + 'docs' + '\\' + 'xml' + '\\' + file
f = open(file_name)
et = parse(f)
print(et)
root = et.getroot()
print(root)
print(root.tag)
print(root.attrib)
print(root.text)
print(root.text.strip())
print(root.getchildren())
for child in root:
print(child.get('name'))
print(root.find('country'))
print(root.findall('country'))
print(root.iterfind('country'))
for e in root.iterfind('country'):
print(e.get('name'))
print(root.findall('rank')) # 找不到非子元素
print(root.iter())
print(list(root.iter()))
print(list(root.iter('rank')))
print(root.findall('country/*')) # *表示匹配孙子节点
print(root.findall('rank')) # 直接查找子元素
print(root.findall('.//rank')) # //表示查找所有层次
print(root.findall('.//rank/..')) # ..表示查找rank的所有父节点
print(root.findall('country[@name]')) # 查找包含name属性的country
print(root.findall('country[@name="Singapore"]'))#查找属性等于特定值的
print(root.findall('country[rank]'))# 查找包含rank的country
print(root.findall('country[rank="5"]'))
print(root.findall('country[1]')) #查找序号为1的country
print(root.findall('country[2]'))
print(root.findall('country[last()]')) #找最后一个country标签
print(root.findall('country[last()-1]')) #找倒数第二个
'''
'''
6-4 如何构建xml文档
实际案例:
某些时候,我们需要将其他格式数据转换为xml
例如,我们要把平安股票csv文件,转换成相应的xml,
test.csv
Date,Open,High,Low,Close,Volume,Adj Close
2016/6/1,8.69,8.74,8.66,8.7,36220400,8.7
pingan.xml
<Data>
<Row>
<Date>2016-07-05</Date>
<Open>8.80</Open>
<High>8.83</High>
<Low>8.77</Low>
<Close>8.81</Close>
<Volume>42203700</Volume>
<AdjClose>8.81</AdjClose>
</Row>
</Data>
解决方案:
使用标准库中的xml.etree.ElementTree,构建ElementTree,使用write方法写入文件
from xml.etree.ElementTree import Element,ElementTree
e = Element('Data') # tag名字 Data 创建元素
print(e.tag)
print(e.set('name','abc')) # 设置Data的属性
from xml.etree.ElementTree import tostring
print(tostring(e))
e.text='123'
print(tostring(e))
e2 = Element('Row') #创建子元素
e3 = Element('Open')
e3.text='8.80'
e2.append(e3)
print(tostring(e2))
e.text = None
e.append(e2)
print(tostring(e))
import os
file = 'demo1.xml'
file_name = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + \
'\\' + 'docs' + '\\' + 'xml' + '\\' + file
et = ElementTree(e)
et.write(file_name)
'''
'''
import csv
from xml.etree.cElementTree import Element,ElementTree
import os
file = 'pingan.csv'
file_name = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + \
'\\' + 'docs' + '\\' + 'csv' + '\\' + file
file1 = 'pingan.xml'
file_name1 = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + \
'\\' + 'docs' + '\\' + 'xml' + '\\' + file1
def xml_pretty(e,level=0):
if len(e) > 0:
e.text = '\n' + '\t' * (level + 1)
for child in e:
xml_pretty(child,level + 1)
child.tail = child.tail[:-1]
e.tail = '\n' + '\t' * level
def csvToXml(fname):
with open(fname,'r') as f:
reader = csv.reader(f)
headers = next(reader)
root = Element('Data')
for row in reader:
eRow = Element('Row')
root.append(eRow)
for tag,text in zip(headers,row):
e = Element(tag)
e.text = text
eRow.append(e)
xml_pretty(root)
return ElementTree(root)
et = csvToXml(file_name)
et.write(file_name1)
'''
'''
6-5 如何读写excel文件
实际案例:
Microsoft Excel是日常办公中使用最频繁的软件,其数据格式为xls、xlsx,一种非常常用的电子表格,小学某班成绩,记录在excel文件中
姓名 语文 数学 外语
李雷 95 99 96
韩梅 98 100 93
张峰 94 95 95
利用python读写excel,添加“总分”列,计算每人的总分
解决方案:
使用pip安装, $ pip install xlrd xlwt
使用第三方库xlrd和xlwt,这两个库分别用于excel读和写
'''
'''
import xlrd
import os
file = 'sum_point.xlsx'
file_name = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + \
'\\' + 'docs' + '\\' + 'excel' + '\\' + file
book = xlrd.open_workbook(file_name)
print(book.sheets())
sheet = book.sheet_by_index(0)
print(sheet.nrows)
print(sheet.ncols)
cell = sheet.cell(0,0)
print(cell)
# cell.ctype 是枚举值 xlrd.XL...
print(type(cell.value))
print(cell.value)
cell2 = sheet.cell(1,1)
print(cell2)
print(type(cell2))
print(cell2.ctype)
print(sheet.row(1))
print(sheet.row_values(1))
print(sheet.row_values(1,1)) # 跳过第一个,第2个1表示从第一个开始
# sheet.put_cell 为表添加1个单元格
import xlwt
wbook = xlwt.Workbook()
wsheet = wbook.add_sheet('sheet1')
# wsheet.write
# wbook.save('output.xlsx')
'''
'''
# 写入失败,有问题!!!!!!!!!
import os
import xlrd
import xlwt
file = 'sum_point.xlsx'
file_name = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + \
'\\' + 'docs' + '\\' + 'excel' + '\\' + file
file1 = 'sum_point_copy.xlsx'
file_name1 = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + \
'\\' + 'docs' + '\\' + 'excel' + '\\' + file1
rbook = xlrd.open_workbook(file_name)
rsheet = rbook.sheet_by_index(0)
nc = rsheet.ncols
rsheet.put_cell(0, nc, xlrd.XL_CELL_TEXT, u'总分', None) # 添加总分的文字,第0行,第rsheet.ncols列,类型,文本
for row in range(1, rsheet.nrows): # 第1行开始,跳过第0列
t = sum(rsheet.row_values(row, 1))
rsheet.put_cell(row, nc, xlrd.XL_CELL_NUMBER, t, None)
wbook = xlwt.Workbook()
wsheet = wbook.add_sheet(rsheet.name)
style = xlwt.easyxf('align:vertical center,horizontal center')
for r in range(rsheet.nrows):
for c in range(rsheet.ncols):
wsheet.write(r, c, rsheet.cell_value(r, c), style)
wbook.save(u'output.xlsx')
'''
|
"""
Algoritmos de PCS3110 em Python
Módulo 3 - Análise de algoritmo e ordenação
"""
class MaxHeap:
""" Implementação de um max-heap.
"""
def __init__(self, lista = None):
if lista == None:
self.lista = []
else:
self.lista = lista
self.heap_size = len(self.lista)
for i in range(MaxHeap.pai(self.heap_size - 1), -1, -1):
self.max_heapify(i)
def __str__(self):
return str(self.lista[:self.heap_size])
@staticmethod
def pai(i):
""" Retorna a posição do pai de i.
"""
return int((i - 1) / 2)
@staticmethod
def filho_esquerda(i):
""" Retorna a posição do filho da esquerda de i.
"""
return 2 * i + 1
@staticmethod
def filho_direita(i):
""" Retorna a posição do filho da direita de i.
"""
return 2 * i + 2
def is_max_heap(self):
""" Retorna True se o Heap é um max-heap. ou False caso contrário.
"""
for i in range(self.heap_size - 1, 0, -1):
if self.lista[i] > self.lista[MaxHeap.pai(i)]:
return False
return True
def max_heapify(self, i):
""" Algoritmo que corrige a posição i de um max-heap.
"""
e = MaxHeap.filho_esquerda(i)
d = MaxHeap.filho_direita(i)
if e < self.heap_size and self.lista[e] > self.lista[i]:
maior = e
else:
maior = i
if d < self.heap_size and self.lista[d] > self.lista[maior]:
maior = d
if maior != i:
temp = self.lista[i]
self.lista[i] = self.lista[maior]
self.lista[maior] = temp
self.max_heapify(maior)
def extrair_maior(self):
""" Extrai o maior elemento de um max-heap.
Joga um ValueError em caso de underflow.
"""
if self.heap_size < 1:
raise ValueError('underflow')
maior = self.lista[0]
self.lista[0] = self.lista[self.heap_size - 1]
self.heap_size -= 1
self.max_heapify(0)
return maior
def inserir(self, chave):
""" Insere o valor da chave no max-heap.
"""
self.heap_size += 1
if len(self.lista) < self.heap_size:
self.lista.append(chave)
else:
self.lista[self.heap_size - 1] = chave
i = self.heap_size - 1
while i > 0 and self.lista[MaxHeap.pai(i)] < chave:
self.lista[i] = self.lista[MaxHeap.pai(i)]
self.lista[MaxHeap.pai(i)] = chave
i = MaxHeap.pai(i)
|
CONTAINERS_DISCOVERY_LOCK_KEY = 'containers_discovery.lock'
CONTAINERS_DISCOVERY_LAST_UPDATE_KEY = 'containers_discovery.last_update'
CONTAINERS_DISCOVERY_DATA_KEY = 'containers_discovery.data'
RESOURCES_DISCOVERY_LOCK_KEY = 'resources_discovery.lock'
RESOURCES_DISCOVERY_LAST_UPDATE_KEY = 'resources_discovery.last_update'
RESOURCES_DISCOVERY_DATA_KEY = 'resources_discovery.data'
|
def assert_revision(revision, author=None, message=None):
"""Asserts values of the given fields in the provided revision.
:param revision: The revision to validate
:param author: that must be present in the ``revision``
:param message: message substring that must be present in ``revision``
"""
if author:
assert author == revision.author
if message:
assert message in revision.message
|
class ScraperFactoryException(Exception):
pass
class SpiderNotFoundError(ScraperFactoryException):
pass
class InvalidUrlError(ScraperFactoryException):
pass
|
"""Functions for calculating biomass from TCH of canopy height models"""
def longo2016_acd(top_of_canopy_height: float) -> float:
"""
Convert `top_of_canopy_height` (tch) to biomass according to
the formula in Longo et al. 2016.
Source:
https://agupubs.onlinelibrary.wiley.com/action/downloadSupplement?
doi=10.1002%2F2016GB005465&file=gbc20478-sup-0001-supplementary.pdf
Note:
The original formula is in units of kgC/m2. We therefore
multiply the result by 10 to get the ACD values in MgC/ha
Args:
top_of_canopy_height (float): Top of canopy height in meters
(meant to work with mean TCH at 50x50m resolution as that
is what was used in the creation of the formula)
Returns:
float: Above ground carbon density in MgC/ha.
"""
# Note: ACD units are in MgC/ha (hence multiplication by 10). To get units in
# kgC/ha, remove multiplication by 10
return 10 * 0.054 * top_of_canopy_height ** 1.76
def asner2014_acd(top_of_canopy_height: float) -> float:
"""
Convert `top_of_canopy_height` (tch) to biomass according to
the general ACD formula in Asner & Mascaro 2014.
Source:
https://www.sciencedirect.com/science/article/pii/S003442571300360X
Args:
top_of_canopy_height (float): Top of canopy height in meters
(meant to work with mean TCH at 50x50m resolution as that
is what was used in the creation of the formula)
Returns:
float: Above ground carbon density in MgC/ha.
"""
# Note: native ACD unit of formula is MgC/ha. To convert to
# kgC/m2, divide by 10.
return 6.8500 * top_of_canopy_height ** 0.9520
def asner2014_colombia_acd(top_of_canopy_height: float) -> float:
"""
Convert `top_of_canopy_height` (tch) to biomass according to
the Colombia ACD formula in Asner & Mascaro 2014.
Source:
https://www.sciencedirect.com/science/article/pii/S003442571300360X
Args:
top_of_canopy_height (float): Top of canopy height in meters
(meant to work with mean TCH at 50x50m resolution as that
is what was used in the creation of the formula)
Returns:
float: Above ground carbon density in MgC/ha.
"""
# Note: native ACD unit of formula is MgC/ha. To convert to
# kgC/m2, divide by 10.
return 2.1011 * top_of_canopy_height ** 1.2682
|
class Solution:
def findRelativeRanks(self, score: List[int]) -> List[str]:
sorted_score = sorted(score,reverse=True)
rankings = {}
for i in range(len(sorted_score)):
if i == 0: rankings[sorted_score[i]] = 'Gold Medal'
elif i == 1: rankings[sorted_score[i]] = 'Silver Medal'
elif i == 2: rankings[sorted_score[i]] = 'Bronze Medal'
else: rankings[sorted_score[i]] = str(i+1)
return [rankings[points] for points in score]
|
""" Utility routines for handling control file contents."""
def cfg_string_to_list(input_string):
""" Convert a string containing items separated by commas into a list."""
if "," in input_string:
output_list = input_string.split(",")
else:
output_list = [input_string]
return output_list
|
for j in range(1, 9):
for i in range(1,j+1):
print("%d * %d = %d" % (i,j,i*j),end="\t")
print()
|
# Relationship instance name
JSON_RELATIONSHIP_INTERACT_WITH = "interaction"
JSON_RUN_TIME = "runtime"
JSON_DEPLOYMENT_TIME = "deploymenttime"
JSON_NODE_DATABASE = "datastore"
JSON_NODE_SERVICE= "service"
JSON_NODE_MESSAGE_BROKER = "messagebroker"
JSON_NODE_MESSAGE_ROUTER = "messagerouter"
JSON_NODE_MESSAGE_ROUTER_KSERVICE = "kservice"
JSON_NODE_MESSAGE_ROUTER_KPROXY = "kproxy"
JSON_NODE_MESSAGE_ROUTER_KINGRESS = "kingress"
JSON_GROUPS_EDGE = "edgegroup"
JSON_GROUPS_TEAM = "squadgroup"
|
""" Sorting algorithms """
def insert_sort(list_num):
""" Insertion sort
Start from second element
Save it alongside with it's index
Run from previous element to first one
While checking if value should be moved
In the end, put saved value after last moved index
"""
for i in range(1, len(list_num)):
value = list_num[i]
j = i - 1
while (j >= 0) and (list_num[j] > value):
list_num[j+1] = list_num[j]
j -= 1
list_num[j+1] = value
|
kilometer = float(input('Digite quantos KM você irá percorrer: '))
price_gas = float(input('Digite o preço da gasolina na sua região: R$'))
cars_consumption = [5, 6, 7, 8, 9, 10, 11, 12, 13]
for i in range(9):
total = (kilometer/cars_consumption[i])*price_gas
print(f'Se seu carro tem a autonomia de {cars_consumption[i]}km por litro, você vai gastar R${total:.2f}')
|
'''
06 - Binning data
When the data on the x axis is a continuous value, it can
be useful to break it into different bins in order to get
a better visualization of the changes in the data.
For this exercise, we will look at the relationship between
tuition and the Undergraduate population abbreviated as UG in
this data. We will start by looking at a scatter plot of the
data and examining the impact of different bin sizes on the
visualization.
'''
# 1 - Create a regplot of Tuition and UG and set the fit_reg parameter to False to disable the regression line.
sns.regplot(data=df,
y='Tuition',
x="UG",
fit_reg=False)
plt.show()
plt.clf()
# 2 - Create another plot with the UG data divided into 5 bins.
sns.regplot(data=df,
y='Tuition',
x="UG",
x_bins=5)
plt.show()
plt.clf()
# 3 - Create a regplot() with the data divided into 8 bins.
sns.regplot(data=df,
y='Tuition',
x="UG",
x_bins=8)
plt.show()
plt.clf()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.