content stringlengths 7 1.05M |
|---|
ALPACA_END_POINT = 'https://paper-api.alpaca.markets'
ALPACA_API_KEY = 'PK45PMO9M1JFIAWKW1X1'
ALPACA_SECRET_KEY = 'l6nOaQQvgPqE98MhKjXkrZFvoKPl6ikJ7inBrEed'
POLYGON_ALPACA_WS = 'wss://alpaca.socket.polygon.io/stocks'
# POLYGON_API_KEY = 'jrQpup0rXAdbYrIRXUTOI8bZ1BkQlJiR'
POLYGON_API_KEY = 'PK45PMO9M1JFIAWKW1X1' |
class Solution:
def countVowelPermutation(self, n: int) -> int:
mod = 10**9 + 7
dp = [[0] * 5 for _ in range(n)]
for j in range(5):
dp[0][j] = 1
for i in range(1, n):
dp[i][0] = (dp[i-1][1] + dp[i-1][2] + dp[i-1][4]) % mod
dp[i][1] = (dp[i-1][0] + dp[i-1][2]) % mod
dp[i][2] = (dp[i-1][1] + dp[i-1][3]) % mod
dp[i][3] = (dp[i-1][2]) % mod
dp[i][4] = (dp[i-1][2] + dp[i-1][3]) % mod
return sum(dp[-1]) % mod
|
# -*- coding: utf-8 -*-
# AtCoder Beginner Contest
if __name__ == '__main__':
n = int(input())
a = list(map(int, input().split()))
count = 0
# See:
# https://beta.atcoder.jp/contests/abc100/submissions/2675457
for ai in a:
while ai % 2 == 0:
ai //= 2
count += 1
print(count)
|
# -*- coding: utf-8 -*-
class RabbitmqClientError(Exception):
pass
class RabbitmqConnectionError(RabbitmqClientError):
pass
class QueueNotFoundError(RabbitmqClientError):
pass
|
# -*- coding: utf-8 -*-
"""
File __init__.py
@author: ZhengYuwei
""" |
def login():
return 'login info'
a = 18
num1 = 30
num2 = 10
num2 = 20
|
A, B, C = map(int, input().split())
if (A*B*C) % 2 == 0:
print(0)
else:
abc = [A, B, C]
abc.sort()
print(abc[0] * abc[1])
|
class BaseUIHandler(object):
def handle_first_run(self):
pass
def init(self):
raise NotImplementedError('No UI handler specified!')
return False
def start(self):
return 1
|
Encoding = {\
['e']: '000',
['\0x20']: '1111',
['t']: '1100',
['a']: '10111',
['o']: '1000',
['n']: '0111',
['i']: '0110',
['s']: '0100',
['r']: '0011',
['h']: '11011',
['l']: '10101',
['d']: '10010',
['c']: '00101',
['u']: '111001',
['m']: '110101',
['f']: '101001',
['p']: '101000',
['g']: '100111',
['y']: '010110',
['w']: '010100',
[',']: '001001',
['.']: '001000',
['b']: '1110101',
['v']: '1101000',
['0']: '0101110',
['k']: '11101110',
['1']: '11101101',
['5']: '11100001',
['2']: '11010011',
['T']: '11010010',
['S']: '10011010',
['"']: '10011000',
['9']: '01011111',
['A']: '01011110',
['M']: '01010110',
['-']: '01010100',
['C']: '111011110',
['I']: '111011000',
['N']: '111010001',
['\0x27']: '111010000',
['4']: '111000110',
['3']: '111000101',
['8']: '111000001',
['B']: '111000000',
['6']: '10110110',
['R']: '10110011',
['P']: '10110010',
['E']: '010101111',
['D']: '010101011',
['H']: '010101010',
['x']: '11101111110',
['\n']: '111011111110',
['\0x9']: '111011111111',
['7']: '1110110011',
['W']: '1110100111',
['L']: '1110100101',
['O']: '1110100100',
['F']: '1110001111',
['Y']: '1110001001',
['G']: '1110001000',
['J']: '1001101110',
['z']: '0101011101',
['j']: '0101011100',
['U']: '11101111100',
['q']: '11101100101',
[':']: '11101100100',
['$']: '11100011101',
['K']: '10011011111',
[';']: '10011011110',
['V']: '111011111010',
['*']: '111000111001',
['?']: '1110001110001',
['Q']: '1110001110000',
['/']: '11101111101110',
['X']: '11101111101101',
['&']: '11101111101100',
['Z']: '111011111011111',
['!']: '1110111110111100',
['%']: '11101111101111011',
['+']: '111011111011110101',
['>']: '1110111110111101000',
['<']: '111011111011110100111',
['(']: '1110111110111101001100',
[')']: '1110111110111101001101',
['=']: '111011111011110100101',
['#']: '1110111110111101001001',
['@']: '1110111110111101001000110',
['[']: '11101111101111010010001110',
[']']: '1110111110111101001000100',
['|']: '11101111101111010010001111',
['~']: '1110111110111101001000010',
['`']: '111011111011110100100010110',
['_']: '1110111110111101001000101110',
['\0x5c']: '1110111110111101001000000',
['^']: '1110111110111101001000011',
['{']: '11101111101111010010001010',
['}']: '1110111110111101001000001',
}
|
product = {
"name":"book",
"quan":3,
"price":4.25,
}
person ={
"name":"zoy",
"first_name":"mol",
"age":39,
}
print(type(product))
print(dir(product))
print(product)
#Obtener los indices o llaves del diccionario
print(product.keys())
print(product.values())
print(product.items())
tienda = [
{"name":"chair", "price":150},
{"name":"soap", "price":10},
{'fifi':'8'}
]
print(tienda) |
# coding=utf-8
ver_info = {"major": 1,
"alias": "Config",
"minor": 0}
cfg_ver_min = 2
cfg_ver_active = 2
|
class DataHeader:
def __init__(self, name, data_type, vocab_file=None, vocab_mode="read"):
self.name = name
self.data_type = data_type
self.vocab_file = vocab_file
self.vocab_mode = vocab_mode
|
def parse_data():
with open('2019/01/input.txt') as f:
data = f.read()
return [int(num) for num in data.splitlines()]
def part_one(data):
return sum(mass // 3 - 2 for mass in data)
def part_two(data):
total = 0
for num in data:
while (num := num // 3 - 2) > 0:
total += num
return total
def main():
data = parse_data()
print(f'Day 01 Part 01: {part_one(data)}')
print(f'Day 01 Part 02: {part_two(data)}')
|
# greatest common divisor
def gcd(a, b):
while b:
a, b = b, a % b
return a
# lowest common multiple
def lcm(a, b):
return (a * b) // gcd(a, b)
|
""" ANIMATION CACHE MANAGER
mGear's animation cache manager is a tool that allows generating a Alembic GPU
cache representation of references rigs inside Autodesk Maya.
:module: mgear.animbits.cache_manager.__init__
"""
__version__ = 1.0
|
fname = input("Enter file name: ")
if len(fname) < 1:
fname = "mbox-short.txt"
fh = open(fname)
count = 0
def handle_line(line):
tokens = line.split(' ')
print(tokens[1])
count += 1
for line in fh:
if (line.startswith("From:")):
continue
if (not line.startswith("From")):
continue
handle_line(line)
print("There were", count, "lines in the file with From as the first word")
|
# Ex012.2
"""Make an algorithm that reads the price of a product, and show it's new price with a 5% discount"""
price = float(input('What is the product price?: '))
new_price = price - (price * 5 / 100)
print(f'The product that coast R$: {price:.2f}')
print(f'Will now coast R$: {new_price:.2f} with 5% discount')
|
#for i in range (1,11):
# print ("%d * 5 = %d" %(i,i*5))
# Printing Pattern
for i in range (1,5):
for j in range (0,i):
print ( " * ", end = '' )
print ('') #NExt line
# For - Else loop
for i in range (5,1,-1):
for j in range(0,i):
print ( " * ", end = '' )
print ('') #NExt line
for i in range(50, 100, 2):
print (i)
else:
print (" No breaks")
print (" Values")
#While loop
i = 10
while i < 25:
print (i)
i = i+1
# Displaying Date and time current
# The continue statement
i =1
while i < 20:
if i == 6:
print ('Hai')
continue
print (i)
i = i+2
|
"""
https://www.codewars.com/kata/52597aa56021e91c93000cb0/python
Given an array (probably with different types of values inside), move all of the zeros to the end,
keeping the order of the rest.
Example:
move_zeros([false,1,0,1,2,0,1,3,"a"])
# returns[false,1,1,2,1,3,"a",0,0]
"""
def move_zeros(array):
num_zeros = 0
output = []
for item in array:
if item == False and type(item) == bool:
output.append(False)
elif item == 0:
num_zeros += 1
else:
output.append(item)
output.extend([0] * num_zeros)
return(output)
# My 2nd approach, in-place:
def move_zeros2(array):
stop = len(array) - 1
pointer = 0
while pointer < stop:
if array[pointer] == False and type(array[pointer]) == bool:
pointer += 1
elif array[pointer] == 0:
array.append(0)
del array[pointer]
stop -= 1
else:
pointer += 1
return array
def move_zeros3(arr):
l = [i for i in arr if isinstance(i, bool) or i != 0]
return l+[0]*(len(arr)-len(l))
print(move_zeros2([False, 1, 0, 1, 2, 0, 1, 3, "a"]))
|
# Shared constants
SEGMENT_LEN = 3 # duration per spectrogram in seconds
FMIN = 30 # min frequency
FMAX = 12500 # max frequency
SAMPLING_RATE = 44100
WIN_LEN = 2048 # FFT window length
BINARY_SPEC_HEIGHT = 32 # binary classifier spectrogram height
SPEC_HEIGHT = 128 # normal spectrogram height
SPEC_WIDTH = 384 # spectrogram width
IGNORE_FILE = 'data/ignore.txt' # classes listed in this file are ignored in analysis
CLASSES_FILE = 'data/classes.txt' # list of classes used in training and analysis
CKPT_PATH = 'data/ckpt' # where to save/load model checkpoint
BINARY_CKPT_PATH = 'data/binary_classifier_ckpt' # model checkpoint for binary classifier
|
def get_input():
puzzle_input = open('./python/inputday01.txt', 'r').read()
return puzzle_input.split('\n')[:-1]
def get_fuel_required(module_mass=0):
return (module_mass//3)-2
def get_fuel_required_for_fuel(fuel_volume=0):
fuel_volume_required = (fuel_volume // 3)-2
if fuel_volume_required <= 0:
return 0
else:
return fuel_volume_required + get_fuel_required_for_fuel(fuel_volume=fuel_volume_required)
def run_part_one():
puzzle_input = get_input()
total_fuel_required = 0
for module_mass in puzzle_input:
total_fuel_required += get_fuel_required(module_mass=int(module_mass))
return total_fuel_required
def run_part_two():
# I could have simply modified the function for get_fuel_required
# but I wanted to make sure the process of part one and part two remained
# intact
puzzle_input = get_input()
total_fuel_required = 0
for module_mass in puzzle_input:
basic_fuel_for_module = get_fuel_required(module_mass=int(module_mass))
total_fuel_required += get_fuel_required_for_fuel(fuel_volume = basic_fuel_for_module) + basic_fuel_for_module
return total_fuel_required
if __name__ == "__main__":
part_one_answer = run_part_one()
print(part_one_answer)
part_two_answer_new = run_part_two()
print(part_two_answer_new)
|
# -*- coding: utf-8
def register(user_store, email, username, first_name, last_name, password):
"""
Register command
"""
return user_store.create(
email=email,
username=username,
first_name=first_name,
last_name=last_name,
password=password)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class Solution(object):
'合并两个有序数组'
def merge(self, a, b):
c = []
h = j = 0
while j < len(a) and h < len(b):
if a[j] < b[h]:
c.append(a[j])
j += 1
else:
c.append(b[h])
h += 1
if j == len(a):
for i in b[h:]:
c.append(i)
else:
for i in a[j:]:
c.append(i)
return c
'旋转数组最小值'
def minArray(self, numbers):
low, high = 0, len(numbers) - 1
while low < high:
pivot = low + (high - low) // 2
if numbers[pivot] < numbers[high]:
high = pivot
elif numbers[pivot] > numbers[high]:
low = pivot + 1
else:
high -= 1
return numbers[low]
if __name__ == '__main__':
nums = [4, 5, 6, 1, 2, 3]
test = Solution()
res = test.minArray(nums)
print('res is', res)
|
SUBLIST = 0
SUPERLIST = 1
EQUAL = 2
UNEQUAL = 3
def sublist(list_one, list_two):
one_chars = map(str, list_one)
two_chars = map(str, list_two)
list_one_str = ",".join(one_chars) + ","
list_two_str = ",".join(two_chars) + ","
if list_one_str == list_two_str:
return 2
elif list_one_str in list_two_str or list_one_str == []:
return 0
elif list_two_str in list_one_str or list_two_str == []:
return 1
else:
return 3
|
# 285. Inorder Successor in BST
# Runtime: 68 ms, faster than 85.36% of Python3 online submissions for Inorder Successor in BST.
# Memory Usage: 18.1 MB, less than 79.18% of Python3 online submissions for Inorder Successor in BST.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# Inorder tTraversal
def inorderSuccessor(self, root: TreeNode, p: TreeNode) -> TreeNode:
stack = []
find_p = False
while root or stack:
while root:
stack.append(root)
root = root.left
node = stack.pop()
if find_p:
return node
elif node == p:
find_p = True
root = node.right
return None |
# -*- coding: utf-8 -*-
"""@package scrape
@date Created on nov. 15 09:30 2017
@author samuel_r
"""
def get_translation(jp_text):
return
|
# -*- coding: utf-8 -*-
class ArchiveService:
def get_service_name(self):
return 'DEFAULT'
def submit(self, url):
pass
class ArchiveException(Exception):
pass
|
'''
Write a program that calculates the Body Mass Index (BMI) from a user's weight and height.
The BMI is a measure of some's weight taking into account their height. e.g. If a tall person and a short person both weigh the same amount, the short person is usually more overweight.
The BMI is calculated by dividing a person's weight (in kg) by the square of their height (in m).
Round the result.
'''
# 🚨 Don't change the code below 👇
height = input("enter your height in m: ")
weight = input("enter your weight in kg: ")
# 🚨 Don't change the code above 👆
#Write your code below this line 👇
bmi = float(weight) / float(height) ** 2
print(str(round(bmi))) |
def reverse(st):
st = st.split()
st.reverse()
st2 = ' '.join(st)
return st2 |
class HyperParameter:
def __init__(self, num_batches, batch_size, epoch, learning_rate, hold_prob, epoch_to_report=100):
self.num_batches = num_batches
self.batch_size = batch_size
self.epoch = epoch
self.learning_rate = learning_rate
self.hold_prob = hold_prob,
self.epoch_to_report = epoch_to_report
def __str__(self):
return "epoch: " + str(self.epoch) + ", num_batches: " + str(self.num_batches) + ", batch_size: " + str(self.batch_size) + ", learning_rate: " + str(self.learning_rate) + ", hold_prob: " + str(self.hold_prob)
|
"""
Keep in mind the following table:
╔════════════╦════════════════════════════════════════════════╗
║ ║ BITS ║
║ ╠═════╦═══════╦════════════╦═════════════════════╣
║ ║ 8 ║ 16 ║ 32 ║ 64 ║
╠════════════╬═════╬═══════╬════════════╬═════════════════════╣
║ MODULUS ║ 127 ║ 32479 ║ 2147483647 ║ 9223372036854775783 ║
╠════════════╬═════╬═══════╬════════════╬═════════════════════╣
║ MULTIPLIER ║ 14 ║ 16374 ║ 48271 ║ ║
╠════════════╬═════╬═══════╬════════════╬═════════════════════╣
║ STREAMS ║ 64 ║ 128 ║ 256 ║ 512 ║
╠════════════╬═════╬═══════╬════════════╬═════════════════════╣
║ JUMPER ║ 14 ║ 32748 ║ 22925 ║ ║
╠════════════╬═════╬═══════╬════════════╬═════════════════════╣
║ CHECKV ║ ║ ║ 399268537 ║ ║
╠════════════╬═════╬═══════╬════════════╬═════════════════════╣
║ CHECKI ║ ║ ║ 10000 ║ ║
╚════════════╩═════╩═══════╩════════════╩═════════════════════╝
"""
# import os
# EXP_DIR = os.path.dirname(os.path.abspath(__file__)) + '/resources'
# PLT_EXT = 'svg'
# RES_EXT = 'txt'
|
# This project created by urhoba
# www.urhoba.net
#region DB Settings
class DBSettings:
sqliteDB = "db.urhoba"
#endregion
#region Mail Settings
class MailSettings:
fromMail = "ahmetbohur@urhoba.net"
fromPassword = ""
smtpHost = "smtp.yandex.com"
smtpPort = 465
#endregion
#region Download Settings
class DownloadSettings:
musicFolder = "songs"
videoFolder = "videos"
#endregion
#region Telegram Settings
class TelegramSettings:
telegramAPI = ""
#endregion |
"""python-homewizard-energy errors."""
class HomeWizardEnergyException(Exception):
"""Base error for python-homewizard-energy."""
class RequestError(HomeWizardEnergyException):
"""Unable to fulfill request.
Raised when host or API cannot be reached.
"""
class InvalidStateError(HomeWizardEnergyException):
"""Raised when the device is not in the correct state."""
class UnsupportedError(HomeWizardEnergyException):
"""Raised when the device is not supported from this library."""
class DisabledError(HomeWizardEnergyException):
"""Raised when device API is disabled. User has to enable API in app."""
|
__author__ = 'Chintalagiri Shashank'
__email__ = 'shashank@chintal.in'
__version__ = '0.2.9'
|
{
'targets': [
{
'target_name': 'rulesjs',
'sources': [ 'src/rulesjs/rules.cc' ],
'include_dirs': ["<!(node -e \"require('nan')\")"],
'dependencies': [ 'src/rules/rules.gyp:rules' ],
'defines': [ '_GNU_SOURCE' ],
'cflags': [ '-Wall', '-O3' ]
}
]
}
|
# Generate key with openssl rand -hex 32
JWT_SECRET_KEY = "46e5c95a2d980476afb2d679b37bb2c8990c25b4ea1075514f67f62f77daf306"
JWT_ALGORITHM = "HS256"
JWT_EXPIRATION_MINUTES = 15
# TODO: Move to environment variables
DB_HOST = 'localhost'
DB_NAME = 'bookstore'
DB_USER = 'postgres'
DB_PASSWORD = 'postgres'
DB_PORT = 5432
REDIS_URL = 'redis://localhost'
TEST = True
TEST_DB_HOST = 'localhost'
TEST_DB_NAME = 'test_bookstore'
TEST_DB_USER = 'postgres'
TEST_DB_PASSWORD = 'postgres'
TEST_DB_PORT = 5432
TEST_REDIS_URL = 'redis://localhost/1'
|
class Difference:
def __init__(self, a):
self.__elements = a
self.maximumDifference = 0
def computeDifference(self):
max_num = max(self.__element)
min_num = min(self.__element)
self.maximumDifference = max_num - min_num
if self.maximumDifference < 0:
self.maximumDifference *= -1
return self.maximumDifference
a = [int(e) for e in input().split(' ')]
d = Difference(a)
d.computeDifference()
print(d.maximumDifference)
|
t = int(input())
output = []
for _ in range(t):
p, a, b, c = [int(x) for x in input().split()]
if a >= p:
minimum = a - p
elif p % a == 0:
minimum = 0
else:
minimum = a - (p % a)
if b >= p:
minimum = min(minimum, b - p)
elif p % b == 0:
minimum = 0
else:
minimum = min(minimum, b - (p % b))
if c >= p:
minimum = min(minimum, c - p)
elif p % c == 0:
minimum = 0
else:
minimum = min(minimum, c - (p % c))
output.append(minimum)
for out in output:
print(out) |
n=int(input());r=""
for i in range(1,n+1):
s=input().strip()
if s=="5 6" or s=="6 5":
r+="Case "+str(i)+": Sheesh Beesh\n"
else:
a=[int(k) for k in s.split()]
a.sort(reverse=True)
if a[0]==a[1]:
if a[0]==1:
r+="Case "+str(i)+": Habb Yakk\n"
elif a[0]==2:
r += "Case " + str(i) + ": Dobara\n"
elif a[0]==3:
r += "Case " + str(i) + ": Dousa\n"
elif a[0]==4:
r += "Case " + str(i) + ": Dorgy\n"
elif a[0]==5:
r += "Case " + str(i) + ": Dabash\n"
else:
r += "Case " + str(i) + ": Dosh\n"
else:
r += "Case " + str(i)+": "
for k in range(2):
if a[k]==1:
r+="Yakk"
elif a[k]==2:
r+="Doh"
elif a[k]==3:
r+="Seh"
elif a[k]==4:
r+="Ghar"
elif a[k]==5:
r+="Bang"
else:
r+="Sheesh"
if k==0:
r+=" "
else:
r+="\n"
print(r,end="")
|
def order(data):
# new_data = []
for i in range(len(data)):
for j in range(len(data) - 1):
if (data[j] > data[j + 1]):
temp_data_j = data[j]
data[j] = data[j + 1]
data[j + 1] = temp_data_j
return data
|
# %% [markdown]
'''
# How to install NVIDIA GPU driver and CUDA on ubuntu
'''
# %% [markdown]
'''
This post is intended to describe how to install NVIDIA GPU driver and CUDA on ubuntu.
I have myself a GTX 560M with ubuntu 18.04.
'''
# %% [markdown]
'''
## Requirements
Before installing, we will first need to find the different version that your GPU support in the following order (in parenthesis my versions):
1. The GPU driver version (390.132)
2. CUDA version (9.0)
3. OS version (ubuntu 18.04) (and optionnally `gcc` version)
### GPU driver version
Got to [this page](https://www.nvidia.com/Download/index.aspx) and fill in all the information, and click on search to find the latest driver version your GPU support.
From here we will download the driver installer that we will use later.
Right-click on `Download` and `copy the link location`.
Back on your computer, paste the link to download the installer with `wget`:
```bash
wget https://www.nvidia.com/content/DriverDownload-March2009/confirmation.php?url=/XFree86/Linux-x86_64/390.132/NVIDIA-Linux-x86_64-390.132.run&lang=us&type=TITAN
```
### CUDA version
CUDA compatibility depends on your driver version you got in the previous section, check [here](https://docs.nvidia.com/deploy/cuda-compatibility/index.html#binary-compatibility) the compatibility matrix to know chich CUDA you can use.
### OS version
Check if your ubuntu version is compatible with this CUDA version.
You should select the right documentation [there](https://docs.nvidia.com/cuda/archive/)
and check the section `system-requirements`, for example https://docs.nvidia.com/cuda/archive/9.0/cuda-installation-guide-linux/index.html#system-requirements.
>**Warning**
>If your ubuntu version is not compatible with CUDA, you should install the good gcc version.
>After [cheking the gcc version](https://docs.nvidia.com/cuda/archive/9.0/cuda-installation-guide-linux/index.html#system-requirements), you can install it and make it your default one:
>```bash
>sudo apt-get install build-essential gcc-6
>sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-6 6
>```
## Installation
Now that we know all the required version, we can start installing the softwares.
First, we make sure to have the build dependencies installed:
```bash
sudo apt-get install build-essential
```
Install the GPU driver by running the installer (we downloaded it previously):
```bash
sudo bash NVIDIA-Linux-x86_64-390.132.run
```
To download the CUDA toolkit installer, select the good release there:
https://developer.nvidia.com/cuda-toolkit-archive
Fill in the different informations, and at the end select `runfile (local)`:
https://developer.nvidia.com/cuda-90-download-archive?target_os=Linux&target_arch=x86_64&target_distro=Ubuntu&target_version=1704&target_type=runfilelocal
>**Note**
>In my case, my CUDA version does not support ubuntu 18.04 so I selected the newest distribution which is 17.04.
Now you can download and run the executable to install the CUDA toolkit.
```bash
wget https://developer.nvidia.com/compute/cuda/9.0/Prod/local_installers/cuda_9.0.176_384.81_linux-run
sudo bash cuda_9.0.176_384.81_linux-run
```
>**Warning**
>After running the CUDA installer, you will be asked if you want to install the NVIDIA Accelerated Graphics Driver for Linux-x86_64. Of course don't do it, we already installed it previously.
You can now follow the [post-installation actions](https://docs.nvidia.com/cuda/archive/9.0/cuda-installation-guide-linux/index.html#post-installation-actions).
The most important is to add the CUDA paths to the environment variable (system wide), so depending on your CUDA version:
```bash
echo "export PATH=/usr/local/cuda-9.0/bin:/usr/local/cuda/bin\${PATH:+:\${PATH}}" | sudo tee -a /etc/profile.d/myenvvars.sh
echo "export LD_LIBRARY_PATH=/usr/local/cuda-9.0/lib64:/usr/local/cuda/lib64\${LD_LIBRARY_PATH:+:\${LD_LIBRARY_PATH}}" | sudo tee -a /etc/profile.d/myenvvars.sh
```
Optionnally check the cuda toolkit samples to test if CUDA is working.
To help the compiler when linking, add cuda libraries to the library path and check:
```bash
echo "/usr/local/cuda-9.0/lib64" | sudo tee /etc/ld.so.conf.d/cuda-9.0.conf
sudo ldconfig -v
```
Finally, reboot your computer:
```bash
sudo reboot
```
'''
# %% [markdown]
'''
# Tags
'''
# %% [markdown]
'''
Software-Development; GPU
''' |
#!/usr/bin/env python3
def clean_up():
try:
raise KeyboardInterrupt
finally:
print('Goodbye, world!')
def divide(x, y):
try:
result = x / y
except ZeroDivisionError:
print("division by zero!")
else:
print("result is", result)
finally:
print("executing finally clause")
if __name__ == "__main__":
# clean_up()
divide(2, 1)
divide(2, 0)
divide("2", "1")
|
# Testando as f strings
# Testing the f strings
nome = 'José'
idade = 33
salario = 957.55
print(f'O {nome} tem {idade} anos e ganha R${salario:.2f}') # PYTHON 3.6+
#print('{} is {} years old.'.format(name, age)) #PYTHON 3
#print('%s is %d years old.' % (name, age)) #PYTHON 2
|
test = {
"name": "q3",
"points": 1,
"hidden": False,
"suites": [
{
"cases": [
{
"code": r"""
>>> len(data["flavor"].unique()) == 4
True
""",
"hidden": False,
"locked": False,
},
{
"code": r"""
>>> for l in ["chocolate", "vanilla", "strawberry", "mint"]:
... assert l in data["flavor"].unique()
""",
"hidden": False,
"locked": False,
},
{
"code": r"""
>>> assert type(price_by_flavor) == pd.Series
""",
"hidden": False,
"locked": False,
},
{
"code": r"""
>>> assert len(price_by_flavor) == 4
""",
"hidden": False,
"locked": False,
},
],
"scored": False,
"setup": "",
"teardown": "",
"type": "doctest"
}
]
} |
# Just a simple time class
# that stores time in 24 hour format
# and displays in period time (AM/PM)
class SimpleTime:
def __init__(self, hour, minute, period):
# assertions for checking
assert(hour > 0 and hour <= 12)
assert(minute >= 0 and minute < 60)
assert(period == "AM" or period == "PM")
self._minute = minute
if period == "AM":
self._hour = hour % 12
else:
self._hour = (hour % 12) + 12
# adds hours to time
def add_hours(self, hours):
assert isinstance(hours, int)
self._hour = (self._hour + hours) % 24
# adds minutes to time
def add_minutes(self, minutes):
assert isinstance(minutes, int)
self.add_hours((self._minute + minutes) // 60)
self._minute = (self._minute + minutes) % 60
# add hours and minutes
def add(self, hours, minutes):
self.add_hours((hours + (minutes // 60)))
self.add_minutes(minutes % 60)
# set the time to the time of another SimpleTime instance
def set(self, other):
assert isinstance(other, SimpleTime)
self._hour = other._hour
self._minute = other._minute
# comparison operators
def __eq__(self, other):
return ((self._hour, self._minute) == (other._hour, other._minute))
def __ne__(self, other):
return ((self._hour, self._minute) != (other._hour, other._minute))
def __lt__(self, other):
return ((self._hour, self._minute) < (other._hour, other._minute))
def __le__(self, other):
return ((self._hour, self._minute) <= (other._hour, other._minute))
def __gt__(self, other):
return ((self._hour, self._minute) > (other._hour, other._minute))
def __ge__(self, other):
return ((self._hour, self._minute) >= (other._hour, other._minute))
def __str__(self):
if self._hour < 12:
if self._hour == 0:
tm = "12:%02d AM" % self._minute
else:
tm = "%d:%02d AM" % (self._hour, self._minute)
else:
if self._hour == 12:
tm = "12:%02d PM" % (self._minute)
else:
tm = "%d:%02d PM" % ((self._hour % 12), self._minute)
return tm
|
file_pickled_dfas = "helper-dfas.pickled"
file_pickled_dfas = "helper-more-dfas.pickled"
day_in_sec = 86400
now_in_sec = time.time()
def get_dfas():
"""Get DFAs from pickled file. If the file is older than a day regenerate it."""
global day_in_sec
global now_in_sec
global __dfa_list
try:
pickle_time, dfa_list = pickle.load(open(file_pickled_dfas, "rb"))
except:
generate_new_f = True
# Error while reading, or pickle to old => regenerate pickled DFAs
if generate_new_f or pickle_time - now_in_sec > day_in_sec:
dfa_list = [
DFA.Universal(), # Matches all lexemes
DFA.Empty(), # Matches the lexeme of zero length
#
dfa('a'),
dfa('ab'),
dfa('a(b?)'),
dfa('ab|abcd'),
# "Branches"
dfa('12|AB'),
dfa('x(12|AB)'),
dfa('(12|AB)x'),
dfa('x(12|AB)x'),
dfa('x(1?2|A?B)x'),
dfa('x(1?2?|A?B?)x'),
# "Loops"
dfa('A+'),
dfa('A(B*)'),
dfa('A((BC)*)'),
dfa('((A+)B+)C+'),
# "BranchesLoops"
dfa('(AB|XY)+'),
dfa('(AB|XY)(DE|FG)*'),
dfa('(AB|XY)+(DE|FG)+'),
dfa('((AB|XY)(DE|FG))+'),
# "Misc"
dfa('(pri|ri|n)+'),
dfa('(p?r?i?|rin|n)+'),
]
pickle.dump((now_in_sec, dfa_list), open(file_pickled_dfas, "wb"))
__dfa_list.extend(dfa_list)
def add_more_DFAs():
global day_in_sec
global now_in_sec
global __dfa_list
try:
pickle_time, dfa_list = pickle.load(open(file_pickled_more_dfas, "rb"))
except:
generate_new_f = True
# Error while reading, or pickle to old => regenerate pickled DFAs
if generate_new_f or pickle_time - now_in_sec > day_in_sec:
dfa_list = [
shapes.get_sm_shape_by_name_with_acceptance(name.strip())
for name in shapes.get_sm_shape_names_list()
]
pickle.dump((now_in_sec, dfa_list), open(file_pickled_more_dfas, "wb"))
__dfa_list.extend(dfa_list)
get_dfas()
|
class BytesIntEncoder:
@staticmethod
def encode(s: str) -> int:
return int.from_bytes(s.encode(), byteorder='big')
@staticmethod
def decode(i: int) -> str:
return i.to_bytes(((i.bit_length() + 7) // 8), byteorder='big').decode()
|
def castleTowers(n, ar):
occurrences_map = {}
max_item = -1
for item in ar:
if item > max_item:
max_item = item
if item in occurrences_map:
occurrences_map[item] += 1
else:
occurrences_map[item] = 1
return occurrences_map[max_item]
if __name__ == "__main__":
n = int(input().strip())
ar = map(int, input().strip().split(' '))
result = castleTowers(n, ar)
print(result)
|
def countMinOperations(target, n):
result = 0
while (True):
zero_count = 0
i = 0
while (i < n):
if ((target[i] & 1) > 0):
break
elif (target[i] == 0):
zero_count += 1
i += 1
if (zero_count == n):
return result
if (i == n):
for j in range(n):
target[j] = target[j] // 2
result += 1
for j in range(i, n):
if (target[j] & 1):
target[j] -= 1
result += 1
|
# generated from genmsg/cmake/pkg-genmsg.context.in
messages_str = "/home/pi/catkin_ws/src/mobrob_util/msg/ME439SensorsRaw.msg;/home/pi/catkin_ws/src/mobrob_util/msg/ME439SensorsProcessed.msg;/home/pi/catkin_ws/src/mobrob_util/msg/ME439WheelSpeeds.msg;/home/pi/catkin_ws/src/mobrob_util/msg/ME439MotorCommands.msg;/home/pi/catkin_ws/src/mobrob_util/msg/ME439WheelAngles.msg;/home/pi/catkin_ws/src/mobrob_util/msg/ME439WheelDisplacements.msg;/home/pi/catkin_ws/src/mobrob_util/msg/ME439PathSpecs.msg;/home/pi/catkin_ws/src/mobrob_util/msg/ME439WaypointXY.msg"
services_str = ""
pkg_name = "mobrob_util"
dependencies_str = "geometry_msgs;std_msgs"
langs = "gencpp;geneus;genlisp;gennodejs;genpy"
dep_include_paths_str = "mobrob_util;/home/pi/catkin_ws/src/mobrob_util/msg;geometry_msgs;/opt/ros/melodic/share/geometry_msgs/cmake/../msg;std_msgs;/opt/ros/melodic/share/std_msgs/cmake/../msg"
PYTHON_EXECUTABLE = "/usr/bin/python2"
package_has_static_sources = '' == 'TRUE'
genmsg_check_deps_script = "/opt/ros/melodic/share/genmsg/cmake/../../../lib/genmsg/genmsg_check_deps.py"
|
#
# Find the one food that is eaten by only one animal.
#
# The animals table has columns (name, species, birthdate) for each individual.
# The diet table has columns (species, food) for each food that a species eats.
#
QUERY = '''
select diet.food, count(animals.name) as num from animals, diet where animals.species = diet.species group by diet.food having num = 1
'''
|
# IE 11 CustomEvent polyfill
src = r"""
(function () {
if ( typeof window.CustomEvent === "function" ) return false; //If not IE
function CustomEvent ( event, params ) {
params = params || { bubbles: false, cancelable: false, detail: undefined };
var evt = document.createEvent( 'CustomEvent' );
evt.initCustomEvent( event, params.bubbles, params.cancelable, params.detail );
return evt;
}
CustomEvent.prototype = window.Event.prototype;
window.CustomEvent = CustomEvent;
})();
""" |
class EmployeeTaskLink:
def __init__(self, linkID, empID, taskID):
self.linkID = linkID
self.empID = empID
self.taskID = taskID
def get_employee(self, list):
for emp in list:
if emp.empID == self.empID:
return emp
def get_task(self, list):
for task in list:
if task.taskID == self.taskID:
return task |
def findDecision(obj): #obj[0]: Passanger, obj[1]: Time, obj[2]: Coupon, obj[3]: Gender, obj[4]: Age, obj[5]: Children, obj[6]: Education, obj[7]: Occupation, obj[8]: Bar, obj[9]: Coffeehouse, obj[10]: Restaurant20to50, obj[11]: Direction_same, obj[12]: Distance
# {"feature": "Age", "instances": 34, "metric_value": 0.9774, "depth": 1}
if obj[4]<=4:
# {"feature": "Passanger", "instances": 29, "metric_value": 0.9294, "depth": 2}
if obj[0]<=1:
# {"feature": "Education", "instances": 18, "metric_value": 0.7642, "depth": 3}
if obj[6]<=4:
# {"feature": "Time", "instances": 17, "metric_value": 0.6723, "depth": 4}
if obj[1]<=1:
return 'False'
elif obj[1]>1:
# {"feature": "Distance", "instances": 8, "metric_value": 0.9544, "depth": 5}
if obj[12]<=1:
# {"feature": "Occupation", "instances": 6, "metric_value": 0.65, "depth": 6}
if obj[7]>1:
return 'False'
elif obj[7]<=1:
# {"feature": "Gender", "instances": 2, "metric_value": 1.0, "depth": 7}
if obj[3]>0:
return 'False'
elif obj[3]<=0:
return 'True'
else: return 'True'
else: return 'False'
elif obj[12]>1:
return 'True'
else: return 'True'
else: return 'False'
elif obj[6]>4:
return 'True'
else: return 'True'
elif obj[0]>1:
# {"feature": "Restaurant20to50", "instances": 11, "metric_value": 0.994, "depth": 3}
if obj[10]<=1.0:
# {"feature": "Distance", "instances": 8, "metric_value": 0.9544, "depth": 4}
if obj[12]>1:
# {"feature": "Time", "instances": 6, "metric_value": 0.65, "depth": 5}
if obj[1]<=3:
return 'False'
elif obj[1]>3:
# {"feature": "Coupon", "instances": 2, "metric_value": 1.0, "depth": 6}
if obj[2]<=2:
return 'True'
elif obj[2]>2:
return 'False'
else: return 'False'
else: return 'True'
elif obj[12]<=1:
return 'True'
else: return 'True'
elif obj[10]>1.0:
return 'True'
else: return 'True'
else: return 'True'
elif obj[4]>4:
# {"feature": "Occupation", "instances": 5, "metric_value": 0.7219, "depth": 2}
if obj[7]<=12:
return 'True'
elif obj[7]>12:
return 'False'
else: return 'False'
else: return 'True'
|
# Copyright 2015 Google Inc. All rights reserved.
#
# 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.
"""Helper functions for shared behavior."""
def topic_name_from_path(path, project):
"""Validate a topic URI path and get the topic name.
:type path: string
:param path: URI path for a topic API request.
:type project: string
:param project: The project associated with the request. It is
included for validation purposes.
:rtype: string
:returns: Topic name parsed from ``path``.
:raises: :class:`ValueError` if the ``path`` is ill-formed or if
the project from the ``path`` does not agree with the
``project`` passed in.
"""
# PATH = 'projects/%s/topics/%s' % (PROJECT, TOPIC_NAME)
path_parts = path.split('/')
if (len(path_parts) != 4 or path_parts[0] != 'projects' or
path_parts[2] != 'topics'):
raise ValueError('Expected path to be of the form '
'projects/{project}/topics/{topic_name}')
if (len(path_parts) != 4 or path_parts[0] != 'projects' or
path_parts[2] != 'topics' or path_parts[1] != project):
raise ValueError('Project from client should agree with '
'project from resource.')
return path_parts[3]
|
"""
Errors about channels.
"""
class FetchChannelFailed(Exception):
"""Raises when fetching a channel is failed."""
pass
class FetchChannelMessagesFailed(Exception):
"""Raises when fetching messages from channel is failed."""
pass
class FetchChannelMessageFailed(Exception):
"""Raises when fetching A message from channel is failed."""
pass
class BulkDeleteMessagesFailed(Exception):
"""Raises when purge messages from channel is failed."""
pass
class EditChannelFailed(Exception):
"""Raises when editing the channel is failed."""
pass
class DeleteChannelFailed(Exception):
"""Raises when deleting the channel is failed."""
pass
|
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
class Constants:
SYS_BOOLEAN: str = "boolean"
SYS_BOOLEAN_TRUE: str = "boolean-true"
SYS_BOOLEAN_FALSE: str = "boolean-false"
|
t = int(input())
while t:
A, B = map(int, input().split())
c = 1
while(c>0):
if(c%2==0):
B -= c
else:
A -= c
if(A<0):
print("Bob")
break
if(B<0):
print("Limak")
break
c += 1
t = t-1
|
## Uppercase is BOLT
# to use: from utils.beautyfy import *
def red(string):
return '\033[1;91m {}\033[00m'.format(string)
def RED(string):
return '\033[1;91m {}\033[00m'.format(string)
def yellow(string):
return '\033[93m {}\033[00m'.format(string)
def YELLOW(string):
return '\033[1;93m {}\033[00m'.format(string)
def blue(string):
return '\033[94m {}\033[00m'.format(string)
def BLUE(string):
return '\033[1;94m {}\033[00m'.format(string)
def green(string):
return '\033[92m {}\033[00m'.format(string)
def GREEN(string):
return '\033[1;92m {}\033[00m'.format(string)
def cyan(string):
return '\033[96m {}\033[00m'.format(string)
def underline(string):
return '\033[4m{}\033[00m'.format(string)
def header(string):
return '\033[95m{}\033[00m'.format(string)
# HEADER = '\033[95m'
# OKBLUE = '\033[94m'
# OKCYAN = '\033[96m'
# OKGREEN = '\033[92m'
# WARNING = '\033[93m'
# FAIL = '\033[91m'
# ENDC = '\033[0m'
# BOLD = '\033[1m'
# UNDERLINE = '\033[4m'
|
# 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.
#
"""Server v2 API library"""
RESOURCE_KEY = 'server'
RESOURCES_KEY = 'servers'
BASE_PATH = '/servers'
def list(
session,
endpoint,
long=False,
all_data=False,
marker=None,
limit=None,
end_marker=None,
**params
):
if all_data:
data = listing = list(
session,
endpoint,
long=long,
marker=marker,
limit=limit,
end_marker=end_marker,
**params
)
while listing:
# TODO(dtroyer): How can we use name here instead?
marker = listing[-1]['id']
listing = list(
session,
endpoint,
long=long,
marker=marker,
limit=limit,
end_marker=end_marker,
**params
)
if listing:
data.extend(listing)
return data
# NOTE(dtroyer): If we settle on not validating input these can be
# passed in **params
if marker:
params['marker'] = marker
if limit:
params['limit'] = limit
if end_marker:
params['end_marker'] = end_marker
# is endpoint or service catalog in session?
url = endpoint + BASE_PATH
if long:
url += "/detail"
return session.get(url, params=params).json()[RESOURCES_KEY]
|
# Time: O(n log n); Space: O(1)
def ship_within_days(weights, days):
low = max(weights)
high = sum(weights)
min_capacity = high
while low <= high:
mid = low + (high - low) // 2
cur_days, cur_daily_weight = 1, 0
for w in weights:
if cur_daily_weight + w > mid:
cur_days += 1
cur_daily_weight = w
else:
cur_daily_weight += w
if cur_days <= days:
min_capacity = min(min_capacity, mid)
high = mid - 1
else:
low = mid + 1
return min_capacity
# Test cases:
print(ship_within_days(weights=[3, 2, 2, 4, 1, 4], days=3))
print(ship_within_days(weights=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], days=5))
print(ship_within_days(weights=[1, 2, 3, 1, 1], days=4))
|
# -*- coding: utf-8 -*-
"""Top-level package for nola."""
__author__ = """Raghuveer Naraharisetti"""
__email__ = 'raghuveernaraharisetti@gmail.com'
__version__ = '0.1.0'
|
# config.py
DEBUG = True
DBHOST = '130.211.198.107'
DBPASS = "gregb00th"
DBPORT = 3306
DBUSER = 'root'
DBNAME = 'baseball_2018'
CLOUDSQL_PROJECT = "Baseball-2018"
CLOUDSQL_INSTANCE = "personalwebsite-165915:us-central1:baseball-2018"
CLOUD_STORAGE_BUCKET = 'analytics_data_extraction'
MAX_CONTENT_LENGTH = 8 * 1024 * 1024
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif', 'txt'])
|
def get_certified_by(filing_data: dict):
user_id = filing_data.get('u_user_id')
if user_id:
first_name = filing_data.get('u_first_name')
middle_name = filing_data.get('u_middle_name')
last_name = filing_data.get('u_last_name')
if first_name or middle_name or last_name:
result = f'{first_name} {middle_name} {last_name}'
result = result.strip()
return result
return user_id
return ''
def get_street_additional(addr_line_2: str, addr_line_3: str):
addr_line_2 = addr_line_2 if addr_line_2 else ''
addr_line_2 = addr_line_2.strip()
addr_line_3 = addr_line_3 if addr_line_3 else ''
result = f'{addr_line_2} {addr_line_3}'
result = result.strip()
return result
def get_party_role_type(corp_type_cd: str, role_type: str):
if role_type == 'FCP':
return 'Completing Party'
elif role_type == 'FIO' or role_type == 'FBO':
if corp_type_cd == 'SP':
return 'Proprietor'
elif corp_type_cd == 'GP':
return 'Partner'
else:
return None
else:
return None
def get_party_type(role_type: str, filing_party_data: dict):
corp_party_business_name = filing_party_data['cp_business_name']
if corp_party_business_name:
return 'organization'
return 'person'
|
file_path = '/esdata/test/11.log'
with open(file_path, 'w') as file:
num = 1000
val = 0
while val <= num:
file.write("{:x}\n".format(val).zfill(12))
val += 1
|
load_modules = {
########### Attacker
'uds_engine_auth_baypass': {
'id_command': 0x71
},
'gen_ping' : {},
'uds_tester_ecu_engine':{
'id_uds': 0x701,
'uds_shift': 0x08,
'uds_key':''
},
'hw_TCP2CAN': {'port': 1111, 'mode': 'client', 'address':'127.0.0.1', 'debug':3},
'hw_TCP2CAN~1': {'port': 1112, 'mode': 'client','address':'127.0.0.1', 'debug':3},
'gen_fuzz':{},
'mod_stat':{},
'mod_stat~2': {}
}
actions = [
{'hw_TCP2CAN~1': {'pipe': 2,'action':'read'}},
{'hw_TCP2CAN': {'pipe': 1,'action':'read'}},
{'gen_ping': { # Generate UDS requests
'pipe': 3,
'delay': 0.06,
'range': [1700, 1800], # ID range (from 1790 to 1794)
'services':[{'service': 0x27, 'sub': 0x01}],
'mode':'UDS'}
},
{'mod_stat': {'pipe': 2}},
{'mod_stat~2': {'pipe': 1}},
{'uds_tester_ecu_engine':
{
'action': 'read',
'pipe': 1
}
},
{'uds_tester_ecu_engine': {
'action': 'write',
'pipe': 3}},
{'gen_fuzz':{
'id':[0x81],'data':[0,0],'index':[0,1],'delay':0.07,'pipe':4,'bytes':(0,0x20)
}},
{'uds_engine_auth_baypass': {
'action': 'write',
'pipe': 4}},
{'hw_TCP2CAN': {'pipe': 3,'action':'write'}},
{'hw_TCP2CAN~1': {'pipe': 4,'action':'write'}}
] |
# More indentation included to distinguish this from the rest.
def server(
host='localhost', port=443, secure=True,
username='admin', password='admin'):
return locals()
# Aligned with opening delimiter.
connection = server(host='localhost', port=443, secure=True,
username='admin', password='admin')
# Hanging indents should add a level.
connection = server(
host='localhost', port=443, secure=True,
username='admin', password='admin')
# The best
connection = server(
host='localhost',
username='admin',
password='admin',
port=443,
secure=True,
)
|
# yacon.definitions.py
#
# This file contains common values that aren't usually changed per
# installation and therefore shouldn't go in the django settings file
# max length of slugs
SLUG_LENGTH = 25
# max length of title
TITLE_LENGTH = 50
# bleach constants
ALLOWED_TAGS = [
'a',
'address',
'b',
'br',
'blockquote',
'code',
'div',
'em',
'h1',
'h2',
'h3',
'h4',
'h5',
'h6',
'hr',
'img',
'i',
'li',
'ol',
'p',
'pre',
'span',
'strike',
'strong',
'sub',
'sup',
'table',
'tbody',
'thead',
'tr',
'td',
'u',
'ul',
]
ALLOWED_ATTRIBUTES = {
'a':['href', 'title'],
'img':['alt', 'src', 'width', 'height', 'style'],
'table':['border', 'cellpadding', 'cellspacing', 'style', ],
'td':['style', ],
'tr':['style', ],
'tbody':['style', ],
'thead':['style', ],
'p':['style', ],
'span':['style', ],
'div':['style', ],
}
ALLOWED_STYLES = [
'background-color',
'border-width',
'border-height',
'border-style',
'color',
'float',
'font-family',
'font-size',
'height',
'margin',
'margin-bottom',
'margin-left',
'margin-right',
'margin-top',
'text-align',
'width',
]
|
# Curso de Python do Curso em Vídeo
# Desafio 05 Aula #07 Operadores aritiméticos
# Faça um algoritimo que leia o salário de um funcionário e mostre seu novo salário com 15% de aumento# preço com 5% de desconto.
# Aluno MaxBarroso
print('Black-Py-Day')
print('Este programa te ajuda a saber qual o novo salário de um funcionário acrescentando uma porcentagem')
salario = float(input('Digite o Salário do funcionário: '))
desc = float(input('Digite qual a % de acréscimo: '))
diferenca = desc / 100 * salario
final = salario + diferenca
print('O novo salário do funcionario é: ', final)
|
''' Break statement
''' |
"""
Statically define whether the measurementheaders should be enabled
TODO: Make this adjustable at runtime
"""
class Measurement_Headers():
Active : bool = True |
#greatest among 3
a=int(input("Enter no:"))
b=int(input("Enter no:"))
c=int(input("Enter no:"))
if a>b:
if a>c:
print(a)
else:
print(c)
else:
if b>c:
print(b)
else:
print(c)
|
# -*- coding: utf-8 -*-
def file_decrypt(data,mode,storetype):
return data
|
# not yet finished
H, M = input().split()
H, M = int(H), int(M)
N = int(input())
m = N % 60
H += N // 60
H %= 24
M = m
# for _ in range(N):
# M += 1
# if M == 60:
# M = 0
# H += 1
# if H == 24:
# H = 0
print(H, M) |
"""
53. Maximum Subarray
Easy
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
A subarray is a contiguous part of an array.
Example 1:
Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
Example 2:
Input: nums = [1]
Output: 1
Example 3:
Input: nums = [5,4,-1,7,8]
Output: 23
Constraints:
1 <= nums.length <= 105
-104 <= nums[i] <= 104
Follow up: If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
"""
# V0
# IDEA : DP
# DP EQUATION :
# -> dp[i+1] = dp[i] + s[i+1] (if dp[i] >= 0 )
# -> dp[i+1] = s[i] (if dp[i] < 0 )
class Solution(object):
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
dp = [nums[0] for i in range(len(nums))]
max_result = nums[0] # if start from nums[0], then must get smaller if there is minus number; will get larger if interger
for i in range(1, len(nums)):
if dp[i-1] < 0:
dp[i] = nums[i]
else:
dp[i] = dp[i-1] + nums[i]
max_result = max(max_result, dp[i])
return max_result
# V0'
# IDEA : DP
class Solution(object):
def maxSubArray(self, nums):
cumsum = nums[0]
max_ = cumsum
if not nums: return 0
for i in range(1, len(nums)):
if cumsum < 0:
cumsum = 0
cumsum += nums[i]
max_ = max(max_, cumsum)
return max_
# V0'
# IDEA : BRUTE FORCE (TLE)
class Solution(object):
def maxSubArray(self, nums):
# edge case
if len(nums) == 1:
return nums[0]
if not nums:
return 0
res = -float('inf')
for i in range(len(nums)):
tmp = []
for j in range(i, len(nums)):
tmp.append(nums[j])
res = max(res, sum(tmp))
return res
# V1''
# https://blog.csdn.net/qqxx6661/article/details/78167981
# IDEA : DP
# DP EQUATION :
# -> dp[i+1] = dp[i] + s[i+1] (if dp[i] >= 0 )
# -> dp[i+1] = s[i] (if dp[i] < 0 )
class Solution(object):
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
current = nums[0]
m = current
for i in range(1, len(nums)):
if current < 0:
current = 0
current += nums[i]
m = max(current, m)
return m
# V1''
# https://blog.csdn.net/qqxx6661/article/details/78167981
# IDEA : DP
# DP STATUS EQUATION :
# dp[i] = dp[i-1] + s[i] (dp[i-1] >= 0)
# dp[i] = s[i] (dp[i-1] < 0)
class Solution(object):
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
dp = [nums[0] for i in range(len(nums))]
max_result = nums[0] # if start from nums[0], then must get smaller if there is minus number; will get larger if interger
for i in range(1, len(nums)):
if dp[i-1] < 0:
dp[i] = nums[i]
else:
dp[i] = dp[i-1] + nums[i]
if max_result < dp[i]:
max_result = dp[i]
return max_result
# V1
# https://blog.csdn.net/hyperbolechi/article/details/43038749
# IDEA : BRUTE FORCE
class Solution:
def maxSubArray(self, arr):
maxval=-10000
for i in range(len(arr)):
for j in range(i,len(arr)):
if maxval<sum(arr[i:j]):
print((i,j))
maxval=max(maxval,sum(arr[i:j]))
result=arr[i:j]
return result
# V1
# IDEA : Optimized Brute Force
# https://leetcode.com/problems/maximum-subarray/solution/
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
max_subarray = -math.inf
for i in range(len(nums)):
current_subarray = 0
for j in range(i, len(nums)):
current_subarray += nums[j]
max_subarray = max(max_subarray, current_subarray)
return max_subarray
# V1
# IDEA : Dynamic Programming, Kadane's Algorithm
# https://leetcode.com/problems/maximum-subarray/solution/
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
# Initialize our variables using the first element.
current_subarray = max_subarray = nums[0]
# Start with the 2nd element since we already used the first one.
for num in nums[1:]:
# If current_subarray is negative, throw it away. Otherwise, keep adding to it.
current_subarray = max(num, current_subarray + num)
max_subarray = max(max_subarray, current_subarray)
return max_subarray
# V1
# IDEA : Divide and Conquer
# https://leetcode.com/problems/maximum-subarray/solution/
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
def findBestSubarray(nums, left, right):
# Base case - empty array.
if left > right:
return -math.inf
mid = (left + right) // 2
curr = best_left_sum = best_right_sum = 0
# Iterate from the middle to the beginning.
for i in range(mid - 1, left - 1, -1):
curr += nums[i]
best_left_sum = max(best_left_sum, curr)
# Reset curr and iterate from the middle to the end.
curr = 0
for i in range(mid + 1, right + 1):
curr += nums[i]
best_right_sum = max(best_right_sum, curr)
# The best_combined_sum uses the middle element and
# the best possible sum from each half.
best_combined_sum = nums[mid] + best_left_sum + best_right_sum
# Find the best subarray possible from both halves.
left_half = findBestSubarray(nums, left, mid - 1)
right_half = findBestSubarray(nums, mid + 1, right)
# The largest of the 3 is the answer for any given input array.
return max(best_combined_sum, left_half, right_half)
# Our helper function is designed to solve this problem for
# any array - so just call it using the entire input!
return findBestSubarray(nums, 0, len(nums) - 1)
# V2
# Time: O(n)
# Space: O(1)
class Solution(object):
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
max_nums = max(nums)
if max_nums < 0:
return max_nums
global_max, local_max = 0, 0
for x in nums:
local_max = max(0, local_max + x)
global_max = max(global_max, local_max)
return global_max |
#!/usr/bin/env python3
def part_one():
result = str(1113122113)
for i in range(40):
result = say(result)
return len(result)
def part_two():
result = str(1113122113)
for i in range(50):
result = say(result)
return len(result)
def say(input):
"""
>>> say(1)
11
>>> say(11)
21
>>> say(21)
1211
>>> say(1211)
111221
>>> say(111221)
312211
"""
result = ""
current_number = input[0]
count = 1
for d in input[1:]:
if current_number == d:
count += 1
else:
result += str(count)
result += current_number
current_number = d
count = 1
result += str(count)
result += current_number
return result
if __name__ == "__main__":
# import doctest
# doctest.testmod()
print(part_one())
print(part_two()) |
""" The problem is that we want to reverse a T[] array in O(N) linear
time complexity and we want the algorithm to be in-place as well!
For example: input is [1,2,3,4,5] then the output is [5,4,3,2,1]
"""
arr = [1, 2, 3, 4, 5, 6]
for i in range(len(arr) // 2):
arr[i], arr[len(arr)-1-i] = arr[len(arr)-1-i], arr[i]
print(arr)
|
"""
Class: Create peripheral objects whenever a new device is found
Methods: Send connection request to given device, disconnect from given device, handle discovery of advertisments
List all available characteristics (services that contain more characteristics)
"""
|
def starify_pval(pval):
if pval > 0.05:
return ""
else:
if pval <= 0.001:
return "***"
if pval <= 0.01:
return "**"
if pval <= 0.05:
return "*"
|
codes = {
"reset": "\u001b[0m",
"black": "\u001b[30m",
"red": "\u001b[31m",
"green": "\u001b[32m",
"light_yellow": "\u001b[93m",
"yellow": "\u001b[33m",
"yellow_background": "\u001b[43m",
"blue": "\u001b[34m",
"purple": "\u001b[35m",
"cyan": "\u001b[36m",
"white": "\u001b[37m",
"bold": "\u001b[1m",
"unbold": "\u001b[21m",
"underline": "\u001b[4m",
"stop_underline": "\u001b[24m",
"blink": "\u001b[5m"
}
def formatter(msg, pre):
post = codes["reset"]
return u"{pre}{msg}{post}".format(**{
'pre': pre,
'msg': msg,
'post': post
})
def rojo(msg):
return formatter(msg, codes["red"])
def verde(msg):
return formatter(msg, codes["green"])
def azul(msg):
return formatter(msg, codes["blue"])
def amarillo(msg):
return formatter(msg, codes["yellow"])
|
################################################################################
# Copyright: Tobias Weber 2020
#
# Apache 2.0 License
#
# This file contains code related to all breadp module
#
################################################################################
class ChecksNotRunException(Exception):
pass
|
# 1) Um posto está vendendo combustíveis com a seguinte tabela de descontos:
#
#Álcool:
#
#até 20 litros, desconto de 3% por litro
#acima de 20 litros, desconto de 5% por litro
#Gasolina:
#
#até 20 litros, desconto de 4% por litro
#acima de 20 litros, desconto de 6% por litro.
#
#Escreva um algoritmo que leia o número de litros vendidos, o tipo de combustível
# (codificado da seguinte forma: A-álcool, G-gasolina),
# calcule e imprima o valor a ser pago pelo cliente sabendo-se que o preço do litro da gasolina é 2,50 reais
# o preço do litro do álcool é 1,90 reais.
alcool20 = .03
alcoolMais = .05
gas20 = .04
gasMais = .06
alcool = 1.90
gas = 2.50
litros = float(input("número de litros vendidos: "))
tipoCombustivel = input("Tipo de Combustivel A-álcool, G-gasolina):")
valorPago = 0.0
if tipoCombustivel == "A" or tipoCombustivel == "a":
valorPago = litros * alcool
if litros > 20:
valorPago -= valorPago * alcoolMais
else:
valorPago -= valorPago * alcool20
elif tipoCombustivel == "G" or tipoCombustivel == "g":
valorPago = litros * gas
if litros > 20:
valorPago -= valorPago * gasMais
else:
valorPago -= valorPago * gas20
else:
print("Tipo de Combustivel invalido")
print(f"valor a ser pago R$ {valorPago:.2f}") |
#
# PySNMP MIB module LIGO-GENERIC-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/LIGO-GENERIC-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:56:36 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")
SingleValueConstraint, ConstraintsUnion, ConstraintsIntersection, ValueSizeConstraint, ValueRangeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ConstraintsUnion", "ConstraintsIntersection", "ValueSizeConstraint", "ValueRangeConstraint")
InetAddressType, InetAddress = mibBuilder.importSymbols("INET-ADDRESS-MIB", "InetAddressType", "InetAddress")
ligoMgmt, = mibBuilder.importSymbols("LIGOWAVE-MIB", "ligoMgmt")
ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup")
sysLocation, = mibBuilder.importSymbols("SNMPv2-MIB", "sysLocation")
NotificationType, ModuleIdentity, Integer32, Counter32, Gauge32, Bits, MibScalar, MibTable, MibTableRow, MibTableColumn, ObjectIdentity, Counter64, TimeTicks, iso, IpAddress, Unsigned32, MibIdentifier = mibBuilder.importSymbols("SNMPv2-SMI", "NotificationType", "ModuleIdentity", "Integer32", "Counter32", "Gauge32", "Bits", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "ObjectIdentity", "Counter64", "TimeTicks", "iso", "IpAddress", "Unsigned32", "MibIdentifier")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
ligoGenericMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 32750, 3, 1))
ligoGenericMIB.setRevisions(('2016-01-15 00:00', '2009-02-13 00:00',))
if mibBuilder.loadTexts: ligoGenericMIB.setLastUpdated('201601150000Z')
if mibBuilder.loadTexts: ligoGenericMIB.setOrganization('LigoWave')
ligoGenericMIBObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 32750, 3, 1, 1))
ligoGenericNotifs = MibIdentifier((1, 3, 6, 1, 4, 1, 32750, 3, 1, 1, 0))
ligoGenericInfo = MibIdentifier((1, 3, 6, 1, 4, 1, 32750, 3, 1, 1, 1))
ligoPingHostsTable = MibTable((1, 3, 6, 1, 4, 1, 32750, 3, 1, 1, 1, 2), )
if mibBuilder.loadTexts: ligoPingHostsTable.setStatus('current')
ligoPingHostsEntry = MibTableRow((1, 3, 6, 1, 4, 1, 32750, 3, 1, 1, 1, 2, 1), ).setIndexNames((0, "LIGO-GENERIC-MIB", "ligoPingAddrType"), (0, "LIGO-GENERIC-MIB", "ligoPingAddr"))
if mibBuilder.loadTexts: ligoPingHostsEntry.setStatus('current')
ligoPingAddrType = MibTableColumn((1, 3, 6, 1, 4, 1, 32750, 3, 1, 1, 1, 2, 1, 1), InetAddressType())
if mibBuilder.loadTexts: ligoPingAddrType.setStatus('current')
ligoPingAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 32750, 3, 1, 1, 1, 2, 1, 2), InetAddress())
if mibBuilder.loadTexts: ligoPingAddr.setStatus('current')
ligoPingTime = MibTableColumn((1, 3, 6, 1, 4, 1, 32750, 3, 1, 1, 1, 2, 1, 3), Integer32()).setUnits('ms').setMaxAccess("readonly")
if mibBuilder.loadTexts: ligoPingTime.setStatus('current')
ligoPingHost = MibTableColumn((1, 3, 6, 1, 4, 1, 32750, 3, 1, 1, 1, 2, 1, 4), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ligoPingHost.setStatus('current')
ligoPowerLoss = NotificationType((1, 3, 6, 1, 4, 1, 32750, 3, 1, 1, 0, 1)).setObjects(("SNMPv2-MIB", "sysLocation"))
if mibBuilder.loadTexts: ligoPowerLoss.setStatus('current')
ligoAdministrativeReboot = NotificationType((1, 3, 6, 1, 4, 1, 32750, 3, 1, 1, 0, 2)).setObjects(("SNMPv2-MIB", "sysLocation"))
if mibBuilder.loadTexts: ligoAdministrativeReboot.setStatus('current')
ligoHeartbeat = NotificationType((1, 3, 6, 1, 4, 1, 32750, 3, 1, 1, 0, 3)).setObjects(("SNMPv2-MIB", "sysLocation"))
if mibBuilder.loadTexts: ligoHeartbeat.setStatus('current')
ligoHighPing = NotificationType((1, 3, 6, 1, 4, 1, 32750, 3, 1, 1, 0, 4)).setObjects(("SNMPv2-MIB", "sysLocation"), ("LIGO-GENERIC-MIB", "ligoPingTime"))
if mibBuilder.loadTexts: ligoHighPing.setStatus('current')
mibBuilder.exportSymbols("LIGO-GENERIC-MIB", ligoGenericMIB=ligoGenericMIB, ligoGenericNotifs=ligoGenericNotifs, ligoPingHost=ligoPingHost, ligoPowerLoss=ligoPowerLoss, ligoGenericMIBObjects=ligoGenericMIBObjects, ligoPingHostsTable=ligoPingHostsTable, ligoAdministrativeReboot=ligoAdministrativeReboot, ligoPingAddrType=ligoPingAddrType, ligoGenericInfo=ligoGenericInfo, ligoPingHostsEntry=ligoPingHostsEntry, ligoHighPing=ligoHighPing, ligoPingTime=ligoPingTime, PYSNMP_MODULE_ID=ligoGenericMIB, ligoPingAddr=ligoPingAddr, ligoHeartbeat=ligoHeartbeat)
|
class Solution:
def bitwiseComplement(self, N: int) -> int:
if N == 0:
return 1
ret = i = 0
while N:
ret |= (((N & 1) ^ 1) << i)
i += 1
N >>= 1
return ret
|
def init():
global games
global debug
global color
global tile_colors
global tile_decorations
global player_colors
global unit_emojis
games = {}
debug = False
color = 0xcc00ff
tile_colors = ["🟥", "🟦", "🟩", "⬛"]
tile_decorations = ["🌲", "🌳"]
player_colors = [0xff3333, 0x3388ff, 0x33ff33, 0x333333]
unit_emojis = ["1️⃣", "2️⃣", "3️⃣", "4️⃣", "5️⃣", "6️⃣", "7️⃣", "8️⃣", "9️⃣"]
|
# table definition
table = {
'table_name' : 'ap_pmt_batch',
'module_id' : 'ap',
'short_descr' : 'Ap batch of payments',
'long_descr' : 'Ap batch of payments by due date',
'sub_types' : None,
'sub_trans' : None,
'sequence' : None,
'tree_params' : None,
'roll_params' : None,
'indexes' : None,
'ledger_col' : 'ledger_row_id',
'defn_company' : None,
'data_company' : None,
'read_only' : False,
}
# column definitions
cols = []
cols.append ({
'col_name' : 'row_id',
'data_type' : 'AUTO',
'short_descr': 'Row id',
'long_descr' : 'Row id',
'col_head' : 'Row',
'key_field' : 'Y',
'data_source': 'gen',
'condition' : None,
'allow_null' : False,
'allow_amend': False,
'max_len' : 0,
'db_scale' : 0,
'scale_ptr' : None,
'dflt_val' : None,
'dflt_rule' : None,
'col_checks' : None,
'fkey' : None,
'choices' : None,
})
cols.append ({
'col_name' : 'created_id',
'data_type' : 'INT',
'short_descr': 'Created id',
'long_descr' : 'Created row id',
'col_head' : 'Created',
'key_field' : 'N',
'data_source': 'gen',
'condition' : None,
'allow_null' : False,
'allow_amend': False,
'max_len' : 0,
'db_scale' : 0,
'scale_ptr' : None,
'dflt_val' : '0',
'dflt_rule' : None,
'col_checks' : None,
'fkey' : None,
'choices' : None,
})
cols.append ({
'col_name' : 'deleted_id',
'data_type' : 'INT',
'short_descr': 'Deleted id',
'long_descr' : 'Deleted row id',
'col_head' : 'Deleted',
'key_field' : 'N',
'data_source': 'gen',
'condition' : None,
'allow_null' : False,
'allow_amend': False,
'max_len' : 0,
'db_scale' : 0,
'scale_ptr' : None,
'dflt_val' : '0',
'dflt_rule' : None,
'col_checks' : None,
'fkey' : None,
'choices' : None,
})
cols.append ({
'col_name' : 'ledger_row_id',
'data_type' : 'INT',
'short_descr': 'Ledger row id',
'long_descr' : 'Ledger row id',
'col_head' : 'Ledger',
'key_field' : 'A',
'data_source': 'ctx',
'condition' : None,
'allow_null' : False,
'allow_amend': False,
'max_len' : 0,
'db_scale' : 0,
'scale_ptr' : None,
'dflt_val' : '{_param.ap_ledger_id}',
'dflt_rule' : None,
'col_checks' : [
[
'ledger_id',
'Cannot change ledger id',
[
['check', '', '$value', '=', '_ctx.ledger_row_id', ''],
['or', '', '$module_row_id', '!=', '_ctx.module_row_id', ''],
],
],
],
'fkey' : ['ap_ledger_params', 'row_id', 'ledger_id', 'ledger_id', False, None],
'choices' : None,
})
cols.append ({
'col_name' : 'batch_number',
'data_type' : 'TEXT',
'short_descr': 'Payment batch number',
'long_descr' : 'Payment batch number',
'col_head' : 'Pmt no',
'key_field' : 'A',
'data_source': 'dflt_if',
'condition' : [['where', '', '_ledger.auto_pmt_batch_no', 'is not', '$None', '']],
'allow_null' : True,
'allow_amend': False,
'max_len' : 15,
'db_scale' : 0,
'scale_ptr' : None,
'dflt_val' : None,
'dflt_rule' : (
'<case>'
'<on_insert>'
'<case>'
'<compare test="[[`if`, ``, `_ledger.auto_pmt_batch_no`, `is not`, `$None`, ``]]">'
'<auto_gen args="_ledger.auto_batch_pmt_no"/>'
'</compare>'
'</case>'
'</on_insert>'
'<default>'
'<fld_val name="batch_number"/>'
'</default>'
'</case>'
),
'col_checks' : None,
'fkey' : None,
'choices' : None,
})
cols.append ({
'col_name' : 'tran_date',
'data_type' : 'DTE',
'short_descr': 'Transaction date',
'long_descr' : 'Transaction date',
'col_head' : 'Date',
'key_field' : 'N',
'data_source': 'input',
'condition' : None,
'allow_null' : False,
# 'allow_amend': False,
'allow_amend': [['where', '', 'posted', 'is', '$False', '']],
'max_len' : 0,
'db_scale' : 0,
'scale_ptr' : None,
'dflt_val' : None,
'dflt_rule' : None,
'col_checks' : [
['per_date', 'Period not open', [
['check', '', '$value', 'pyfunc',
'custom.date_funcs.check_tran_date,"ap",ledger_row_id', ''],
]],
],
'fkey' : None,
'choices' : None,
})
cols.append ({
'col_name' : 'text',
'data_type' : 'TEXT',
'short_descr': 'Text',
'long_descr' : 'Line of text to appear on reports',
'col_head' : 'Text',
'key_field' : 'N',
'data_source': 'input',
'condition' : None,
'allow_null' : False,
'allow_amend': False,
'max_len' : 0,
'db_scale' : 0,
'scale_ptr' : None,
'dflt_val' : 'Payment',
'dflt_rule' : None,
'col_checks' : None,
'fkey' : None,
'choices' : None,
})
cols.append ({
'col_name' : 'currency_id',
'data_type' : 'INT',
'short_descr': 'Batch currency',
'long_descr' : 'Currency used for this batch',
'col_head' : 'Currency',
'key_field' : 'N',
'data_source': 'dflt_if',
'condition' : [['where', '', '_ledger.currency_id', 'is not', '$None', '']],
'allow_null' : False,
'allow_amend': False,
'max_len' : 0,
'db_scale' : 0,
'scale_ptr' : None,
'dflt_val' : '{_ledger.currency_id}',
'dflt_rule' : None,
'col_checks' : None,
'fkey' : ['adm_currencies', 'row_id', 'currency', 'currency', False, 'curr'],
'choices' : None,
})
cols.append ({
'col_name' : 'pmt_cb_ledger_id',
'data_type' : 'INT',
'short_descr': 'Cash book for payments',
'long_descr' : 'Cash book to use for payments',
'col_head' : 'Pmt cb code',
'key_field' : 'N',
'data_source': 'null_if',
'condition' : [
['where', '', '_ledger.pmt_tran_source', '!=', "'cb'", ''],
],
'allow_null' : True, # null means 'not posted from cash book'
'allow_amend': True,
'max_len' : 0,
'db_scale' : 0,
'scale_ptr' : None,
'dflt_val' : None,
'dflt_rule' : (
'<case>'
'<compare test="[[`if`, ``, `_ledger.pmt_tran_source`, `=`, `~cb~`, ``]]">'
'<fld_val name="_param.cb_ledger_id"/>'
'</compare>'
'</case>'
),
'col_checks' : [
[
'pmt_cb_id',
'Cash book id required if payments posted from cashbook',
[
['check', '(', '_ledger.pmt_tran_source', '=', "'cb'", ''],
['and', '', '$value', 'is not', '$None', ')'],
['or', '(', '_ledger.pmt_tran_source', '!=', "'cb'", ''],
['and', '', '$value', 'is', '$None', ')'],
],
],
[
'pmt_curr_id',
'Cash book currency id does not match batch currency id',
[
['check', '', '$value', 'is', '$None', ''],
['or', '', 'pmt_cb_ledger_id>currency_id', '=', 'currency_id', ''],
],
],
],
'fkey' : ['cb_ledger_params', 'row_id', 'pmt_cb_id', 'ledger_id', False, 'cash_books'],
'choices' : None,
})
cols.append ({
'col_name' : 'due_tot',
'data_type' : '$TRN',
'short_descr': 'Due total',
'long_descr' : 'Due total amount - updated from ap_pmt_batch_det',
'col_head' : 'Due amt',
'key_field' : 'N',
'data_source': 'aggr',
'condition' : None,
'allow_null' : False,
'allow_amend': False,
'max_len' : 0,
'db_scale' : 2,
'scale_ptr' : 'currency_id>scale',
'dflt_val' : '0',
'dflt_rule' : None,
'col_checks' : None,
'fkey' : None,
'choices' : None,
})
cols.append ({
'col_name' : 'pmt_tot',
'data_type' : '$TRN',
'short_descr': 'Payment total',
'long_descr' : 'Payment total amount - updated from ap_pmt_batch_det',
'col_head' : 'Pmt amt',
'key_field' : 'N',
'data_source': 'aggr',
'condition' : None,
'allow_null' : False,
'allow_amend': False,
'max_len' : 0,
'db_scale' : 2,
'scale_ptr' : 'currency_id>scale',
'dflt_val' : '0',
'dflt_rule' : None,
'col_checks' : None,
'fkey' : None,
'choices' : None,
})
cols.append ({
'col_name' : 'posted',
'data_type' : 'BOOL',
'short_descr': 'Posted?',
'long_descr' : 'Has transaction been posted?',
'col_head' : 'Posted?',
'key_field' : 'N',
'data_source': 'prog',
'condition' : None,
'allow_null' : False,
'allow_amend': False,
'max_len' : 0,
'db_scale' : 0,
'scale_ptr' : None,
'dflt_val' : 'false',
'dflt_rule' : None,
'col_checks' : None,
'fkey' : None,
'choices' : None,
})
# virtual column definitions
virt = []
virt.append ({
'col_name' : 'tran_type',
'data_type' : 'TEXT',
'short_descr': 'Transaction type',
'long_descr' : 'Transaction type - used in gui to ask "Post another?"',
'col_head' : 'Tran type',
'sql' : "'ap_pmt'",
})
# cursor definitions
cursors = []
cursors.append({
'cursor_name': 'unposted_pmt',
'title': 'Unposted ap payments',
'columns': [
['tran_number', 100, False, True],
['supp_row_id>party_row_id>party_id', 80, False, True],
['supp_row_id>party_row_id>display_name', 160, True, True],
['tran_date', 80, False, True],
['pmt_amt', 100, False, True],
],
'filter': [
['where', '', 'posted', '=', "'0'", ''],
],
'sequence': [['tran_number', False]],
'formview_name': 'ap_payment',
})
# actions
actions = []
actions.append([
'on_setup',
'<case>'
'<compare test="[[\'if\', \'\', \'_ctx.module_id\', \'=\', \'~ap~\', \'\']]">'
'<case>'
'<compare test="[[\'if\', \'\', \'_ledger.pmt_tran_source\', \'=\', \'~na~\', \'\']]">'
'<aib_error head="Payment param" body="No payment transactions allowed"/>'
'</compare>'
'</case>'
'</compare>'
'</case>'
])
actions.append([
'upd_checks', [
[
'recheck_date',
'Period is closed',
[
['check', '', '$exists', 'is', '$True', ''],
['or', '', 'tran_date', 'pyfunc',
'custom.date_funcs.check_tran_date,"ap",ledger_row_id', ''],
],
],
],
])
|
# Given a binary tree, return all root-to-leaf paths.
#
# Note: A leaf is a node with no children.
#
# Example:
#
# Input:
#
# 1
# / \
# 2 3
# \
# 5
#
# Output: ["1->2->5", "1->3"]
#
# Explanation: All root-to-leaf paths are: 1->2->5, 1->3
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def binary_tree_paths(root_node: TreeNode) -> [str]:
paths = []
if not root_node:
return paths
return get_path(root_node, '', paths)
def get_path(node: TreeNode, path: str, paths: [str]) -> [str]:
new_paths = list(paths)
if not node.left and not node.right:
new_paths.append(path + str(node.val))
return new_paths
if node.left:
new_paths += get_path(node.left, path + str(node.val) + '->', paths)
if node.right:
new_paths += get_path(node.right, path + str(node.val) + '->', paths)
return new_paths
|
"""
Doctests
Doctests são testes que colocamos na docstring das funções/métodos Python.
def soma(a, b):
# soma os números a e b
#>>> soma(1, 2)
#3
#>>> soma(4, 6)
#10
#
return a + b
Para rodar um test do doctest:
python -m doctest -v nome_do_mobulo.py
# Saída
Trying:
soma(1, 2)
Expecting:
3
ok
1 items had no tests:
doctests
1 items passed all tests:
1 tests in doctests.soma
1 tests in 2 items.
1 passed and 0 failed.
Test passed.
# Outro Exemplo, Aplicando o TDD
def duplicar(valores):
#duplica os valores em uma lista
#>>> duplicar([1, 2, 3, 4])
#[2, 4, 6, 8]
#>>> duplicar([])
#[]
#>>> duplicar(['a', 'b', 'c'])
#['aa', 'bb', 'cc']
#>>> duplicar([True, None])
#Traceback (most recent call last):
# ...
#TypeError: unsupported operand type(s) for *: 'int' and 'NoneType'
#
#return [2 * elemento for elemento in valores]
# Erro inesperado...
OBS: Dentro do doctest, o Python não reconhece string com aspas duplas. Precisa ser aspas simples.
def fala_oi():
#Fala oi
#>>> fala_oi()
#'oi'
#
#return "oi"
"""
# Um último caso estranho...
def verdade():
"""Retorna verdade
>>> verdade()
True
"""
return True
|
"""
This is a dedicated editor for specifying camera set rigs. It allows
the artist to preset a multi-rig type. They can then use the
create menus for quickly creating complicated rigs.
"""
class BaseUI:
"""
Each region of the editor UI is abstracted into a UI class that
contains all of the widgets for that objects and relavant callbacks.
This base class should not be instanced as this is only a container
for common code.
"""
def __init__(self, parent):
"""
Class initialization. We simply hold onto the parent layout.
"""
pass
def control(self):
"""
Return the master control for this UI.
"""
pass
def parent(self):
"""
Return the parent instace of this UI. This can be None.
"""
pass
def setControl(self, control):
"""
Set the pointer to the control handle for this UI. This is
the main control that parents or children can reference
for UI updates.
"""
pass
class NewCameraSetUI(BaseUI):
"""
UI for adding 'new' camera set.
"""
def __init__(self, parent):
"""
Class constructor
"""
pass
def buildLayout(self):
"""
Construct the UI for this class.
"""
pass
def name(self):
"""
Name of this UI component.
"""
pass
def newTemplate(self, *args):
"""
Create a new template and adding the template to the
UI layout for user manipulation.
"""
pass
def rebuild(self):
"""
Rebuild the UI. We find the parent class and tell it
to kickstart the rebuild.
"""
pass
def resetSettings(self, *args):
"""
Reset to the default settings and rebuild the UI.
"""
pass
def resetUI(self):
"""
Tells all ui templates to reset their ui handles. This
is done because this UI templates hold onto some
local data that must be cleared out before rebuilding
"""
pass
def saveSettings(self, *args):
"""
Call the template manager to store its current settings
"""
pass
class NamingTemplateUI(BaseUI):
"""
This class encapsulates all of the UI around multi rig naming templates.
"""
def __init__(self, parent, mgr, template):
"""
Class initializer.
"""
pass
def addLayer(self, *args):
"""
Add a new layer to this object.
"""
pass
def autoCreateCkboxChange(self, args, layer='0'):
"""
Called when the check box is changed.
"""
pass
def buildLayout(self):
"""
Build a new multi-rig template UI.
"""
pass
def cameraSetNameChanged(self, arg):
pass
def createIt(self, *args):
"""
Function called when the user clicks the 'Create' button.
This will force the creation of a new rig.
"""
pass
def deleteLayer(self, args, layer='0'):
"""
Called when the delete layer button is clicked.
"""
pass
def layerCameraChanged(self, args, layer='0'):
"""
Called when the option menu group changes.
"""
pass
def layerPrefixChanged(self, args, layer='0'):
"""
Called when the prefix changes for a layer.
"""
pass
def layoutForLayer(self, layer):
"""
Build the UI for the specified layer. We need to access the
UI data later in callbacks. So we store the data inside
a dictionary for reference layer.
"""
pass
def multiRigNameChanged(self, ui):
"""
Called when the user changes the name of this multi-rig
using the supplied text box.
"""
pass
def namingPrefixChanged(self, arg):
"""
Called when the users changes the prefix name used for the
multi-rig.
"""
pass
def removeDef(self, *args):
"""
Remove this object from the list.
"""
pass
def resetUI(self):
pass
class CameraSetEditor(BaseUI):
"""
Main class for the camera set editor.
"""
def __init__(self, parent='None'):
"""
Class constructor.
"""
pass
def buildLayout(self):
"""
Build the main layout for the class. This will kickstart all
UI creation for the class. You should have a window instance
created for the layouts to parent under.
"""
pass
def create(self):
"""
Create a new instance of the window. If there is already a instance
then show it instead of creating a new instance.
"""
pass
def name(self):
"""
Return the name for this editor.
"""
pass
def rebuild(self):
"""
Force the rebuild of the UI. This happens when
users create new templates.
"""
pass
def createIt():
"""
Create a new window instance of the Camera Set Editor.
"""
pass
gEditorWindowInstance = None
|
a=input()
b=a[::-1]
if a==b:
print("yes")
else:
print("no")
|
def getBMR(weightLBS, heightINCHES, age):
weightKG = weightLBS*.453592
heightCM = heightINCHES*2.54
BMR = 10*weightKG+.25*heightCM-5*age+5
return BMR
|
s = '¹÷É´¹Ò®¾¤¦ò¤®¾¤µÈ¾¤Â©¨¡¾¨ö®¾¤¦ò¤®¾¤µÈ¾¤Ã¦È'
# s = '¡¾²½ñ¢ñªÒ, ²½ñ, ¦ò¤¢º¤ê†Ã§Éá¾²½ñ'
s = 'À»ñ©Ã¹ÉÁª¡, À»ñ©Ã¹ÉÀ², À»ñ©Ã¹É¹ñ¡, À»ñ©Ã¹ÉçɮÒÄ©É'
s = '¦ô®ªÒ, µøÈªÒ, ´óµøÈ, ª˜¤µøÈ'
s = 'ªó, À£¾½, ¥ñ¤¹¸½, ¡¾Àª˜,-ຊະນະ'
s = 'À»ñ©Ã¹ÉÀ¡ó©¦ó, À»ñ©Ã¹ÉÀ¯ñ¦ó'
# for i in range(161, 255):
# print(chr(i))
# if i in s_lao_map_uc:
# print("======> ", s_lao_map_uc[i])
def converter(c):
s_lao_map_uc = {
155 : "ດ", 156 : "ຕ", 157 : "ຖ", 158 : "$", 159 : "ນ", 160 : "ບ", 161 : "ປ",
160 : "$", 161 : "ກ", 162 : "ຂ", 163 : "ຄ", 164 : "ງ", 165 : "ຈ", 166 : "ສ", 167 : "ຊ", 168 : "ຍ", 169 : "ດ", 170 : "ຕ", 171 : "ຖ", 172 : "$", 173 : "ນ", 174 : "ບ", 175 : "ປ",
176 : "ຜ", 177 : "ຝ", 178 : "ພ", 179 : "ຟ", 180 : "ມ", 181 : "ຢ", 182 : "$", 183 : "$", 184 : "ວ", 185 : "ຫ", 186 : "ອ", 187 : "ຮ", 188 : "ຽ", 189 : "ະ", 190 : "າ", 191 : "ໍາ",
192 : "ເ", 193 : "ແ", 194 : "ໂ", 195 : "ໃ", 196 : "ໄ", 197 : "ໆ", 198 : "ຯ", 199 : "$", 200 : "່", 201 : "້", 202 : "໊", 203 : "໋", 204 : "໌", 205 : "ຫຼ", 206 : "ໜ", 207 : "$",
208 : "ຸ", 209 : "ູ", 210 : "ໍ່", 211 : "ໍ້", 212 : "ໍ່າ", 213 : "ໍ້າ", 214 : "ໍ", 215 : "ັ", 216 : "ິ", 217 : "ີ", 218 : "ຶ", 219 : "ື", 220 : "ົ", 221 : "ຸ", 222 : "ູ", 223 : "$",
224 : "0", 225 : "$", 226 : "$", 227 : "$", 228 : "$", 229 : "$", 230 : "$", 231 : "$", 232 : "$", 233 : "$", 234 : "ທ", 235 : "ຣ", 236 : "ລ", 237 : "ົ້", 238 : "$", 239 : "$",
240 : "ໍ", 241 : "ັ", 242 : "ິ", 243 : "ີ", 244 : "ຶ", 245 : "ື", 246 : "ົ", 247 : "ຸ", 248 : "ູ", 249 : "ຼ", 250 : "່", 251 : "້", 252 : "໊", 253 : "໋", 254 : "໌", 255 : "$"}
return s_lao_map_uc[ord(c)] if ord(c) in s_lao_map_uc else c
with open(r'c:/Users/Phanakhone/Desktop/lao_converter/todo.txt', 'r', encoding='utf-8') as f:
data = f.read().splitlines()
for i in data:
for c in i:
print(converter(c), end='')
if converter(c) == "$":
print(ord(c),"============")
print()
|
class SocialErrorMessages:
"""
Create SocialErrorMessages object
"""
def __init__(self, base_url: str):
self._full_messages = {
"email facebook error": f"""<p>We can't get your email. Please, check <a href=\"https://facebook.com/settings\">your facebook settings</a>. Make sure you have email there.</p>
<p><a href=\"{base_url}/login\">Back</p>
""",
"email exists": f"""<p>Email already exists.</p>
<p><a href=\"{base_url}/login\">Back</p>
""",
"ban": f"""<p>User has been banned.</p>
<p><a href=\"{base_url}/login\">Back</p>""",
}
self._server_error = "Unknown error"
def get_error_message(self, msg: str) -> str:
return self._full_messages.get(msg) or self._server_error
def get_error_message(msg: str, base_url: str) -> str:
error_messages = SocialErrorMessages(base_url)
return error_messages.get_error_message(msg)
|
n = int(input("Please Enter a value for N:\n"))
count = 0
sum = 0
while count <= n :
sum = sum+count
count +=1
print("Sum of N natural numbers: " + str(sum)) |
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 21 16:50:47 2020
@author: ucobiz
"""
inputObj = open("newfile.txt")
outputObj = open("output-newfile.txt", "w")
# convert the sentence into UPPERCASE
for sentence in inputObj:
newSentenceUpper = sentence.upper()
outputObj.writelines(newSentenceUpper)
inputObj.close()
outputObj.close()
|
# subsets 78
# ttungl@gmail.com
# Given a set of distinct integers, nums, return all possible subsets (the power set).
# Note: The solution set must not contain duplicate subsets.
# For example,
# If nums = [1,2,3], a solution is:
# [
# [3],
# [1],
# [2],
# [1,2,3],
# [1,3],
# [2,3],
# [1,2],
# []
# ]
class Solution(object):
def subsets(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
#######
# sol 1: iterative
# runtime: 42ms
res = [[]]
for i in nums:
res += [j + [i] for j in res]
return res
#######
# sol 2: DFS recursively
# runtime: 42ms
def DFS(nums, index, path, res):
res.append(path)
[DFS(nums, i + 1, path + [nums[i]], res) for i in range(index, len(nums))]
res = []
DFS(nums, 0, [], res)
return res
|
# integer = int(input("Please fill number:"))
integer = 12
result = tuple()
for i in range(0,integer,2 ):
result = result + (i,)
print(result) |
APIS = {
'apis',
'keyvaluemaps',
'targetservers',
'caches',
'developers',
'apiproducts',
'apps',
'userroles',
}
class Struct:
def __init__(self, **entries):
self.__dict__.update(entries)
def __repr__(self):
return f"{self.__dict__}"
def empty_snapshot():
return Struct(
apis={},
keyvaluemaps={},
targetservers={},
caches={},
developers=[],
apps={},
apiproducts=[],
userroles=[],
)
|
# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
GDAL_LIBRARY_PATH = "/Applications/Postgres.app/Contents/Versions/9.4/lib/libgdal.dylib"
GEOS_LIBRARY_PATH = "/Applications/Postgres.app/Contents/Versions/9.4/lib/libgeos_c.dylib"
DATABASES = {
'default': {
'ENGINE': 'django.contrib.gis.db.backends.postgis',
'NAME': 'tor_nodes_map',
'USER': '',
'PASSWORD': '',
'HOST': '',
'PORT': '',
}
}
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
|
# -*- coding:UTF-8 -*-
#! /usr/bin/python3
# 字符串 内建函数
String_a = 'iPhone'
String_b = 'Apple'
# 首字母大写
print('=====首字母大写=====\n注意调用方法:')
print(String_a,'->',str.capitalize(String_a))
print(String_b,'->',String_b.capitalize()) # 注意调用方法
print('=====字符填充=====')
print('填充字符,默认填充空格:',String_a.center(20))# 填充字符
print('左对齐填充',String_b.ljust(20,'-'))# 左对齐填充
print('右对齐填充',String_b.rjust(20,'-'))# 右对齐填充
print('右对齐,前补零:',String_b.zfill(20)) # 返回长度为 width 的字符串,原字符串右对齐,前面填充0
print('=====计算出现次数=====')
print('注意调用方法:\np出现:',String_b.count('p'),'次')# 计算某字符串出现次数
print('p出现:',str.count(String_b,'p'),'次')
# bytes.decode(encoding="utf-8", errors="strict")
# encode(encoding='UTF-8',errors='strict')
String_C = 'a b c d c'
print(String_C.expandtabs(tabsize=8)) # 用制表符扩充???
print('=====查找值的索引=====')
print('查找b的索引,可规定查找区间,存在返回其索引,不存在返回-1:',String_C.find('b',0,5)) # 返回索引,不存在返回-1
print('查找c的索引,可规定查找区间,存在返回其索引,不存在会报错:',String_C.index('c',3,5)) # 跟find()方法一样,只不过如果str不在字符串中会报一个异常.
print('类似于find()函数,从右边开始查找.',String_C.rfind('b',0,5)) # 类似于 find()函数,不过是从右边开始查找.
print('类似于index()函数,从右边开始查找.',String_C.rindex('c'),'\n\b=====判断函数=====') # 类似于 index(),不过是从右边开始..
del String_C;String_c = '1z2y3x4w5v6u'
print('判断是否为仅包含字母和数的非空字符串',String_c.isalnum()) # 判断是否为仅包含字母和数的非空字符串
print('判断是否为仅包含字母的非空字符串',String_c.isalpha()) # 判断是否为仅包含字母的非空字符串
print('如果字符串只包含数字则返回 True 否则返回 False',String_c.isdigit()) # 如果字符串只包含数字则返回 True 否则返回 False.
print('检查字符串是否只包含十进制字符,如果是返回 true,否则返回 false',String_c.isdecimal()) # 检查字符串是否只包含十进制字符,如果是返回 true,否则返回 false。
print('字符串若包含至少一个区分大小写的字符,且所有这些字符都是小写,则返回True',String_c.islower()) # 如果字符串中包含至少一个区分大小写的字符,并且所有这些字符都是小写,则返回 True
print('字符串若包含至少一个区分大小写的字符,且所有这些字符都是大写,则返回True','AAA'.isupper()) # 如果字符串中包含至少一个区分大小写的字符,并且所有这些字符都是大写,则返回 True
print('如果字符串中只包含数字字符,则返回 True,否则返回 False',String_c.isnumeric()) # 如果字符串中只包含数字字符,则返回 True,否则返回 False
print('如果字符串中只包含空白,则返回 True,否则返回 False.'," ".isspace()) # 如果字符串中只包含空白,则返回 True,否则返回 False.
String_C = 'today is a perfect good day'
print(String_C.title())
print((String_C.title()).istitle()) # 如果字符串是标题化的(见 title())则返回 True,否则返回 False
print(String_a.join(String_b)) # 以指定字符串作为分隔符,将 seq 中所有的元素(的字符串表示)合并为一个新的字符串
# 返回字符串长度
print(String_b.__len__())
print(len(String_b))
print('aWafAFS2CALjaka'.lower()) # 转换字符串中所有大写字符为小写.
print('aWafAFS2CALjaka'.upper()) # 转换字符串中所有小写字符为大写.
print('aWafAFS2CALjaka'.swapcase()) # 转换字符串中所有大小写互换.
print('=====首末字符删除=====')
print('aaaaaasaaaaaa'.lstrip('a')) # 截掉字符串左边的空格或指定字符.
print('aaaaaasaaaaaa'.rstrip('a')) # 删除字符串字符串末尾的空格或指定字符.
print('aaaaaasaaaaaa'.strip('a')) # 在字符串上执行 lstrip()和 rstrip()
print('=====最大最小字母=====')
print(max(String_b)) # 返回字符串 str 中最大的字母。
print(min(String_b)) # 返回字符串 str 中最小的字母。
print('AA12AA23AA3fjlAA12flA'.replace('AA','???',3)) # 把 将字符串中的 str1 替换成 str2,如果 max 指定,则替换不超过 max 次。
print('AA12AA23AA3fjlAA12flA'.split('AA',2)) # 次数可用num=string.count(str)),以 str 为分隔符截取字符串,num指定截取个数
print(String_c.startswith('1',0,5)) # 检查字符串是否是以 输入参数 开头,是则返回 True,否则返回 False。beg和end指定范围内检查。
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.