content
stringlengths 7
1.05M
|
---|
MODEL_FOLDER_NAME = 'models'
FASTTEXT_MODEL_NAME = 'fasttext.magnitude'
GLOVE_MODEL_NAME = 'glove.magnitude'
WORD2VEC_MODEL_NAME = 'word2vec.magnitude'
ELMO_MODEL_NAME = 'elmo.magnitude'
BERT_MODEL_NAME = ''
UNIVERSAL_SENTENCE_ENCODER_MODEL_NAME = 'https://tfhub.dev/google/universal-sentence-encoder/1'
DB_STORAGE_TYPE = 'db'
QUEUE_STORAGE_TYPE = 'queue'
INMEMORY_STORAGE_TYPE = 'inmemory'
LOG_FILE_PATH = 'C:\\Users\\rupachak\\Documents\\Github\\IterativeQueryAugment\\logs\\app.log' # Replace your log file path here
|
def CHECK(UNI, PWI, usernameArray, PasswordArray):
for UN in usernameArray:
if UN == UNI:
for PW in PasswordArray:
if PW == PWI:
if usernameArray.index(UNI) == PasswordArray.index(PWI):
return True
def login(correctMessage, inCorrectMessage, usernameInputPrompt, passwordInputPrompt, usernameArray, PasswordArray):
if CHECK(input(usernameInputPrompt), input(passwordInputPrompt), usernameArray, PasswordArray):
print(correctMessage)
return True
else:
print(inCorrectMessage)
|
m = [
'common',
'leap'
]
y = 2024
# outside in
if y%4 ==0:
if y%100 ==0:
if y%400 ==0:
y=1
else:
y=0
else:
y=1
else:
y=0
print(m[y])
# inside out
y=2024
if y%400==0:
y=1
elif y%100==0:
y=0
elif y%4==0:
y=1
else:
y=0
print(m[y])
# from the middle
y=2024
if y%100==0:
if y%400==0:
y=1
else:
y=0
elif y%4==0:
y=1
else:
y=0
print(m[y])
# logical aggregation
# put all the logical condition together
y = 2024
if (y%4 == 0 and y%100 != 0) or y%400==0:
y = 1
else:
y = 0
print(m[y])
########## CODING GOLF ?!
# one-liners
y = 2024
print(['common','leap'][y%4==0 and y%100!=0 or y%400==0])
|
def create_markdown_content(
input_file: str,
import_list: list[str],
global_import_table: dict[str,str],
mermaid_diagrams: list[str],
debug_dump: str,
) -> str:
debug_block = create_markdown_debug_dump_block(debug_content=debug_dump)
import_block = turn_out_the_import_list(
import_list=import_list, global_import_table=global_import_table
)
mermaid_blocks = "\n".join(mermaid_diagrams)
return (
f"# {input_file}\n\n"
f"{import_block}\n"
"---\n"
f"{mermaid_blocks}"
"---\n"
"\n"
f"{debug_block}\n"
)
def turn_out_the_import_list(
import_list: list[str], global_import_table: dict[str,str]
) -> str:
list_str = "### Imports\n\n"
for import_item in import_list:
url = global_import_table[import_item]
if url:
list_str += f" - [{import_item}]({url})\n"
else:
list_str += f" - {import_item}\n"
return list_str
def create_markdown_debug_dump_block(debug_content: str) -> str:
return (
"<details>\n"
"<summary>Debug AST model dump</summary>\n\n"
"```\n"
f"{debug_content}\n"
"```\n"
"</details>\n"
)
|
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
# pylint: disable=line-too-long
# pylint: disable=too-many-lines
def maintenance_public_configuration_list(client):
return client.list()
def maintenance_public_configuration_show(client,
resource_name):
return client.get(resource_name=resource_name)
def maintenance_applyupdate_show(client,
resource_group_name,
provider_name,
resource_type,
resource_name,
apply_update_name):
return client.get(resource_group_name=resource_group_name,
provider_name=provider_name,
resource_type=resource_type,
resource_name=resource_name,
apply_update_name=apply_update_name)
def maintenance_applyupdate_create(client,
resource_group_name,
provider_name,
resource_type,
resource_name,
resource_parent_type=None,
resource_parent_name=None):
if resource_group_name and all(v is not None for v in [provider_name, resource_parent_type, resource_parent_name, resource_type, resource_name]):
return client.create_or_update_parent(resource_group_name=resource_group_name,
provider_name=provider_name,
resource_parent_type=resource_parent_type,
resource_parent_name=resource_parent_name,
resource_type=resource_type,
resource_name=resource_name)
return client.create_or_update(resource_group_name=resource_group_name,
provider_name=provider_name,
resource_type=resource_type,
resource_name=resource_name)
def maintenance_applyupdate_update(client,
resource_group_name,
provider_name,
resource_type,
resource_name):
return client.create_or_update(resource_group_name=resource_group_name,
provider_name=provider_name,
resource_type=resource_type,
resource_name=resource_name)
def maintenance_applyupdate_get_parent(client,
resource_group_name,
resource_parent_type,
resource_parent_name,
provider_name,
resource_type,
resource_name,
apply_update_name):
return client.get_parent(resource_group_name=resource_group_name,
resource_parent_type=resource_parent_type,
resource_parent_name=resource_parent_name,
provider_name=provider_name,
resource_type=resource_type,
resource_name=resource_name,
apply_update_name=apply_update_name)
def maintenance_assignment_list(client,
resource_group_name,
provider_name,
resource_type,
resource_name):
return client.list(resource_group_name=resource_group_name,
provider_name=provider_name,
resource_type=resource_type,
resource_name=resource_name)
def maintenance_assignment_create(client,
resource_group_name,
provider_name,
resource_type,
resource_name,
configuration_assignment_name,
resource_parent_type=None,
resource_parent_name=None,
location=None,
maintenance_configuration_id=None,
resource_id=None):
if resource_group_name and all(v is not None for v in [provider_name, resource_parent_type, resource_parent_name, resource_type, resource_name, configuration_assignment_name]):
return client.create_or_update_parent(resource_group_name=resource_group_name,
provider_name=provider_name,
resource_parent_type=resource_parent_type,
resource_parent_name=resource_parent_name,
resource_type=resource_type,
resource_name=resource_name,
configuration_assignment_name=configuration_assignment_name,
location=location,
maintenance_configuration_id=maintenance_configuration_id,
resource_id=resource_id)
return client.create_or_update(resource_group_name=resource_group_name,
provider_name=provider_name,
resource_type=resource_type,
resource_name=resource_name,
configuration_assignment_name=configuration_assignment_name,
location=location,
maintenance_configuration_id=maintenance_configuration_id,
resource_id=resource_id)
def maintenance_assignment_update(client,
resource_group_name,
provider_name,
resource_type,
resource_name,
configuration_assignment_name,
location=None,
maintenance_configuration_id=None,
resource_id=None):
return client.create_or_update(resource_group_name=resource_group_name,
provider_name=provider_name,
resource_type=resource_type,
resource_name=resource_name,
configuration_assignment_name=configuration_assignment_name,
location=location,
maintenance_configuration_id=maintenance_configuration_id,
resource_id=resource_id)
def maintenance_assignment_delete(client,
resource_group_name,
provider_name,
resource_type,
resource_name,
configuration_assignment_name,
resource_parent_type=None,
resource_parent_name=None):
if resource_group_name and all(v is not None for v in [provider_name, resource_parent_type, resource_parent_name, resource_type, resource_name, configuration_assignment_name]):
return client.delete_parent(resource_group_name=resource_group_name,
provider_name=provider_name,
resource_parent_type=resource_parent_type,
resource_parent_name=resource_parent_name,
resource_type=resource_type,
resource_name=resource_name,
configuration_assignment_name=configuration_assignment_name)
return client.delete(resource_group_name=resource_group_name,
provider_name=provider_name,
resource_type=resource_type,
resource_name=resource_name,
configuration_assignment_name=configuration_assignment_name)
def maintenance_assignment_list_parent(client,
resource_group_name,
provider_name,
resource_parent_type,
resource_parent_name,
resource_type,
resource_name):
return client.list_parent(resource_group_name=resource_group_name,
provider_name=provider_name,
resource_parent_type=resource_parent_type,
resource_parent_name=resource_parent_name,
resource_type=resource_type,
resource_name=resource_name)
def maintenance_configuration_list(client):
return client.list()
def maintenance_configuration_show(client,
resource_group_name,
resource_name):
return client.get(resource_group_name=resource_group_name,
resource_name=resource_name)
def maintenance_configuration_create(client,
resource_group_name,
resource_name,
location=None,
tags=None,
namespace=None,
extension_properties=None,
maintenance_scope=None,
visibility=None,
maintenance_window_start_date_time=None,
maintenance_window_expiration_date_time=None,
maintenance_window_duration=None,
maintenance_window_time_zone=None,
maintenance_window_recur_every=None):
return client.create_or_update(resource_group_name=resource_group_name,
resource_name=resource_name,
location=location,
tags=tags,
namespace=namespace,
extension_properties=extension_properties,
maintenance_scope=maintenance_scope,
visibility=visibility,
start_date_time=maintenance_window_start_date_time,
expiration_date_time=maintenance_window_expiration_date_time,
duration=maintenance_window_duration,
time_zone=maintenance_window_time_zone,
recur_every=maintenance_window_recur_every)
def maintenance_configuration_update(client,
resource_group_name,
resource_name,
location=None,
tags=None,
namespace=None,
extension_properties=None,
maintenance_scope=None,
visibility=None,
maintenance_window_start_date_time=None,
maintenance_window_expiration_date_time=None,
maintenance_window_duration=None,
maintenance_window_time_zone=None,
maintenance_window_recur_every=None):
return client.update(resource_group_name=resource_group_name,
resource_name=resource_name,
location=location,
tags=tags,
namespace=namespace,
extension_properties=extension_properties,
maintenance_scope=maintenance_scope,
visibility=visibility,
start_date_time=maintenance_window_start_date_time,
expiration_date_time=maintenance_window_expiration_date_time,
duration=maintenance_window_duration,
time_zone=maintenance_window_time_zone,
recur_every=maintenance_window_recur_every)
def maintenance_configuration_delete(client,
resource_group_name,
resource_name):
return client.delete(resource_group_name=resource_group_name,
resource_name=resource_name)
def maintenance_update_list(client,
resource_group_name,
provider_name,
resource_type,
resource_name):
return client.list(resource_group_name=resource_group_name,
provider_name=provider_name,
resource_type=resource_type,
resource_name=resource_name)
def maintenance_update_list_parent(client,
resource_group_name,
provider_name,
resource_parent_type,
resource_parent_name,
resource_type,
resource_name):
return client.list_parent(resource_group_name=resource_group_name,
provider_name=provider_name,
resource_parent_type=resource_parent_type,
resource_parent_name=resource_parent_name,
resource_type=resource_type,
resource_name=resource_name)
|
class Stack:
"""Klasa stosu używana do tworzenia labiryntu"""
def __init__(self):
self.__st = []
def push(self, val_1, val_2):
self.__st.append((val_1, val_2))
def pop(self):
if len(self.__st) != 0:
return self.__st.pop()
else:
return [-1]
def clear(self):
self.__st = []
def size(self):
return len(self.__st)
def __str__(self):
str = ""
for i in self.__st:
str += "({0} , {1}), ".format(i[0], i[1])
str += "\n"
return str
|
'''4.Faça um programa que leia uma palavra e some 1 no valor ASCII de cada caractere da
palavra. Imprima a string resultante.'''
sermo = list(input("Digite uma palavra:"))
for i,p in enumerate(sermo):
sermo[i] = chr((ord(p))+1)
sermo = "".join(sermo)
print(f"Nova string: {sermo}")
|
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
class ADOConstants:
"""
Constants specific to Azure Devops API clients and classes
"""
work_item_relations = {
'parent': 'System.LinkTypes.Hierarchy-Reverse',
'child': 'System.LinkTypes.Hierarchy-Forward'
}
|
class Solution:
def subarraySum(self, nums: List[int], k: int) -> int:
cum_sum = [0]
for num in nums:
cum_sum.append(num+cum_sum[-1])
cum_sum.pop(0)
seen_map = {0:1}
ans = 0
for csum in cum_sum:
if csum-k in seen_map:
ans+=seen_map[csum-k]
seen_map[csum] = seen_map.get(csum,0)+1
return ans
|
height = float(input("Please enter the height in m: \n"))
weight = float(input("Please enter the weight in kg: \n"))
bmi = weight / height ** 2
print(int(bmi))
|
#The file contains only the CTC function and the proposed model format. (Not the complete code)
def ctc_lambda_func(args):
y_pred, labels, input_length, label_length = args
y_pred = y_pred[:, 2:, :]
return K.ctc_batch_cost(labels, y_pred, input_length, label_length)
def train(img_w, load=False):
# Input Parameters
img_h = 64
# Network parameters
conv_filters = 16
kernel_size = (3, 3)
pool_size = 2
time_dense_size = 32
rnn_size = 512
if K.image_data_format() == 'channels_first':
input_shape = (1, img_w, img_h)
else:
input_shape = (img_w, img_h, 1)
batch_size = 32
downsample_factor = pool_size ** 2
tiger_train = TextImageGenerator('/data/anpr_ocr__train', 'train', img_w, img_h, batch_size, downsample_factor)
tiger_train.build_data()
tiger_val = TextImageGenerator('/data/anpr_ocr__train', 'val', img_w, img_h, batch_size, downsample_factor)
tiger_val.build_data()
act = 'relu'
input_data = Input(name='the_input', shape=input_shape, dtype='float32')
inner = Conv2D(conv_filters, kernel_size, padding='same',
activation=act, kernel_initializer='he_normal',
name='conv1')(input_data)
inner = MaxPooling2D(pool_size=(pool_size, pool_size), name='max1')(inner)
inner = Conv2D(conv_filters, kernel_size, padding='same',
activation=act, kernel_initializer='he_normal',
name='conv2')(inner)
inner = MaxPooling2D(pool_size=(pool_size, pool_size), name='max2')(inner)
conv_to_rnn_dims = (img_w // (pool_size ** 2), (img_h // (pool_size ** 2)) * conv_filters)
inner = Reshape(target_shape=conv_to_rnn_dims, name='reshape')(inner)
# cuts down input size going into RNN:
inner = Dense(time_dense_size, activation=act, name='dense1')(inner)
# Two layers of bidirecitonal GRUs
gru_1 = GRU(rnn_size, return_sequences=True, kernel_initializer='he_normal', name='gru1')(inner)
gru_1b = GRU(rnn_size, return_sequences=True, go_backwards=True, kernel_initializer='he_normal', name='gru1_b')(inner)
gru1_merged = add([gru_1, gru_1b])
gru_2 = GRU(rnn_size, return_sequences=True, kernel_initializer='he_normal', name='gru2')(gru1_merged)
gru_2b = GRU(rnn_size, return_sequences=True, go_backwards=True, kernel_initializer='he_normal', name='gru2_b')(gru1_merged)
# transforms RNN output to character activations:
inner = Dense(tiger_train.get_output_size(), kernel_initializer='he_normal',
name='dense2')(concatenate([gru_2, gru_2b]))
y_pred = Activation('softmax', name='softmax')(inner)
Model(inputs=input_data, outputs=y_pred).summary()
labels = Input(name='the_labels', shape=[tiger_train.max_text_len], dtype='float32')
input_length = Input(name='input_length', shape=[1], dtype='int64')
label_length = Input(name='label_length', shape=[1], dtype='int64')
# Keras doesn't currently support loss funcs with extra parameters
# so CTC loss is implemented in a lambda layer
loss_out = Lambda(ctc_lambda_func, output_shape=(1,), name='ctc')([y_pred, labels, input_length, label_length])
# clipnorm seems to speeds up convergence
sgd = SGD(lr=0.02, decay=1e-6, momentum=0.9, nesterov=True, clipnorm=5)
if load:
model = load_model('./tmp_model.h5', compile=False)
else:
model = Model(inputs=[input_data, labels, input_length, label_length], outputs=loss_out)
# the loss calc occurs elsewhere, so use a dummy lambda func for the loss
model.compile(loss={'ctc': lambda y_true, y_pred: y_pred}, optimizer=sgd)
if not load:
# captures output of softmax so we can decode the output during visualization
test_func = K.function([input_data], [y_pred])
model.fit_generator(generator=tiger_train.next_batch(),
steps_per_epoch=tiger_train.n,
epochs=1,
validation_data=tiger_val.next_batch(),
validation_steps=tiger_val.n)
return model
|
# -*- coding: utf-8 -*-
__title__ = 'ahegao'
__description__ = 'Ahegao API wrapper'
__url__ = 'https://github.com/AhegaoTeam/AhegaoAPI'
__version__ = '1.0.1'
__build__ = 11
__author__ = 'SantaSpeen'
__author_email__ = '[email protected]'
__license__ = "MIT"
__copyright__ = 'Copyright 2022 Ahegao Team'
|
# design in each module
class Cube(object):
def __init__(self):
pass
class Rhombic(object):
def __init__(self):
pass
class Sphere(object):
def __init__(self):
pass
|
# write a program to print out all the numbers from 0 to 100 that are divisble by 7
for i in range(0, 101, 7):
print(i)
|
class Solution:
def solve(self, matrix):
pq = [[0, i] for i in range(len(matrix[0]))]
for r in range(len(matrix)):
new_pq = []
for c in range(len(matrix[0])):
if pq[0][1] == c:
top = heappop(pq)
heappush(new_pq, [pq[0][0]+matrix[r][c], c])
heappush(pq, top)
else:
heappush(new_pq, [pq[0][0]+matrix[r][c], c])
pq = new_pq
return pq[0][0]
|
def rotate(text, key):
num_letters = 26
key = key % num_letters
l_min = ord('a')
u_min = ord('A')
text = list(
map((lambda s:
s if not s.isalpha()
else chr(l_min + (((ord(s) - l_min) + key) % num_letters))
if s.islower()
else chr(u_min + (((ord(s) - u_min) + key) % num_letters))),
list(text)))
return ''.join(text)
|
# coding: utf-8
def sumSquare(n):
'''takes a positive integer n and returns sum of dquares of all the positive integers smaller than n'''
if n < 0:
return 'Needs a positive number. But Negative given'
else:
return sum([x**2 for x in range(1, n)])
print(sumSquare(4))
|
#test = []
#test.append('Gustavo')
#test.append(40)
#guys = []
#guys.append(test[:])
#test[0] = 'Maria'
#test[1] = 22
#print(test, guys[0][1])
galera = list()
dado = []
for c in range(0, 5):
dado.append(str(input('Qual é o seu nome? ')))
dado. append(int(input('Qual é a sua idade?')))
galera.append(dado[:])
dado.clear()
for pessoa in galera:
print(f'{pessoa[0]} tem {pessoa[1]} anos de idade.')
|
#
# @lc app=leetcode id=327 lang=python3
#
# [327] Count of Range Sum
#
# https://leetcode.com/problems/count-of-range-sum/description/
#
# algorithms
# Hard (35.94%)
# Likes: 995
# Dislikes: 116
# Total Accepted: 48.9K
# Total Submissions: 135.4K
# Testcase Example: '[-2,5,-1]\n-2\n2'
#
# Given an integer array nums and two integers lower and upper, return the
# number of range sums that lie in [lower, upper] inclusive.
#
# Range sum S(i, j) is defined as the sum of the elements in nums between
# indices i and j inclusive, where i <= j.
#
#
# Example 1:
#
#
# Input: nums = [-2,5,-1], lower = -2, upper = 2
# Output: 3
# Explanation: The three ranges are: [0,0], [2,2], and [0,2] and their
# respective sums are: -2, -1, 2.
#
#
# Example 2:
#
#
# Input: nums = [0], lower = 0, upper = 0
# Output: 1
#
#
#
# Constraints:
#
#
# 1 <= nums.length <= 10^4
# -2^31 <= nums[i] <= 2^31 - 1
# -3 * 10^4 <= lower <= upper <= 3 * 10^4
#
#
#
# Follow up: A naive algorithm of O(n^2) is trivial, Could you do better than
# that?
#
# @lc code=start
class Solution:
def __init__(self):
self.prefix_sum = [0]
self.count = 0
def countRangeSum(self, nums: List[int], lower: int, upper: int) -> int:
running_sum = 0
for i in range(len(nums)):
running_sum += nums[i]
self.prefix_sum.append(running_sum)
self.helper(0, len(nums), lower, upper)
return self.count
def helper(self, start, end, lower, upper):
# sum(i, j) in [lower, upper]
# prefix_sum[j] - prefix_sum[i] >= lower
# prefix_sum[j] - prefix_sum[i] <= upper
# prefix_sum[j] >= prefix_sum[i] + lower
# prefix_sum[j] <= prefix_sum[i] + upper
if start >= end:
return
mid = start + (end - start) // 2
self.helper(start, mid, lower, upper)
self.helper(mid + 1, end, lower, upper)
for i in range(start, mid + 1):
left = bisect_left(self.prefix_sum[mid + 1: end + 1], self.prefix_sum[i] + lower)
right = bisect_right(self.prefix_sum[mid + 1: end + 1], self.prefix_sum[i] + upper)
self.count += right - left
# merge sort
i, j = start, mid + 1
tmp = []
while i <= mid and j <= end:
if self.prefix_sum[i] <= self.prefix_sum[j]:
tmp.append(self.prefix_sum[i])
i += 1
else:
tmp.append(self.prefix_sum[j])
j += 1
if i <= mid:
tmp.extend(self.prefix_sum[i:])
if j <= end:
tmp.extend(self.prefix_sum[j:])
for i in range(end - start + 1):
self.prefix_sum[start + i] = tmp[i]
# @lc code=end
|
# Author: btjanaka (Bryon Tjanaka)
# Problem: (HackerRank) the-minion-game
# Title: The Minion Game
# Link: https://www.hackerrank.com/challenges/the-minion-game/
# Idea: The basic idea is to count all substrings for each player, but we can't
# just list out all the substrings because that is O(n^2), and the string can be
# of length 10^6 here. A more efficient way is to recognize that there are
# len(string) - i substrings that start at any index i (0-based), so if the
# character at index i is a vowel, we count len(string) - i additional
# substrings that start with vowels.
# Difficulty: Medium
# Tags: list, math, string
def minion_game(string):
consonants = 0
vowels = 0
for i in range(len(string)):
score = len(string) - i
if string[i] in "AEIOU":
vowels += score
else:
consonants += score
if consonants > vowels:
print(f"Stuart {consonants}")
elif consonants < vowels:
print(f"Kevin {vowels}")
else:
print("Draw")
if __name__ == '__main__':
s = input()
minion_game(s)
|
class LevenshteinCostCalculator:
"""
Cost calculator using Levenshtein minimum edit distance costs of 1 for insertion and deletion and 2 for substitution
(given a letter is not substituted for itself).
Can also be used as a basic cost calculator for non-letter inputs.
"""
def insertion_cost(self, letter):
"""
Returns cost of inserting a given letter (or other item)
:param letter: the letter to be inserted
:return: constant cost of 1 for any letter
"""
return 1
def deletion_cost(self, letter):
"""
Returns cost of deleting a given letter (or other item)
:param letter: the letter to be deleted
:return: constant cost of 2 for any letter
"""
return 1
def substitution_cost(self, letter1, letter2):
"""
Returns cost of substituting one letter (or other item) for another
:param letter1: letter to be substituted
:param letter2: letter to substitute with
:return: constant cost of 2 if the letters are different, 0 otherwise (equivalent to an insertion + deletion)
"""
return 0 if letter1 == letter2 else 2
|
class APIException(OSError):
def __init__(self, message = None, url="https://Bungie.net/"):
msg = "There was an error when accessing the Destiny API"
if message is not None:
msg += ": " + message
super().__init__(msg)
self._url = url
self._message = msg
@property
def url(self):
return self._url
@property
def message(self):
return self._message
class GeneralException(Exception):
def __init__(self, message):
super().__init__(message)
class ManifestError(IOError):
def __init__(self, message, SQL=None):
super().__init__(message)
self._SQL = SQL
@property
def SQL(self):
return self._SQL
|
IN_PREFIXES = {
'BA',
'BS',
'BUS MS',
'Certificate',
'Graduate Certificate',
'MA',
'Master of Arts',
'Master\'s',
'MBA/MA',
'ME Certificate',
'ME MD/PhD Program',
'ME Program',
'MS',
'P.B.C.',
'Post Bacc Certificate',
'Post Baccalaureate Certificate',
'Post Master\'s Cert',
'Post-Baccalaureate Certificate',
'Post-Masters Certificate'
}
# the order of this list matters!
# the algorithm removes the *first* matching prefix, so if "MBA" appears before
# "MBA Global", for example, then the major "MBA Global Finance" will become
# "Global Finance" and not "Finance"
SPACE_PREFIXES = [
'BS',
'BUS MBA Global -',
'BUS MBA',
'DRPH-PT,',
'EDU M.Ed.',
'EDU MS',
'EDU PMC',
'EN',
'GC',
'MA',
'MBA Global -',
'MBA',
'MBA/MPH',
'ME MA',
'ME MS',
'ME PhD',
'MED',
'ME',
'MPH,',
'MPH/MSW,',
'MPH-PTIB,',
'MPH-RES,',
'MS,',
'MS'
]
|
class Disc:
_instance_count = 0
def __init__(self, name, symbol, code=None):
cls = type(self)
self.code = cls._instance_count if code is None else code
self.name = name
self.symbol = symbol
cls._instance_count += 1 if cls._instance_count < 1000 else 0
def __int__(self):
return self.code
def __repr__(self):
return f'<Disc {self.name!r}, {self.symbol!r}>'
|
# Problem 1
# Multiples of 3 and 5
# If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9.
# The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000.
count = 0
for x in range(1000):
if (not x % 3) or (not x % 5):
count += x
# Альтернативное решение через список
count = sum([x for x in range(1000) if (not x % 3) or (not x % 5)])
|
def list_towers():
raise NotImplementedError
def create_tower(body):
raise NotImplementedError
def get_tower(tower_id):
raise NotImplementedError
def update_tower(tower_id, body):
raise NotImplementedError
def delete_tower(tower_id):
raise NotImplementedError
|
# sample input
array = [ 2, 1, 2, 2, 2, 3, 4, 2 ]
to_move = 2
expected = [4, 1, 3, 2, 2, 2, 2, 2]
# Simple testing function
def test(expected, actual):
if expected == actual:
print('Working')
else:
print('Not working, expected:', expected, 'actual:', actual)
# O(n) solution
def move_element_to_end(array, toMove):
i = 0
swap = len(array) - 1
while i < swap:
while i < swap and array[swap] == toMove:
swap -=1
if array[i] == toMove:
array[i], array[swap] = array[swap], array[i]
i += 1
return array
test(expected, move_element_to_end(array, to_move))
|
#
# @lc app=leetcode.cn id=72 lang=python3
#
# [72] edit-distance
#
None
# @lc code=end
|
"""
Update Index
"""
name = "02_upgrade_users_unique_email"
dependencies = ["01_upgrade_users"]
def upgrade(db):
db.users.create_index([('email', 1)], unique=True)
def downgrade(db):
pass
|
#
# PySNMP MIB module HM2-NETCONFIG-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HM2-NETCONFIG-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:19:02 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
ObjectIdentifier, OctetString, Integer = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "OctetString", "Integer")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsUnion, SingleValueConstraint, ValueSizeConstraint, ValueRangeConstraint, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "SingleValueConstraint", "ValueSizeConstraint", "ValueRangeConstraint", "ConstraintsIntersection")
HmEnabledStatus, hm2ConfigurationMibs = mibBuilder.importSymbols("HM2-TC-MIB", "HmEnabledStatus", "hm2ConfigurationMibs")
ifIndex, InterfaceIndex = mibBuilder.importSymbols("IF-MIB", "ifIndex", "InterfaceIndex")
InetAddress, InetAddressType, InetAddressPrefixLength = mibBuilder.importSymbols("INET-ADDRESS-MIB", "InetAddress", "InetAddressType", "InetAddressPrefixLength")
TimeFilter, = mibBuilder.importSymbols("RMON2-MIB", "TimeFilter")
NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance")
Counter64, Unsigned32, Bits, MibScalar, MibTable, MibTableRow, MibTableColumn, Counter32, MibIdentifier, ModuleIdentity, Gauge32, TimeTicks, iso, Integer32, ObjectIdentity, NotificationType, IpAddress = mibBuilder.importSymbols("SNMPv2-SMI", "Counter64", "Unsigned32", "Bits", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Counter32", "MibIdentifier", "ModuleIdentity", "Gauge32", "TimeTicks", "iso", "Integer32", "ObjectIdentity", "NotificationType", "IpAddress")
MacAddress, TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "MacAddress", "TextualConvention", "DisplayString")
hm2NetConfigMib = ModuleIdentity((1, 3, 6, 1, 4, 1, 248, 11, 20))
hm2NetConfigMib.setRevisions(('2011-03-16 00:00',))
if mibBuilder.loadTexts: hm2NetConfigMib.setLastUpdated('201103160000Z')
if mibBuilder.loadTexts: hm2NetConfigMib.setOrganization('Hirschmann Automation and Control GmbH')
hm2NetConfigMibNotifications = MibIdentifier((1, 3, 6, 1, 4, 1, 248, 11, 20, 0))
hm2NetConfigMibObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 248, 11, 20, 1))
hm2NetStaticGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 248, 11, 20, 1, 1))
hm2NetACDGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 248, 11, 20, 1, 2))
hm2NetMacGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 248, 11, 20, 1, 3))
hm2NetHiDiscoveryGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 248, 11, 20, 1, 4))
hm2NetMacACDGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 248, 11, 20, 1, 5))
hm2NetOobMgmtGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 248, 11, 20, 1, 6))
hm2NetConfigProtocol = MibScalar((1, 3, 6, 1, 4, 1, 248, 11, 20, 1, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("none", 1), ("bootp", 2), ("dhcp", 3))).clone('dhcp')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hm2NetConfigProtocol.setStatus('current')
hm2NetLocalIPAddrType = MibScalar((1, 3, 6, 1, 4, 1, 248, 11, 20, 1, 1, 2), InetAddressType().clone('ipv4')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hm2NetLocalIPAddrType.setStatus('current')
hm2NetLocalIPAddr = MibScalar((1, 3, 6, 1, 4, 1, 248, 11, 20, 1, 1, 3), InetAddress().clone(hexValue="00000000")).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hm2NetLocalIPAddr.setStatus('current')
hm2NetPrefixLength = MibScalar((1, 3, 6, 1, 4, 1, 248, 11, 20, 1, 1, 4), InetAddressPrefixLength()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hm2NetPrefixLength.setStatus('current')
hm2NetGatewayIPAddrType = MibScalar((1, 3, 6, 1, 4, 1, 248, 11, 20, 1, 1, 5), InetAddressType().clone('ipv4')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hm2NetGatewayIPAddrType.setStatus('current')
hm2NetGatewayIPAddr = MibScalar((1, 3, 6, 1, 4, 1, 248, 11, 20, 1, 1, 6), InetAddress().clone(hexValue="00000000")).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hm2NetGatewayIPAddr.setStatus('current')
hm2NetVlanID = MibScalar((1, 3, 6, 1, 4, 1, 248, 11, 20, 1, 1, 7), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4042)).clone(1)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hm2NetVlanID.setStatus('current')
hm2NetVlanPriority = MibScalar((1, 3, 6, 1, 4, 1, 248, 11, 20, 1, 1, 8), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 7))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hm2NetVlanPriority.setStatus('current')
hm2NetIpDscpPriority = MibScalar((1, 3, 6, 1, 4, 1, 248, 11, 20, 1, 1, 9), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 63))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hm2NetIpDscpPriority.setStatus('current')
hm2NetMgmtPort = MibScalar((1, 3, 6, 1, 4, 1, 248, 11, 20, 1, 1, 10), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hm2NetMgmtPort.setStatus('current')
hm2NetDHCPClientId = MibScalar((1, 3, 6, 1, 4, 1, 248, 11, 20, 1, 1, 11), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: hm2NetDHCPClientId.setStatus('current')
hm2NetAction = MibScalar((1, 3, 6, 1, 4, 1, 248, 11, 20, 1, 1, 50), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("other", 1), ("activate", 2))).clone('other')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hm2NetAction.setStatus('current')
hm2NetACDStatus = MibScalar((1, 3, 6, 1, 4, 1, 248, 11, 20, 1, 2, 1), HmEnabledStatus().clone('enable')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hm2NetACDStatus.setStatus('current')
hm2NetACDDetectionMode = MibScalar((1, 3, 6, 1, 4, 1, 248, 11, 20, 1, 2, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("activeAndPassive", 1), ("activeDetectionOnly", 2), ("passiveDetectionOnly", 3))).clone('activeAndPassive')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hm2NetACDDetectionMode.setStatus('current')
hm2NetACDOngoingProbeStatus = MibScalar((1, 3, 6, 1, 4, 1, 248, 11, 20, 1, 2, 3), HmEnabledStatus().clone('enable')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hm2NetACDOngoingProbeStatus.setStatus('current')
hm2NetACDDelay = MibScalar((1, 3, 6, 1, 4, 1, 248, 11, 20, 1, 2, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(20, 500)).clone(200)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hm2NetACDDelay.setStatus('current')
hm2NetACDReleaseDelay = MibScalar((1, 3, 6, 1, 4, 1, 248, 11, 20, 1, 2, 7), Integer32().subtype(subtypeSpec=ValueRangeConstraint(3, 3600)).clone(15)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hm2NetACDReleaseDelay.setStatus('current')
hm2NetACDMaxProtection = MibScalar((1, 3, 6, 1, 4, 1, 248, 11, 20, 1, 2, 9), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 100)).clone(1)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hm2NetACDMaxProtection.setStatus('current')
hm2NetACDProtectInterval = MibScalar((1, 3, 6, 1, 4, 1, 248, 11, 20, 1, 2, 11), Integer32().subtype(subtypeSpec=ValueRangeConstraint(20, 10000)).clone(10000)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hm2NetACDProtectInterval.setStatus('current')
hm2NetACDFaultState = MibScalar((1, 3, 6, 1, 4, 1, 248, 11, 20, 1, 2, 13), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("true", 1), ("false", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: hm2NetACDFaultState.setStatus('current')
hm2NetACDTrapEnable = MibScalar((1, 3, 6, 1, 4, 1, 248, 11, 20, 1, 2, 15), HmEnabledStatus().clone('enable')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hm2NetACDTrapEnable.setStatus('current')
hm2NetACDAddrTable = MibTable((1, 3, 6, 1, 4, 1, 248, 11, 20, 1, 2, 20), )
if mibBuilder.loadTexts: hm2NetACDAddrTable.setStatus('current')
hm2NetACDAddrEntry = MibTableRow((1, 3, 6, 1, 4, 1, 248, 11, 20, 1, 2, 20, 1), ).setIndexNames((0, "HM2-NETCONFIG-MIB", "hm2NetACDTimeMark"))
if mibBuilder.loadTexts: hm2NetACDAddrEntry.setStatus('current')
hm2NetACDTimeMark = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 20, 1, 2, 20, 1, 1), TimeFilter()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hm2NetACDTimeMark.setStatus('current')
hm2NetACDAddrType = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 20, 1, 2, 20, 1, 3), InetAddressType()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hm2NetACDAddrType.setStatus('current')
hm2NetACDIPAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 20, 1, 2, 20, 1, 5), InetAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hm2NetACDIPAddr.setStatus('current')
hm2NetACDMAC = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 20, 1, 2, 20, 1, 7), MacAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hm2NetACDMAC.setStatus('current')
hm2NetACDifIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 20, 1, 2, 20, 1, 9), InterfaceIndex()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hm2NetACDifIndex.setStatus('current')
hm2NetLocalBurnedInMacAddr = MibScalar((1, 3, 6, 1, 4, 1, 248, 11, 20, 1, 3, 1), MacAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hm2NetLocalBurnedInMacAddr.setStatus('current')
hm2NetLocalAdminMacAddress = MibScalar((1, 3, 6, 1, 4, 1, 248, 11, 20, 1, 3, 2), MacAddress().clone(hexValue="000000000000")).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hm2NetLocalAdminMacAddress.setStatus('current')
hm2NetMacAddressType = MibScalar((1, 3, 6, 1, 4, 1, 248, 11, 20, 1, 3, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("burned-in", 1), ("local", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: hm2NetMacAddressType.setStatus('current')
hm2NetHiDiscoveryOperation = MibScalar((1, 3, 6, 1, 4, 1, 248, 11, 20, 1, 4, 1), HmEnabledStatus().clone('enable')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hm2NetHiDiscoveryOperation.setStatus('current')
hm2NetHiDiscoveryMode = MibScalar((1, 3, 6, 1, 4, 1, 248, 11, 20, 1, 4, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("readWrite", 1), ("readOnly", 2))).clone('readWrite')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hm2NetHiDiscoveryMode.setStatus('current')
hm2NetHiDiscoveryBlinking = MibScalar((1, 3, 6, 1, 4, 1, 248, 11, 20, 1, 4, 3), HmEnabledStatus().clone('disable')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hm2NetHiDiscoveryBlinking.setStatus('current')
hm2NetHiDiscoveryProtocol = MibScalar((1, 3, 6, 1, 4, 1, 248, 11, 20, 1, 4, 4), Bits().clone(namedValues=NamedValues(("none", 0), ("v1", 1), ("v2", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: hm2NetHiDiscoveryProtocol.setStatus('current')
hm2NetHiDiscoveryRelay = MibScalar((1, 3, 6, 1, 4, 1, 248, 11, 20, 1, 4, 5), HmEnabledStatus().clone('enable')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hm2NetHiDiscoveryRelay.setStatus('current')
hm2NetMacACDStatus = MibScalar((1, 3, 6, 1, 4, 1, 248, 11, 20, 1, 5, 1), HmEnabledStatus().clone('disable')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hm2NetMacACDStatus.setStatus('current')
hm2NetMacACDConflictAddress = MibScalar((1, 3, 6, 1, 4, 1, 248, 11, 20, 1, 5, 2), MacAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hm2NetMacACDConflictAddress.setStatus('current')
hm2NetACDNotification = NotificationType((1, 3, 6, 1, 4, 1, 248, 11, 20, 0, 1)).setObjects(("HM2-NETCONFIG-MIB", "hm2NetACDTimeMark"), ("HM2-NETCONFIG-MIB", "hm2NetACDAddrType"), ("HM2-NETCONFIG-MIB", "hm2NetACDIPAddr"), ("HM2-NETCONFIG-MIB", "hm2NetACDMAC"), ("HM2-NETCONFIG-MIB", "hm2NetACDifIndex"))
if mibBuilder.loadTexts: hm2NetACDNotification.setStatus('current')
hm2NetMacACDNotification = NotificationType((1, 3, 6, 1, 4, 1, 248, 11, 20, 0, 2)).setObjects(("IF-MIB", "ifIndex"), ("HM2-NETCONFIG-MIB", "hm2NetMacACDConflictAddress"))
if mibBuilder.loadTexts: hm2NetMacACDNotification.setStatus('current')
hm2NetOobMgmtAdminState = MibScalar((1, 3, 6, 1, 4, 1, 248, 11, 20, 1, 6, 1), HmEnabledStatus().clone('enable')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hm2NetOobMgmtAdminState.setStatus('current')
hm2NetOobMgmtProtocol = MibScalar((1, 3, 6, 1, 4, 1, 248, 11, 20, 1, 6, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("none", 1), ("bootp", 2), ("dhcp", 3))).clone('none')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hm2NetOobMgmtProtocol.setStatus('current')
hm2NetOobMgmtIPAddrType = MibScalar((1, 3, 6, 1, 4, 1, 248, 11, 20, 1, 6, 3), InetAddressType().clone('ipv4')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hm2NetOobMgmtIPAddrType.setStatus('current')
hm2NetOobMgmtIPAddr = MibScalar((1, 3, 6, 1, 4, 1, 248, 11, 20, 1, 6, 4), InetAddress().clone(hexValue="00000000")).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hm2NetOobMgmtIPAddr.setStatus('current')
hm2NetOobMgmtPrefixLength = MibScalar((1, 3, 6, 1, 4, 1, 248, 11, 20, 1, 6, 5), InetAddressPrefixLength()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hm2NetOobMgmtPrefixLength.setStatus('current')
hm2NetOobMgmtGatewayIPAddrType = MibScalar((1, 3, 6, 1, 4, 1, 248, 11, 20, 1, 6, 6), InetAddressType().clone('ipv4')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hm2NetOobMgmtGatewayIPAddrType.setStatus('current')
hm2NetOobMgmtGatewayIPAddr = MibScalar((1, 3, 6, 1, 4, 1, 248, 11, 20, 1, 6, 7), InetAddress().clone(hexValue="00000000")).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hm2NetOobMgmtGatewayIPAddr.setStatus('current')
hm2NetOobMgmtMacAddress = MibScalar((1, 3, 6, 1, 4, 1, 248, 11, 20, 1, 6, 8), MacAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hm2NetOobMgmtMacAddress.setStatus('current')
hm2NetOobMgmtOperState = MibScalar((1, 3, 6, 1, 4, 1, 248, 11, 20, 1, 6, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("up", 1), ("down", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: hm2NetOobMgmtOperState.setStatus('current')
hm2NetOobMgmtAction = MibScalar((1, 3, 6, 1, 4, 1, 248, 11, 20, 1, 6, 50), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("other", 1), ("activate", 2))).clone('other')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hm2NetOobMgmtAction.setStatus('current')
mibBuilder.exportSymbols("HM2-NETCONFIG-MIB", hm2NetACDAddrType=hm2NetACDAddrType, hm2NetOobMgmtGatewayIPAddr=hm2NetOobMgmtGatewayIPAddr, hm2NetMacACDConflictAddress=hm2NetMacACDConflictAddress, hm2NetConfigMibNotifications=hm2NetConfigMibNotifications, hm2NetHiDiscoveryGroup=hm2NetHiDiscoveryGroup, hm2NetHiDiscoveryBlinking=hm2NetHiDiscoveryBlinking, hm2NetOobMgmtProtocol=hm2NetOobMgmtProtocol, hm2NetACDGroup=hm2NetACDGroup, hm2NetOobMgmtAction=hm2NetOobMgmtAction, hm2NetDHCPClientId=hm2NetDHCPClientId, hm2NetACDDetectionMode=hm2NetACDDetectionMode, hm2NetACDNotification=hm2NetACDNotification, hm2NetACDIPAddr=hm2NetACDIPAddr, hm2NetGatewayIPAddr=hm2NetGatewayIPAddr, hm2NetMacGroup=hm2NetMacGroup, hm2NetACDAddrEntry=hm2NetACDAddrEntry, hm2NetACDMaxProtection=hm2NetACDMaxProtection, hm2NetACDFaultState=hm2NetACDFaultState, hm2NetHiDiscoveryRelay=hm2NetHiDiscoveryRelay, hm2NetOobMgmtIPAddr=hm2NetOobMgmtIPAddr, hm2NetHiDiscoveryMode=hm2NetHiDiscoveryMode, hm2NetLocalIPAddrType=hm2NetLocalIPAddrType, hm2NetMgmtPort=hm2NetMgmtPort, hm2NetMacAddressType=hm2NetMacAddressType, hm2NetVlanPriority=hm2NetVlanPriority, hm2NetLocalBurnedInMacAddr=hm2NetLocalBurnedInMacAddr, hm2NetACDTimeMark=hm2NetACDTimeMark, hm2NetACDMAC=hm2NetACDMAC, hm2NetPrefixLength=hm2NetPrefixLength, hm2NetHiDiscoveryProtocol=hm2NetHiDiscoveryProtocol, hm2NetMacACDGroup=hm2NetMacACDGroup, hm2NetOobMgmtGroup=hm2NetOobMgmtGroup, hm2NetConfigMibObjects=hm2NetConfigMibObjects, hm2NetOobMgmtIPAddrType=hm2NetOobMgmtIPAddrType, hm2NetLocalIPAddr=hm2NetLocalIPAddr, hm2NetGatewayIPAddrType=hm2NetGatewayIPAddrType, hm2NetACDReleaseDelay=hm2NetACDReleaseDelay, hm2NetACDOngoingProbeStatus=hm2NetACDOngoingProbeStatus, hm2NetHiDiscoveryOperation=hm2NetHiDiscoveryOperation, hm2NetOobMgmtAdminState=hm2NetOobMgmtAdminState, hm2NetACDProtectInterval=hm2NetACDProtectInterval, hm2NetOobMgmtPrefixLength=hm2NetOobMgmtPrefixLength, hm2NetOobMgmtMacAddress=hm2NetOobMgmtMacAddress, hm2NetACDifIndex=hm2NetACDifIndex, hm2NetACDTrapEnable=hm2NetACDTrapEnable, hm2NetAction=hm2NetAction, hm2NetLocalAdminMacAddress=hm2NetLocalAdminMacAddress, hm2NetOobMgmtGatewayIPAddrType=hm2NetOobMgmtGatewayIPAddrType, hm2NetVlanID=hm2NetVlanID, PYSNMP_MODULE_ID=hm2NetConfigMib, hm2NetStaticGroup=hm2NetStaticGroup, hm2NetACDDelay=hm2NetACDDelay, hm2NetConfigMib=hm2NetConfigMib, hm2NetACDAddrTable=hm2NetACDAddrTable, hm2NetIpDscpPriority=hm2NetIpDscpPriority, hm2NetACDStatus=hm2NetACDStatus, hm2NetMacACDStatus=hm2NetMacACDStatus, hm2NetOobMgmtOperState=hm2NetOobMgmtOperState, hm2NetConfigProtocol=hm2NetConfigProtocol, hm2NetMacACDNotification=hm2NetMacACDNotification)
|
def binary_search(A, target):
A = str(A)
lo = 0
hi = len(A)
index = None
while lo <= hi:
mid = round(lo + (hi - lo) / 2)
mid_ele = int(A[mid])
if mid_ele == target:
index = mid
break
if mid_ele < target:
lo = mid + 1
else:
hi = mid - 1
if index is not None:
return index
return "Not Found!"
def shipWithinDays(weights, D):
left, right = max(weights), sum(weights)
while left < right:
mid, need, cur = (left + right) / 2, 1, 0
for w in weights:
if cur + w > mid:
need += 1
cur = 0
cur += w
if need > D:
left = mid + 1
else:
right = mid
return round(left)
def binary_search_with_recursion(A, target):
low = A[0]
high = A[-1]
mid = (low + high) // 2
try:
if mid == target:
return A.index(mid)
if mid < target:
return binary_search_with_recursion(A[mid + 1: high], target)
if mid > target:
return binary_search_with_recursion(A[low: mid - 1], target)
except:
return "Not Found!"
if __name__ == "__main__":
# print(binary_search(5567889, 8))
# print(shipWithinDays([3,2,2,4,1,4],3))
print(binary_search_with_recursion([2, 2, 2, 4, 1, 4], 3))
|
tree = PipelineElement('DecisionTreeClassifier',
hyperparameters={'criterion': ['gini'],
'min_samples_split': IntegerRange(2, 4)})
svc = PipelineElement('LinearSVC',
hyperparameters={'C': FloatRange(0.5, 25)})
my_pipe += Stack('final_stack', [tree, svc], use_probabilities=True)
my_pipe += PipelineElement('LinearSVC')
my_pipe.fit(X, y)
|
class Solution:
def assignTasks(self, servers: List[int], tasks: List[int]) -> List[int]:
ans = []
free = [] # (weight, index, freeTime)
used = [] # (freeTime, weight, index)
for i, weight in enumerate(servers):
heapq.heappush(free, (weight, i, 0))
for i, executionTime in enumerate(tasks):
# poll all servers that'll be free at time i
while used and used[0][0] <= i:
curr = heapq.heappop(used)
heapq.heappush(free, (curr[1], curr[2], curr[0]))
if free:
curr = heapq.heappop(free)
ans.append(curr[1])
heapq.heappush(used, (i + executionTime, curr[0], curr[1]))
else:
curr = heapq.heappop(used)
ans.append(curr[2])
heapq.heappush(used, (curr[0] + executionTime, curr[1], curr[2]))
return ans
|
#
# PySNMP MIB module XYLAN-IP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/XYLAN-IP-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:38:41 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols("ASN1", "OctetString", "ObjectIdentifier", "Integer")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueSizeConstraint, ValueRangeConstraint, ConstraintsIntersection, ConstraintsUnion, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "ValueRangeConstraint", "ConstraintsIntersection", "ConstraintsUnion", "SingleValueConstraint")
ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup")
NotificationType, Gauge32, ObjectIdentity, Unsigned32, ModuleIdentity, MibIdentifier, iso, IpAddress, Counter32, Counter64, MibScalar, MibTable, MibTableRow, MibTableColumn, Bits, TimeTicks, Integer32 = mibBuilder.importSymbols("SNMPv2-SMI", "NotificationType", "Gauge32", "ObjectIdentity", "Unsigned32", "ModuleIdentity", "MibIdentifier", "iso", "IpAddress", "Counter32", "Counter64", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Bits", "TimeTicks", "Integer32")
TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString")
xylanIpArch, = mibBuilder.importSymbols("XYLAN-BASE-MIB", "xylanIpArch")
xylanIpFilterGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 800, 2, 13, 1))
xylanIpMiscGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 800, 2, 13, 2))
xylanIpRipFilterTable = MibTable((1, 3, 6, 1, 4, 1, 800, 2, 13, 1, 1), )
if mibBuilder.loadTexts: xylanIpRipFilterTable.setStatus('mandatory')
xylanIpRipFilterEntry = MibTableRow((1, 3, 6, 1, 4, 1, 800, 2, 13, 1, 1, 1), ).setIndexNames((0, "XYLAN-IP-MIB", "xylanIpRipFilterNum"))
if mibBuilder.loadTexts: xylanIpRipFilterEntry.setStatus('mandatory')
xylanIpRipFilterNum = MibTableColumn((1, 3, 6, 1, 4, 1, 800, 2, 13, 1, 1, 1, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: xylanIpRipFilterNum.setStatus('mandatory')
xylanIpRipFilterAdminState = MibTableColumn((1, 3, 6, 1, 4, 1, 800, 2, 13, 1, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("active", 1), ("delete", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: xylanIpRipFilterAdminState.setStatus('mandatory')
xylanIpRipFilterType = MibTableColumn((1, 3, 6, 1, 4, 1, 800, 2, 13, 1, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("rip-output", 1), ("rip-input", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: xylanIpRipFilterType.setStatus('mandatory')
xylanIpRipFilterNet = MibTableColumn((1, 3, 6, 1, 4, 1, 800, 2, 13, 1, 1, 1, 4), IpAddress()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: xylanIpRipFilterNet.setStatus('mandatory')
xylanIpRipFilterNetMask = MibTableColumn((1, 3, 6, 1, 4, 1, 800, 2, 13, 1, 1, 1, 5), IpAddress()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: xylanIpRipFilterNetMask.setStatus('mandatory')
xylanIpRipFilterMode = MibTableColumn((1, 3, 6, 1, 4, 1, 800, 2, 13, 1, 1, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("allow", 1), ("block", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: xylanIpRipFilterMode.setStatus('mandatory')
xylanIpRipFilterGroupId = MibTableColumn((1, 3, 6, 1, 4, 1, 800, 2, 13, 1, 1, 1, 7), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: xylanIpRipFilterGroupId.setStatus('mandatory')
xylanIpRipFilterVlanId = MibTableColumn((1, 3, 6, 1, 4, 1, 800, 2, 13, 1, 1, 1, 8), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: xylanIpRipFilterVlanId.setStatus('mandatory')
xylanIpRipFilterWanType = MibTableColumn((1, 3, 6, 1, 4, 1, 800, 2, 13, 1, 1, 1, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("not-used", 1), ("frame-relay", 2), ("ppp", 3)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: xylanIpRipFilterWanType.setStatus('mandatory')
xylanIpRipFilterSlot = MibTableColumn((1, 3, 6, 1, 4, 1, 800, 2, 13, 1, 1, 1, 10), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: xylanIpRipFilterSlot.setStatus('mandatory')
xylanIpRipFilterPort = MibTableColumn((1, 3, 6, 1, 4, 1, 800, 2, 13, 1, 1, 1, 11), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: xylanIpRipFilterPort.setStatus('mandatory')
xylanIpRipFilterVc = MibTableColumn((1, 3, 6, 1, 4, 1, 800, 2, 13, 1, 1, 1, 12), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: xylanIpRipFilterVc.setStatus('mandatory')
xylanIpRipFilterPeerId = MibTableColumn((1, 3, 6, 1, 4, 1, 800, 2, 13, 1, 1, 1, 13), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: xylanIpRipFilterPeerId.setStatus('mandatory')
xylanIpAssocMacTable = MibTable((1, 3, 6, 1, 4, 1, 800, 2, 13, 2, 1), )
if mibBuilder.loadTexts: xylanIpAssocMacTable.setStatus('mandatory')
xylanIpAssocEntry = MibTableRow((1, 3, 6, 1, 4, 1, 800, 2, 13, 2, 1, 1), ).setIndexNames((0, "XYLAN-IP-MIB", "xylanIpAssocAddr"))
if mibBuilder.loadTexts: xylanIpAssocEntry.setStatus('mandatory')
xylanIpAssocAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 800, 2, 13, 2, 1, 1, 1), IpAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: xylanIpAssocAddr.setStatus('mandatory')
xylanIpAssocMac = MibTableColumn((1, 3, 6, 1, 4, 1, 800, 2, 13, 2, 1, 1, 2), OctetString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: xylanIpAssocMac.setStatus('mandatory')
xylanIpAssocSlot = MibTableColumn((1, 3, 6, 1, 4, 1, 800, 2, 13, 2, 1, 1, 3), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: xylanIpAssocSlot.setStatus('mandatory')
xylanIpAssocIntf = MibTableColumn((1, 3, 6, 1, 4, 1, 800, 2, 13, 2, 1, 1, 4), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: xylanIpAssocIntf.setStatus('mandatory')
xylanIpAssocDupMac = MibTableColumn((1, 3, 6, 1, 4, 1, 800, 2, 13, 2, 1, 1, 5), OctetString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: xylanIpAssocDupMac.setStatus('mandatory')
xylanIpAssocDupSlot = MibTableColumn((1, 3, 6, 1, 4, 1, 800, 2, 13, 2, 1, 1, 6), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: xylanIpAssocDupSlot.setStatus('mandatory')
xylanIpAssocDupIntf = MibTableColumn((1, 3, 6, 1, 4, 1, 800, 2, 13, 2, 1, 1, 7), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: xylanIpAssocDupIntf.setStatus('mandatory')
mibBuilder.exportSymbols("XYLAN-IP-MIB", xylanIpAssocEntry=xylanIpAssocEntry, xylanIpRipFilterWanType=xylanIpRipFilterWanType, xylanIpAssocSlot=xylanIpAssocSlot, xylanIpRipFilterPort=xylanIpRipFilterPort, xylanIpRipFilterNum=xylanIpRipFilterNum, xylanIpRipFilterGroupId=xylanIpRipFilterGroupId, xylanIpRipFilterSlot=xylanIpRipFilterSlot, xylanIpRipFilterType=xylanIpRipFilterType, xylanIpRipFilterVc=xylanIpRipFilterVc, xylanIpAssocDupMac=xylanIpAssocDupMac, xylanIpAssocDupIntf=xylanIpAssocDupIntf, xylanIpAssocDupSlot=xylanIpAssocDupSlot, xylanIpRipFilterVlanId=xylanIpRipFilterVlanId, xylanIpFilterGroup=xylanIpFilterGroup, xylanIpRipFilterNetMask=xylanIpRipFilterNetMask, xylanIpRipFilterTable=xylanIpRipFilterTable, xylanIpAssocAddr=xylanIpAssocAddr, xylanIpRipFilterNet=xylanIpRipFilterNet, xylanIpAssocMacTable=xylanIpAssocMacTable, xylanIpAssocIntf=xylanIpAssocIntf, xylanIpRipFilterMode=xylanIpRipFilterMode, xylanIpAssocMac=xylanIpAssocMac, xylanIpRipFilterEntry=xylanIpRipFilterEntry, xylanIpRipFilterPeerId=xylanIpRipFilterPeerId, xylanIpMiscGroup=xylanIpMiscGroup, xylanIpRipFilterAdminState=xylanIpRipFilterAdminState)
|
"""
Given a string, determine if it is a palindrome, considering only alphanumeric
characters and ignoring cases.
For example 'A man, a plan, a canal: Panama' is a palindrome
while 'race a car' is not.
"""
def is_palindrome(sentence):
def normalize():
alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z']
digits = [str(digit) for digit in range(0, 10)]
alphanum = set(alphabet + digits)
for c in sentence:
c = c.lower()
if c in alphanum:
yield c
normalized_sentence = list(normalize())
return normalized_sentence == list(reversed(normalized_sentence))
def test_is_palindrome():
assert is_palindrome("A man, a plan, a canal: Panama")
|
def sign_out() -> str:
return """
public func signOut() {
SessionManager.shared.session = nil
}
""".strip() + '\n'
|
# for em dicionário
personInformation = {
'nome':'Marcelo',
'sexo': 'Masculino',
'idade': 25,
'peso': 68
}
for person in personInformation:
print('{}: {}'.format(person, personInformation[person]))
|
class IBANValidationException(Exception):
"""The IBAN did not validate"""
class BankDoesNotExistException(IBANValidationException):
"""The Bank does not exists"""
|
# from test_mpu65c02.py, 71 tests
class Common65C02Tests:
"""CMOS 65C02 Tests"""
# Reset
def test_reset_clears_decimal_flag(self):
# W65C02S Datasheet, Apr 14 2009, Table 7-1 Operational Enhancements
# NMOS 6502 decimal flag = indetermine after reset, CMOS 65C02 = 0
mpu = self._make_mpu()
mpu.p = mpu.DECIMAL
mpu.reset()
self.assertEqual(0, mpu.p & mpu.DECIMAL)
# ADC Zero Page, Indirect
def test_adc_bcd_off_zp_ind_carry_clear_in_accumulator_zeroes(self):
mpu = self._make_mpu()
mpu.a = 0x00
# $0000 ADC ($0010)
# $0010 Vector to $ABCD
self._write(mpu.memory, 0x0000, (0x72, 0x10))
self._write(mpu.memory, 0x0010, (0xCD, 0xAB))
mpu.memory[0xABCD] = 0x00
mpu.step()
self.assertEqual(0x0002, mpu.pc)
self.assertEqual(5, mpu.processorCycles)
self.assertEqual(0x00, mpu.a)
self.assertEqual(0, mpu.p & mpu.CARRY)
self.assertEqual(0, mpu.p & mpu.NEGATIVE)
self.assertEqual(mpu.ZERO, mpu.p & mpu.ZERO)
def test_adc_bcd_off_zp_ind_carry_set_in_accumulator_zero(self):
mpu = self._make_mpu()
mpu.a = 0
mpu.p |= mpu.CARRY
# $0000 ADC ($0010)
# $0010 Vector to $ABCD
self._write(mpu.memory, 0x0000, (0x72, 0x10))
self._write(mpu.memory, 0x0010, (0xCD, 0xAB))
mpu.memory[0xABCD] = 0x00
mpu.step()
self.assertEqual(0x0002, mpu.pc)
self.assertEqual(5, mpu.processorCycles)
self.assertEqual(0x01, mpu.a)
self.assertEqual(0, mpu.p & mpu.NEGATIVE)
self.assertEqual(0, mpu.p & mpu.ZERO)
self.assertNotEqual(mpu.CARRY, mpu.p & mpu.CARRY)
def test_adc_bcd_off_zp_ind_carry_clear_in_no_carry_clear_out(self):
mpu = self._make_mpu()
mpu.a = 0x01
# $0000 ADC ($0010)
# $0010 Vector to $ABCD
self._write(mpu.memory, 0x0000, (0x72, 0x10))
self._write(mpu.memory, 0x0010, (0xCD, 0xAB))
mpu.memory[0xABCD] = 0xFE
mpu.step()
self.assertEqual(0x0002, mpu.pc)
self.assertEqual(5, mpu.processorCycles)
self.assertEqual(0xFF, mpu.a)
self.assertEqual(mpu.NEGATIVE, mpu.p & mpu.NEGATIVE)
self.assertEqual(0, mpu.p & mpu.CARRY)
self.assertEqual(0, mpu.p & mpu.ZERO)
def test_adc_bcd_off_zp_ind_carry_clear_in_carry_set_out(self):
mpu = self._make_mpu()
mpu.a = 0x02
# $0000 ADC ($0010)
# $0010 Vector to $ABCD
self._write(mpu.memory, 0x0000, (0x72, 0x10))
self._write(mpu.memory, 0x0010, (0xCD, 0xAB))
mpu.memory[0xABCD] = 0xFF
mpu.step()
self.assertEqual(0x0002, mpu.pc)
self.assertEqual(5, mpu.processorCycles)
self.assertEqual(0x01, mpu.a)
self.assertEqual(mpu.CARRY, mpu.p & mpu.CARRY)
self.assertEqual(0, mpu.p & mpu.NEGATIVE)
self.assertEqual(0, mpu.p & mpu.ZERO)
def test_adc_bcd_off_zp_ind_overflow_cleared_no_carry_01_plus_01(self):
mpu = self._make_mpu()
mpu.p &= ~(mpu.CARRY)
mpu.a = 0x01
# $0000 ADC ($0010)
# $0010 Vector to $ABCD
self._write(mpu.memory, 0x0000, (0x72, 0x10))
self._write(mpu.memory, 0x0010, (0xCD, 0xAB))
mpu.memory[0xABCD] = 0x01
mpu.step()
self.assertEqual(0x0002, mpu.pc)
self.assertEqual(0x02, mpu.a)
self.assertEqual(0, mpu.p & mpu.OVERFLOW)
def test_adc_bcd_off_zp_ind_overflow_cleared_no_carry_01_plus_ff(self):
mpu = self._make_mpu()
mpu.p &= ~(mpu.CARRY)
mpu.a = 0x01
# $0000 ADC ($0010)
# $0010 Vector to $ABCD
self._write(mpu.memory, 0x0000, (0x72, 0x10))
self._write(mpu.memory, 0x0010, (0xCD, 0xAB))
mpu.memory[0xABCD] = 0xFF
mpu.step()
self.assertEqual(0x0002, mpu.pc)
self.assertEqual(0x00, mpu.a)
self.assertEqual(0, mpu.p & mpu.OVERFLOW)
def test_adc_bcd_off_zp_ind_overflow_set_no_carry_7f_plus_01(self):
mpu = self._make_mpu()
mpu.p &= ~(mpu.CARRY)
mpu.a = 0x7f
# $0000 ADC ($0010)
# $0010 Vector to $ABCD
self._write(mpu.memory, 0x0000, (0x72, 0x10))
self._write(mpu.memory, 0x0010, (0xCD, 0xAB))
mpu.memory[0xABCD] = 0x01
mpu.step()
self.assertEqual(0x0002, mpu.pc)
self.assertEqual(0x80, mpu.a)
self.assertEqual(mpu.OVERFLOW, mpu.p & mpu.OVERFLOW)
def test_adc_bcd_off_zp_ind_overflow_set_no_carry_80_plus_ff(self):
mpu = self._make_mpu()
mpu.p &= ~(mpu.CARRY)
mpu.a = 0x80
# $0000 ADC ($0010)
# $0010 Vector to $ABCD
self._write(mpu.memory, 0x0000, (0x72, 0x10))
self._write(mpu.memory, 0x0010, (0xCD, 0xAB))
mpu.memory[0xABCD] = 0xFF
mpu.step()
self.assertEqual(0x0002, mpu.pc)
self.assertEqual(0x7f, mpu.a)
self.assertEqual(mpu.OVERFLOW, mpu.p & mpu.OVERFLOW)
def test_adc_bcd_off_zp_ind_overflow_set_on_40_plus_40(self):
mpu = self._make_mpu()
mpu.a = 0x40
# $0000 ADC ($0010)
# $0010 Vector to $ABCD
self._write(mpu.memory, 0x0000, (0x72, 0x10))
self._write(mpu.memory, 0x0010, (0xCD, 0xAB))
mpu.memory[0xABCD] = 0x40
mpu.step()
self.assertEqual(0x0002, mpu.pc)
self.assertEqual(0x80, mpu.a)
self.assertEqual(mpu.NEGATIVE, mpu.p & mpu.NEGATIVE)
self.assertEqual(mpu.OVERFLOW, mpu.p & mpu.OVERFLOW)
self.assertEqual(0, mpu.p & mpu.ZERO)
# AND Zero Page, Indirect
def test_and_zp_ind_all_zeros_setting_zero_flag(self):
mpu = self._make_mpu()
mpu.a = 0xFF
# $0000 AND ($0010)
# $0010 Vector to $ABCD
self._write(mpu.memory, 0x0000, (0x32, 0x10))
self._write(mpu.memory, 0x0010, (0xCD, 0xAB))
mpu.memory[0xABCD] = 0x00
mpu.step()
self.assertEqual(0x0002, mpu.pc)
self.assertEqual(5, mpu.processorCycles)
self.assertEqual(0x00, mpu.a)
self.assertEqual(mpu.ZERO, mpu.p & mpu.ZERO)
self.assertEqual(0, mpu.p & mpu.NEGATIVE)
def test_and_zp_ind_zeros_and_ones_setting_negative_flag(self):
mpu = self._make_mpu()
mpu.a = 0xFF
# $0000 AND ($0010)
# $0010 Vector to $ABCD
self._write(mpu.memory, 0x0000, (0x32, 0x10))
self._write(mpu.memory, 0x0010, (0xCD, 0xAB))
mpu.memory[0xABCD] = 0xAA
mpu.step()
self.assertEqual(0x0002, mpu.pc)
self.assertEqual(5, mpu.processorCycles)
self.assertEqual(0xAA, mpu.a)
self.assertEqual(mpu.NEGATIVE, mpu.p & mpu.NEGATIVE)
self.assertEqual(0, mpu.p & mpu.ZERO)
# BIT (Absolute, X-Indexed)
def test_bit_abs_x_copies_bit_7_of_memory_to_n_flag_when_0(self):
mpu = self._make_mpu()
mpu.p &= ~(mpu.NEGATIVE)
mpu.x = 0x02
# $0000 BIT $FEEB,X
self._write(mpu.memory, 0x0000, (0x3C, 0xEB, 0xFE))
mpu.memory[0xFEED] = 0xFF
mpu.a = 0xFF
mpu.step()
self.assertEqual(mpu.NEGATIVE, mpu.p & mpu.NEGATIVE)
self.assertEqual(4, mpu.processorCycles)
self.assertEqual(0x0003, mpu.pc)
def test_bit_abs_x_copies_bit_7_of_memory_to_n_flag_when_1(self):
mpu = self._make_mpu()
mpu.p |= mpu.NEGATIVE
mpu.x = 0x02
# $0000 BIT $FEEB,X
self._write(mpu.memory, 0x0000, (0x3C, 0xEB, 0xFE))
mpu.memory[0xFEED] = 0x00
mpu.a = 0xFF
mpu.step()
self.assertEqual(0, mpu.p & mpu.NEGATIVE)
self.assertEqual(4, mpu.processorCycles)
self.assertEqual(0x0003, mpu.pc)
def test_bit_abs_x_copies_bit_6_of_memory_to_v_flag_when_0(self):
mpu = self._make_mpu()
mpu.p &= ~(mpu.OVERFLOW)
mpu.x = 0x02
# $0000 BIT $FEEB,X
self._write(mpu.memory, 0x0000, (0x3C, 0xEB, 0xFE))
mpu.memory[0xFEED] = 0xFF
mpu.a = 0xFF
mpu.step()
self.assertEqual(mpu.OVERFLOW, mpu.p & mpu.OVERFLOW)
self.assertEqual(4, mpu.processorCycles)
self.assertEqual(0x0003, mpu.pc)
def test_bit_abs_x_copies_bit_6_of_memory_to_v_flag_when_1(self):
mpu = self._make_mpu()
mpu.p |= mpu.OVERFLOW
mpu.x = 0x02
# $0000 BIT $FEEB,X
self._write(mpu.memory, 0x0000, (0x3C, 0xEB, 0xFE))
mpu.memory[0xFEED] = 0x00
mpu.a = 0xFF
mpu.step()
self.assertEqual(0, mpu.p & mpu.OVERFLOW)
self.assertEqual(4, mpu.processorCycles)
self.assertEqual(0x0003, mpu.pc)
def test_bit_abs_x_stores_result_of_and_in_z_preserves_a_when_1(self):
mpu = self._make_mpu()
mpu.p &= ~mpu.ZERO
mpu.x = 0x02
# $0000 BIT $FEEB,X
self._write(mpu.memory, 0x0000, (0x3C, 0xEB, 0xFE))
mpu.memory[0xFEED] = 0x00
mpu.a = 0x01
mpu.step()
self.assertEqual(mpu.ZERO, mpu.p & mpu.ZERO)
self.assertEqual(0x01, mpu.a)
self.assertEqual(0x00, mpu.memory[0xFEED])
self.assertEqual(4, mpu.processorCycles)
self.assertEqual(0x0003, mpu.pc)
def test_bit_abs_x_stores_result_of_and_nonzero_in_z_preserves_a(self):
mpu = self._make_mpu()
mpu.p |= mpu.ZERO
mpu.x = 0x02
# $0000 BIT $FEEB,X
self._write(mpu.memory, 0x0000, (0x3C, 0xEB, 0xFE))
mpu.memory[0xFEED] = 0x01
mpu.a = 0x01
mpu.step()
self.assertEqual(0, mpu.p & mpu.ZERO) # result of AND is non-zero
self.assertEqual(0x01, mpu.a)
self.assertEqual(0x01, mpu.memory[0xFEED])
self.assertEqual(4, mpu.processorCycles)
self.assertEqual(0x0003, mpu.pc)
def test_bit_abs_x_stores_result_of_and_when_zero_in_z_preserves_a(self):
mpu = self._make_mpu()
mpu.p &= ~(mpu.ZERO)
mpu.x = 0x02
# $0000 BIT $FEEB,X
self._write(mpu.memory, 0x0000, (0x3C, 0xEB, 0xFE))
mpu.memory[0xFEED] = 0x00
mpu.a = 0x01
mpu.step()
self.assertEqual(mpu.ZERO, mpu.p & mpu.ZERO) # result of AND is zero
self.assertEqual(0x01, mpu.a)
self.assertEqual(0x00, mpu.memory[0xFEED])
self.assertEqual(4, mpu.processorCycles)
self.assertEqual(0x0003, mpu.pc)
# BIT (Immediate)
def test_bit_imm_does_not_affect_n_and_z_flags(self):
mpu = self._make_mpu()
mpu.p |= mpu.NEGATIVE | mpu.OVERFLOW
# $0000 BIT #$FF
self._write(mpu.memory, 0x0000, (0x89, 0xff))
mpu.a = 0x00
mpu.step()
self.assertEqual(mpu.NEGATIVE, mpu.p & mpu.NEGATIVE)
self.assertEqual(mpu.OVERFLOW, mpu.p & mpu.OVERFLOW)
self.assertEqual(0x00, mpu.a)
self.assertEqual(2, mpu.processorCycles)
self.assertEqual(0x02, mpu.pc)
def test_bit_imm_stores_result_of_and_in_z_preserves_a_when_1(self):
mpu = self._make_mpu()
mpu.p &= ~mpu.ZERO
# $0000 BIT #$00
self._write(mpu.memory, 0x0000, (0x89, 0x00))
mpu.a = 0x01
mpu.step()
self.assertEqual(mpu.ZERO, mpu.p & mpu.ZERO)
self.assertEqual(0x01, mpu.a)
self.assertEqual(2, mpu.processorCycles)
self.assertEqual(0x02, mpu.pc)
def test_bit_imm_stores_result_of_and_when_nonzero_in_z_preserves_a(self):
mpu = self._make_mpu()
mpu.p |= mpu.ZERO
# $0000 BIT #$01
self._write(mpu.memory, 0x0000, (0x89, 0x01))
mpu.a = 0x01
mpu.step()
self.assertEqual(0, mpu.p & mpu.ZERO) # result of AND is non-zero
self.assertEqual(0x01, mpu.a)
self.assertEqual(2, mpu.processorCycles)
self.assertEqual(0x02, mpu.pc)
def test_bit_imm_stores_result_of_and_when_zero_in_z_preserves_a(self):
mpu = self._make_mpu()
mpu.p &= ~(mpu.ZERO)
# $0000 BIT #$00
self._write(mpu.memory, 0x0000, (0x89, 0x00))
mpu.a = 0x01
mpu.step()
self.assertEqual(mpu.ZERO, mpu.p & mpu.ZERO) # result of AND is zero
self.assertEqual(0x01, mpu.a)
self.assertEqual(2, mpu.processorCycles)
self.assertEqual(0x02, mpu.pc)
# BIT (Zero Page, X-Indexed)
def test_bit_zp_x_copies_bit_7_of_memory_to_n_flag_when_0(self):
mpu = self._make_mpu()
mpu.p &= ~(mpu.NEGATIVE)
# $0000 BIT $0010,X
self._write(mpu.memory, 0x0000, (0x34, 0x10))
mpu.memory[0x0013] = 0xFF
mpu.x = 0x03
mpu.a = 0xFF
mpu.step()
self.assertEqual(0x0002, mpu.pc)
self.assertEqual(4, mpu.processorCycles)
self.assertEqual(mpu.NEGATIVE, mpu.p & mpu.NEGATIVE)
def test_bit_zp_x_copies_bit_7_of_memory_to_n_flag_when_1(self):
mpu = self._make_mpu()
mpu.p |= mpu.NEGATIVE
# $0000 BIT $0010,X
self._write(mpu.memory, 0x0000, (0x34, 0x10))
mpu.memory[0x0013] = 0x00
mpu.x = 0x03
mpu.a = 0xFF
mpu.step()
self.assertEqual(0x0002, mpu.pc)
self.assertEqual(4, mpu.processorCycles)
self.assertEqual(0, mpu.p & mpu.NEGATIVE)
def test_bit_zp_x_copies_bit_6_of_memory_to_v_flag_when_0(self):
mpu = self._make_mpu()
mpu.p &= ~(mpu.OVERFLOW)
# $0000 BIT $0010,X
self._write(mpu.memory, 0x0000, (0x34, 0x10))
mpu.memory[0x0013] = 0xFF
mpu.x = 0x03
mpu.a = 0xFF
mpu.step()
self.assertEqual(0x0002, mpu.pc)
self.assertEqual(4, mpu.processorCycles)
self.assertEqual(mpu.OVERFLOW, mpu.p & mpu.OVERFLOW)
def test_bit_zp_x_copies_bit_6_of_memory_to_v_flag_when_1(self):
mpu = self._make_mpu()
mpu.p |= mpu.OVERFLOW
# $0000 BIT $0010,X
self._write(mpu.memory, 0x0000, (0x34, 0x10))
mpu.memory[0x0013] = 0x00
mpu.x = 0x03
mpu.a = 0xFF
mpu.step()
self.assertEqual(0x0002, mpu.pc)
self.assertEqual(4, mpu.processorCycles)
self.assertEqual(0, mpu.p & mpu.OVERFLOW)
def test_bit_zp_x_stores_result_of_and_in_z_preserves_a_when_1(self):
mpu = self._make_mpu()
mpu.p &= ~mpu.ZERO
# $0000 BIT $0010,X
self._write(mpu.memory, 0x0000, (0x34, 0x10))
mpu.memory[0x0013] = 0x00
mpu.x = 0x03
mpu.a = 0x01
mpu.step()
self.assertEqual(mpu.ZERO, mpu.p & mpu.ZERO)
self.assertEqual(0x0002, mpu.pc)
self.assertEqual(4, mpu.processorCycles)
self.assertEqual(0x01, mpu.a)
self.assertEqual(0x00, mpu.memory[0x0010 + mpu.x])
def test_bit_zp_x_stores_result_of_and_when_nonzero_in_z_preserves_a(self):
mpu = self._make_mpu()
mpu.p |= mpu.ZERO
# $0000 BIT $0010,X
self._write(mpu.memory, 0x0000, (0x34, 0x10))
mpu.memory[0x0013] = 0x01
mpu.x = 0x03
mpu.a = 0x01
mpu.step()
self.assertEqual(0, mpu.p & mpu.ZERO) # result of AND is non-zero
self.assertEqual(0x0002, mpu.pc)
self.assertEqual(4, mpu.processorCycles)
self.assertEqual(0x01, mpu.a)
self.assertEqual(0x01, mpu.memory[0x0010 + mpu.x])
def test_bit_zp_x_stores_result_of_and_when_zero_in_z_preserves_a(self):
mpu = self._make_mpu()
mpu.p &= ~(mpu.ZERO)
# $0000 BIT $0010,X
self._write(mpu.memory, 0x0000, (0x34, 0x10))
mpu.memory[0x0013] = 0x00
mpu.x = 0x03
mpu.a = 0x01
mpu.step()
self.assertEqual(0x0002, mpu.pc)
self.assertEqual(4, mpu.processorCycles)
self.assertEqual(mpu.ZERO, mpu.p & mpu.ZERO) # result of AND is zero
self.assertEqual(0x01, mpu.a)
self.assertEqual(0x00, mpu.memory[0x0010 + mpu.x])
# CMP Zero Page, Indirect
def test_cmp_zpi_sets_z_flag_if_equal(self):
mpu = self._make_mpu()
mpu.a = 0x42
# $0000 AND ($10)
# $0010 Vector to $ABCD
self._write(mpu.memory, 0x0000, (0xd2, 0x10))
self._write(mpu.memory, 0x0010, (0xCD, 0xAB))
mpu.memory[0xABCD] = 0x42
mpu.step()
self.assertEqual(0x0002, mpu.pc)
self.assertEqual(5, mpu.processorCycles)
self.assertEqual(0x42, mpu.a)
self.assertEqual(mpu.ZERO, mpu.p & mpu.ZERO)
self.assertEqual(0, mpu.p & mpu.NEGATIVE)
def test_cmp_zpi_resets_z_flag_if_unequal(self):
mpu = self._make_mpu()
mpu.a = 0x43
# $0000 AND ($10)
# $0010 Vector to $ABCD
self._write(mpu.memory, 0x0000, (0xd2, 0x10))
self._write(mpu.memory, 0x0010, (0xCD, 0xAB))
mpu.memory[0xABCD] = 0x42
mpu.step()
self.assertEqual(0x0002, mpu.pc)
self.assertEqual(5, mpu.processorCycles)
self.assertEqual(0x43, mpu.a)
self.assertEqual(0, mpu.p & mpu.ZERO)
self.assertEqual(0, mpu.p & mpu.NEGATIVE)
# EOR Zero Page, Indirect
def test_eor_zp_ind_flips_bits_over_setting_z_flag(self):
mpu = self._make_mpu()
mpu.a = 0xFF
# $0000 EOR ($0010)
# $0010 Vector to $ABCD
self._write(mpu.memory, 0x0000, (0x52, 0x10))
self._write(mpu.memory, 0x0010, (0xCD, 0xAB))
mpu.memory[0xABCD] = 0xFF
mpu.step()
self.assertEqual(0x0002, mpu.pc)
self.assertEqual(5, mpu.processorCycles)
self.assertEqual(0x00, mpu.a)
self.assertEqual(0xFF, mpu.memory[0xABCD])
self.assertEqual(mpu.ZERO, mpu.p & mpu.ZERO)
def test_eor_zp_ind_flips_bits_over_setting_n_flag(self):
mpu = self._make_mpu()
mpu.a = 0x00
# $0000 EOR ($0010)
# $0010 Vector to $ABCD
self._write(mpu.memory, 0x0000, (0x52, 0x10))
self._write(mpu.memory, 0x0010, (0xCD, 0xAB))
mpu.memory[0xABCD] = 0xFF
mpu.step()
self.assertEqual(0x0002, mpu.pc)
self.assertEqual(5, mpu.processorCycles)
self.assertEqual(0xFF, mpu.a)
self.assertEqual(0xFF, mpu.memory[0xABCD])
self.assertEqual(mpu.NEGATIVE, mpu.p & mpu.NEGATIVE)
self.assertEqual(0, mpu.p & mpu.ZERO)
# INC Accumulator
def test_inc_acc_increments_accum(self):
mpu = self._make_mpu()
mpu.memory[0x0000] = 0x1A
mpu.a = 0x42
mpu.step()
self.assertEqual(0x0001, mpu.pc)
self.assertEqual(0x43, mpu.a)
self.assertEqual(0, mpu.p & mpu.ZERO)
self.assertEqual(0, mpu.p & mpu.NEGATIVE)
def test_inc_acc_increments_accum_rolls_over_and_sets_zero_flag(self):
mpu = self._make_mpu()
mpu.memory[0x0000] = 0x1A
mpu.a = 0xFF
mpu.step()
self.assertEqual(0x0001, mpu.pc)
self.assertEqual(0x00, mpu.a)
self.assertEqual(mpu.ZERO, mpu.p & mpu.ZERO)
self.assertEqual(0, mpu.p & mpu.NEGATIVE)
def test_inc_acc_sets_negative_flag_when_incrementing_above_7F(self):
mpu = self._make_mpu()
mpu.memory[0x0000] = 0x1A
mpu.a = 0x7F
mpu.step()
self.assertEqual(0x0001, mpu.pc)
self.assertEqual(0x80, mpu.a)
self.assertEqual(0, mpu.p & mpu.ZERO)
self.assertEqual(mpu.NEGATIVE, mpu.p & mpu.NEGATIVE)
# JMP Indirect Absolute X-Indexed
def test_jmp_iax_jumps_to_address(self):
mpu = self._make_mpu()
mpu.x = 2
# $0000 JMP ($ABCD,X)
# $ABCF Vector to $1234
self._write(mpu.memory, 0x0000, (0x7C, 0xCD, 0xAB))
self._write(mpu.memory, 0xABCF, (0x34, 0x12))
mpu.step()
self.assertEqual(0x1234, mpu.pc)
self.assertEqual(6, mpu.processorCycles)
# LDA Zero Page, Indirect
def test_lda_zp_ind_loads_a_sets_n_flag(self):
mpu = self._make_mpu()
mpu.a = 0x00
# $0000 LDA ($0010)
# $0010 Vector to $ABCD
self._write(mpu.memory, 0x0000, (0xB2, 0x10))
self._write(mpu.memory, 0x0010, (0xCD, 0xAB))
mpu.memory[0xABCD] = 0x80
mpu.step()
self.assertEqual(0x0002, mpu.pc)
self.assertEqual(5, mpu.processorCycles)
self.assertEqual(0x80, mpu.a)
self.assertEqual(mpu.NEGATIVE, mpu.p & mpu.NEGATIVE)
self.assertEqual(0, mpu.p & mpu.ZERO)
def test_lda_zp_ind_loads_a_sets_z_flag(self):
mpu = self._make_mpu()
mpu.a = 0x00
# $0000 LDA ($0010)
# $0010 Vector to $ABCD
self._write(mpu.memory, 0x0000, (0xB2, 0x10))
self._write(mpu.memory, 0x0010, (0xCD, 0xAB))
mpu.memory[0xABCD] = 0x00
mpu.step()
self.assertEqual(0x0002, mpu.pc)
self.assertEqual(5, mpu.processorCycles)
self.assertEqual(0x00, mpu.a)
self.assertEqual(mpu.ZERO, mpu.p & mpu.ZERO)
self.assertEqual(0, mpu.p & mpu.NEGATIVE)
# ORA Zero Page, Indirect
def test_ora_zp_ind_zeroes_or_zeros_sets_z_flag(self):
mpu = self._make_mpu()
mpu.p &= ~(mpu.ZERO)
mpu.a = 0x00
mpu.y = 0x12 # These should not affect the ORA
mpu.x = 0x34
# $0000 ORA ($0010)
# $0010 Vector to $ABCD
self._write(mpu.memory, 0x0000, (0x12, 0x10))
self._write(mpu.memory, 0x0010, (0xCD, 0xAB))
mpu.memory[0xABCD] = 0x00
mpu.step()
self.assertEqual(0x0002, mpu.pc)
self.assertEqual(5, mpu.processorCycles)
self.assertEqual(0x00, mpu.a)
self.assertEqual(mpu.ZERO, mpu.p & mpu.ZERO)
def test_ora_zp_ind_turns_bits_on_sets_n_flag(self):
mpu = self._make_mpu()
mpu.p &= ~(mpu.NEGATIVE)
mpu.a = 0x03
# $0000 ORA ($0010)
# $0010 Vector to $ABCD
self._write(mpu.memory, 0x0000, (0x12, 0x10))
self._write(mpu.memory, 0x0010, (0xCD, 0xAB))
mpu.memory[0xABCD] = 0x82
mpu.step()
self.assertEqual(0x0002, mpu.pc)
self.assertEqual(5, mpu.processorCycles)
self.assertEqual(0x83, mpu.a)
self.assertEqual(mpu.NEGATIVE, mpu.p & mpu.NEGATIVE)
self.assertEqual(0, mpu.p & mpu.ZERO)
# STA Zero Page, Indirect
def test_sta_zp_ind_stores_a_leaves_a_and_n_flag_unchanged(self):
mpu = self._make_mpu()
mpu.p = flags = 0xFF & ~(mpu.NEGATIVE)
mpu.a = 0xFF
# $0000 STA ($0010)
# $0010 Vector to $FEED
self._write(mpu.memory, 0x0000, (0x92, 0x10))
self._write(mpu.memory, 0x0010, (0xED, 0xFE))
mpu.memory[0xFEED] = 0x00
mpu.step()
self.assertEqual(0x0002, mpu.pc)
self.assertEqual(5, mpu.processorCycles)
self.assertEqual(0xFF, mpu.memory[0xFEED])
self.assertEqual(0xFF, mpu.a)
self.assertEqual(flags, mpu.p)
def test_sta_zp_ind_stores_a_leaves_a_and_z_flag_unchanged(self):
mpu = self._make_mpu()
mpu.p = flags = 0xFF & ~(mpu.ZERO)
mpu.a = 0x00
# $0000 STA ($0010)
# $0010 Vector to $FEED
self._write(mpu.memory, 0x0000, (0x92, 0x10))
self._write(mpu.memory, 0x0010, (0xED, 0xFE))
mpu.memory[0xFEED] = 0xFF
mpu.step()
self.assertEqual(0x0002, mpu.pc)
self.assertEqual(5, mpu.processorCycles)
self.assertEqual(0x00, mpu.memory[0xFEED])
self.assertEqual(0x00, mpu.a)
self.assertEqual(flags, mpu.p)
# SBC Zero Page, Indirect
def test_sbc_zp_ind_all_zeros_and_no_borrow_is_zero(self):
mpu = self._make_mpu()
mpu.p &= ~(mpu.DECIMAL)
mpu.p |= mpu.CARRY # borrow = 0
mpu.a = 0x00
# $0000 SBC ($10)
# $0010 Vector to $FEED
self._write(mpu.memory, 0x0000, (0xF2, 0x10))
self._write(mpu.memory, 0x0010, (0xED, 0xFE))
mpu.memory[0xFEED] = 0x00
mpu.step()
self.assertEqual(0x0002, mpu.pc)
self.assertEqual(5, mpu.processorCycles)
self.assertEqual(0x00, mpu.a)
self.assertEqual(0, mpu.p & mpu.NEGATIVE)
self.assertEqual(mpu.CARRY, mpu.CARRY)
self.assertEqual(mpu.ZERO, mpu.p & mpu.ZERO)
def test_sbc_zp_ind_downto_zero_no_borrow_sets_z_clears_n(self):
mpu = self._make_mpu()
mpu.p &= ~(mpu.DECIMAL)
mpu.p |= mpu.CARRY # borrow = 0
mpu.a = 0x01
# $0000 SBC ($10)
# $0010 Vector to $FEED
self._write(mpu.memory, 0x0000, (0xF2, 0x10))
self._write(mpu.memory, 0x0010, (0xED, 0xFE))
mpu.memory[0xFEED] = 0x01
mpu.step()
self.assertEqual(0x0002, mpu.pc)
self.assertEqual(5, mpu.processorCycles)
self.assertEqual(0x00, mpu.a)
self.assertEqual(0, mpu.p & mpu.NEGATIVE)
self.assertEqual(mpu.CARRY, mpu.CARRY)
self.assertEqual(mpu.ZERO, mpu.p & mpu.ZERO)
def test_sbc_zp_ind_downto_zero_with_borrow_sets_z_clears_n(self):
mpu = self._make_mpu()
mpu.p &= ~(mpu.DECIMAL)
mpu.p &= ~(mpu.CARRY) # borrow = 1
mpu.a = 0x01
# $0000 SBC ($10)
# $0010 Vector to $FEED
self._write(mpu.memory, 0x0000, (0xF2, 0x10))
self._write(mpu.memory, 0x0010, (0xED, 0xFE))
mpu.memory[0xFEED] = 0x00
mpu.step()
self.assertEqual(0x0002, mpu.pc)
self.assertEqual(5, mpu.processorCycles)
self.assertEqual(0x00, mpu.a)
self.assertEqual(0, mpu.p & mpu.NEGATIVE)
self.assertEqual(mpu.CARRY, mpu.CARRY)
self.assertEqual(mpu.ZERO, mpu.p & mpu.ZERO)
def test_sbc_zp_ind_downto_four_with_borrow_clears_z_n(self):
mpu = self._make_mpu()
mpu.p &= ~(mpu.DECIMAL)
mpu.p &= ~(mpu.CARRY) # borrow = 1
mpu.a = 0x07
# $0000 SBC ($10)
# $0010 Vector to $FEED
self._write(mpu.memory, 0x0000, (0xF2, 0x10))
self._write(mpu.memory, 0x0010, (0xED, 0xFE))
mpu.memory[0xFEED] = 0x02
mpu.step()
self.assertEqual(0x0002, mpu.pc)
self.assertEqual(5, mpu.processorCycles)
self.assertEqual(0x04, mpu.a)
self.assertEqual(0, mpu.p & mpu.NEGATIVE)
self.assertEqual(0, mpu.p & mpu.ZERO)
self.assertEqual(mpu.CARRY, mpu.CARRY)
# STZ Zero Page
def test_stz_zp_stores_zero(self):
mpu = self._make_mpu()
mpu.memory[0x0032] = 0x88
# #0000 STZ $32
mpu.memory[0x0000:0x0000 + 2] = [0x64, 0x32]
self.assertEqual(0x88, mpu.memory[0x0032])
mpu.step()
self.assertEqual(0x00, mpu.memory[0x0032])
self.assertEqual(0x0002, mpu.pc)
self.assertEqual(3, mpu.processorCycles)
# STZ Zero Page, X-Indexed
def test_stz_zp_x_stores_zero(self):
mpu = self._make_mpu()
mpu.memory[0x0032] = 0x88
# $0000 STZ $32,X
mpu.memory[0x0000:0x0000 + 2] = [0x74, 0x32]
self.assertEqual(0x88, mpu.memory[0x0032])
mpu.step()
self.assertEqual(0x00, mpu.memory[0x0032])
self.assertEqual(0x0002, mpu.pc)
self.assertEqual(4, mpu.processorCycles)
# STZ Absolute
def test_stz_abs_stores_zero(self):
mpu = self._make_mpu()
mpu.memory[0xFEED] = 0x88
# $0000 STZ $FEED
mpu.memory[0x0000:0x0000 + 3] = [0x9C, 0xED, 0xFE]
self.assertEqual(0x88, mpu.memory[0xFEED])
mpu.step()
self.assertEqual(0x00, mpu.memory[0xFEED])
self.assertEqual(0x0003, mpu.pc)
self.assertEqual(4, mpu.processorCycles)
# STZ Absolute, X-Indexed
def test_stz_abs_x_stores_zero(self):
mpu = self._make_mpu()
mpu.memory[0xFEED] = 0x88
mpu.x = 0x0D
# $0000 STZ $FEE0,X
mpu.memory[0x0000:0x0000 + 3] = [0x9E, 0xE0, 0xFE]
self.assertEqual(0x88, mpu.memory[0xFEED])
self.assertEqual(0x0D, mpu.x)
mpu.step()
self.assertEqual(0x00, mpu.memory[0xFEED])
self.assertEqual(0x0003, mpu.pc)
self.assertEqual(5, mpu.processorCycles)
# TSB Zero Page
def test_tsb_zp_ones(self):
mpu = self._make_mpu()
mpu.memory[0x00BB] = 0xE0
# $0000 TSB $BD
self._write(mpu.memory, 0x0000, [0x04, 0xBB])
mpu.a = 0x70
self.assertEqual(0xE0, mpu.memory[0x00BB])
mpu.step()
self.assertEqual(0xF0, mpu.memory[0x00BB])
self.assertEqual(0, mpu.p & mpu.ZERO)
self.assertEqual(0x0002, mpu.pc)
self.assertEqual(5, mpu.processorCycles)
def test_tsb_zp_zeros(self):
mpu = self._make_mpu()
mpu.memory[0x00BB] = 0x80
# $0000 TSB $BD
self._write(mpu.memory, 0x0000, [0x04, 0xBB])
mpu.a = 0x60
self.assertEqual(0x80, mpu.memory[0x00BB])
mpu.step()
self.assertEqual(0xE0, mpu.memory[0x00BB])
self.assertEqual(mpu.ZERO, mpu.p & mpu.ZERO)
self.assertEqual(0x0002, mpu.pc)
self.assertEqual(5, mpu.processorCycles)
# TSB Absolute
def test_tsb_abs_ones(self):
mpu = self._make_mpu()
mpu.memory[0xFEED] = 0xE0
# $0000 TSB $FEED
self._write(mpu.memory, 0x0000, [0x0C, 0xED, 0xFE])
mpu.a = 0x70
self.assertEqual(0xE0, mpu.memory[0xFEED])
mpu.step()
self.assertEqual(0xF0, mpu.memory[0xFEED])
self.assertEqual(0, mpu.p & mpu.ZERO)
self.assertEqual(0x0003, mpu.pc)
self.assertEqual(6, mpu.processorCycles)
def test_tsb_abs_zeros(self):
mpu = self._make_mpu()
mpu.memory[0xFEED] = 0x80
# $0000 TSB $FEED
self._write(mpu.memory, 0x0000, [0x0C, 0xED, 0xFE])
mpu.a = 0x60
self.assertEqual(0x80, mpu.memory[0xFEED])
mpu.step()
self.assertEqual(0xE0, mpu.memory[0xFEED])
self.assertEqual(mpu.ZERO, mpu.p & mpu.ZERO)
self.assertEqual(0x0003, mpu.pc)
self.assertEqual(6, mpu.processorCycles)
# TRB Zero Page
def test_trb_zp_ones(self):
mpu = self._make_mpu()
mpu.memory[0x00BB] = 0xE0
# $0000 TRB $BD
self._write(mpu.memory, 0x0000, [0x14, 0xBB])
mpu.a = 0x70
self.assertEqual(0xE0, mpu.memory[0x00BB])
mpu.step()
self.assertEqual(0x80, mpu.memory[0x00BB])
self.assertEqual(0, mpu.p & mpu.ZERO)
self.assertEqual(0x0002, mpu.pc)
self.assertEqual(5, mpu.processorCycles)
def test_trb_zp_zeros(self):
mpu = self._make_mpu()
mpu.memory[0x00BB] = 0x80
# $0000 TRB $BD
self._write(mpu.memory, 0x0000, [0x14, 0xBB])
mpu.a = 0x60
self.assertEqual(0x80, mpu.memory[0x00BB])
mpu.step()
self.assertEqual(0x80, mpu.memory[0x00BB])
self.assertEqual(mpu.ZERO, mpu.p & mpu.ZERO)
self.assertEqual(0x0002, mpu.pc)
self.assertEqual(5, mpu.processorCycles)
# TRB Absolute
def test_trb_abs_ones(self):
mpu = self._make_mpu()
mpu.memory[0xFEED] = 0xE0
# $0000 TRB $FEED
self._write(mpu.memory, 0x0000, [0x1C, 0xED, 0xFE])
mpu.a = 0x70
self.assertEqual(0xE0, mpu.memory[0xFEED])
mpu.step()
self.assertEqual(0x80, mpu.memory[0xFEED])
self.assertEqual(0, mpu.p & mpu.ZERO)
self.assertEqual(0x0003, mpu.pc)
self.assertEqual(6, mpu.processorCycles)
def test_trb_abs_zeros(self):
mpu = self._make_mpu()
mpu.memory[0xFEED] = 0x80
# $0000 TRB $FEED
self._write(mpu.memory, 0x0000, [0x1C, 0xED, 0xFE])
mpu.a = 0x60
self.assertEqual(0x80, mpu.memory[0xFEED])
mpu.step()
self.assertEqual(0x80, mpu.memory[0xFEED])
self.assertEqual(mpu.ZERO, mpu.p & mpu.ZERO)
self.assertEqual(0x0003, mpu.pc)
self.assertEqual(6, mpu.processorCycles)
def test_dec_a_decreases_a(self):
mpu = self._make_mpu()
# $0000 DEC A
self._write(mpu.memory, 0x0000, [0x3A])
mpu.a = 0x48
mpu.step()
self.assertEqual(0, mpu.p & mpu.ZERO)
self.assertEqual(0, mpu.p & mpu.NEGATIVE)
self.assertEqual(0x47, mpu.a)
def test_dec_a_sets_zero_flag(self):
mpu = self._make_mpu()
# $0000 DEC A
self._write(mpu.memory, 0x0000, [0x3A])
mpu.a = 0x01
mpu.step()
self.assertEqual(mpu.ZERO, mpu.p & mpu.ZERO)
self.assertEqual(0, mpu.p & mpu.NEGATIVE)
self.assertEqual(0x00, mpu.a)
def test_dec_a_wraps_at_zero(self):
mpu = self._make_mpu()
# $0000 DEC A
self._write(mpu.memory, 0x0000, [0x3A])
mpu.a = 0x00
mpu.step()
self.assertEqual(0, mpu.p & mpu.ZERO)
self.assertEqual(mpu.NEGATIVE, mpu.p & mpu.NEGATIVE)
self.assertEqual(0xFF, mpu.a)
def test_bra_forward(self):
mpu = self._make_mpu()
# $0000 BRA $10
self._write(mpu.memory, 0x0000, [0x80, 0x10])
mpu.step()
self.assertEqual(0x12, mpu.pc)
self.assertEqual(2, mpu.processorCycles)
def test_bra_backward(self):
mpu = self._make_mpu()
# $0240 BRA $F0
self._write(mpu.memory, 0x0204, [0x80, 0xF0])
mpu.pc = 0x0204
mpu.step()
self.assertEqual(0x1F6, mpu.pc)
self.assertEqual(3, mpu.processorCycles) # Crossed boundry
# WAI
def test_wai_sets_waiting(self):
mpu = self._make_mpu()
self.assertFalse(mpu.waiting)
# $0240 WAI
self._write(mpu.memory, 0x0204, [0xCB])
mpu.pc = 0x0204
mpu.step()
self.assertTrue(mpu.waiting)
self.assertEqual(0x0205, mpu.pc)
self.assertEqual(3, mpu.processorCycles)
# Test Helpers
def _get_target_class(self):
return devices.mpu65c02.MPU
|
# Time: O(nlogn + nlogw), n = len(nums), w = max(nums)-min(nums)
# Space: O(1)
# Given an integer array, return the k-th smallest distance among all the pairs.
# The distance of a pair (A, B) is defined as the absolute difference between A and B.
#
# Example 1:
# Input:
# nums = [1,3,1]
# k = 1
# Output: 0
# Explanation:
# Here are all the pairs:
# (1,3) -> 2
# (1,1) -> 0
# (3,1) -> 2
# Then the 1st smallest distance pair is (1,1), and its distance is 0.
#
# Note:
# 2 <= len(nums) <= 10000.
# 0 <= nums[i] < 1000000.
# 1 <= k <= len(nums) * (len(nums) - 1) / 2.
# Binary search with sliding window solution
class Solution(object):
def smallestDistancePair(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
# Sliding window solution
def possible(guess, nums, k):
# Is there k or more pairs with distance <= guess?
count, left = 0, 0
for right, num in enumerate(nums):
while num-nums[left] > guess:
left += 1
count += right-left
return count >= k
nums.sort()
left, right = 0, nums[-1]-nums[0]+1
while left < right:
mid = left + (right-left)/2
if possible(mid, nums, k):
right = mid
else:
left = mid+1
return left
|
class A:
def f(self):
print("f() in A")
class B:
def f(self):
print("f() in B")
class D(A,B):
pass
class E(B,A):
pass
print(D.mro())
print(E.mro())
d = D()
d.f()
e = E()
e.f()
|
def is_pangram(text):
"""
Checks if a string is a pangram.
"""
alphabet = 'abcdefghijklmnopqrstuvwxyz'
text = text.lower()
for letter in alphabet:
if letter not in text:
return False
return True
print(is_pangram('The quick brown fox jumps over the lazy dog.'))
def needle_in_haystack(needle, haystack):
"""
Checks if a string is in another string.
"""
return needle in haystack
|
'''
* @Author: csy
* @Date: 2019-04-28 13:50:45
* @Last Modified by: csy
* @Last Modified time: 2019-04-28 13:50:45
'''
digits = list(range(0, 10))
print(digits)
print(min(digits))
print(max(digits))
print(sum(digits))
|
class Solution(object):
def setZeroes(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
colZeroFlag = False
for i in range(0, len(matrix)):
if matrix[i][0] == 0:
colZeroFlag = True
for j in range(1, len(matrix[0])):
if matrix[i][j] == 0:
matrix[i][0] = matrix[0][j] = 0
for i in reversed(range(0, len(matrix))):
for j in reversed(range(1, len(matrix[0]))):
if matrix[i][0] == 0 or matrix[0][j] == 0:
matrix[i][j] = 0
if colZeroFlag:
matrix[i][0] = 0
|
class constants:
NONE = 0
X = 1
O = 2
class variables:
explored = 0
def print_board(board):
print(simbol(board[0])+"|"+simbol(board[1])+"|"+simbol(board[2]))
print("-----")
print(simbol(board[3])+"|"+simbol(board[4])+"|"+simbol(board[5]))
print("-----")
print(simbol(board[6])+"|"+simbol(board[7])+"|"+simbol(board[8]))
def set_board(map, data):
for y in range(9):
map[y] = constants.X if data[y] == 'X' else constants.O if data[y] == 'O' else constants.NONE
def set_cell(b, y, x, s):
b[y*3+x] = s
def get_cell(b, y, x):
return b[y*3+x]
def simbol(c):
if (c == constants.X):
return 'X'
if (c == constants.O):
return 'O'
return ' '
def legend(c):
if (c == constants.X):
return "X"
if (c == constants.O):
return "O"
return "Nobody"
def game_status(board):
variables.explored += 1
# diags
if (board[0] == constants.X and board[4] == constants.X and board[8] == constants.X):
return constants.X
if (board[2] == constants.X and board[4] == constants.X and board[6] == constants.X):
return constants.X
# horizontal
if (board[0] == constants.X and board[1] == constants.X and board[2] == constants.X):
return constants.X
if (board[3] == constants.X and board[4] == constants.X and board[5] == constants.X):
return constants.X
if (board[6] == constants.X and board[7] == constants.X and board[8] == constants.X):
return constants.X
# vertical
if (board[0] == constants.X and board[3] == constants.X and board[6] == constants.X):
return constants.X
if (board[1] == constants.X and board[4] == constants.X and board[7] == constants.X):
return constants.X
if (board[2] == constants.X and board[5] == constants.X and board[8] == constants.X):
return constants.X
# diags
if (board[0] == constants.O and board[4] == constants.O and board[8] == constants.O):
return constants.O
if (board[2] == constants.O and board[4] == constants.O and board[6] == constants.O):
return constants.O
# horizontal
if (board[0] == constants.O and board[1] == constants.O and board[2] == constants.O):
return constants.O
if (board[3] == constants.O and board[4] == constants.O and board[5] == constants.O):
return constants.O
if (board[6] == constants.O and board[7] == constants.O and board[8] == constants.O):
return constants.O
# vertical
if (board[0] == constants.O and board[3] == constants.O and board[6] == constants.O):
return constants.O
if (board[1] == constants.O and board[4] == constants.O and board[7] == constants.O):
return constants.O
if (board[2] == constants.O and board[5] == constants.O and board[8] == constants.O):
return constants.O
return constants.NONE # tie or unfinished
|
RequiredKeyIsMissing = \
"No value was found for the required key `{key_name}`"
RequiredKeyIsWrongType = (
"Required key `{key_name}` has the wrong " +
"type of `{invalid_type}`. The value of this key " +
"should have the type `{expected_type}`"
)
DirectiveStructureError = (
"The following directive `{directive}` has an invalid structure. " +
"{problem}. "
)
|
def source():
pass
def sink(x):
pass
def alarm():
x = source()
sink(x)
|
# from: http://www.rosettacode.org/wiki/Babbage_problem#Python
def main():
print([x for x in range(30000) if (x * x) % 1000000 == 269696][0])
if __name__ == "__main__":
main()
|
print ('making summary table....')
#Adjust "Summary" dataframe
Summary.rename(columns={'RSL_ID':'WALIS_ID'},inplace=True)
Summary['WALIS_ID']='RSL_' + Summary['WALIS_ID'].astype(str)
Summary.insert(loc=13, column='Paleo water depth estimate (m)', value='')
Summary.insert(loc=14, column='Upper limit of living range (m)', value='')
Summary.insert(loc=15, column='Lower limit of living range (m)', value='')
Summary['Reported age (ka)'].astype(float,errors='ignore')
Summary['Reported age uncertainty (ka)'].astype(float,errors='ignore')
Summary['U-Series recalculated age (ka)'].astype(float,errors='ignore')
Summary['U-Series recalculate age uncertainty (ka)'].astype(float,errors='ignore')
Summary['U-Series corrected age (speleothems, ka)'].astype(float,errors='ignore')
Summary['U-Series corrected age uncertainty (speleothems, ka)'].astype(float,errors='ignore')
Summary['Originally accepted?']=Summary['Originally accepted?'].replace('1', 'Yes')
Summary['Originally accepted?']=Summary['Originally accepted?'].replace('0', 'No')
#Create U-Series "Summary" dataframe
Summary_useries = pd.DataFrame()
useries_rsl=useries[useries['Are RSL estimates available for this record?']=='Yes']
Summary_useries['WALIS_ID']=useries_rsl['WALIS U-Series ID']
Summary_useries['WALIS_ID']='USeries_' + Summary_useries['WALIS_ID'].astype(str)
Summary_useries['Latitude']=useries_rsl['Latitude (decimal degrees)'].astype(float)
Summary_useries['Longitude']=useries_rsl['Longitude (decimal degrees)'].astype(float)
Summary_useries['Site']=useries_rsl['Site']
Summary_useries['Subsite']=useries_rsl['Additional site information']
Summary_useries['Nation']=''
Summary_useries['Region']=''
Summary_useries['Type of datapoint']='Sea Level Indicator'
Summary_useries['RSL Indicator']='Single '+useries_rsl['Material type']
Summary_useries['RSL indicator description']=useries_rsl['Facies description']+' '+useries_rsl['Taxa information (as reported)']
Summary_useries['Elevation measurement technique']=useries_rsl['Elevation measurement method']
Summary_useries['Elevation (m)']=pd.to_numeric(useries_rsl['Elevation above MSL (m)'], errors='coerce')
Summary_useries['Elevation error (m)']=pd.to_numeric(useries_rsl['Elevation uncertainty used (m)'], errors='coerce')
Summary_useries['Paleo water depth estimate (m)']=pd.to_numeric(useries_rsl['Paleo water depth estimate (m)'], errors='coerce')
Summary_useries['Upper limit of living range (m)']=pd.to_numeric(useries_rsl['Upper limit of living range (m)'], errors='coerce')
Summary_useries['Lower limit of living range (m)']=pd.to_numeric(useries_rsl['Lower limit of living range (m)'], errors='coerce')
Summary_useries['RWL']=np.nan
Summary_useries['IR']=np.nan
Summary_useries['Vertical datum']=useries_rsl['Original elevation datum used']
Summary_useries['Paleo RSL (m)']=useries_rsl['paleo RSL (m)'].astype(float,errors='ignore')
Summary_useries['Paleo RSL uncertainty (m)']=useries_rsl['paleo RSL uncertainty (m)'].astype(float,errors='ignore')
Summary_useries['Dating technique']='U-Series'
Summary_useries['Timing constraint']='Equal to'
Summary_useries['Originally reported ID']=useries_rsl['Reported ID']
Summary_useries['Analysis ID']=useries_rsl['Analysis ID']
Summary_useries['Material_type']=useries_rsl['Material type']
Summary_useries['Reported age (ka)']=useries_rsl['Reported age (ka)'].astype(float,errors='ignore')
Summary_useries['Reported age uncertainty (ka)']=useries_rsl['Reported ageuncertainty (ka, ±2σ)'].astype(float,errors='ignore')
Summary_useries['U-Series recalculated age (ka)']=useries_rsl['Recalculated Conventional Age (ka)'].astype(float,errors='ignore')
Summary_useries['U-Series recalculate age uncertainty (ka)']=useries_rsl['Recalculated Conventional Age uncert. (±2σ)'].astype(float,errors='ignore')
Summary_useries['U-Series corrected age (speleothems, ka)']=useries_rsl['Corrected reported age (ka)'].astype(float,errors='ignore')
Summary_useries['U-Series corrected age uncertainty (speleothems, ka)']=useries_rsl['Corrected reported age uncert. (ka, ±2σ)'].astype(float,errors='ignore')
Summary_useries['Stratigraphy Upper Age (ka)']=np.nan
Summary_useries['Stratigraphy Lower Age (ka)']=np.nan
Summary_useries['MIS limit']=''
Summary_useries['Marine Isotopic Stage']=''
Summary_useries['Quality of RSL information']=''
Summary_useries['Quality of age information']=''
# added for detailed summary
Summary_useries['WALIS U-series ID']=''
Summary_useries['WALIS AAR ID']=''
Summary_useries['WALIS ESR ID']=''
Summary_useries['WALIS LUM ID']=''
Summary_useries['WALIS strat ID']=''
Summary_useries['Sample Latitude']=''
Summary_useries['Sample Longitude']=''
Summary_useries['Originally accepted?']=useries_rsl['Accepted?']
Summary_useries['Accepted by other study?']=useries_rsl['Accepted in other study?']
# end added for detailed summary
Summary_useries['Reference(s)']=useries_rsl['Reference(s)']
Summary_useries['Record Created by']=useries_rsl['Record created by']
Summary_useries['Last Update']=useries_rsl['Last Update']
Summary2 = pd.concat([Summary,Summary_useries])
Summary = Summary2.copy()
Summary['Paleo water depth estimate (m)']=Summary['Paleo water depth estimate (m)'].replace('',np.nan).astype(float)
Summary['Upper limit of living range (m)']=Summary['Upper limit of living range (m)'].replace('',np.nan).astype(float)
Summary['Lower limit of living range (m)']=Summary['Lower limit of living range (m)'].replace('',np.nan).astype(float)
Summary['Reported age (ka)']=Summary['Reported age (ka)'].replace('Not Reported',np.nan)
Summary['Reported age (ka)']=Summary['Reported age (ka)'].replace('',np.nan).astype(float)
Summary['Reported age uncertainty (ka)'] = Summary['Reported age uncertainty (ka)'].replace('N/A','')
Summary['Reported age uncertainty (ka)'] = Summary['Reported age uncertainty (ka)'].replace('Not Reported','')
Summary['Reported age uncertainty (ka)']=Summary['Reported age uncertainty (ka)'].replace('',np.nan).astype(float)
Summary['U-Series recalculated age (ka)']=Summary['U-Series recalculated age (ka)'].replace('',np.nan).astype(float)
Summary['U-Series recalculate age uncertainty (ka)']=Summary['U-Series recalculate age uncertainty (ka)'].replace('',np.nan).astype(float)
Summary['U-Series corrected age (speleothems, ka)'] = Summary['U-Series corrected age (speleothems, ka)'].replace(['ND'],'')
Summary['U-Series corrected age (speleothems, ka)']=Summary['U-Series corrected age (speleothems, ka)'].replace('',np.nan).astype(float)
Summary['U-Series corrected age uncertainty (speleothems, ka)'] = Summary['U-Series corrected age uncertainty (speleothems, ka)'].replace(['ND'],'')
Summary['U-Series corrected age uncertainty (speleothems, ka)']=Summary['U-Series corrected age uncertainty (speleothems, ka)'].replace('',np.nan).astype(float)
# Insert standard uncertainties if not reported
Summary['Reported age uncertainty (ka)'].fillna(Summary['Reported age (ka)']*30/100, inplace = True)
Summary['U-Series recalculate age uncertainty (ka)'].fillna(Summary['U-Series recalculated age (ka)']*30/100, inplace = True)
Summary['U-Series corrected age uncertainty (speleothems, ka)'].fillna(Summary['U-Series corrected age (speleothems, ka)']*30/100, inplace = True)
# If 'Timing constraint' is empty, set it equal to 'MIS limit'
Summary['Timing constraint'] = Summary[['Timing constraint', 'MIS limit']].apply(lambda x: x[0] if x[0] else x[1], axis=1)
# If it still empty, replace with 'Equal to'
Summary['Timing constraint'].replace('','Equal to',inplace=True)
# If upper or lower ages are zero, set both to null
Summary['Stratigraphy Upper Age (ka)'].loc[(Summary['Stratigraphy Upper Age (ka)'] == 0)] = np.nan
Summary['Stratigraphy Lower Age (ka)'].loc[(Summary['Stratigraphy Lower Age (ka)'] == 0)] = np.nan
# If upper or lower ages are null, set the other to null as well
Summary['Stratigraphy Upper Age (ka)'] = np.where(Summary['Stratigraphy Lower Age (ka)'].isnull(), np.nan, Summary['Stratigraphy Upper Age (ka)'])
Summary['Stratigraphy Lower Age (ka)'] = np.where(Summary['Stratigraphy Upper Age (ka)'].isnull(), np.nan, Summary['Stratigraphy Lower Age (ka)'])
# Search the MIS definitions for age limits constraints and substitute them
MIS_ages.set_index('MIS name',inplace=True)
Summary=Summary.join(MIS_ages, on='Marine Isotopic Stage')
Summary['Stratigraphy Upper Age (ka)'].fillna(Summary['MIS start age'], inplace = True)
Summary['Stratigraphy Upper Age (ka)']=Summary['Stratigraphy Upper Age (ka)'].astype(float)
Summary['Stratigraphy Lower Age (ka)'].fillna(Summary['MIS end age'], inplace = True)
Summary['Stratigraphy Lower Age (ka)']=Summary['Stratigraphy Lower Age (ka)'].astype(float)
Summary.drop(columns=['MIS ID','MIS peak age','MIS start age','MIS end age'],inplace=True)
# Make sample to RSL index point distance
# Thanks: https://stackoverflow.com/questions/29545704/fast-haversine-approximation-python-pandas
def haversine_np(lon1, lat1, lon2, lat2):
"""
Calculate the great circle distance between two points
on the earth (specified in decimal degrees)
All args must be of equal length.
"""
lon1, lat1, lon2, lat2 = map(np.radians, [lon1, lat1, lon2, lat2])
dlon = lon2 - lon1
dlat = lat2 - lat1
a = np.sin(dlat/2.0)**2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon/2.0)**2
c = 2 * np.arcsin(np.sqrt(a))
km = 6367 * c
return km
### To solve for null values
Summary['Sample Longitude'] = np.where(Summary['Sample Longitude'] == '', 99999, Summary['Sample Longitude'])
Summary['Sample Longitude']=Summary['Sample Longitude'].astype(float)
Summary['Sample Latitude'] = np.where(Summary['Sample Latitude'] == '', 99999, Summary['Sample Latitude'])
Summary['Sample Latitude']=Summary['Sample Latitude'].astype(float)
Summary['Distance from sample'] = haversine_np(Summary['Longitude'],Summary['Latitude'],Summary['Sample Longitude'],Summary['Sample Latitude'])
Summary['Distance from sample']=np.where(Summary['Sample Longitude'] == 99999, np.nan, Summary['Distance from sample'])
Summary['Sample Longitude'] = np.where(Summary['Sample Longitude'] == 99999, np.nan, Summary['Sample Longitude'])
Summary['Sample Latitude'] = np.where(Summary['Sample Latitude'] == 99999, np.nan, Summary['Sample Latitude'])
Summary.sort_values(by=['WALIS_ID'],ascending=True)
print ('Done!')
|
def song_decoder(song):
result = song.replace("WUB" , " ")
result = ' '.join(result.split())
return result
|
# -*- coding: utf-8 -*-
def platform2str(platform: str) -> str:
""" get full platform name """
if platform == "amd":
return "AMD Tahiti 7970"
elif platform == "nvidia":
return "NVIDIA GTX 970"
else:
raise LookupError
def escape_suite_name(g: str) -> str:
""" format benchmark suite name for display """
c = g.split('-')
if c[0] == "amd" or c[0] == "nvidia":
return c[0].upper() + " SDK"
if c[0] == "npb" or c[0] == "shoc":
return c[0].upper()
elif c[0] == "parboil" or c[0] == "polybench" or c[0] == "rodinia":
return c[0].capitalize()
else:
raise LookupError
def escape_benchmark_name(g: str) -> str:
"""escape benchmark name for display"""
c = g.split('-')
return escape_suite_name(c[0]).split()[0] + "." + c[-2]
|
#Escreva um programa que leia um valor em metros e o exiba convertido em centímetros e milímetros.
n = float(input('Digite o valor em metros: '))
km = n / 1000
hm = n / 100
dam = n / 10
dm = n*10
cm = n*100
mm = n*1000
print('Você digitou {} metros.'.format(n))
print('Este valor, corresponde a: ')
print('{}km \n {}hm \n {}dam \n {}dm \n {}cm \n {}mm'.format(km, hm, dam, dm, cm, mm))
|
def print_row(star_count):
for _ in range(star_count, size - 1):
print(' ', end='')
for _ in range(star_count):
print('*', end=' ')
print('*')
size = int(input())
for star_count in range(size):
print_row(star_count)
for star_count in range(size - 2, -1, -1):
print_row(star_count)
|
def recur_fibo(n):
if n <= 1:
return n
else:
return (recur_fibo(n - 1) + recur_fibo(n - 2))
nterms = int(input('You want output many elements '))
if nterms < 0:
print('Enter the positive number')
else:
print("fibonacci sequence")
for i in range(nterms):
print(recur_fibo(i))
|
class Solution:
def twoSum(self, numbers: List[int], target: int) -> List[int]:
n = len(numbers)
last_num = None
for i in range(n):
num1 = numbers[i]
if num1 != last_num:
for j in range(i+1, n):
num2 = numbers[j]
sum_ = num1 + num2
if sum_ == target:
return [i+1, j+1]
elif sum_ > target:
break
last_num = num1
|
NInput = int(input())
xcoor = []
ycoor = []
for i in range(NInput):
x, y = map(int, input().split())
xcoor.append(x)
ycoor.append(y)
for i in range(0, len(xcoor)):
minIndex = i
for j in range(i+1, len(xcoor)):
if xcoor[j] < xcoor[minIndex]:
xcoor[j], xcoor[minIndex] = xcoor[minIndex], xcoor[j]
ycoor[j], ycoor[minIndex] = ycoor[minIndex], ycoor[j]
for i in range(0, len(xcoor)):
if i+1 < len(xcoor):
if xcoor[i] == xcoor[i+1]:
if ycoor[i] > ycoor[i+1]:
ycoor[i], ycoor[i+1] = ycoor[i+1], ycoor[i]
for i in range(0, len(xcoor)):
print(xcoor[i], " ", ycoor[i])
|
# Should only need to modify these paths in this file:
# - BTFM_BASE
# - LSP_DATASET_DIR
# - LSPET_DATASET_DIR
# - COCO_DATASET_DIR
# - MPII_DATASET_DIR
# - TDPW_DATASET_DIR
# - MI3_DATASET_DIR
# - MI3_PP_DATASET_DIR
# - UPI_S1H_DATASET_DIR
# Note that this relies on a filesystem that supports symlinks
# Set up output path
BTFM_BASE='/media/data/btfm'
# Set up other paths in output for preprocessed data
BTFM_PP='/pp'
BTFM_PP_LSP=BTFM_PP+'/lsp'
BTFM_PP_LSPET=BTFM_PP+'/lspet'
BTFM_PP_MPII=BTFM_PP+'/mpii'
BTFM_PP_3DPW=BTFM_PP+'/3dpw'
BTFM_PP_3DPW_SILHOUETTE=BTFM_PP_3DPW+'/silhouette'
BTFM_PP_3DPW_SILHOUETTE_VALID=BTFM_PP_3DPW+'/good_3dpw_annotations.pkl'
BTFM_PP_COCO=BTFM_PP+'/coco'
BTFM_PP_COCO_SILHOUETTE=BTFM_PP_COCO+'/silhouette'
# Pre-processed files
LSP_CSV=BTFM_PP_LSP+'/lsp.csv'
LSPET_CSV=BTFM_PP_LSPET+'/lspet.csv'
MPII_RELEASE_PICKLE=BTFM_PP_MPII+'/mpii-RELEASE.pickle'
# Set up paths to datasets (absolute)
LSP_DATASET_DIR='/media/data/lsp'
LSPET_DATASET_DIR='/media/data/lspet'
COCO_DATASET_DIR='/media/data/coco2017'
MPII_DATASET_DIR='/media/data/mpii'
TDPW_DATASET_DIR='/media/data/3dpw'
MI3_DATASET_DIR='/media/data/mpi_inf_3dhp/mpi_inf_3dhp/download'
MI3_PP_DATASET_DIR='/media/data/mpi_inf_3dhp_pp'
UPI_S1H_DATASET_DIR='/media/data/up/upi-s1h'
SSP3D_DATASET_DIR='/media/data/SSP-3D'
# Other weights
MASK_RCNN_WEIGHTS='/media/data/maskrcnn_weights/mask_rcnn_coco.h5'
# Required preprocessing
# LSP: convertlsp.m to convert joints.mat to lsp.csv
# LSPET: convertlspet.m to convert joints.mat to lspet.csv
# MPII: 1) convertmpii.m to convert mpii_human_pose_v1_u12_1.mat to set of csv files
# 2) Convert output files (RELEASE.txt and *.csv) to pickle with convertmpii.py
# The following paths are all relative, starting from BTFM_BASE
LSP_DIR='/lsp'
LSP_IMG_DIR=LSP_DIR + '/images'
LSPET_DIR='/lspet'
LSPET_IMG_DIR=LSPET_DIR+'/images'
COCO_DIR='/coco2017'
COCO_TRAIN_IMG=COCO_DIR+'/train2017'
COCO_VAL_IMG=COCO_DIR+'/val2017'
COCO_TEST_IMG=COCO_DIR+'/test2017'
COCO_TRAIN_ANNOT=COCO_DIR+'/annotations/person_keypoints_train2017.json'
COCO_VAL_ANNOT=COCO_DIR+'/annotations/person_keypoints_val2017.json'
COCO_TEST_INFO=COCO_DIR+'/annotations/image_info_test2017.json'
# dev is a smaller set
#COCO_TEST_INFO=COCO_DIR+'/annotations/image_info_test-dev2017.json'
MPII_DIR='/mpii'
MPII_IMG_DIR=MPII_DIR+'/images'
TDPW_DIR='/3dpw'
TDPW_IMG_DIR=TDPW_DIR+'/imageFiles'
TDPW_SEQ_DIR=TDPW_DIR+'/sequenceFiles'
TDPW_TRAIN_DIR=TDPW_SEQ_DIR+'/train'
TDPW_VAL_DIR=TDPW_SEQ_DIR+'/validation'
TDPW_TEST_DIR=TDPW_SEQ_DIR+'/test'
MI3_DIR='/mpi_inf_3dhp'
MI3_TEST_DIR=MI3_DIR+'/mpi_inf_3dhp_test_set/mpi_inf_3dhp_test_set'
MI3_PP_DIR='/mi3_pp'
UPI_S1H_DIR='/upi-s1h'
UPI_S1H_MPII=UPI_S1H_DIR+'/data/mpii'
UPI_S1H_MPII_IMG=UPI_S1H_MPII+'/images'
UPI_S1H_MPII_ANNOT=UPI_S1H_MPII+'/correspondences.csv'
SSP3D_DIR='/ssp-3d'
|
class Solution:
def calPoints(self, ops: List[str]) -> int:
array = []
for op in ops:
if op == 'C':
array.pop()
elif op == 'D':
array.append(array[-1]*2)
elif op == "+":
array.append(array[-1] + array[-2])
else:
array.append(int(op))
return sum(array)
|
# stringparser.py
#
# Ronald Rihoo
def findFirstQuotationMarkFromTheLeft(string):
for i in xrange(len(string) - 1, 0, -1):
if string[i] == '"':
return i
def findFirstQuotationMarkFromTheRight(string):
for i in range(len(string)):
if string[i] == '"':
return i
def splitLeftAspect_toChar(string, fromIndex, char):
string = string[0:fromIndex]
for i in xrange(len(string) - 1, 0, -1):
if string[i] == char:
return string[i:].replace("\\", "")
def splitRightAspect_toChar(string, fromIndex, char):
string = string[fromIndex:]
for i in xrange(len(string)):
if string[i] == char:
return string[:i+1].replace("\\", "")
def splitLeftAspect_toSubstring(string, fromIndex, chars):
string = string[0:fromIndex]
l = len(chars)
for i in xrange(len(string) - 1, 0, -1):
if i < len(string) - l:
if string[i:i+l] == chars:
return string[i:]
def splitRightAspect_toSubstring(string, fromIndex, chars):
string = string[fromIndex:]
l = len(chars)
for i in xrange(len(string)):
if string[i:i+l] == chars:
return string[:i+l]
def getFullQuoteViaKeywordLaterals(string, keyword):
if keyword in string:
i = string.index(keyword)
x = splitLeftAspect_toChar(string, i, '"')
y = splitRightAspect_toChar(string, i, '"')
try: return x + y
except: return "No results"
def removeBackslashes(string):
return string.replace("\\", "")
def getHtmlLinkViaKeywordLaterals(string, keyword):
if keyword in string:
i = string.index(keyword)
y = splitRightAspect_toChar(string, i, '"')
# if string = ...somewebpage.html" <- notice double-quotation mark placement
if (y[len(y)-5:] == '.html'):
x = splitLeftAspect_toChar(string, i, '"')[1:]
# expected: string = somecode"somelink... <- notice double-quotation mark placement
try:
return x + y
except:
# expected: string = somecodehttp://somelink... <- notice no double-quotation mark
try:
x = splitLeftAspect_toSubstring(string, i, 'http')
return x + y
except:
return "Not found."
# if string = ...somewebpage.html > some text ..." <- notice double-quotation mark placement
elif (y[:5] == '.html'):
y = y[:5]
x = splitLeftAspect_toChar(string, i, '"')
# expected: string = somecode"somelink... <- there exists a double-quotation mark
try:
return x[1:] + y
except:
try:
# expected: string = somecodehttp://somelink... <- no double-quotation mark
x = splitLeftAspect_toSubstring(string, i, 'http')
return x + y
except:
return "Not found."
else:
try:
x = splitLeftAspect_toSubstring(string, i, 'http')
y = splitRightAspect_toSubstring(string, i, '.html')
return x + y
except:
return "Not found."
return
|
#!/usr/bin/python
# coding=utf-8
class Fibs(object):
def __init__(self):
self.a = 0
self.b = 1
def next(self):
self.a, self.b = self.b, self.a + self.b
return self.a
def __iter__(self):
return self
if __name__ == "__main__":
fibs = Fibs()
for fib in fibs:
if fib > 1000:
break
print(fib)
|
# This sample tests that arbitrary expressions (including
# subscripts) work for decorators. This support was added
# in Python 3.9.
my_decorators = (staticmethod, classmethod, property)
class Foo:
# This should generate an error if version < 3.9.
@my_decorators[0]
def my_static_method():
return 3
# This should generate an error if version < 3.9.
@my_decorators[1]
def my_class_method(cls):
return 3
# This should generate an error if version < 3.9.
@my_decorators[2]
def my_property(self):
return 3
Foo.my_static_method()
Foo.my_class_method()
Foo().my_property
|
largura=l=int(input("digite a largura: "))
altura=a=int(input("digite a altura: "))
while altura>0:
largura=l
while largura >0:
if (altura==a or altura ==1):
print("#", end="")
else:
if largura==1 or largura ==l:
print("#", end="")
else:
print("", end=" ")
largura-=1
print()
altura-=1
|
'''
Author: jianzhnie
Date: 2021-11-08 18:25:03
LastEditTime: 2022-02-25 11:12:28
LastEditors: jianzhnie
Description:
'''
|
#String Rotation:Assumeyou have a method isSubstringwhich checks if oneword is a substring of another. Given two strings, sl and s2, write code to check if s2 is a rotation of sl using only one call to isSubstring (e.g., "waterbottle" is a rotation of"erbottlewat").
#do special caracters as spaces are in the strign or do they matter A:only letters from a-z
#if the word is terbottlewa erbottlewat
# i dont know how to make it o(n) will use 2 indices and see how far i go
def rotation(str1,str2):# O(n)
ith=0
jth=0
while jth < len(str2): #this is O(n)
if str1[ith]==str2[jth]:
ith+=1
else:
ith=0
jth+=1
return isSubstring(str2[:-ith], str1)
def isSubstring(str1,str2):
return str1 in str2 #this is O(n)
print (rotation("terbottlewa","erbottlewat"))
print (rotation("waterbottle","erbottlewat"))
#lol i did it in O(n) i was considering that the string checks could lead me
#to a different O(n*sub(n)) or something like it
# i think this solution might be faulty
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Withdraw Views
Created on Tue Aug 17 14:16:44 2021
Version: 1.0
Universidad Santo Tomás Tunja
Simulation
@author: Juana Valentina Mendoza Santamaría
@author: Alix Ivonne Chaparro Vasquez
presented to: Martha Susana Contreras Ortiz
"""
def showWithdrawal():
print("┌───────────────────────────────────────────────────────────────────────────┐")
print("| ┌─────────────────────────────────────────────────────────────────────┐ |")
print("| | | |")
print("|▓▓| . . . . |▓▓|")
print("| | o |\ /| o | | | |")
print("| | ,,_o_ | \/ |. . .,-. . .-...-... . |.-. .-. .--. |.-. | |")
print("| | c'' )? | || | | ) | ( ( || | | | ) | | |-.' | |")
print("|▓▓| '''' ' '`--| |`-´-´ ` --`|`-`|`--| '`-´ `-´`-' `-' `- |▓▓|")
print("| | ; | ._.'._.' ; | |")
print("| | `-' ' `-' | |")
print("| | ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ | |")
print("|▓▓| ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ |▓▓|")
print("| | ░░░░░░ 1) $ 100.000 ░░░░ 3) $ 500.000 ░░░░ 5) $ 1'000.000 ░░░░░ | |")
print("| | ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ | |")
print("| | ░░░░░░ 2) $ 200.000 ░░░░ 4) $ 700.000 ░░░░ 6) Other amount ░░░░░ | |")
print("|▓▓| ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ |▓▓|")
print("| | ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ | |")
print("| └─────────────────────────────────────────────────────────────────────┘ |")
print("└───────────────────────────────────────────────────────────────────────────┘")
print("| ┌─────────────────┐ ┌─────────────────┐ |")
print("| | RECEIPT | | CARD ↓ | |")
print("| └─────────────────┘ └─────────────────┘ |")
print("| ─────────────────── ┌───────────────────┐ |")
print("| └ ┘ |\____________\─────| |")
print("| ||__|░░░░░░░░░░░|___| |")
print("| └───└───────────┘───┘ |")
print("| |")
print("| ┌───────────────────────────────────────────┐ |")
print("| └───────────────────────────────────────────┘ |")
print("| |")
print("└───────────────────────────────────────────────────────────────────────────┘|\n")
def showOtherAmount():
print("┌───────────────────────────────────────────────────────────────────────────┐")
print("| ┌─────────────────────────────────────────────────────────────────────┐ |")
print("| | | |")
print("|▓▓| . . . . |▓▓|")
print("| | o |\ /| o | | | |")
print("| | ,,_o_ | \/ |. . .,-. . .-...-... . |.-. .-. .--. |.-. | |")
print("| | c'' )? | || | | ) | ( ( || | | | ) | | |-.' | |")
print("|▓▓| '''' ' '`--| |`-´-´ ` --`|`-`|`--| '`-´ `-´`-' `-' `- |▓▓|")
print("| | ; | ._.'._.' ; | |")
print("| | `-' ' `-' | |")
print("| | ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ | |")
print("|▓▓| ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ |▓▓|")
print("| | ░░Please, enter the withdrawal amount from $10.000 to $3'000.000.░░ | |")
print("| | ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ | |")
print("| | ░░░░░░░░░░░░░░░░░░░░░░░░░░ $___________ ░░░░░░░░░░░░░░░░░░░░░░░░░░ | |")
print("|▓▓| ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ |▓▓|")
print("| | ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ | |")
print("| └─────────────────────────────────────────────────────────────────────┘ |")
print("└───────────────────────────────────────────────────────────────────────────┘")
print("| ┌─────────────────┐ ┌─────────────────┐ |")
print("| | RECEIPT | | CARD ↓ | |")
print("| └─────────────────┘ └─────────────────┘ |")
print("| ─────────────────── ┌───────────────────┐ |")
print("| └ ┘ |\____________\─────| |")
print("| ||__|░░░░░░░░░░░|___| |")
print("| └───└───────────┘───┘ |")
print("| |")
print("| ┌───────────────────────────────────────────┐ |")
print("| └───────────────────────────────────────────┘ |")
print("| |")
print("└───────────────────────────────────────────────────────────────────────────┘|\n")
def showInvalidAmount():
print("┌───────────────────────────────────────────────────────────────────────────┐")
print("| ┌─────────────────────────────────────────────────────────────────────┐ |")
print("| | | |")
print("|▓▓| . . . . |▓▓|")
print("| | o |\ /| o | | | |")
print("| | ,,_o_ | \/ |. . .,-. . .-...-... . |.-. .-. .--. |.-. | |")
print("| | c'' )? | || | | ) | ( ( || | | | ) | | |-.' | |")
print("|▓▓| '''' ' '`--| |`-´-´ ` --`|`-`|`--| '`-´ `-´`-' `-' `- |▓▓|")
print("| | ; | ._.'._.' ; | |")
print("| | `-' ' `-' | |")
print("| | ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ | |")
print("|▓▓| ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ |▓▓|")
print("| | ░░ The selected amount is incorrect. ░░ | |")
print("| | ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ | |")
print("| | ░░ I'm sorry! ░░ | |")
print("|▓▓| ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ |▓▓|")
print("| | ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ | |")
print("| └─────────────────────────────────────────────────────────────────────┘ |")
print("└───────────────────────────────────────────────────────────────────────────┘")
print("| ┌─────────────────┐ ┌─────────────────┐ |")
print("| | RECEIPT | | CARD ↓ | |")
print("| └─────────────────┘ └─────────────────┘ |")
print("| ─────────────────── ┌───────────────────┐ |")
print("| └ ┘ |\____________\─────| |")
print("| ||__|░░░░░░░░░░░|___| |")
print("| └───└───────────┘───┘ |")
print("| |")
print("| ┌───────────────────────────────────────────┐ |")
print("| └───────────────────────────────────────────┘ |")
print("| |")
print("└───────────────────────────────────────────────────────────────────────────┘|\n")
def showValidAmount():
print("┌───────────────────────────────────────────────────────────────────────────┐")
print("| ┌─────────────────────────────────────────────────────────────────────┐ |")
print("| | | |")
print("|▓▓| . . . . |▓▓|")
print("| | o |\ /| o | | | |")
print("| | ,,_o_ | \/ |. . .,-. . .-...-... . |.-. .-. .--. |.-. | |")
print("| | c'' )? | || | | ) | ( ( || | | | ) | | |-.' | |")
print("|▓▓| '''' ' '`--| |`-´-´ ` --`|`-`|`--| '`-´ `-´`-' `-' `- |▓▓|")
print("| | ; | ._.'._.' ; | |")
print("| | `-' ' `-' | |")
print("| | ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ | |")
print("|▓▓| ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ |▓▓|")
print("| | ░░ The operation has been successful. ░░ | |")
print("| | ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ | |")
print("| | ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ | |")
print("|▓▓| ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ |▓▓|")
print("| | ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ | |")
print("| └─────────────────────────────────────────────────────────────────────┘ |")
print("└───────────────────────────────────────────────────────────────────────────┘")
print("| ┌─────────────────┐ ┌─────────────────┐ |")
print("| | RECEIPT | | CARD ↓ | |")
print("| └─────────────────┘ └─────────────────┘ |")
print("| ─────────────────── ┌───────────────────┐ |")
print("| └ ┘ |\____________\─────| |")
print("| ||__|░░░░░░░░░░░|___| |")
print("| └───└───────────┘───┘ |")
print("| |")
print("| ┌───────────────────────────────────────────┐ |")
print("| └───────────────────────────────────────────┘ |")
print("| |")
print("└───────────────────────────────────────────────────────────────────────────┘|\n")
|
def fibbs(n):
"""
Input: the nth number.
Output: the number of the Fibonacci sequence via iteration.
"""
sequence = []
for i in range(n+1):
if i == 0:
sequence.append(0)
elif i == 1:
sequence.append(1)
else:
total = sequence[i - 2] + sequence[i - 1]
sequence.append(total)
return (sequence[-1])
def fibbs_r(n, a = 0, b = 1):
"""
Input: the nth number.
Output: the number of the Fiboacci sequence via recursion.
"""
if n == a:
return a
if n == b:
return b
else:
return (fibbs_r(n-1) + fibbs_r(n - 2))
|
def fromETH(amt, px):
return amt*px
def toETH(amt, px):
return amt/px
def toOVL(amt, px):
return fromETH(amt, px)
def fromOVL(amt, px):
return toETH(amt, px)
def px_from_ret(px0: float, ret: float) -> float:
'''get the new price given a return'''
ret = ret/100
return (ret + 1)*px0
def pnl(amt, ret):
return amt * (1 + ret/100)
def get_imbalance(longs, shorts):
return longs - shorts
def funding(k, imb):
return k*imb
def funding_rate(k, imb, side_oi):
'''side_oi is volume of long or short side'''
return k*imb/side_oi
|
def simpleornot(n, out=0):
"""
Функция определяет простое или нет число
:param n: натурально число от 1 до 1000
:param out: 1 - выводим 1 или 0,
0 - печатает
:return: 1 для простого, 0 для непростого
"""
if type(n) == int:
if 0 < n < 1001:
if n == 1 and n == 2:
if out:
return 1
else:
print(f'{n} - простое число')
elif 0 not in [n % i for i in range(2, n)]:
if out:
return 1
else:
print(f'{n} - простое число')
else:
if out:
return 0
else:
print(f'{n} - непростое число')
else:
print(f'Введите натурально число от 1 до 1000')
else:
print(f'Введите натурально число от 1 до 1000')
def find_deviders(n,out='all'):
"""
Функция выводит список всех делителей
:param n: натурально число от 1 до 1000
:param out: 'all' - выводит все простые,
'min' - выводит минимальный,
'max' - выводит максимальный,
:return: список всех делителей,
или мин или макс из них
"""
if type(n) == int:
if 0 < n < 1001:
all_div =[i for i in range(1, n + 1) if n % i == 0]
if out == 'all': return all_div
if out == 'max': return max(all_div)
if out == 'min': return min(all_div)
else:
print(f'Введите натурально число от 1 до 1000')
else:
print(f'Введите натурально число от 1 до 1000')
def show_simpledeviders(n, out='all'):
"""
Функция выводит список всех простых делителей,
или минимальный или максимальный простой делитель
:param n: натурально число от 1 до 1000
:param out: 'all' - выводит все простые,
'min' - выводит минимальный,
'max' - выводит максимальный,
:return: список, мин или макс простых делителей.
"""
deviders = find_deviders(n, 'all')
simp_dev = [el for el in deviders if simpleornot(el,1)]
if out == 'all': return simp_dev
elif out == 'max': return max(simp_dev)
elif out == 'min': return min(simp_dev)
def simple_multipliers(n):
"""
Функция раскладывает число на простые множители
:param n: натурально число от 1 до 1000
:return: список всех делителей
"""
ans = []
d = 2
while d * d <= n:
if n % d == 0:
ans.append(d)
n //= d
else:
d += 1
if n > 1:
ans.append(n)
return ans
if __name__ == '__main__':
n = 169
simpleornot(n, 0)
print(find_deviders(n))
print(show_simpledeviders(n, 'max'))
print(simple_multipliers(n))
|
class Results:
def __init__(self, error, error_type, description, sequence, activity=None, activity_class=None):
self.error = error
self.error_type = error_type
self.description = description
self.sequence = sequence
self.activity = activity
self.activity_class = activity_class
|
n=3
z=65
for i in range(n):
k=z
for j in range(n-i):
print(' ',end='')
for j in range(2*i+1):
print(chr(k),end='')
k-=1
z=z+2
print()
for i in range(1,n):
c=z-4
for j in range(i):
print(' ',end='')
for j in range((2*n)-2*i-1):
print(chr(c),end='')
c-=1
z=z-2
print()
|
with open("pos_tweets.txt") as input_file:
text = input_file.read()
text_set = set(text.split(" "))
for word in text_set:
print(word,text.count(word))
|
#coding=utf-8
__all__ = ["ModelConfig", "TrainerConfig"]
class ModelConfig(object):
vocab_size = 104810
embedding_dim = 300
embedding_droprate = 0.3
lstm_depth = 3
lstm_hidden_dim = 300
lstm_hidden_droprate = 0.3
passage_indep_embedding_dim = 300
passage_aligned_embedding_dim = 300
beam_size = 32
dict_path = "data/featurized/vocab.txt"
pretrained_emb_path = "data/featurized/embeddings.npy"
class TrainerConfig(object):
learning_rate = 1e-3
l2_decay_rate = 5e-4
gradient_clipping_threshold = 20
data_dir = "data/featurized"
save_dir = "models"
use_gpu = False
trainer_count = 1
train_batch_size = trainer_count * 8
epochs = 20
# This parameter is for debug printing.
# If it set to 0, no information will be printed.
show_parameter_status_period = 0
checkpoint_period = 100
log_period = 5
# This parameter is used to resume training.
# This path can be set to a previously trained model.
init_model_path = None
|
a0 = 27.5
a4 = a0 * 2 ** 4
default_key = "c"
match_roman = "[ivIV]?[ivIV]?[iI]?"
intervals = {"P1": 0, "m2": 1, "M2": 2, "m3": 3, "M3": 4, "P4": 5, "TT": 6, "P5": 7, "m6": 8, "M6": 9, "m7": 10, "M7": 11, "P8": 12, "m9": 13, "M9": 14, "m10": 15, "M10": 16, "P11": 17, "d12": 18, "P12": 19, "m13": 20, "M13": 21, "m14": 22, "M14": 23, "P15": 24}
base_qualities = {"^": ["P1", "M3", "P5"], "-": ["P1", "m3", "P5"], "*": ["P1", "m3", "TT"], "+": ["P1", "M3", "m6"]}
extensions = {"7": ["m7"], "^7": ["M7"], "9": ["m7", "M9"], "^9": ["M7", "M9"], "11": ["m7", "M9", "P11"], "^11": ["M7", "M9", "P11"], "69": ["M6", "M9"], "6": ["M6"]}
chord_romans = {"i": 0, "ii": 2, "iii": 4, "iv": 5, "v": 7, "vi": 9, "vii": 11}
progressions = {"I": ["iii", "vi", "ii", "IV", "V", "vii*"], "i": ["VII", "III", "VI", "ii*", "iv", "V", "vii*"], "ii": ["V", "vii*"], "iii": ["vi"], "III": ["VI"], "IV": ["V", "vii*"], "iv": ["V", "vii*"], "V": ["I", "i"], "v": ["I", "i"], "vi": ["ii", "IV"], "VI": ["ii*", "iv"], "vii*": ["I", "i"], "vii": ["I", "i"]}
equal = tuple([2 ** (i / 12) for i in range(12)])
just = ((1.0, 1.0), (16.0, 15.0), (9.0, 8.0), (6.0, 5.0), (5.0, 4.0), (4.0, 3.0), (45.0, 32.0), (3.0, 2.0), (8.0, 5.0), (5.0, 3.0), (9.0, 5.0), (15.0, 8.0))
terry = ((1.0, 1.0), (16.0, 15.0), (10.0, 9.0), (6.0, 5.0), (5.0, 4.0), (4.0, 3.0), (64.0, 45.0), (3.0, 2.0), (8.0, 5.0), (27.0, 16.0), (16.0, 9.0), (15.0, 8.0))
young = ((1.0, 1.0), (567.0, 512.0), (9.0, 8.0), (147.0, 128.0), (21.0, 16.0), (1323.0, 1024.0), (189.0, 128.0), (3.0, 2.0), (49.0, 32.0), (7.0, 4.0), (441.0, 256.0), (63.0, 32.0))
louis = (1, math.sqrt(5) * 0.5, math.sqrt(6) * 0.5, math.sqrt(7) * 0.5, math.sqrt(2), math.sqrt(9) * 0.5, math.sqrt(10) * 0.5, math.sqrt(11) * 0.5, math.sqrt(3), math.sqrt(13) * 0.5, math.sqrt(14) * 0.5, math.sqrt(15) * 0.5)
major = (0, 2, 4, 5, 7, 9, 11)
minor = (0, 2, 3, 5, 7, 8, 10)
chromatic = tuple(range(12))
scales = {"major": major, "minor": minor, "super_locrian": (0, 2 - 1, 4 - 1, 5 - 1, 7 - 1, 9 - 1, 11 - 1), "neapolitan_minor": (0, 2 - 1, 4 - 1, 5, 7, 9 - 1, 11), "neapolitan_major": (0, 2 - 1, 4 - 1, 5, 7, 9, 11), "oriental": (0, 2 - 1, 4, 5, 7 - 1, 9, 11 - 1), "double_harmonic": (0, 2 - 1, 4, 5, 7, 9 - 1, 11), "enigmatic": (0, 2 - 1, 4, 5 + 1, 7 + 1, 9 + 1, 11)}
notes = {"a": 0, "a#": 1, "bb": 1, "b": 2, "c": 3, "c#": 4, "db": 4, "d": 5, "d#": 6, "eb": 6, "e": 7, "f": 8, "f#": 9, "gb": 9, "g": 10, "g#": 11, "ab": 11}
midi_notes = {"a": 21, "a#": 22, "bb": 22, "b": 23, "c": 24, "c#": 25, "db": 25, "d": 26, "d#": 27, "eb": 27, "e": 28, "f": 29, "f#": 30, "gb": 30, "g": 31, "g#": 32, "ab": 32}
def mtof(midi_note):
return 2 ** ((midi_note - 69) / 12.0) * 440
def ftom(freq):
return math.log(freq / 440.0, 2) * 12 + 69
def ftomi(freq):
return int(round(ftom(freq)))
def extractPitchClass(pitch):
parsed = re.match("([a-zA-Z]#?b?)(\d+)", pitch)
try:
pitch_class = parsed.group(1)
except AttributeError:
return pitch
return pitch_class
def ptom(pitch):
pitch_class = extractPitchClass(pitch.lower())
register = int(pitch[-1])
midi_note = midi_map[pitch_class]
midi_note += register * 12
return midi_note
def edo(degree, divs=12):
return 2 ** (degree / float(divs))
def edo_ratios(divs=12):
return [(edo(i, divs), 1.0) for i in range(1, divs + 1)]
def edo_scale(divs=12):
return [edo(i, divs) for i in range(1, divs + 1)]
def nti(note):
""" Note to index
returns the index of enharmonic note names
or False if not found
"""
return notes.get(note, False)
def ntf(note, octave=None, ratios=None):
""" Note to freq
"""
note = note.lower()
if re.match("[a-zA-Z]#?b?\d+", note) is not None:
parsed = re.match("([a-zA-Z]#?b?)(\d+)", note)
note = parsed.group(1)
octave = int(parsed.group(2))
if ratios is None:
ratios = terry
if octave is None:
octave = 4
note_index = nti(note)
mult = ratios[note_index][0] / ratios[note_index][1]
if note_index >= 3:
octave -= 1
return mult * a0 * 2.0 ** octave
def stf(index):
degree = index % 24
octave = index / 24
return (2 ** (degree / 24.0)) * (a0 / 4.0) * (2.0 ** octave)
def mtf(midi_note):
return 2 ** ((midi_note - 69) / 12.0) * 440.0
def fts(freq):
all_freq = [stf(index) for index in range(2 ** 8)]
count = 0
cfreq = 0
while freq > cfreq and count < 2 ** 8:
cfreq = all_freq[count]
count = count + 1
count = count - 1
return count % 55
def nts(note, octave):
octave = octave if octave >= -2 else -2
octave = octave if octave <= 8 else 8
degree = notes[note] * 2
degree = degree + ((octave + 2) * 24)
return degree
def getmultiplier(ratios, scale, degree):
base = scale[(degree - 1) % len(scale)]
octave = degree // (len(scale) + 1)
mult = ratios[base]
if isinstance(mult, tuple):
mult = mult[0] / mult[1]
mult = mult * 2 ** octave
return mult
def int_to_byte_list(val):
return list(map(int, list(bin(val))[2:]))
def str_to_byte_list(val):
return list(map(int, val))
def to_scale_mask(mapping):
mask = []
if isinstance(mapping, int):
mask = int_to_byte_list(mapping)
elif isinstance(mapping, bytes):
for i in list(mapping):
mask += int_to_byte_list(i)
elif isinstance(mapping, str):
mask = str_to_byte_list(mapping)
elif isinstance(mapping, list) or isinstance(mapping, tuple):
mask = list(map(int, mapping))
else:
raise NotImplemented
return mask
def scale_mask_to_indexes(mask):
mask = to_scale_mask(mask)
scale_indexes = []
for i, m in enumerate(mask):
if m == 1:
scale_indexes += [i]
return scale_indexes
def tofreqs(degrees=None, root=261.63, ratios=None, scale=None, scale_mask=None):
if ratios is None:
ratios = just
if scale is None:
scale = major
if degrees is None:
degrees = range(len(scale))
if scale_mask is not None:
scale = scale_mask_to_indexes(scale_mask)
freqs = []
for degree in degrees:
freq = root * getmultiplier(ratios, scale, degree)
freqs += [freq]
return freqs
def fromdegrees(scale_degrees=None, octave=2, root="c", scale=None, ratios=None):
if scale_degrees is None:
scale_degrees = [1, 3, 5]
if ratios is None:
ratios = terry
if scale is None:
scale = major
freqs = []
root = ntf(root, octave)
for index, degree in enumerate(scale_degrees):
degree = int(degree)
register = degree // (len(scale) + 1)
chromatic_degree = scale[(degree - 1) % len(scale)]
ratio = ratios[chromatic_degree]
freqs += [root * (ratio[0] / ratio[1]) * 2 ** register]
return freqs
def get_quality(name):
quality = "-" if name.islower() else "^"
quality = "*" if re.match(match_roman + "[*]", name) is not None else quality
return quality
def get_extension(name):
return re.sub(match_roman + "[/*+]?", "", name)
def get_intervals(name):
quality = get_quality(name)
extension = get_extension(name)
chord = base_qualities[quality]
if extension != "":
chord = chord + extensions[extension]
return chord
def get_freq_from_chord_name(name, root=440, octave=3, ratios=just):
index = get_chord_root_index(name)
freq = ratios[index]
freq = root * (freq[0] / freq[1]) * 2 ** octave
return freq
def strip_chord(name):
root = re.sub("[#b+/*^0-9]+", "", name)
return root.lower()
def get_chord_root_index(name):
root = chord_romans[strip_chord(name)]
if "#" in name:
root += 1
if "b" in name:
root -= 1
return root % 12
def add_intervals(a, b):
a = intervals[a]
b = intervals[b]
c = a + b
for interval, index in intervals.items():
if c == index:
c = interval
return c
def get_ratio_from_interval(interval, ratios):
try:
index = intervals[interval]
except IndexError:
log("Interval out of range, doh. Here have a P1")
index = 0
try:
ratio = ratios[index]
ratio = ratio[0] / ratio[1]
except IndexError:
base_index = index % 12
ratio = ratios[base_index]
ratio = ratio[0] / ratio[1]
register = (index - base_index) / 12
ratio *= 2 ** register
return ratio
def next_chord(name):
name = strip_chord(name)
return random.choice(progressions[name])
def chord(name, key=None, octave=3, ratios=None):
if key is None:
key = default_key
if ratios is None:
ratios = terry
key = ntf(key, octave, ratios)
root = ratios[get_chord_root_index(name)]
root = key * (root[0] / root[1])
name = re.sub("[#b]+", "", name)
chord = get_intervals(name)
chord = [get_ratio_from_interval(interval, ratios) for interval in chord]
chord = [root * ratio for ratio in chord]
return chord
def chords(names, key=None, octave=3, ratios=just):
if key is None:
key = default_key
return [chord(name, key, octave, ratios) for name in names]
def fit_scale(freq, scale):
return min(scale, key=lambda x: abs(x - freq))
def fit(freq, low=20, high=20000, get_change=False):
""" fit the given freq within the given freq range,
by transposing up or down octaves """
if high < low * 2:
high = low * 2
def shift(freq, low, high, octave_shift=0):
if freq < low:
return shift(freq * 2, low, high, octave_shift + 1)
if freq > high:
return shift(freq * 0.5, low, high, octave_shift - 1)
return freq, octave_shift
freq, octave = shift(freq, low, high)
if octave == 0:
mult = 1
elif octave > 0:
mult = 2 ** octave
elif octave < 0:
mult = 1.0 / (2 ** abs(octave))
if get_change == True:
return freq, mult
else:
return freq
|
def cipher():
user_input = input("Please provide a word: ")
|
# -*- coding: utf-8 -*-
usr_number = int(input("Enter a number to calculate: "))
if usr_number > 1:
for n in range(2, usr_number):
if (usr_number % n == 0):
print(f'{n} is not a prime number')
else:
print(f'{n} is a prime number')
|
date_fullyear = '[0-9]{4}'
date_mday = '[0-9]{2}'
date_month = '[0-9]{2}'
full_date = f'{date_fullyear}-{date_month}-{date_mday}'
time_hour = '[0-9]{2}'
time_minute = '[0-9]{2}'
time_second = '[0-9]{2}'
time_secfrac = '\\.[0-9]+'
partial_time = f'{time_hour}:{time_minute}:{time_second}({time_secfrac})?'
time_numoffset = f'[+\\-]{time_hour}:{time_minute}'
time_offset = f'([zZ]|{time_numoffset})'
full_time = f'{partial_time}{time_offset}'
date_time = f'{full_date}[tT]{full_time}'
|
'''
Verifique se uma determinada string tem todos os símbolos em maiúsculas.
Se a string estiver vazia ou não tiver nenhuma letra,
a função deve retornar True.
Entrada: uma string.
Saída: um booleano.
'''
def remove_space(text):
text_space = []
for item in text:
if item != ' ':
text_space.append(item)
return text_space
def is_all_upper(text: str) -> bool:
contador = 0
if text == '' or text.isnumeric():
return True
else:
text = remove_space(text)
for item in text:
if item.isupper():
contador = contador + 1
if contador == text.__len__():
return True
else:
return False
if __name__ == '__main__':
# print("Example:")
#print(is_all_upper('ALL UPPER'))
# These "asserts" are used for self-checking and not for an auto-testing
#assert is_all_upper('ALL UPPER') == True
#assert is_all_upper('all lower') == False
#assert is_all_upper('mixed UPPER and lower') == False
#assert is_all_upper('') == True
#assert is_all_upper('Hi') == False
assert is_all_upper('123') == True
#print("Coding complete? Click 'Check' to earn cool rewards!")
|
__author__ = 'schien'
INSTALLED_APPS += ('storages',)
STATICFILES_STORAGE = 'storages.backends.s3boto.S3BotoStorage'
S3_URL = 'https://%s.s3.amazonaws.com/' % AWS_STORAGE_BUCKET_NAME
STATIC_URL = S3_URL
AWS_LOCATION = '/static'
AWS_HEADERS = { # see http://developer.yahoo.com/performance/rules.html#expires
'Expires': 'Thu, 31 Dec 2099 20:00:00 GMT',
'Cache-Control': 'max-age=94608000',
}
|
class SubMerchant:
def __init__(self):
self.cardAcceptorID = None
self.country = None
self.phoneNumber = None
self.address1 = None
self.postalCode = None
self.locality = None
self.name = None
self.administrativeArea = None
self.region = None
self.email = None
def set_card_acceptor_id(self, value):
self.cardAcceptorID = value
def set_country(self, value):
self.country = value
def set_phone_number(self, value):
self.phoneNumber = value
def set_address1(self, value):
self.address1 = value
def set_postal_code(self, value):
self.postalCode = value
def set_locality(self, value):
self.locality = value
def set_name(self, value):
self.name = value
def set_administrative_area(self, value):
self.administrativeArea = value
def set_region(self, value):
self.region = value
def set_email(self, value):
self.email = value
|
environment = 'MountainCar-v0'
bin_count = 9
goal_positon = 0.5
position_min = -1.2
position_max = 0.6
velocity_min = -0.07
velocity_max = 0.07
num_episodes = 10000
max_steps_in_episode = 200
verbose = 100
learning_rate = 10e-3
eps = 1
discount_factor = 0.9
panelty = -300
test_episodes = 100
bonus = 500
q_table_path="MountainCar-v0.npy"
|
#!/usr/bin/python
def BubbleSort(val):
for passnum in range(len(val)-1,0,-1):
for i in range(passnum):
if val[i]>val[i+1]:
temp = val[i]
val[i] = val[i+1]
val[i+1] = temp
DaftarAngka = [23,7,32,99,4,15,11,20]
BubbleSort(DaftarAngka)
print(DaftarAngka)
|
"""Slack toolbox"""
def make_slack_response(
response_type="ephemeral", text="", attachments=None, blocks=None
):
return {
"response_type": response_type,
"text": text,
"attachments": [attachments] if attachments else [],
"blocks": blocks if blocks else [],
}
|
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Constants for GradientFuzz training process."""
# Execution time limits.
DATA_GEN_TIMEOUT = 60 * 60 * 1
TRAIN_TIMEOUT = 60 * 60 * 2
LOC_GEN_TIMEOUT = 60 * 60 * 3
MUT_GEN_TIMEOUT = 60 * 60 * 3
# Dataset size.
MIN_NUM_INPUTS = 10
# Shorten number of runs during unit tests.
NUM_TEST_EPOCHS = 5
NUM_EPOCHS = 50
# For GCS.
GRADIENTFUZZ_DIR = 'gradientfuzz'
# Corpus directory (corpora backups stored here).
CORPUS_DIR = 'corpus'
CORPUS_SUFFIX = '-raw-inputs'
# Script names.
GENERATE_DATA_SCRIPT = 'libfuzzer_to_numpy.py'
TRAIN_MODEL_SCRIPT = 'train.py'
GENERATE_LOCATIONS_SCRIPT = 'gradient_gen_critical_locs.py'
GENERATE_MUTATIONS_SCRIPT = 'gen_mutations.py'
# For `libfuzzer_to_numpy.py`.
INPUT_DIR_FLAG = '--input-dir'
DATASET_NAME_FLAG = '--dataset-name'
CUTOFF_PERCENTILE_FLAG = '--cutoff-percentile'
CUTOFF_STD_FLAG = '--cutoff-std'
MEDIAN_MULT_FLAG = '--median-mult-cutoff'
FUZZ_TARGET_BINARY_FLAG = '--fuzz-target-binary'
DEFAULT_MEDIAN_MULT_CUTOFF = '2'
# For `train.py`.
RUN_NAME_FLAG = '--run-name'
NEUZZ_CONFIG_FLAG = '--neuzz-config'
LR_FLAG = '--lr'
EPOCHS_FLAG = '--epochs'
OPTIMIZER_FLAG = '--optimizer'
VAL_SPLIT_FLAG = '--val-split'
ARCHITECTURE_FLAG = '--architecture'
BATCH_SIZE_FLAG = '--batch-size'
VAL_BATCH_SIZE_FLAG = '--val-batch-size'
NUM_HIDDEN_FLAG = '--num-hidden'
RUN_NAME_SUFFIX = '-gradientfuzz'
# For `gradient_gen_critical_locs.py`.
PATH_TO_SEEDS_FLAG = '--path-to-seeds'
PATH_TO_LENGTHS_FLAG = '--path-to-lengths'
GENERATION_NAME_FLAG = '--generation-name'
GRADIENT_GEN_METHOD_FLAG = '--gradient-gen-method'
NUM_OUTPUT_LOCS_FLAG = '--num-output-locs'
TOP_K_FLAG = '--top-k'
# For `gen_mutations.py`.
MUTATION_NAME_FLAG = '--mutation-name'
MUTATION_GEN_METHOD_FLAG = '--mutation-gen-method'
NUM_MUTATIONS_FLAG = '--num-mutations'
NEIGHBORHOOD_MAX_WIDTH_FLAG = '--neighborhood-max-width'
ARITH_MIN_FLAG = '--arith-min'
ARITH_MAX_FLAG = '--arith-max'
class ExitCode:
"""Exit code for training and generation."""
SUCCESS = 0
INVALID_PATH = 1
CORPUS_TOO_SMALL = 2
TENSORFLOW_ERROR = 3
|
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
USER_OWNER_TYPE = "User"
DASHBOARD_OWNER_TYPE = "Dashboard"
NAME_FIELD = "name"
DESCRIPTION_FIELD = "description"
JSON_METADATA_FIELD = "json_metadata"
OWNER_ID_FIELD = "owner_id"
OWNER_TYPE_FIELD = "owner_type"
DASHBOARD_ID_FIELD = "dashboard_id"
OWNER_OBJECT_FIELD = "owner_object"
DASHBOARD_FIELD = "dashboard"
PARAMS_PROPERTY = "params"
FILTER_SET_API_PERMISSIONS_NAME = "FilterSets"
|
def paired_digits_count(data, skip):
return sum([int(d) for i, d in enumerate(data) if data[i - skip] == d])
with open("day01.txt") as f:
data = f.readline()
half = int(len(data) / 2)
print("2017 day 1 part 1: %d" % paired_digits_count(data, 1))
print("2017 day 1 part 2: %d" % paired_digits_count(data, half))
|
print("Please enter how many marbles you would like: ", end = "")
n = int(input())
while n != 0:
print("Please enter the how many marbles player one is taking: ", end = "")
take = int(input())
if n <= 5:
print("Player one wins!")
break
elif take > n or take > 5 or take == 0:
print("You're entering a number too large.")
else:
n -= take
print("There are", n, "marbles left")
print("Please enter the how many marbles player two is taking:", end = "")
take = int(input())
if n <= 5:
print("Player two wins!")
break
elif take > n or take > 5 or take == 0:
print("You're entering a number too large")
else:
n -= take
print("There are", n, "marbles left")
|
# Soultion for Project Euler Problem #8 - https://projecteuler.net/problem=8
# (c) 2017 dpetker
TEST_VAL = '7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450'
curr_max = 0
def multiply_range(test_str):
curr_prod = 1
for c in test_str:
curr_prod *= int(c)
return curr_prod
for ctr in range(0, len(TEST_VAL) - 13):
temp_prod = multiply_range(TEST_VAL[ctr : ctr + 13])
if temp_prod > curr_max:
curr_max = temp_prod
print('The thirteen adjacent digits in the 1000-digit number that have the greatest product is {}'.format(curr_max))
|
"""
Sponge Knowledge Base
Demo - action context actions
"""
class ActionWithContextActions(Action):
def onConfigure(self):
self.withLabel("Action with context actions").withArgs([
StringType("arg1").withLabel("Argument 1"),
StringType("arg2").withLabel("Argument 2")
]).withNoResult().withFeature("contextActions", [
SubAction("ActionWithContextActionsContextAction1").withArg("arg", "@this"),
SubAction("ActionWithContextActionsContextAction2").withArg("arg", "arg2"),
SubAction("ActionWithContextActionsContextAction3").withArg("arg2", "arg2"),
SubAction("ActionWithContextActionsContextAction4").withArg("arg1NotVisible", "arg1"),
SubAction("ActionWithContextActionsContextAction5").withArg("arg", "@this"),
SubAction("ActionWithContextActionsContextAction6").withArg("arg", "@this"),
SubAction("MarkdownText")
])
self.withFeature("icon", "attachment")
def onCall(self, arg1, arg2):
pass
class ActionWithContextActionsContextAction1(Action):
def onConfigure(self):
self.withLabel("Context action 1").withArgs([
RecordType("arg").withFields([
StringType("arg1").withLabel("Argument 1"),
StringType("arg2").withLabel("Argument 2")
]).withFeature("visible", False)
]).withResult(StringType())
self.withFeatures({"visible":False, "icon":"tortoise"})
def onCall(self, arg):
return arg["arg1"]
class ActionWithContextActionsContextAction2(Action):
def onConfigure(self):
self.withLabel("Context action 2").withArgs([
StringType("arg").withLabel("Argument"),
StringType("additionalText").withLabel("Additional text"),
]).withResult(StringType())
self.withFeatures({"visible":False, "icon":"tortoise"})
def onCall(self, arg, additionalText):
return arg + " " + additionalText
class ActionWithContextActionsContextAction3(Action):
def onConfigure(self):
self.withLabel("Context action 3").withArgs([
StringType("arg1").withLabel("Argument 1"),
StringType("arg2").withLabel("Argument 2"),
StringType("additionalText").withLabel("Additional text"),
]).withResult(StringType())
self.withFeatures({"visible":False, "icon":"tortoise"})
def onCall(self, arg1, arg2, additionalText):
return arg1 + " " + arg2 + " " + additionalText
class ActionWithContextActionsContextAction4(Action):
def onConfigure(self):
self.withLabel("Context action 4").withArgs([
StringType("arg1NotVisible").withLabel("Argument 1 not visible").withFeatures({"visible":False}),
StringType("arg2").withLabel("Argument 2"),
]).withResult(StringType())
self.withFeatures({"visible":False, "icon":"tortoise"})
def onCall(self, arg1NotVisible, arg2):
return arg1NotVisible + " " + arg2
class ActionWithContextActionsContextAction5(Action):
def onConfigure(self):
self.withLabel("Context action 5").withArgs([
RecordType("arg").withFields([
StringType("arg1").withLabel("Argument 1"),
StringType("arg2").withLabel("Argument 2")
]).withFeatures({"visible":False}),
StringType("additionalText").withLabel("Additional text")
]).withResult(StringType())
self.withFeatures({"visible":False, "icon":"tortoise"})
def onCall(self, arg, additionalText):
return arg["arg1"] + " " + additionalText
class ActionWithContextActionsContextAction6(Action):
def onConfigure(self):
self.withLabel("Context action 6").withArgs([
RecordType("arg").withFields([
StringType("arg1").withLabel("Argument 1"),
StringType("arg2").withLabel("Argument 2")
])
]).withNoResult()
self.withFeatures({"visible":False, "icon":"tortoise"})
def onCall(self, arg):
pass
|
city = "narva"
estonianPopulation = [
["tallinn", 441000],
["tartu", 94000],
["narva", 58000],
["parnu", 41000]
]
for p in estonianPopulation:
if p[0] == city:
print("Population of " + p[0].capitalize() + ": " + str(p[1]))
break
|
"""
def my_function():
print("I'm inside function")
def function1():
var2 = 5
print(var1)
def function2():
var3 = 7
print(var3)
print(var1)
#print(var2)
"""
def func():
var4 = 6
if var4 > var1:
print("var4 is bigger in func")
else:
print("var4 is smaller in func")
def my_f():
for i in range(10):
print(i)
var1 = 3
my_function()
function1()
function2()
func()
my_f()
print("all functions are finished")
|
def iter_rings(data, pathcodes):
ring = []
# TODO: Do this smartly by finding when pathcodes changes value and do
# smart indexing on data, instead of iterating over each coordinate
for point, code in zip(data, pathcodes):
if code == 'M':
# Emit the path and start a new one
if len(ring):
yield ring
ring = [point]
elif code == 'L':
ring.append(point)
else:
raise ValueError('Unrecognized code: {}'.format(code))
if len(ring):
yield ring
|
text = 'hello'
fileName = 'data.txt'
file=open(fileName, 'w')
file.write(text)
file.close()
file = open(fileName, 'r')
input_text = file.readline()
file.close()
print(input_text)
|
class SearchNode:
def __init__(self, pos, parent=None, cost_to_origin=0, cost_to_target=0):
self.pos = pos # Might have to change to tuple
self.parent = parent
self.neighbours = []
self.cost_to_origin = cost_to_origin
self.cost_to_target = cost_to_target
def get_total_cost(self):
"""
Function that computes our node's current total cost
"""
return self.cost_to_origin + self.cost_to_target
def __str__(self):
return f"Pos: {self.pos}, Parent: {self.parent.pos}"
def __repr__(self):
return str(self)
class SearchTree:
def __init__(self):
self.root = None
self.target_pos = None
self.mapa = None
self.objective = None
self.open_nodes = []
self.closed_nodes = []
self.newly_created_nodes = []
self.limit = 1500 #TODO: TEST WITH DIFFERENT VALUES
def search_for_path(
self,
mapa,
current_pos,
target_pos,
enemies,
time_to_explode=None,
objective="FIND_WALL",
dangerous_tiles=[],
):
"""
Function used to search for the best path between a given position and target
@param mapa: Our current map
@param current_pos: Our root node's position
@param target_pos: Our target's position
"""
self.mapa = mapa
self.objective = objective
self.root = SearchNode(current_pos)
self.target_pos = target_pos
self.open_nodes = [self.root]
self.closed_nodes = []
self.newly_created_nodes = []
open_nodes_number = 0
while self.open_nodes != []:
# Get the currently open, lowest cost node
current_node = min(self.open_nodes, key=lambda node: node.get_total_cost())
self.open_nodes.remove(current_node)
self.closed_nodes.append(current_node)
# Check if that node is the goal
if self.check_if_goal_reached(current_node.pos, target_pos, objective):
return self.get_path(current_node)
if (
current_node.neighbours == []
): # Compute the node's neighbours if it has none yet
self.compute_node_neighbours(
current_node, enemies, time_to_explode, dangerous_tiles
)
for neighbour_node in current_node.neighbours:
if neighbour_node in self.closed_nodes:
continue
new_cost_to_neighbour = current_node.cost_to_origin + 1
if (
neighbour_node not in self.open_nodes
or new_cost_to_neighbour < neighbour_node.cost_to_origin
):
neighbour_node.cost_to_origin = new_cost_to_neighbour
neighbour_node.parent = current_node
if neighbour_node not in self.open_nodes:
self.open_nodes.append(neighbour_node)
open_nodes_number += 1
if open_nodes_number > self.limit:
return None
return None
def compute_distance(self, pos_one, pos_two):
"""
Function that computes the possible shortest distance between 2 positions
@param pos_one: Starting position
@param pos_one: Target position
"""
return abs(pos_two[0] - pos_one[0] + pos_two[1] - pos_one[1])
def compute_node_neighbours(self, node, enemies, time_to_explode, dangerous_tiles):
"""
Function that computes all possible moves starting at a given node and adds them to the node's neighbours
@param node: The node who'se neighbours we want to discover
"""
for i in ["w", "a", "s", "d"]:
if self.objective == "POWER_UP" or self.objective == "EXIT":
cx, cy = node.pos
if i == "w":
next_pos = cx, cy - 1
if i == "a":
next_pos = cx - 1, cy
if i == "s":
next_pos = cx, cy + 1
if i == "d":
next_pos = cx + 1, cy
if not self.mapa.is_blocked(next_pos) or next_pos == self.target_pos:
# If we still haven't created that node, create it
if not any(
created_node.pos == next_pos
for created_node in self.newly_created_nodes
):
neighbour = SearchNode(
next_pos,
node,
node.cost_to_origin + 1,
self.compute_distance(next_pos, self.target_pos),
)
node.neighbours.append(neighbour)
self.newly_created_nodes.append(neighbour)
else:
node.neighbours.append(
[
created_node
for created_node in self.newly_created_nodes
if created_node.pos == next_pos
][0]
)
else:
next_pos = self.mapa.calc_pos(node.pos, i)
if next_pos != node.pos:
# If we still haven't created that node, create it
if not any(
created_node.pos == next_pos
for created_node in self.newly_created_nodes
):
neighbour = SearchNode(
next_pos,
node,
node.cost_to_origin + 1,
self.compute_distance(next_pos, self.target_pos),
)
node.neighbours.append(neighbour)
self.newly_created_nodes.append(neighbour)
else:
node.neighbours.append(
[
created_node
for created_node in self.newly_created_nodes
if created_node.pos == next_pos
][0]
)
def check_if_goal_reached(self, test_pos, target_pos, objective):
"""
Function used to check if we've reached our goal
@param node: The node we want to know the path to
"""
if objective == "FIND_WALL":
return (
test_pos == (target_pos[0] - 1, target_pos[1])
or test_pos == (target_pos[0] + 1, target_pos[1])
or test_pos == (target_pos[0], target_pos[1] - 1)
or test_pos == (target_pos[0], target_pos[1] + 1)
)
return test_pos == target_pos
def get_path(self, node):
"""
Function used to backtrack and return our path
@param node: The node we want to know the path to
"""
if node.parent == None:
return [node.pos]
path = self.get_path(node.parent)
path += [node.pos]
return path
|
class Node(object):
"""二叉树节点"""
def __init__(self, elem=-1, lchild=None, rchild=None):
self.elem = elem
self.lchild = lchild
self.rchild = rchild
class CompleteBinaryTree(object):
"""完全二叉树"""
def __init__(self, root=None):
self.root = root
def add(self, elem):
"""添加节点"""
node = Node(elem)
# 如果树是空的,则对根节点赋值
if self.root == None:
self.root = node
else:
queue = [self.root]
# 广度遍历
while True:
# 出队一个元素
cur = queue.pop(0)
if cur.lchild == None:
cur.lchild = node
return
elif cur.rchild == None:
cur.rchild = node
return
else:
# 如果左右子树都不为空,入队继续遍历
queue.append(cur.lchild)
queue.append(cur.rchild)
def breadth_travel(self):
"""广度优先遍历"""
if self.root == None:
return
queue = [self.root]
while queue:
node = queue.pop(0)
print(node.elem, end=' ')
if node.lchild != None:
queue.append(node.lchild)
if node.rchild != None:
queue.append(node.rchild)
def preorder(self, node):
"""先序遍历"""
if node == None:
return
print(node.elem, end=' ')
self.preorder(node.lchild)
self.preorder(node.rchild)
def inorder(self, node):
"""中序遍历"""
if node == None:
return
self.inorder(node.lchild)
print(node.elem, end=' ')
self.inorder(node.rchild)
def postorder(self, node):
"""后序遍历"""
if node == None:
return
self.postorder(node.lchild)
self.postorder(node.rchild)
print(node.elem, end=' ')
if __name__ == '__main__':
tree = CompleteBinaryTree()
for i in range(10):
tree.add(i)
tree.breadth_travel()
print()
tree.preorder(tree.root)
print()
tree.inorder(tree.root)
print()
tree.postorder(tree.root)
|
def sl_a_func():
pass
def sl_a_func2():
pass
class SlAClass():
def __init__(self):
pass
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def new_tips(argv):
def tips(func):
def nei(a, b):
print("start %s %s" %(argv, func.__name__))
func(a, b)
print("stop")
return nei
return tips
@new_tips('add_modules')
def add(a, b):
print(a + b)
@new_tips('sub_modules')
def sub(a, b):
print(a - b)
print(add(4, 5))
print(add(7, 3))
|
def spacify(string, spaces=2):
"""Add spaces to the beginning of each line in a multi-line string."""
return spaces * " " + (spaces * " ").join(string.splitlines(True))
def multilinify(sequence, sep=","):
"""Make a multi-line string out of a sequence of strings."""
sep += "\n"
return "\n" + sep.join(sequence)
def listify(obj):
"""Convert non-list objects to lists."""
if obj is None:
return []
else:
return obj if isinstance(obj, (list, tuple)) else [obj]
|
def tail(filepath, n):
"""Similate Unix' tail -n, read in filepath, parse it into a list,
strip newlines and return a list of the last n lines"""
with open(filepath) as f:
file = f.read()
tail_result = file.split('\n')[-n:]
return tail_result
|
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param two ListNodes
@return a ListNode
"""
def mergeTwoLists(self, l1, l2):
if l1 is None:
return l2
if l2 is None:
return l1
head = ListNode(0)
l3 = head
while l1 and l2:
if l1.val < l2.val:
l3 = l1
l1 = l1.next
l3 = l3.next
else:
l3 = l2
l2 = l2.next
l3 =l3.next
if l1:
l3.next = l1
if l2:
l3.next = l2
return head
|
N, M = map(int, input().split())
A = list(map(int, input().split()))
days = N - sum(A)
if days < 0:
print(-1)
else:
print(days)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.