content stringlengths 7 1.05M |
|---|
"""Created by sgoswami on 8/30/17."""
"""Given a binary tree where all the right nodes are either leaf nodes with a sibling (a left node that shares the
same parent node) or empty, flip it upside down and turn it into a tree where the original right nodes turned into
left leaf nodes."""
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def upsideDownBinaryTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
if not root or not root.left:
return root
new_root = self.upsideDownBinaryTree(root.left)
root.left.left = root.right
root.left.right = root
root.left = None
root.right = None
return new_root
|
# C100--- python classes
class Car(object):
"""
blueprint for car
"""
def __init__(self, modelInput, colorInput, companyInput, speed_limitInput):
self.color = colorInput
self.company = companyInput
self.speed_limit = speed_limitInput
self.model = modelInput
def start(self):
print("started")
def stop(self):
print("stopped")
def accelarate(self):
print("accelarating...")
"accelarator functionality here"
def change_gear(self, gear_type):
print("gear changed")
" gear related functionality here"
audi = Car("A6", "red", "audi", 80)
print(audi.start())
|
class ConfigSVM:
# matrix_size = 1727
# matrix_size = 1219
# matrix_size = 1027
matrix_size = 798
# matrix_size = 3 |
print('\033[1;93m-=-\033[m' * 15)
print(f'\033[1;31m{"LARGEST AND SMALLEST ON THE LIST":^45}\033[m', )
print('\033[1;93m-=-\033[m' * 15)
numbers = list()
largest = 0
big_position = list()
small_position = list()
numbers.append(int(input(f'Type a number for the position {0}: ')))
smallest = numbers[0]
for i in range(1, 5):
numbers.append(int(input(f'Type a number for the position {i}: ')))
if numbers[i] > largest:
largest = numbers[i]
if numbers[i] < smallest:
smallest = numbers[i]
print('-=-' * 15)
print('You entered the valors: ', end='')
for n in numbers:
print(n, end=' ')
for i in range(0, 5):
if numbers[i] == largest:
big_position.append(i)
if numbers[i] == smallest:
small_position.append(i)
print(f'\nThe largest number entered was: {largest} in the positions ', end='')
for n in big_position:
print(f'{n}... ', end='')
print(f'\nThe smallest number entered was: {smallest} in the positions ', end='')
for n in small_position:
print(f'{n}... ', end='')
|
# Copyright (c) 2015 The WebRTC project authors. All Rights Reserved.
#
# Use of this source code is governed by a BSD-style license
# that can be found in the LICENSE file in the root of the source
# tree. An additional intellectual property rights grant can be found
# in the file PATENTS. All contributing project authors may
# be found in the AUTHORS file in the root of the source tree.
{
'includes': [ '../build/common.gypi', ],
'conditions': [
['OS=="ios"', {
'targets': [
{
'target_name': 'rtc_api_objc',
'type': 'static_library',
'dependencies': [
'<(webrtc_root)/base/base.gyp:rtc_base_objc',
],
'sources': [
'objc/RTCIceServer+Private.h',
'objc/RTCIceServer.h',
'objc/RTCIceServer.mm',
],
'xcode_settings': {
'CLANG_ENABLE_OBJC_ARC': 'YES',
'CLANG_WARN_OBJC_MISSING_PROPERTY_SYNTHESIS': 'YES',
'GCC_PREFIX_HEADER': 'objc/WebRTC-Prefix.pch',
},
}
],
}], # OS=="ios"
],
}
|
getObject = {
'primaryRouter': {
'datacenter': {'id': 1234, 'longName': 'TestDC'},
'fullyQualifiedDomainName': 'fcr01.TestDC'
},
'id': 1234,
'vlanNumber': 4444,
'firewallInterfaces': None
}
|
"""Library package info"""
author = "linuxdaemon"
version_info = (0, 3, 0)
version = ".".join(map(str, version_info))
__all__ = ("author", "version_info", "version")
|
"""The module has following classes:
- Room"""
class Room(object):
'''Takes name and description of the object and initializes paths.\nProvides methods \n\t go(direction) and,\n\t add_paths(paths)'''
def __init__(self, name, description):
self.name = name
self.description = description
self.paths = {}
def go(self, direction):
return self.paths.get(direction, None)
def add_paths(self, paths):
return self.paths.update(paths)
|
class Car:
def wheels(self):
print('Car.wheels')
return 4
class Bike(Car):
def wheels(self):
return 2
class Truck(Car):
def wheels(self):
print('Truck.wheels: start')
super().wheels()
print('Truck.wheels: end')
return 6
car = Bike()
print(car.wheels()) # 2
truck = Truck()
print(truck.wheels()) # 6
|
class NodeEndpoint:
protocol = ''
host = ''
port = ''
@staticmethod
def from_parameters(protocol, host, port):
endpoint = NodeEndpoint()
endpoint.protocol = protocol
endpoint.host = host
endpoint.port = port
return endpoint
@staticmethod
def from_json(endpoint_json):
return NodeEndpoint.from_parameters(
endpoint_json['protocol'],
endpoint_json['host'],
endpoint_json['port'])
def url(self):
return '{0}://{1}:{2}/'.format(self.protocol, self.host, self.port) |
class SchemaConstructionException(Exception):
def __init__(self, claz):
self.cls = claz
class SchemaParseException(Exception):
def __init__(self, errors):
self.errors = errors
class ParseError(object):
def __init__(self, path, inner):
self.path = path
self.inner = inner
class CheckFailed(object):
def __init__(self, check_fn, failed_value):
self.check_fn = check_fn
self.failed_value = failed_value
|
"""
Created on Sun Feb 15 01:52:42 2015
@author: Enes Kemal Ergin
The Field: Introduction to Complex Numbers (Video 2)
"""
# complex number = (real part) + (imaginary part) * i
## Pyhton use j for doing complex
1j
1+3j
(1+3j) + (10+20j)
x = 1+3j
(x-1)**2
# (-9+0j) -> -9
x.real
# 1.0
x.imag
# 3.0
## Write a procedure solve(a,b,c) to solve ax + b = c
def solve(a,b,c):
return (c-b)/a
solve(10, 5, 30)
# We can use the same procedure to calculate complex numbers as well.
solve(10+5j, 5, 20)
# (1.2-0.6j)
# Same procedure works for complex numbers.
|
class Solution:
def maxPerformance(self, n: int, speed: List[int], efficiency: List[int], k: int) -> int:
modulo = 10 ** 9 + 7
# build tuples of (efficiency, speed)
candidates = zip(efficiency, speed)
# sort the candidates by their efficiencies
candidates = sorted(candidates, key=lambda t:t[0], reverse=True)
speed_heap = []
speed_sum, perf = 0, 0
for curr_efficiency, curr_speed in candidates:
# maintain a heap for the fastest (k-1) speeds
if len(speed_heap) > k-1:
speed_sum -= heapq.heappop(speed_heap)
heapq.heappush(speed_heap, curr_speed)
# calculate the maximum performance with the current member as the least efficient one in the team
speed_sum += curr_speed
perf = max(perf, speed_sum * curr_efficiency)
return perf % modulo
|
"""Helper functions used in various modules."""
def deserialize_thing_id(thing_id):
"""Convert base36 reddit 'thing id' string into int tuple."""
return tuple(int(x, base=36) for x in thing_id[1:].split("_"))
def update_sr_tables(cursor, subreddit):
"""Update tables of subreddits and subreddit-moderator relationships."""
_, subreddit_id = deserialize_thing_id(subreddit.fullname)
# Add subreddits and update subscriber counts
cursor.execute(
"INSERT OR IGNORE INTO subreddits (id, display_name) VALUES(?,?)",
(subreddit_id, str(subreddit)),
)
cursor.execute(
"UPDATE subreddits SET subscribers = ? " "WHERE id = ?",
(subreddit.subscribers, subreddit_id),
)
# Refresh listing of subreddits' moderators
cursor.execute(
"DELETE FROM subreddit_moderator " "WHERE subreddit_id = ?",
(subreddit_id,),
)
for moderator in subreddit.moderator():
cursor.execute(
"INSERT OR IGNORE INTO users (username) " "VALUES(?)",
(str(moderator),),
)
cursor.execute(
"SELECT id FROM users WHERE username = ?", (str(moderator),)
)
moderator_id = cursor.fetchone()[0]
cursor.execute(
"INSERT OR IGNORE INTO subreddit_moderator "
"(subreddit_id, moderator_id) VALUES(?,?)",
(subreddit_id, moderator_id),
)
|
"""Test the link to the help docco."""
def test_help_redirect_to_rtd(webapp, f_httpretty):
"""Test we redirect to read the docs."""
f_httpretty.HTTPretty.allow_net_connect = False
response = webapp.get('/help')
assert response.status_code == 302
assert response.headers['location'] == 'https://dnstwister.readthedocs.org/en/stable/web.html'
|
# Minimum Size Subarray Sum
class Solution:
def minSubArrayLen(self, target, nums):
length = len(nums)
Invalid = length + 1
left, right = 0, 0
added = nums[left]
if added >= target:
return 1
ans = Invalid
while True:
if left + 1 <= right and added - nums[left] >= target:
added -= nums[left]
left += 1
ans = min(ans, right - left + 1)
continue
if right < length - 1:
added += nums[right + 1]
right += 1
if added >= target:
ans = min(ans, right - left + 1)
continue
# cannot reduct left side, cannot expand to right.
# break here
break
return 0 if ans == Invalid else ans
if __name__ == "__main__":
sol = Solution()
target = 7
nums = [2,3,1,2,4,3]
target = 4
nums = [1,4,4]
target = 11
nums = [1,1,1,1,1,1,1,1]
target = 11
nums = [12]
target = 15
nums = [1,2,3,4,5]
print(sol.minSubArrayLen(target, nums))
|
# http://codingbat.com/prob/p165321
def near_ten(num):
return (num % 10 <= 2) or (num % 10 >= 8)
|
# 计算圆的周长和面积(其二:用变量表示圆周率)
PI = 3.14159 # 圆周率
r = float(input('半径:'))
print('圆的周长是', 2 * PI * r, '。')
print('面积是', PI * r * r, '。')
|
class WorkerNode(object):
def __init__(self, ip, k8s_name, k8s_is_ready):
self.ip = ip
self.k8s_name = k8s_name
self.k8s_is_ready = k8s_is_ready
self.k8s_pod_num = 0
self.vc = None
self.to_turn_on = False
self.to_turn_off = False
class Pod(object):
def __init__(self, vc, host_ip, pending):
self.vc = vc
self.host_ip = host_ip
self.pending = pending
class VirtualCluster(object):
def __init__(self, name, is_full, is_guaranteed):
self.name = name
self.is_full = is_full
self.is_guaranteed = is_guaranteed
|
filmler= {
"Kara Korsanın Laneti":{"Yapım Yılı":1957,"Imdb":8.2,"Tür":"Korku"},
"Sineğin İntikamı":{"Yapım Yılı":2957,"Imdb":1.2,"Tür":"Belgesel"}
}
def filmEkle():
film_adı = input("Film adı girin: ")
global filmler
if film_adı:
yapım_yılı = input("Yapım yılını girin: ")
imdb = input("İmdb puanını girin: ")
film_türü = input("Film türünü girin: ")
filmler[film_adı]= {"Yapım Yılı":yapım_yılı,"Imdb":imdb,"Tür":film_türü}
print("Film başarıyla eklendi")
else:
print("Film adı boş bırakılamaz.")
def filmSil():
film_adı = input("Film adı girin: ")
if film_adı:
filmler.pop(film_adı)
print("Film başarıyla silindi")
else:
print("Film adı boş bırakılamaz.")
def filmGetir():
aranan_film_adı= input("Aradığını filmin adını girin: ")
if aranan_film_adı in filmler.keys():
film = filmler.get(aranan_film_adı)
yapım_yılı= film.get("Yapım Yılı","Yapım yılı girilmemiş")
imdb= film.get("Imdb","Imdb puanı girilmemiş")
film_türü= film.get("Tür","Film türü girilmemiş")
print("Film adı: {} Yapım Yılı: {} Imdb: {} Tür: {}".format(aranan_film_adı,yapım_yılı,imdb,film_türü))
else:
print("Film mevcut değil")
def filmleriListele():
for film in filmler:
film_adı = film
yapım_yılı= filmler[film_adı].get("Yapım Yılı","Yapım yılı girilmemiş")
imdb= filmler[film_adı].get("Imdb","Imdb puanı girilmemiş")
film_türü= filmler[film_adı].get("Tür","Film türü girilmemiş")
print("Film adı: {} Yapım Yılı: {} Imdb: {} Tür: {}".format(film_adı,yapım_yılı,imdb,film_türü))
print("="*80)
input("Devam etmek için bir tuşa basın.")
while True:
print("""
[1] Tüm filmleri listele
[2] Film ara
[3] Film ekle
[4] Film sil
""")
secenek= int(input("Seçiminizi yapın: "))
if secenek == 1:
filmleriListele()
elif secenek == 2:
filmGetir()
elif secenek == 3:
filmEkle()
elif secenek == 4:
filmSil() |
class Solution:
def countAndSay(self, n):
numb = 1
w = 1
while n > 1:
w = Solution.CountSay(numb)
numb = w
n -= 1
return str(w)
def CountSay(no):
tnumb = str(no)
x = tnumb[0]
count = 1
strr = ""
for i in range(1, len(tnumb) + 1):
if i == len(tnumb):
strr += str(count) + str(x)
break
if tnumb[i] == x:
count += 1
else:
strr += str(count) + str(x)
x = tnumb[i]
count = 1
return int(strr)
|
# domoticz configuration
DOMOTICZ_SERVER_IP = "xxx.xxx.x.xxx"
DOMOTICZ_SERVER_PORT = "xxxx"
DOMOTICZ_USERNAME = ""
DOMOTICZ_PASSWORD = ""
# sensor dictionary to add own sensors
# if you don't want to use the raw voltage option, just write -1 in the VOLTAGE_IDX value field
sensors = { 1: {"MAC": "xx:xx:xx:xx:xx:xx", "TH_IDX": 1, "VOLTAGE_IDX": -1, "UPDATED": False},
2: {"MAC": "xx:xx:xx:xx:xx:xx", "TH_IDX": 2, "VOLTAGE_IDX": -1, "UPDATED": False},
3: {"MAC": "xx:xx:xx:xx:xx:xx", "TH_IDX": 3, "VOLTAGE_IDX": -1, "UPDATED": False}}
# other configuration
TEMPERATURE_PREC = 2
# Logfile configuration
LOG_FILE_NAME = "loginfo.log"
LOG_FILE_SIZE = 16384 # file size in bytes
|
n = int(input('Digite um número para calcular seu Fatorial: '))
c = n
f = 1
print('Calculando {}! = '.format(n), end='')
while c > 0:
print('{}'.format(c), end='')
print(' x ' if c > 1 else ' = ', end='')
f *= c
c -= 1
print('{}'.format(f))
'''fazer com for
for i in range(n, 0, -1):
print('{}'.format(i), end='')
print(' x ' if i > 1 else ' = ', end='')
f *= i
i -= 1
print('{}'.format(f))
''' |
del_items(0x8009E2A0)
SetType(0x8009E2A0, "char StrDate[12]")
del_items(0x8009E2AC)
SetType(0x8009E2AC, "char StrTime[9]")
del_items(0x8009E2B8)
SetType(0x8009E2B8, "char *Words[117]")
del_items(0x8009E48C)
SetType(0x8009E48C, "struct MONTH_DAYS MonDays[12]")
|
class FunctionLink:
def __init__(self, linked_function):
self.__linked_function = linked_function
@property
def linked_function(self):
return self.__linked_function
|
workers = 2
timeout = 120
reload = True
limit_request_field_size = 0
limit_request_line = 0
|
n = int(input('Digite um número: '))
c = 0
for i in range(1, n + 1):
if n % i == 0:
c += 1
print('\033[1;33m{}\033[m'.format(i), end=' ')
else:
print('\033[1;31m{}\033[m'.format(i), end=' ')
print('O número {} foi divisível {} vezes'.format(n, c))
if c == 2:
print('E por isso ele é PRIMO!')
else:
print('E por isso ele NÃO É PRIMO!')
|
def codesTable(char):
table = {
"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": "--..",
".-": "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",
"0": "-----", "1": ".----", "2": "..---", "3": "...--", "4": "....-",
"5": ".....", "6": "-....", "7": "--...", "8": "---..", "9": "----.",
"-----": "0", ".----": "1", "..---": "2", "...--": "3", "....-": "4",
".....": "5", "-....": "6", "--...": "7", "---..": "8", "----.": "9"
}
return table[char]
def encoding(text):
text, finished_text = text.upper(), ""
for symbol in text:
if symbol.isalnum():
finished_text += codesTable(symbol) + " "
return finished_text
def decoding(text):
text, finished_text = text.upper(), ""
for code in text.split():
finished_text += codesTable(code)
return finished_text
def assembly(mode):
text = str(input("[+] Enter your text - "))
if mode == 0:
finished_text = encoding(text)
else:
finished_text = decoding(text)
print("\n »» The result of encoding by Morse algorithm. ««")
print(finished_text)
def main():
print("[x] Morse cryptography algorithm. [x]")
print(" • 0. Encoding mode.\n • 1. Decoding mode.")
mode = int(input("[?] Select program mode - "))
assembly(mode)
if __name__ == '__main__':
main()
|
GITHUB_TOKENS = ['GH_TOKEN']
GITHUB_URL_FILE = 'rawGitUrls.txt'
GITHUB_API_URL = 'https://api.github.com/search/code?q='
GITHUB_API_COMMIT_URL = 'https://api.github.com/repos/'
GITHUB_SEARCH_PARAMS = '&sort=indexed&o=desc'
GITHUB_BASE_URL = 'https://github.com'
GITHUB_MAX_RETRY = 10
XDISCORD_WEBHOOKURL = 'https://discordapp.com/api/webhooks/7XXXXXXXXXXXXXX/XXXXXXXXXXXXXXXXXXXXXX'
XSLACK_WEBHOOKURL = 'https://hooks.slack.com/services/TXXXXXXXX/BXXXXXXXX/XXXXXXXXXXXXXXXXXXXXXXX'
TELEGRAM_CONFIG = {
"token": "1437557225:AAHpOqwOZ4Xlap",
"chat_id": "Code"
}
|
# -*- coding:utf-8 -*-
# /usr/bin/env python
"""
Author: Albert King
date: 2019/11/14 20:32
contact: jindaxiang@163.com
desc: 学术板块配置文件
"""
# EPU
epu_home_url = "http://www.policyuncertainty.com/index.html"
# FF-factor
ff_home_url = "http://mba.tuck.dartmouth.edu/pages/faculty/ken.french/data_library.html"
|
class Fish:
def __init__(self,filename):
with open(filename,'r') as input_file:
ages = [int(age) for age in input_file.readline().strip('\n').split(',')]
# create a population breakdown - for each age contains a count of number of fish in this age group. Needed to make this scale
self.population = {}
for index in range(0,9):
self.population[index] = 0
for age in ages:
self.population[age] += 1
# Simulate (good for Parts 1 and 2)
def simulate(self,days):
for day in range(1,days+1):
# remember number in group zero - these will all move to 6 and for each one a new 8 will be added
# the number in each group moves down one group (8 through 1)
# group 8 goes to number in group 0
# group 6 is incremented by number in group 0
group0 = self.population[0]
for index in range(1,9):
self.population[index-1] = self.population[index]
self.population[8] = group0
self.population[6] += group0
# return a sum in all groups
return sum(self.population.values())
|
class QuickSort(object):
"In Place Quick Sort"
def __init__(self, arr):
self.arr = arr
def sort(self, left_i, right_i):
if right_i - left_i < 1:
return
pivot_i = self.partition(left_i, right_i)
self.sort(left_i, pivot_i - 1)
self.sort(pivot_i + 1, right_i)
def partition(self, left_i, right_i):
pivot_i = right_i
lesser_i = left_i
for i in range(left_i, right_i):
if arr[i] < arr[pivot_i]:
self.swap(i, lesser_i)
lesser_i += 1
self.swap(pivot_i, lesser_i)
self.print_arr()
return lesser_i
def swap(self, index_1, index_2):
arr[index_1], arr[index_2] = arr[index_2], arr[index_1]
def print_arr(self):
print(" ".join(list(map(str, arr))))
n = int(input().strip())
arr = list(map(int, input().strip().split(" ")))
quicksort = QuickSort(arr)
quicksort.sort(0, len(arr) - 1)
|
def validate(instruction) -> bool:
"""Validates an instruction
Parameters
----------
instruction : BaseCommand
The instruction to validate
Returns
-------
bool
Valid or not valid
"""
switch = {
# R Type instructions
"add": validate_3_rtype,
"addu": validate_3_rtype,
"and": validate_3_rtype,
"nor": validate_3_rtype,
"or": validate_3_rtype,
"sll": validate_2_itype,
"sllv": validate_3_rtype,
"slt": validate_3_rtype,
"sltu": validate_3_rtype,
"sra": validate_2_itype,
"srav": validate_3_rtype,
"srl": validate_2_itype,
"srlv": validate_3_rtype,
"sub": validate_3_rtype,
"subu": validate_3_rtype,
"xor": validate_3_rtype,
"div": validate_2_rtype,
"divu": validate_2_rtype,
"jalr": validate_jalr,
"mul": validate_2_rtype,
"mult": validate_2_rtype,
"madd": validate_2_rtype,
"maddu": validate_2_rtype,
"msub": validate_2_rtype,
"msubu": validate_2_rtype,
"move": validate_2_rtype,
"not": validate_2_rtype,
"teq": validate_2_rtype,
"tge": validate_2_rtype,
"tgeu": validate_2_rtype,
"tlt": validate_2_rtype,
"tltu": validate_2_rtype,
"tne": validate_2_rtype,
"jr": validate_1_rtype,
"mfhi": validate_1_rtype,
"mflo": validate_1_rtype,
"mthi": validate_1_rtype,
"mtlo": validate_1_rtype,
"syscall": validate_0_rtype,
"eret": validate_0_rtype,
"nop": validate_0_rtype,
# I Type instructions
"addi": validate_2_itype,
"addiu": validate_2_itype,
"andi": validate_2_itype,
"beq": validate_2_itype,
"bne": validate_2_itype,
"ori": validate_2_itype,
"slti": validate_2_itype,
"sltiu": validate_2_itype,
"xori": validate_2_itype,
"li": validate_1_itype,
"la": validate_optional_2_itype,
"bgezal": validate_1_itype,
"beqz": validate_1_itype,
"bgez": validate_1_itype,
"bgtz": validate_1_itype,
"blez": validate_1_itype,
"bltz": validate_1_itype,
"bnez": validate_1_itype,
"lui": validate_1_itype,
"tgei": validate_1_itype,
"teqi": validate_1_itype,
"tgeiu": validate_1_itype,
"tlti": validate_1_itype,
"tltiu": validate_1_itype,
"tnei": validate_1_itype,
"bge": validate_optional_2_itype,
"sw": validate_optional_2_itype,
"sc": validate_optional_2_itype,
"swl": validate_optional_2_itype,
"lw": validate_optional_2_itype,
"ll": validate_optional_2_itype,
"lb": validate_optional_2_itype,
"lbu": validate_optional_2_itype,
"lh": validate_optional_2_itype,
"lhu": validate_optional_2_itype,
"sb": validate_optional_2_itype,
"sh": validate_optional_2_itype,
# J-Type Instructions
"j": validate_jtype,
"jal": validate_jtype,
}
try:
func = switch[instruction.command]
res = func(instruction)
except KeyError:
res = True
print(f"Validation for {instruction.command} not implemented")
except:
res = False
return res
list_of_registers = (
"$zero",
"$v0",
"$v1",
"$a0",
"$a1",
"$a2",
"$a3",
"$t0",
"$t1",
"$t2",
"$t3",
"$t4",
"$t5",
"$t6",
"$t7",
"$s0",
"$s1",
"$s2",
"$s3",
"$s4",
"$s5",
"$s6",
"$s7",
"$t8",
"$t9",
"$sp",
"$ra",
)
def validate_jalr(inst):
return validate_1_rtype(inst) or validate_2_rtype(inst)
def validate_3_rtype(instruction) -> bool:
"""Validates R-Type instructions with 3 registers
Parameters
----------
instruction : R-Type
R-types with 3 registers
Returns
-------
bool
[Syntax correct or not]
"""
rd = instruction.destination_register
rs = instruction.source_register
rt = instruction.target_register
check1 = rd is not None
check2 = rs is not None
check3 = rt is not None
if (
rd.name in list_of_registers
and rs.name in list_of_registers
and rt.name in list_of_registers
):
return check1 and check2 and check3
return False
def validate_2_rtype(instruction) -> bool:
"""Validates R-Type instructions with 2 registers
Parameters
----------
instruction : R-Type
R-types with 2 registers
Returns
-------
bool
[Syntax correct or not]
"""
rd = instruction.destination_register
rs = instruction.source_register
rt = instruction.target_register
check1 = rd is not None
check2 = rs is not None
check3 = rt is None
if rd.name in list_of_registers and rs.name in list_of_registers:
return check1 and check2 and check3
return False
def validate_1_rtype(instruction) -> bool:
"""Validates R-Type instructions with 1 registers
Parameters
----------
instruction : R-Type
R-types with 1 registers
Returns
-------
bool
[Syntax correct or not]
"""
rd = instruction.destination_register
rs = instruction.source_register
rt = instruction.target_register
check1 = rd is not None
check2 = rs is None
check3 = rt is None
if rd.name in list_of_registers:
return check1 and check2 and check3
return False
def validate_0_rtype(instruction) -> bool:
"""Validates R-Type instructions with 0 registers
Parameters
----------
instruction : R-Type
R-types with 0 registers
Returns
-------
bool
[Syntax correct or not]
"""
rd = instruction.destination_register
rs = instruction.source_register
rt = instruction.target_register
check1 = rd is None
check2 = rs is None
check3 = rt is None
return check1 and check2 and check3
def validate_2_itype(instruction) -> bool:
"""Validates I-Type instructions with 2 registers
Parameters
----------
instruction : I-Type
I-types with 2 registers
Returns
-------
bool
[Syntax correct or not]
"""
destination = instruction.destination_register
source = instruction.source_register
immediate = instruction.immediate
check1 = destination is not None
check2 = source is not None
check3 = immediate is not None
if instruction.command in ("beq", "bne", "sll", "srl", "sra") and isinstance(
immediate._value, str
):
if destination.name in list_of_registers and source.name in list_of_registers:
return check1 and check2 and check3
elif (
destination.name in list_of_registers
and isinstance(immediate(), int)
and source.name in list_of_registers
):
return check1 and check2 and check3
return False
def validate_optional_2_itype(instruction) -> bool:
"""Validates I-Type instructions with optional 2 registers
Parameters
----------
instruction : I-Type
I-types with 2 optional registers
Returns
-------
bool
[Syntax correct or not]
"""
destination = instruction.destination_register
target = instruction.target_register
source = instruction.source_register
immediate = instruction.immediate
check1 = destination is not None
check2 = immediate is not None
check3 = target is None
if destination.name in list_of_registers:
if source is not None and source.name in list_of_registers:
return check1 and check2 and check3
elif source is None:
return check1 and check2 and check3
return False
def validate_1_itype(instruction) -> bool:
"""Validates I-Type instructions with 1 registers
Parameters
----------
instruction : I-Type
I-types with 1 registers
Returns
-------
bool
[Syntax correct or not]
"""
destination = instruction.destination_register
target = instruction.target_register
immediate = instruction.immediate
source = instruction.source_register
check1 = destination is not None
check2 = target is None
check3 = immediate is not None
check4 = source is None
if destination.name in list_of_registers:
return check1 and check2 and check3 and check4
return False
def validate_jtype(instruction) -> bool:
"""Validates J-Type instructions
Parameters
----------
instruction : J-Type
Returns
-------
bool
[Syntax correct or not]
"""
address = instruction.address
check = address is not None
return check
|
a = []
for i in range(100):
a.append(i)
if (n := len(a)) > 10:
print(f"List is too long ({n} elements, expected <= 10)") |
# model initial conditions
x = -1
y = 0
z = 0.5
t = 0
# model constants
_alpha = 0.3
gamma = 0.01
# gradients
palette_relaxing_red = [color(180, 15, 48), color(255, 251, 213)]
palette_shahabi = [color(104, 250, 0), color(166, 1, 116)]
palette_flare = [color(245, 174, 25), color(241, 40, 16)]
palette_rose_colored_lenses = [color(100, 112, 163), color(232, 203, 191)]
palette_mean_fruit = [color(247, 193, 158), color(219, 138, 222)]
theta = 0
running = True
points = []
frame_count = 0
scale_factor = 20.0
scale_factor_step = 0
initial_scale_factor = 20.0
final_scale_factor = 20.0
full_scale_time = 8.5 # in seconds
movie_length = 50 # in seconds
def setup():
global scale_factor_step
size(1200, 1200, P3D)
ellipseMode(RADIUS)
background(255)
smooth()
rescaling_frames = (movie_length - full_scale_time)*60
rescaling_fps_frequency = (rescaling_frames * final_scale_factor)/initial_scale_factor
scale_factor_step = 1/rescaling_fps_frequency
def eval_stroke_color(value,max_value,palette):
current_color = lerpColor(palette[1], palette[0], float(value)/max_value)
stroke(current_color)
#noFill()
fill(current_color)
def draw():
global x,y,z,t,points,theta,frame_count,scale_factor
strokeWeight(1)
background(255)
#camera positioning
camera(40,40,200,
0,0,0,
0.0,1.0,0.0)
# incremental resizing of the scene (fading)
if frame_count < 60*full_scale_time:
scale(initial_scale_factor)
else:
print("Scale factor: " + str(scale_factor))
print(scale_factor_step)
scale_factor -= scale_factor_step
scale(scale_factor)
# differential equations model
dt = 0.02
dx = (y * (z - 1 + x**2) + gamma * x)*dt
dy = (x * (3 * z + 1 - x**2) + gamma * y)*dt
dz = (-2 * z * (_alpha + x * y))*dt
# increment derivatives
x += dx
y += dy
z += dz
t += dt
p = PVector(x,y,z)
points.append(p)
theta+=0.05
rotateX(theta/5)
rotateY(theta/2)
#rotateZ(theta/3)
beginShape()
for p in points:
strokeWeight(max(p.z * 100, 1.0))
eval_stroke_color(p.z * 100,50,palette_flare)
vertex(p.x, p.y, p.z)
endShape()
saveFrame("movie_2/rab_fabri_####.png")
frame_count+=1
print(frame_count)
if frame_count >= movie_length*60:
noLoop()
def keyPressed():
global running
save("lorentz" + str(random(1000)) + ".png")
if running:
noLoop()
running = False
else:
loop()
running = True
print("Saved")
|
def get_bid(exchange, symbol, n=1):
return 0
def get_bid(exchange, symbol, n=1):
return 0
|
def build_tuple_type(*columns):
class Tuple(object):
__slots__ = columns
def __init__(self, d=None, **kw):
if d is None:
d = kw
for k in self.__slots__:
setattr(self, k, d.get(k))
def __getitem__(self, k):
if k in self.__slots__:
return getattr(self, k)
def __contains__(self, value):
return value in self.__slots__
def __eq__(self, value):
for k in self.__slots__:
if getattr(self, k) != value[k]:
return False
return True
def __ne__(self, value):
for k in self.__slots__:
if getattr(self, k) != value[k]:
return True
return False
def __repr__(self):
d = self.asdict()
return 'WCF ' + d.__repr__()
def __hash__(self):
return hash(tuple(self.values()))
def get(self, k, default=None):
if k in self.__slots__:
try:
return getattr(self, k)
except AttributeError:
return default
def keys(self):
return self.__slots__
def items(self):
result = []
for k in self.__slots__:
result.append((k, getattr(self, k)))
return result
def values(self):
result = []
for k in self.__slots__:
result.append(getattr(self, k))
return result
def select(self, keys):
result = {}
for k in keys:
if k in self.__slots__:
result[k] = getattr(self, k)
return result
def asdict(self):
result = {}
for k in self.__slots__:
result[k] = getattr(self, k)
return result
return Tuple
|
# ------------------------------------------------------------------------------
# Site Configuration File
# ------------------------------------------------------------------------------
theme = "carbon"
title = "Holly Demo"
tagline = "A blog-engine plugin for Ivy."
extensions = ["holly"]
holly = {
"homepage": {
"root_urls": ["@root/blog//", "@root/animalia//"],
},
"roots": [
{
"root_url": "@root/blog//",
},
{
"root_url": "@root/animalia//",
},
],
}
|
def Prime_number(n):
a = []
for i in range(2,n+1):
e1 = n % i
if e1 == 0:
b.append(e1)
if len(a) > 1:
print('FALSE')
print('This is not a prime number!')
elif len(a) == 1:
print('TRUE')
print('This is a Prime number!')
Prime_number(int(input('Please give your number: '))) |
class Platform:
def __init__(self, designer, debug):
self.designer = designer
self.debug = debug
def generate_wrappers(self):
raise Exception("Method not implemented")
def create_mem(self, mem_type, name, data_type, size, init):
raise Exception("Method not implemented")
def create_mem_from(self, mem_type, memory):
return self.create_mem(mem_type, memory.name, memory.data_type, memory.size, memory.init)
def create_fifo(self):
raise Exception("Method not implemented")
def add_intrinsic(self, designer, intrinsic):
raise Exception("Method not implemented")
def get_keys(self):
return {}
|
# Here I've implemented a method of finding square root of imperfect square
# Steps (Pseudocode): visit http://burningmath.blogspot.in/2013/12/finding-square-roots-of-numbers-that.html
# Read the steps carefully or you'll not understand the program!
# To check is number is a perfect square or not
def is_perfect_square(n):
if isinstance(n, float):
return (False, None)
for i in range(n + 1):
if i * i == n:
return (True, i)
return (False, None)
# Average
def average(*args):
hold = list(args)
return sum(hold) / len(hold)
# Method
# Just implementation of steps on above webpage
def sqrt_of_imperfect_square(a, certainty=6):
is_square = is_perfect_square(a)
if is_square[0]:
return "{} is a perfect square .It's root is {}.".format(a, is_square[1])
else:
a = int(a)
tmp = None
s1 = max([float(x * x) for x in range(0, a)])
while True:
s2 = a / s1
tmp = average(s1, s2)
if not (round(tmp * tmp, certainty) == float(a)):
s1 = tmp
continue
else:
return tmp
return -1 # This condition will normally never occur
# Test
case = 2613
res = sqrt_of_imperfect_square(case, 9)
print("Test case: " + str(case))
print("Root: " + str(res))
print("Root Squared: " + str(res * res))
|
"""Constants that define units"""
AUTO = 'auto'
METRIC = 'metric'
US = 'us'
UK = 'uk'
CA = 'ca'
|
usuario = input("Informe o nome de usuario: ")
senha = input("Informe a senha: ")
while usuario == senha:
print("Usuario deve ser diferente da senha!\n")
senha = input("Informe uma nova senha: ")
else:
print("Dados confirmados") |
# Criei uma função para receber o parâmetro e validá-lo ao mesmo tempo
def testeCodigoValido():
while True:
codigoProdutos = int(input('Digite o código do produto entre 10000 e 30000:'))
# Se o código for menor que 10000 e maior que 30000 ele retorna: código invalido
# e faz o usuário digitar novamente
if(codigoProdutos < 10000):
print('[CODIGO INVALIDO] Tente de novo! ')
continue
if(codigoProdutos > 30000):
print('[CODIGO INVALIDO] Tente de novo!')
continue
else:
# Se for dentro do intervalo o número é retornado
return codigoProdutos
# Depois de validar o número, eu converti em uma string
# E atribui a string em uma lista
numeroValido = str(testeCodigoValido())
listaDeCodigo = [numeroValido]
# Com o número em formato de lista comecei a fazer os cálculos e armazenar em funções
def soma1():
# Seleciono o número específico dentro da lista, faço o cálculo e retorno o resultado
n1 = int(listaDeCodigo[0][0])
resultado = n1 * 2
return resultado
def soma2():
n1 = int(listaDeCodigo[0][1])
resultado = n1 * 3
return resultado
def soma3():
n1 = int(listaDeCodigo[0][2])
resultado = n1 * 4
return resultado
def soma4():
n1 = int(listaDeCodigo[0][3])
resultado = n1 * 5
return resultado
def soma5():
n1 = int(listaDeCodigo[0][4])
resultado = n1 * 6
return resultado
# Função para pegar o resultado da divisão de todos os números
def resultado():
somaTodos = soma1() + soma2() + soma3() + soma4() + soma5()
resultadoDivisao = somaTodos % 7
return resultadoDivisao
# E retornei o resultado em uma string
resultadoString = str(resultado())
# Imprimindo na tela
print('{}-{}'.format(numeroValido, resultadoString))
|
print()
n = 0
tot = 0
soma = 0
media = 0
maior = 0
menor = 0
opc = ''
while (opc != 'N'):
n = int(input('Informe um número: '))
tot += 1
soma += n
if(n > maior):
maior = n
else:
menor = n
opc = str(input('Deseja continuar: [S/N]: ')).upper()
print()
media = soma / tot
print('O maior número digitado foi {} e o menor foi {}. A média dos números é igual a {}.'.format(maior, menor, media))
print() |
"""
This is a simple binary search algorithm for python.
This is the exact implementation of the pseudocode written in README.
"""
def binary_search(item_list,item):
left_index = 0
right_index = len(item_list)-1
while left_index <= right_index:
middle_index = (left_index+right_index) // 2
if item_list[middle_index] < item:
left_index=middle_index+1
elif item_list[middle_index] > item:
right_index=middle_index-1
else:
return middle_index
return None
#Simple demonstration of the function
if __name__=='__main__':
print (binary_search([1,3,5,7],3))
print (binary_search([1,2,5,7,97],0))
|
# Dependency Inversion Principle (SOLID)
# https://www.geeksforgeeks.org/dependecy-inversion-principle-solid/
# SGVP391900 | 12:03 7Mar19
# Mootto - Any higher classes should always depend upon the abstraction of the class
# rather than the detail.
class Employee(object):
def Work():
pass
class Manager():
def __init__(self):
self.employees=[]
def addEmployee(self,a):
self.employees.append(a)
# self.developers=[]
# self.designers=[]
# self.testers=[]
# def addDeveloper(self, dev):
# self.developers.append(dev)
# def addDesigners(self, design):
# self.designers.append(design)
# def addTesters(self, testers):
# self.testers.append(testers)
class Developer(Employee):
def __init__(self):
print ("developer added")
def Work():
print ("truning coffee into code")
class Designer(Employee):
def __init__(self):
print ("designer added")
def Work():
print ("turning lines to wireframes")
class Testers(object):
def __init__(self):
print ("tester added")
def Work():
print ("testing everything out there")
if __name__ == "__main__":
a=Manager()
# a.addDeveloper(Developer())
# a.addDesigners(Designer())
a.addEmployee(Developer())
a.addEmployee(Designer()) |
# desafio050 Soma dos Pares For
#Desenvolva um progama que leia 6 números inteiros e mostre a soma apenas daqueles que forem pares. se o
# valor for impar, desconsidere-o.
acumulador = cont = 0
for c in range(1, 7):
valor = int(input("Digite o {} número:".format(c)))
if valor % 2 == 0:
acumulador = acumulador + valor
cont = cont + 1
print('Você informou {} números pares e a soma entre eles é {}'.format(cont, acumulador))
|
def asarray(a, dtype=None, order=None):
"""Convert the input to an array.
Parameters
----------
a : array_like
Input data, in any form that can be converted to an array. This
includes lists, lists of tuples, tuples, tuples of tuples, tuples
of lists and ndarrays.
dtype : data-type, optional
By default, the data-type is inferred from the input data.
order : {'C', 'F'}, optional
Whether to use row-major (C-style) or
column-major (Fortran-style) memory representation.
Defaults to 'C'.
Returns
-------
out : ndarray
Array interpretation of `a`. No copy is performed if the input
is already an ndarray with matching dtype and order. If `a` is a
subclass of ndarray, a base class ndarray is returned.
"""
return array(a, dtype, copy=False, order=order)
asarray(10) |
[b'z' if foldnuls and not word else
b'y' if foldspaces and word == 0x20202020 else
(chars2[word // 614125] +
chars2[word // 85 % 7225] +
chars[word % 85])
]
|
inputs = {"sentence": "a very well-made, funny and entertaining picture."}
archive = (
"https://storage.googleapis.com/allennlp-public-models/"
"basic_stanford_sentiment_treebank-2020.06.09.tar.gz"
)
predictor = Predictor.from_path(archive)
interpreter = SimpleGradient(predictor)
interpretation = interpreter.saliency_interpret_from_json(inputs)
print(interpretation)
|
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 6 15:17:07 2019
@author: bdobson
"""
"""Constants
"""
M3_S_TO_ML_D = 86.4
MM_KM2_TO_ML = 1e-3 * 1e6 * 1e3 * 1e-6
PCT_TO_PROP = 1e-2
PROP_TO_PCT = 100
L_TO_ML = 1e-6
FLOAT_ACCURACY = 1e-10 |
# File: adldap_view.py
#
# Copyright (c) 2021-2022 Splunk Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software distributed under
# the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
# either express or implied. See the License for the specific language governing permissions
# and limitations under the License.
def get_ctx_result(result):
ctx_result = {}
param = result.get_param()
summary = result.get_summary()
data = result.get_data()
ctx_result['param'] = param
if (data):
ctx_result['data'] = data[0]
if (summary):
ctx_result['summary'] = summary
return ctx_result
def display_attributes(provides, all_app_runs, context):
context['results'] = results = []
context['attributes'] = []
print("DEBUG all_app_runs = {}".format(all_app_runs))
for summary, action_results in all_app_runs:
for result in action_results:
ctx_result = get_ctx_result(result)
if (not ctx_result):
continue
results.append(ctx_result)
print("DEBUG ctx_result = {}".format(ctx_result))
# populate keys into 'attributes' variable for django template
try:
for n in list(ctx_result['data']['entries'][0]['attributes'].keys()):
if n not in context['attributes']:
context['attributes'].append(n)
except Exception as e:
context['attributes'] = False
context['error'] = str(e)
return 'display_attributes.html'
|
while True:
try:
p = input()
d = 0
for i in range(len(p)):
if(p[i]=='('):
d += 1
elif(p[i]==')'):
d -= 1
if(d < 0):
break
if(d != 0):
print('incorrect')
else:
print('correct')
except EOFError:
break |
f = open('69_sample.txt')
# read 1st line
data = f.readline()
print (data)
# read second line
data = f.readline()
print (data)
f.close()
|
class Node(object):
def __init__(self, val, children):
self.val = val
self.children = children
class Solution(object):
def trace(self, node, nodelist):
if node is None:
return
for n in node.children:
self.trace(n, nodelist)
nodelist.append(node.val)
def postorder(self, root):
"""
:type root: Node
:rtype: List[int]
"""
nodelist = []
self.trace(root, nodelist)
return nodelist
if __name__ == '__main__':
solution = Solution()
root = Node(1, [])
root.children.append(Node(3, []))
root.children.append(Node(2, []))
root.children.append(Node(4, []))
print(solution.postorder(root))
else:
pass
|
bot = {'owner': '',
'client_id': '',
'version': '',
'prefix': '|',
'pstart': 'python3 ./main.py',
'game': '',
'token': '',
'invite_url': '',
'update_name': '',
'release_details': './data/misc/releaseplaceholder.txt',
'checkin_details': './data/misc/checkin.txt',
'checkin_channel': '',
'update_details': './data/misc/update.txt',
'startup_time': '',
'pstart_time': '',
'imgur_client_id': '',
'imgur_client_secret': ''}
|
"""
Module to contain the configuration information loaded from the config file.
DO NOT MODIFY THIS FILE!
Use yaml files in configurations directory to change the settings.
"""
# Optional settings (set defaults)
show_labels = False
show_sensory = False
show_individual = False
display_legend = True
combination_strategy = "avg"
confidence_threshold = 0
light_multiplier = 1
wind_multiplier = 1
polarisation_multiplier = 1
# Defined flags, makes tracking cue definitions easier
polarisation_defined = False
# Cue configuration lists
cues_roll_one = []
cues_roll_two = []
def print_configuration():
print("=== Optional configuration ===\n"
"show-labels: " + str(show_labels) + "\n"
"show-geometry: " + str(show_sensory) + "\n"
"show-individual: " + str(show_individual) + "\n"
"display-legend: " + str(display_legend) + "\n"
"combination-strategy: " + combination_strategy + "\n"
"confidence-threshold: " + str(confidence_threshold) + "\n"
"light-multiplier: " + str(light_multiplier) + "\n"
"wind-multiplier: " + str(wind_multiplier) + "\n"
"polarisation-multiplier: " + str(polarisation_multiplier) + "\n"
"===============================\n")
|
"""
This module provide solution for first task.
"""
def change_sub_strings(text, pattern, new_string):
"""
Function for changing all entrance of pattern to new_string.
:param text: str
String for changing.
:param pattern: str
String which should be removed. Any suffix of this string shouldn't be
equal to prefix of same length.
:param new_string: str
String which should be added.
:return:
String with changed pattern to new_string.
"""
if not isinstance(text, str) or not isinstance(pattern, str) or \
not isinstance(new_string, str):
assert TypeError
for i in range(1, len(pattern)):
if pattern[:i] == pattern[-i:]:
raise ValueError
return new_string.join(text.split(pattern))
def change_sentences(lines):
"""
Function for set all letters to lower case, changing all 'snake' to
'python' and filtering all sentence where no 'python' or 'anaconda'
:param lines: list with str
List of sentences for processing.
:return:
List of sentences with 'python' and 'anaconda'.
"""
if not isinstance(lines, list):
raise TypeError
result = []
for line in lines:
if not isinstance(line, str):
raise TypeError
line = change_sub_strings(line.lower(), 'snake', 'python')
if 'python' in line and 'anaconda' in line:
result.append(line)
return result
def solution1(input_file_name, output_file_name):
"""
Function for solving first task.
:param input_file_name: str
Name of file for processing.
:param output_file_name: str
Name of file for writing result.
:return:
Text with changed substrings.
"""
if not isinstance(input_file_name, str) or \
not isinstance(output_file_name, str):
raise TypeError
try:
with open(input_file_name, 'r') as f_in:
with open(output_file_name, 'w') as f_out:
f_out.writelines(change_sentences(f_in.readlines()))
except FileNotFoundError:
print("can't open file in first solution")
|
ENTRY_POINT = 'fizz_buzz'
FIX = """
Update doc string to remove requirement for print.
"""
#[PROMPT]
def fizz_buzz(n: int):
"""Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13.
>>> fizz_buzz(50)
0
>>> fizz_buzz(78)
2
>>> fizz_buzz(79)
3
"""
#[SOLUTION]
ns = []
for i in range(n):
if i % 11 == 0 or i % 13 == 0:
ns.append(i)
s = ''.join(list(map(str, ns)))
ans = 0
for c in s:
ans += (c == '7')
return ans
#[CHECK]
METADATA = {}
def check(candidate):
assert candidate(50) == 0
assert candidate(78) == 2
assert candidate(79) == 3
assert candidate(100) == 3
assert candidate(200) == 6
assert candidate(4000) == 192
assert candidate(10000) == 639
assert candidate(100000) == 8026
|
""" constants """
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
PATH_RASPICAM = "/raspicam_node/image/compressed"
PATH_USBCAM = "/usb_cam/image_raw/compressed"
PATH_LIDAR = "/scan"
PATH_ASSETS = "../assets/"
PATH_GALAPAGOS_STATE = "/galapagos_state"
# SELECTED_STATE = "" # ! deprecated
MAX_SPEED = 0.22
TURNING_SPEED = 0.13
TUNNEL_SPEED = 0.22
SPEED_VALUES = {
'fast': 1,
'little': 0.6,
'normal': 0.6,
# 'normal': 0.4, # For slow speed
'slow': 0.3,
'slower': 0.2,
'stop': 0,
'back': -1
}
BUF_SIZE = 3
# RUN_MODE = 'debug' # ! Deprecated
RUN_MODE = 'nono'
RUN_TYPE = '' # ! Deprecated
#############################################################
ARRAY_K = [[480.0, 0, 320.0],
[0.0, 320.0, 230.0],
[0.0, 0.0, 1.0]]
# [ [클수록 아래볼록 작을수록 위볼록] , [+ :오른쪽치우침, - :왼쪽치우침] , ]
ARRAY_D = [0.0, 0.0, 0.0, 0.0]
#### modified by minsoo -190810 ##############################
REF_IMAGE_PATH = {
"parking": "parking.jpg",
"left": "left.png",
"right": "right.png",
"three": "T_2.png",
"construction": "construction.jpg",
"tunnel": "tunnel.png"
}
# # threshold values
# THRESHOLD_PARKING = 26
# # threshold values
# THRESHOLD_LEFT_RIGHT_MIN = 8
# # threshold values
# THRESHOLD_LEFT_RIGHT_MAX = 17
# # threshold values
# THRESHOLD_INTERSECTION = 15
DEFAULT_LIDAR_DEGREE = 4
# NOTE: New Contstantsw
THRESHOLDS = {
"parking": 26,
"left_right_min": 8,
"left_right_max": 17,
"intersection": 8,
"tunnel": 10,
"construction": 25
}
LIDAR_DIRECTIONS = {
'front': 0,
'left_biased': 10,
'frontleft': 45,
'leftside': 50,
'left': 90,
'back': 180,
'right': 270,
'frontright': 315,
'right_biased': 350
}
|
def type2diabetes(filepath):
"""
1. Takes a text file as the only parameter and returns means and std of the phenotype typeII diabetes
2. Search for data labels on the text file and read text file to csv file starting from the
rows of labels present
3. Replace missing data '--' with NaN and drop missing data
4. Looking for all 17 snps (we have in our data bank) in the uploaded file
5. Recreate a list of 8 pairs of snp information: rsid and corresponding genotype
6. Obtain effect values for each snp and sum up to get a polygenic risk score
7. Based on the polygenic risk score, return a mean and std of the bmi phenotype
"""
fopen = open(filepath,mode='r+')
fread = fopen.readlines()
x = '# rsid chromosome position genotype'
n = 0
for line in fread:
n += 1
if x in line:
break
df = pd.read_csv (filepath,'\s+', skiprows=n, names=['rsid','chromosome','position','genotype'])
#df = df.replace('--', pd.NaT) # need to correct this on the data extract file
#df = df.dropna
testfile = df[(df['rsid'] == 'rs560887') |
(df['rsid'] =='rs10830963') |
(df['rsid'] == 'rs14607517')|
(df['rsid'] == 'rs2191349') |
(df['rsid'] == 'rs780094') |
(df['rsid'] == 'rs11708067') |
(df['rsid'] == 'rs7944584') |
(df['rsid'] == 'rs10885122') |
(df['rsid'] == 'rs174550') |
(df['rsid'] == 'rs11605924') |
(df['rsid'] == 'rs11920090') |
(df['rsid'] == 'rs7034200') |
(df['rsid'] == 'rs340874') |
(df['rsid'] == 'rs11071657') |
(df['rsid'] == 'rs13266634') |
(df['rsid'] == 'rs7903146') |
(df['rsid'] == 'rs35767')]
testlist = []
for i in range(0, len(testfile.index)-1):
rsid = testfile.iloc[i,0]
genotype = testfile.iloc[i,3]
i = (rsid, genotype) # tuples of one rsid with genotype
testlist.append(i) # a list of tuples
gendata = pd.read_csv('Genetic Data.csv')
gendata['effect'] = pd.to_numeric(gendata['effect'])
total = 0
for i in testlist:
snp = gendata[(gendata['rsid'] == i[0]) & (gendata['genotype'] == i[1])]
effect = snp.iloc[i,4]
total += effect
if total < 13:
return (92.5, 8.7)
elif total == 13:
return (93.6, 8.8)
elif total == 14:
return (94.2, 8.6)
elif total == 15:
return (94.3, 8.8)
elif total == 16:
return (95.2, 8.9)
elif total == 17:
return (95.4, 8.7)
elif total == 18:
return (95.9, 8.9)
elif total == 19:
return (96.5, 8.7)
elif total == 20:
return (97.3, 8.8)
elif total == 21:
return (98.1, 8.6)
elif total == 22:
return (98.6, 8.7)
else:
return (98.6, 8.6)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jul 12 10:49:34 2020
@author: ravi
"""
def recordBreaker(arr):
peak = 0
cmax = float("-inf")
if len(arr)==0:
return 0
if len(arr)==1:
return 1
for i in range(len(arr)):
if i==0:
if arr[i]>arr[i+1]:
if arr[i]>cmax:
cmax=arr[i]
peak+=1
if i>0 and i<len(arr)-1:
if arr[i]>arr[i-1] and arr[i]>arr[i+1]:
if arr[i]>cmax:
cmax = arr[i]
peak+=1
if i==len(arr)-1:
if arr[i]>arr[i-1]:
if arr[i]>cmax:
cmax = arr[i]
peak+=1
return peak
t = int(input())
for i in range(t):
n = int(input())
arr = list(map(int,input().split()))
ans = recordBreaker(arr)
print("Case #"+str(i+1)+":",str(ans)) |
N = int(input())
for i in range(N):
line = input()
print("I am Toorg!") |
def divide(n1, n2):#dessa forma levantamos o erro sem parar o cod
if n2 == 0:#se n2 for igual a zero
raise ValueError("n2 nao pode ser 0 ")
return n1 / n2
try:
print(divide(n1=2,n2=1))
except ValueError as error:
print('Voce esta tentando dividir por zero')
print('log:', error) |
# 566. Reshape the Matrix
# Runtime: 109 ms, faster than 30.83% of Python3 online submissions for Reshape the Matrix.
# Memory Usage: 14.7 MB, less than 87.88% of Python3 online submissions for Reshape the Matrix.
class Solution:
# Using Queue
def matrixReshape(self, mat: list[list[int]], r: int, c: int) -> list[list[int]]:
if len(mat) == 0 or r * c != len(mat) * len(mat[0]):
return mat
nums = []
for i in range(len(mat)):
for j in range(len(mat[0])):
nums.append(mat[i][j])
res = [[0 for _ in range(c)] for _ in range(r)]
for i in range(r):
for j in range(c):
res[i][j] = nums.pop(0)
return res |
def is_odd(n):
return n%2 == 1
def is_even(n):
return n%2 == 0
print('------------- Filter --------------')
lst_a = list(range(10))
print(lst_a)
lst_c = filter(is_odd,lst_a)
print(lst_c)
# filter返回的迭代器对象只能迭代一次
print("iteraction 1:")
for elem in lst_c:
print(elem, end=" ")
print()
print("iteraction 2:")
for elem in lst_c:
print(elem, end=" ")
print()
lst_c = filter(is_even,lst_a)
print(list(lst_c))
|
def n_primos (x):
numero =2
quantidadeDePrimos=0
while numero<=x:
divisor = 2
divisores=0
while divisor<numero:
if numero%divisor==0:
divisores+=1
divisor+=1
if divisores==0:
quantidadeDePrimos+=1
numero+=1
return quantidadeDePrimos |
#Now let's make things a little more challenging.
#
#Last exercise, you wrote a function called word_count that
#counted the number of words in a string essentially by
#counting the spaces. However, if there were multiple spaces
#in a row, it would incorrectly add additional words. For
#example, it would have counted the string "Hi David" as
#4 words instead of 2 because there are two additional
#spaces.
#
#Revise your word_count method so that if it encounters
#multiple consecutive spaces, it does *not* count an
#additional word. For example, these three strings should
#all be counted as having two words:
#
# "Hi David"
# "Hi David"
# "Hi David"
#
#Other than ignoring consecutive spaces, the directions are
#the same: write a function called word_count that returns an
#integer representing the number of words in the string, or
#return "Not a string" if the input isn't a string. You may
#assume that if the input is a string, it starts with a
#letter word instead of a space.
#Write your function here!
def word_count(my_string):
word_count = 1
try:
string_len = len(my_string)
i = 0
while string_len > 0:
try:
if my_string[i] == " " and not my_string[i+1] == " ":
word_count += 1
i += 1
string_len -= 1
except IndexError:
pass
return word_count
except TypeError:
return "Not a string"
#Below are some lines of code that will test your function.
#You can change the value of the variable(s) to test your
#function with different inputs.
#
#If your function works correctly, this will originally
#print:
#Word Count: 4
#Word Count: 2
#Word Count: Not a string
#Word Count: Not a string
#Word Count: Not a string
print("Word Count:", word_count("Four words are here!"))
print("Word Count:", word_count("Hi David"))
print("Word Count:", word_count(5))
print("Word Count:", word_count(5.1))
print("Word Count:", word_count(True))
|
def sortByHeight(a):
trees = []
peoples = []
for i in range(len(a)):
if (a[i] != -1):
peoples.append(a[i])
else:
trees.append(i)
peoples = sorted(peoples)
for i in range(len(trees)):
peoples.insert(trees[i], -1)
return peoples |
class Helper(object):
defaultText = """Eddie knowledge - what your opponents don't want you to know.\n\nCommands:
.help
.changes
.fd <CHAR> [<MOVENAME>]
.fds <CHAR> [<MOVENAME>]
.atklevel <LEVEL>
.alias <ALIAS>
.addalias <ALIAS> | <VALUE>
.removealias <ALIAS>
.charnames\n
If you want to know more about a command, you can invoke its specific help by calling .help [command].
Example: .help fd\n
For feature requests or bug reports etc., hit me up on Discord (prk`#1874)."""
helpText = """Displays information about public commands of Eddie."""
changesText = """Sends a link to changelog."""
fdText = """Displays framedata of a specific move. Character names are:
Axl
Bedman
Chipp
Elphelt
Faust
I-No
Ky
May
Millia
Potemkin
Ramlethal
Sin
Slayer
Sol
Sol-DI
Venom
Zato
Leo
Jack-O
Jam
Johnny
Raven
Kum
Dizzy
Answer
Baiken
Normals or command normals are written in the standard way of numpad directions and P/K/S/H/D for the button used.
Special moves are named with their actual names. Some of the names are rather weird. In order to deal with that, the command will first search for a perfect fit. If that has not been found, it will search for moves which can be written in the following form:
% MOVENAME %
meaning that movename can start with anything and end with anything, as long as MOVENAME is present in the string. In case more moves are found (e.g. Leo has two versions of Graviert Wuerde), all are displayed.
In case no MOVENAME is specified, Eddie sends a private message containing all the possible moves that a character has stored in the database.
In case 3 or more moves are found which correspond to MOVENAME, all of them are sent in direct message to prevent cluttering of chat."""
fdsText = """Displays framedata of a specific move in a simplified manner. Character names are the same as when using the .fd command. Only displays startup, active frames, recovery frames, adv/ib adv and attack level.
Special moves are named with their actual names. Some of the names are rather weird. In order to deal with that, the command will first search for a perfect fit. If that has not been found, it will search for moves which can be written in the following form:
% MOVENAME %
meaning that movename can start with anything and end with anything, as long as MOVENAME is present in the string. In case more moves are found (e.g. Leo has two versions of Graviert Wuerde), all are displayed.
In case no MOVENAME is specified, Eddie sends a private message containing all the possible moves that a character has stored in the database.
In case 3 or more moves are found which correspond to MOVENAME, all of them are sent in direct message to prevent cluttering of chat."""
atklevelText = """Displays data of an attack level."""
aliasText = """Displays value of an alias."""
addaliasText = """Adds alias which can be used to search for moves. Example:
.addalias nobiru | anti air attack
If an alias already exists, it will not be overwritten."""
aliasesText = """Sends a list of existing aliases as a PM."""
removealiasText = """Removes a specified alias from the DB. Currently usable only by admin."""
charnamesText = """Sends a PM with a list of character names in the DB."""
helpTable = dict()
helpTable['default'] = defaultText
helpTable['help'] = helpText
helpTable['changes'] = changesText
helpTable['fd'] = fdText
helpTable['fds'] = fdsText
helpTable['atklevel'] = atklevelText
helpTable['alias'] = aliasText
helpTable['addalias'] = addaliasText
helpTable['aliases'] = aliasesText
helpTable['removealias'] = removealiasText
helpTable['charnames'] = charnamesText
def getHelptext(self, *kw):
if len(kw) == 0:
return self.helpTable.get('default')
return self.helpTable.get(kw[0])
|
nome = str(input('qual o seu nome '))
print('Prazer em te conhecer {:-^20}! \n'.format(nome))
n = int(input(' Bem vindo a Tabuada, digite um numero para ver o resultado: '))
multiplicando = 0
cont = 0
while cont <= 10:
print(n * multiplicando)
multiplicando = multiplicando + 1
cont = cont + 1
|
"""
@FileName: __init__.py.py
@Description: Implement __init__.py
@Author: Ryuk
@CreateDate: 2021/06/27
@LastEditTime: 2021/06/27
@LastEditors: Please set LastEditors
@Version: v0.1
""" |
__all__ = ["RefMixin"]
class RefMixin:
def __init__(self, loop, ref=True):
self.loop = loop
self.ref = ref
self._ref_increased = False
def _increase_ref(self):
if self.ref:
self._ref_increased = True
self.loop.increase_ref()
def _decrease_ref(self):
if self._ref_increased:
self._ref_increased = False
self.loop.decrease_ref()
def __del__(self):
self._decrease_ref()
|
#!/usr/bin/env python3
max_seat = 0
with open('input.txt') as infile:
for line in infile:
row = 0
col = 0
for c in line:
if c == 'B':
row = 2*row + 1
if c == 'F':
row *= 2
if c == 'R':
col = 2*col + 1
if c == 'L':
col *= 2
seat_id = row * 8 + col
max_seat = max(max_seat, seat_id)
print(max_seat) |
# -*- coding: utf-8 -*-
"""
@contact: lishulong.never@gmail.com
@time: 2018/3/25 上午11:07
""" |
class Solution:
def closedIsland(self, grid: List[List[int]]) -> int:
m = len(grid)
n = len(grid[0])
vis = [[0]*n for i in range(m)]
res = 0
def bfs(i,j):
vis[i][j] = 1
q = [(i,j)]
valid = 1
while len(q)> 0 :
r,c = q.pop(0)
if r == 0 or r == m-1 or c == 0 or c == n-1 :
valid = 0
dire = [(1,0),(0,-1),(0,1),(-1,0)]
for dx,dy in dire:
x = r + dx
y = c+ dy
if 0<=x<m and 0<=y<n and grid[x][y] == 0 and not vis[x][y] :
vis[x][y] = 1
q.append((x,y))
return valid
for i in range(m):
for j in range(n):
if not vis[i][j] and grid[i][j] == 0 :
if bfs(i,j):
res += 1
return res
|
'''
Escreva um programa que leia um número N inteiro qualquer e mostre na tela os N primeiros elementos de uma Sequência de Fibonacci.
Ex: 0 - 1 - 1 - 2 - 3 - 5 - 8
'''
print('-='*20)
print('Sequencia de Fibonacci')
print('-='*20)
n = int(input('Quantos Termos Voce quer Mostrar: '))
t1 = 0
t2 = 1
print('~'*40)
print('{} > {} > '.format(t1,t2),end='')
cont = 3
while cont <= n:
t3 = t1+t2
print(' {} > '.format(t3),end='')
cont += 1
t1 = t2
t2 = t3
print(' FIM ')
|
UK = "curb accessorise accessorised accessorises accessorising acclimatisation acclimatise acclimatised acclimatises acclimatising accoutrements aeon aeons aerogramme aerogrammes aeroplane aeroplanes aesthete aesthetes aesthetic aesthetically aesthetics aetiology ageing aggrandisement agonise agonised agonises agonising agonisingly almanack almanacks aluminium amortisable amortisation amortisations amortise amortised amortises amortising amphitheatre amphitheatres anaemia anaemic anaesthesia anaesthetic anaesthetics anaesthetise anaesthetised anaesthetises anaesthetising anaesthetist anaesthetists anaesthetize anaesthetized anaesthetizes anaesthetizing analogue analogues analyse analysed analyses analysing anglicise anglicised anglicises anglicising annualised antagonise antagonised antagonises antagonising apologise apologised apologises apologising appal appals appetiser appetisers appetising appetisingly arbour arbours archaeological archaeologically archaeologist archaeologists archaeology ardour armour armoured armourer armourers armouries armoury artefact artefacts authorise authorised authorises authorising axe backpedalled backpedalling bannister bannisters baptise baptised baptises baptising bastardise bastardised bastardises bastardising battleaxe baulk baulked baulking baulks bedevilled bedevilling behaviour behavioural behaviourism behaviourist behaviourists behaviours behove behoved behoves bejewelled belabour belaboured belabouring belabours bevelled bevvies bevvy biassed biassing bingeing bougainvillaea bougainvillaeas bowdlerise bowdlerised bowdlerises bowdlerising breathalyse breathalysed breathalyser breathalysers breathalyses breathalysing brutalise brutalised brutalises brutalising buses busing caesarean caesareans calibre calibres calliper callipers callisthenics canalise canalised canalises canalising cancellation cancellations cancelled cancelling candour cannibalise cannibalised cannibalises cannibalising canonise canonised canonises canonising capitalise capitalised capitalises capitalising caramelise caramelised caramelises caramelising carbonise carbonised carbonises carbonising carolled carolling catalogue catalogued catalogues cataloguing catalyse catalysed catalyses catalysing categorise categorised categorises categorising cauterise cauterised cauterises cauterising cavilled cavilling centigramme centigrammes centilitre centilitres centimetre centimetres centralise centralised centralises centralising centre centred centrefold centrefolds centrepiece centrepieces centres channelled channelling characterise characterised characterises characterising cheque chequebook chequebooks chequered cheques chilli chimaera chimaeras chiselled chiselling circularise circularised circularises circularising civilise civilised civilises civilising clamour clamoured clamouring clamours clangour clarinettist clarinettists collectivise collectivised collectivises collectivising colonisation colonise colonised coloniser colonisers colonises colonising colour colourant colourants coloured coloureds colourful colourfully colouring colourize colourized colourizes colourizing colourless colours commercialise commercialised commercialises commercialising compartmentalise compartmentalised compartmentalises compartmentalising computerise computerised computerises computerising conceptualise conceptualised conceptualises conceptualising connexion connexions contextualise contextualised contextualises contextualising cosier cosies cosiest cosily cosiness cosy councillor councillors counselled counselling counsellor counsellors crenellated criminalise criminalised criminalises criminalising criticise criticised criticises criticising crueller cruellest crystallisation crystallise crystallised crystallises crystallising cudgelled cudgelling customise customised customises customising cypher cyphers decentralisation decentralise decentralised decentralises decentralising decriminalisation decriminalise decriminalised decriminalises decriminalising defence defenceless defences dehumanisation dehumanise dehumanised dehumanises dehumanising demeanour demilitarisation demilitarise demilitarised demilitarises demilitarising demobilisation demobilise demobilised demobilises demobilising democratisation democratise democratised democratises democratising demonise demonised demonises demonising demoralisation demoralise demoralised demoralises demoralising denationalisation denationalise denationalised denationalises denationalising deodorise deodorised deodorises deodorising depersonalise depersonalised depersonalises depersonalising deputise deputised deputises deputising desensitisation desensitise desensitised desensitises desensitising destabilisation destabilise destabilised destabilises destabilising dialled dialling dialogue dialogues diarrhoea digitise digitised digitises digitising disc discolour discoloured discolouring discolours discs disembowelled disembowelling disfavour dishevelled dishonour dishonourable dishonourably dishonoured dishonouring dishonours disorganisation disorganised distil distils dramatisation dramatisations dramatise dramatised dramatises dramatising draught draughtboard draughtboards draughtier draughtiest draughts draughtsman draughtsmanship draughtsmen draughtswoman draughtswomen draughty drivelled drivelling duelled duelling economise economised economises economising edoema editorialise editorialised editorialises editorialising empathise empathised empathises empathising emphasise emphasised emphasises emphasising enamelled enamelling enamoured encyclopaedia encyclopaedias encyclopaedic endeavour endeavoured endeavouring endeavours energise energised energises energising enrol enrols enthral enthrals epaulette epaulettes epicentre epicentres epilogue epilogues epitomise epitomised epitomises epitomising equalisation equalise equalised equaliser equalisers equalises equalising eulogise eulogised eulogises eulogising evangelise evangelised evangelises evangelising exorcise exorcised exorcises exorcising extemporisation extemporise extemporised extemporises extemporising externalisation externalisations externalise externalised externalises externalising factorise factorised factorises factorising faecal faeces familiarisation familiarise familiarised familiarises familiarising fantasise fantasised fantasises fantasising favour favourable favourably favoured favouring favourite favourites favouritism favours feminise feminised feminises feminising fertilisation fertilise fertilised fertiliser fertilisers fertilises fertilising fervour fibre fibreglass fibres fictionalisation fictionalisations fictionalise fictionalised fictionalises fictionalising fillet filleted filleting fillets finalisation finalise finalised finalises finalising flautist flautists flavour flavoured flavouring flavourings flavourless flavours flavoursome flyer flier foetal foetid foetus foetuses formalisation formalise formalised formalises formalising fossilisation fossilise fossilised fossilises fossilising fraternisation fraternise fraternised fraternises fraternising fulfil fulfilment fulfils funnelled funnelling galvanise galvanised galvanises galvanising gambolled gambolling gaol gaolbird gaolbirds gaolbreak gaolbreaks gaoled gaoler gaolers gaoling gaols gases gauge gauged gauges gauging generalisation generalisations generalise generalised generalises generalising ghettoise ghettoised ghettoises ghettoising gipsies glamorise glamorised glamorises glamorising glamour globalisation globalise globalised globalises globalising glueing goitre goitres gonorrhoea gramme grammes gravelled grey greyed greying greyish greyness greys grovelled grovelling groyne groynes gruelling gruellingly gryphon gryphons gynaecological gynaecologist gynaecologists gynaecology haematological haematologist haematologists haematology haemoglobin haemophilia haemophiliac haemophiliacs haemorrhage haemorrhaged haemorrhages haemorrhaging haemorrhoids harbour harboured harbouring harbours harmonisation harmonise harmonised harmonises harmonising homoeopath homoeopathic homoeopaths homoeopathy homogenise homogenised homogenises homogenising honour honourable honourably honoured honouring honours hospitalisation hospitalise hospitalised hospitalises hospitalising humanise humanised humanises humanising humour humoured humouring humourless humours hybridise hybridised hybridises hybridising hypnotise hypnotised hypnotises hypnotising hypothesise hypothesised hypothesises hypothesising idealisation idealise idealised idealises idealising idolise idolised idolises idolising immobilisation immobilise immobilised immobiliser immobilisers immobilises immobilising immortalise immortalised immortalises immortalising immunisation immunise immunised immunises immunising impanelled impanelling imperilled imperilling individualise individualised individualises individualising industrialise industrialised industrialises industrialising inflexion inflexions initialise initialised initialises initialising initialled initialling instal instalment instalments instals instil instils institutionalisation institutionalise institutionalised institutionalises institutionalising intellectualise intellectualised intellectualises intellectualising internalisation internalise internalised internalises internalising internationalisation internationalise internationalised internationalises internationalising ionisation ionise ionised ioniser ionisers ionises ionising italicise italicised italicises italicising itemise itemised itemises itemising jeopardise jeopardised jeopardises jeopardising jewelled jeweller jewellers jewellery judgement kilogramme kilogrammes kilometre kilometres labelled labelling labour laboured labourer labourers labouring labours lacklustre legalisation legalise legalised legalises legalising legitimise legitimised legitimises legitimising leukaemia levelled leveller levellers levelling libelled libelling libellous liberalisation liberalise liberalised liberalises liberalising licence licenced licences licencing likeable lionisation lionise lionised lionises lionising liquidise liquidised liquidiser liquidisers liquidises liquidising litre litres localise localised localises localising louvre louvred louvres lustre magnetise magnetised magnetises magnetising manoeuvrability manoeuvrable manoeuvre manoeuvred manoeuvres manoeuvring manoeuvrings marginalisation marginalise marginalised marginalises marginalising marshalled marshalling marvelled marvelling marvellous marvellously materialisation materialise materialised materialises materialising maximisation maximise maximised maximises maximising meagre mechanisation mechanise mechanised mechanises mechanising mediaeval memorialise memorialised memorialises memorialising memorise memorised memorises memorising mesmerise mesmerised mesmerises mesmerising metabolise metabolised metabolises metabolising metre metres micrometre micrometres militarise militarised militarises militarising milligramme milligrammes millilitre millilitres millimetre millimetres miniaturisation miniaturise miniaturised miniaturises miniaturising minibuses minimise minimised minimises minimising misbehaviour misdemeanour misdemeanours misspelt mitre mitres mobilisation mobilise mobilised mobilises mobilising modelled modeller modellers modelling modernise modernised modernises modernising moisturise moisturised moisturiser moisturisers moisturises moisturising monologue monologues monopolisation monopolise monopolised monopolises monopolising moralise moralised moralises moralising motorised mould moulded moulder mouldered mouldering moulders mouldier mouldiest moulding mouldings moulds mouldy moult moulted moulting moults moustache moustached moustaches moustachioed multicoloured nationalisation nationalisations nationalise nationalised nationalises nationalising naturalisation naturalise naturalised naturalises naturalising neighbour neighbourhood neighbourhoods neighbouring neighbourliness neighbourly neighbours neutralisation neutralise neutralised neutralises neutralising normalisation normalise normalised normalises normalising odour odourless odours oesophagus oesophaguses oestrogen offence offences omelette omelettes optimise optimised optimises optimising organisation organisational organisations organise organised organiser organisers organises organising orthopaedic orthopaedics ostracise ostracised ostracises ostracising outmanoeuvre outmanoeuvred outmanoeuvres outmanoeuvring overemphasise overemphasised overemphasises overemphasising oxidisation oxidise oxidised oxidises oxidising paederast paederasts paediatric paediatrician paediatricians paediatrics paedophile paedophiles paedophilia palaeolithic palaeontologist palaeontologists palaeontology panelled panelling panellist panellists paralyse paralysed paralyses paralysing parcelled parcelling parlour parlours particularise particularised particularises particularising passivisation passivise passivised passivises passivising pasteurisation pasteurise pasteurised pasteurises pasteurising patronise patronised patronises patronising patronisingly pedalled pedalling pedestrianisation pedestrianise pedestrianised pedestrianises pedestrianising penalise penalised penalises penalising pencilled pencilling personalise personalised personalises personalising pharmacopoeia pharmacopoeias philosophise philosophised philosophises philosophising philtre philtres phoney plagiarise plagiarised plagiarises plagiarising plough ploughed ploughing ploughman ploughmen ploughs ploughshare ploughshares polarisation polarise polarised polarises polarising politicisation politicise politicised politicises politicising popularisation popularise popularised popularises popularising pouffe pouffes practise practised practises practising praesidium praesidiums pressurisation pressurise pressurised pressurises pressurising pretence pretences primaeval prioritisation prioritise prioritised prioritises prioritising privatisation privatisations privatise privatised privatises privatising professionalisation professionalise professionalised professionalises professionalising programme programmes prologue prologues propagandise propagandised propagandises propagandising proselytise proselytised proselytiser proselytisers proselytises proselytising psychoanalyse psychoanalysed psychoanalyses psychoanalysing publicise publicised publicises publicising pulverisation pulverise pulverised pulverises pulverising pummelled pummelling pyjama pyjamas pzazz quarrelled quarrelling radicalise radicalised radicalises radicalising rancour randomise randomised randomises randomising rationalisation rationalisations rationalise rationalised rationalises rationalising ravelled ravelling realisable realisation realisations realise realised realises realising recognisable recognisably recognisance recognise recognised recognises recognising reconnoitre reconnoitred reconnoitres reconnoitring refuelled refuelling regularisation regularise regularised regularises regularising remodelled remodelling remould remoulded remoulding remoulds reorganisation reorganisations reorganise reorganised reorganises reorganising revelled reveller revellers revelling revitalise revitalised revitalises revitalising revolutionise revolutionised revolutionises revolutionising rhapsodise rhapsodised rhapsodises rhapsodising rigour rigours ritualised rivalled rivalling romanticise romanticised romanticises romanticising rumour rumoured rumours sabre sabres saltpetre sanitise sanitised sanitises sanitising satirise satirised satirises satirising saviour saviours savour savoured savouries savouring savours savoury scandalise scandalised scandalises scandalising sceptic sceptical sceptically scepticism sceptics sceptre sceptres scrutinise scrutinised scrutinises scrutinising secularisation secularise secularised secularises secularising sensationalise sensationalised sensationalises sensationalising sensitise sensitised sensitises sensitising sentimentalise sentimentalised sentimentalises sentimentalising sepulchre sepulchres serialisation serialisations serialise serialised serialises serialising sermonise sermonised sermonises sermonising sheikh shovelled shovelling shrivelled shrivelling signalise signalised signalises signalising signalled signalling smoulder smouldered smouldering smoulders snivelled snivelling snorkelled snorkelling snowplough snowploughs socialisation socialise socialised socialises socialising sodomise sodomised sodomises sodomising solemnise solemnised solemnises solemnising sombre specialisation specialisations specialise specialised specialises specialising spectre spectres spiralled spiralling splendour splendours squirrelled squirrelling stabilisation stabilise stabilised stabiliser stabilisers stabilises stabilising standardisation standardise standardised standardises standardising stencilled stencilling sterilisation sterilisations sterilise sterilised steriliser sterilisers sterilises sterilising stigmatisation stigmatise stigmatised stigmatises stigmatising storey storeys subsidisation subsidise subsidised subsidiser subsidisers subsidises subsidising succour succoured succouring succours sulphate sulphates sulphide sulphides sulphur sulphurous summarise summarised summarises summarising swivelled swivelling symbolise symbolised symbolises symbolising sympathise sympathised sympathiser sympathisers sympathises sympathising synchronisation synchronise synchronised synchronises synchronising synthesise synthesised synthesiser synthesisers synthesises synthesising syphon syphoned syphoning syphons systematisation systematise systematised systematises systematising tantalise tantalised tantalises tantalising tantalisingly tasselled technicolour temporise temporised temporises temporising tenderise tenderised tenderises tenderising terrorise terrorised terrorises terrorising theatre theatregoer theatregoers theatres theorise theorised theorises theorising tonne tonnes towelled towelling toxaemia tranquillise tranquillised tranquilliser tranquillisers tranquillises tranquillising tranquillity tranquillize tranquillized tranquillizer tranquillizers tranquillizes tranquillizing tranquilly transistorised traumatise traumatised traumatises traumatising travelled traveller travellers travelling travelogue travelogues trialled trialling tricolour tricolours trivialise trivialised trivialises trivialising tumour tumours tunnelled tunnelling tyrannise tyrannised tyrannises tyrannising tyre tyres unauthorised uncivilised underutilised unequalled unfavourable unfavourably unionisation unionise unionised unionises unionising unorganised unravelled unravelling unrecognisable unrecognised unrivalled unsavoury untrammelled urbanisation urbanise urbanised urbanises urbanising utilisable utilisation utilise utilised utilises utilising valour vandalise vandalised vandalises vandalising vaporisation vaporise vaporised vaporises vaporising vapour vapours verbalise verbalised verbalises verbalising victimisation victimise victimised victimises victimising videodisc videodiscs vigour visualisation visualisations visualise visualised visualises visualising vocalisation vocalisations vocalise vocalised vocalises vocalising vulcanised vulgarisation vulgarise vulgarised vulgarises vulgarising waggon waggons watercolour watercolours weaselled weaselling westernisation westernise westernised westernises westernising womanise womanised womaniser womanisers womanises womanising woollen woollens woollies woolly worshipped worshipping worshipper yodelled yodelling yoghourt yoghourts yoghurt yoghurts".lower().split()
US = "kerb accessorize accessorized accessorizes accessorizing acclimatization acclimatize acclimatized acclimatizes acclimatizing accouterments eon eons aerogram aerograms airplane airplanes esthete esthetes esthetic esthetically esthetics etiology aging aggrandizement agonize agonized agonizes agonizing agonizingly almanac almanacs aluminum amortizable amortization amortizations amortize amortized amortizes amortizing amphitheater amphitheaters anemia anemic anesthesia anesthetic anesthetics anesthetize anesthetized anesthetizes anesthetizing anesthetist anesthetists anesthetize anesthetized anesthetizes anesthetizing analog analogs analyze analyzed analyzes analyzing anglicize anglicized anglicizes anglicizing annualized antagonize antagonized antagonizes antagonizing apologize apologized apologizes apologizing appall appalls appetizer appetizers appetizing appetizingly arbor arbors archeological archeologically archeologist archeologists archeology ardor armor armored armorer armorers armories armory artifact artifacts authorize authorized authorizes authorizing ax backpedaled backpedaling banister banisters baptize baptized baptizes baptizing bastardize bastardized bastardizes bastardizing battleax balk balked balking balks bedeviled bedeviling behavior behavioral behaviorism behaviorist behaviorists behaviors behoove behooved behooves bejeweled belabor belabored belaboring belabors beveled bevies bevy biased biasing binging bougainvillea bougainvilleas bowdlerize bowdlerized bowdlerizes bowdlerizing breathalyze breathalyzed breathalyzer breathalyzers breathalyzes breathalyzing brutalize brutalized brutalizes brutalizing busses bussing cesarean cesareans caliber calibers caliper calipers calisthenics canalize canalized canalizes canalizing cancelation cancelations canceled canceling candor cannibalize cannibalized cannibalizes cannibalizing canonize canonized canonizes canonizing capitalize capitalized capitalizes capitalizing caramelize caramelized caramelizes caramelizing carbonize carbonized carbonizes carbonizing caroled caroling catalog cataloged catalogs cataloging catalyze catalyzed catalyzes catalyzing categorize categorized categorizes categorizing cauterize cauterized cauterizes cauterizing caviled caviling centigram centigrams centiliter centiliters centimeter centimeters centralize centralized centralizes centralizing center centered centerfold centerfolds centerpiece centerpieces centers channeled channeling characterize characterized characterizes characterizing check checkbook checkbooks checkered checks chili chimera chimeras chiseled chiseling circularize circularized circularizes circularizing civilize civilized civilizes civilizing clamor clamored clamoring clamors clangor clarinetist clarinetists collectivize collectivized collectivizes collectivizing colonization colonize colonized colonizer colonizers colonizes colonizing color colorant colorants colored coloreds colorful colorfully coloring colorize colorized colorizes colorizing colorless colors commercialize commercialized commercializes commercializing compartmentalize compartmentalized compartmentalizes compartmentalizing computerize computerized computerizes computerizing conceptualize conceptualized conceptualizes conceptualizing connection connections contextualize contextualized contextualizes contextualizing cozier cozies coziest cozily coziness cozy councilor councilors counseled counseling counselor counselors crenelated criminalize criminalized criminalizes criminalizing criticize criticized criticizes criticizing crueler cruelest crystallization crystallize crystallized crystallizes crystallizing cudgeled cudgeling customize customized customizes customizing cipher ciphers decentralization decentralize decentralized decentralizes decentralizing decriminalization decriminalize decriminalized decriminalizes decriminalizing defense defenseless defenses dehumanization dehumanize dehumanized dehumanizes dehumanizing demeanor demilitarization demilitarize demilitarized demilitarizes demilitarizing demobilization demobilize demobilized demobilizes demobilizing democratization democratize democratized democratizes democratizing demonize demonized demonizes demonizing demoralization demoralize demoralized demoralizes demoralizing denationalization denationalize denationalized denationalizes denationalizing deodorize deodorized deodorizes deodorizing depersonalize depersonalized depersonalizes depersonalizing deputize deputized deputizes deputizing desensitization desensitize desensitized desensitizes desensitizing destabilization destabilize destabilized destabilizes destabilizing dialed dialing dialog dialogs diarrhea digitize digitized digitizes digitizing disk discolor discolored discoloring discolors disks disemboweled disemboweling disfavor disheveled dishonor dishonorable dishonorably dishonored dishonoring dishonors disorganization disorganized distill distills dramatization dramatizations dramatize dramatized dramatizes dramatizing draft draftboard draftboards draftier draftiest drafts draftsman draftsmanship draftsmen draftswoman draftswomen drafty driveled driveling dueled dueling economize economized economizes economizing edema editorialize editorialized editorializes editorializing empathize empathized empathizes empathizing emphasize emphasized emphasizes emphasizing enameled enameling enamored encyclopedia encyclopedias encyclopedic endeavor endeavored endeavoring endeavors energize energized energizes energizing enroll enrolls enthrall enthralls epaulet epaulets epicenter epicenters epilog epilogs epitomize epitomized epitomizes epitomizing equalization equalize equalized equalizer equalizers equalizes equalizing eulogize eulogized eulogizes eulogizing evangelize evangelized evangelizes evangelizing exorcize exorcized exorcizes exorcizing extemporization extemporize extemporized extemporizes extemporizing externalization externalizations externalize externalized externalizes externalizing factorize factorized factorizes factorizing fecal feces familiarization familiarize familiarized familiarizes familiarizing fantasize fantasized fantasizes fantasizing favor favorable favorably favored favoring favorite favorites favoritism favors feminize feminized feminizes feminizing fertilization fertilize fertilized fertilizer fertilizers fertilizes fertilizing fervor fiber fiberglass fibers fictionalization fictionalizations fictionalize fictionalized fictionalizes fictionalizing filet fileted fileting filets finalization finalize finalized finalizes finalizing flutist flutists flavor flavored flavoring flavorings flavorless flavors flavorsome flier flyer fetal fetid fetus fetuses formalization formalize formalized formalizes formalizing fossilization fossilize fossilized fossilizes fossilizing fraternization fraternize fraternized fraternizes fraternizing fulfill fulfillment fulfills funneled funneling galvanize galvanized galvanizes galvanizing gamboled gamboling jail jailbird jailbirds jailbreak jailbreaks jailed jailer jailers jailing jails gasses gage gaged gages gaging generalization generalizations generalize generalized generalizes generalizing ghettoize ghettoized ghettoizes ghettoizing gypsies glamorize glamorized glamorizes glamorizing glamor globalization globalize globalized globalizes globalizing gluing goiter goiters gonorrhea gram grams graveled gray grayed graying grayish grayness grays groveled groveling groin groins grueling gruelingly griffin griffins gynecological gynecologist gynecologists gynecology hematological hematologist hematologists hematology hemoglobin hemophilia hemophiliac hemophiliacs hemorrhage hemorrhaged hemorrhages hemorrhaging hemorrhoids harbor harbored harboring harbors harmonization harmonize harmonized harmonizes harmonizing homeopath homeopathic homeopaths homeopathy homogenize homogenized homogenizes homogenizing honor honorable honorably honored honoring honors hospitalization hospitalize hospitalized hospitalizes hospitalizing humanize humanized humanizes humanizing humor humored humoring humorless humors hybridize hybridized hybridizes hybridizing hypnotize hypnotized hypnotizes hypnotizing hypothesize hypothesized hypothesizes hypothesizing idealization idealize idealized idealizes idealizing idolize idolized idolizes idolizing immobilization immobilize immobilized immobilizer immobilizers immobilizes immobilizing immortalize immortalized immortalizes immortalizing immunization immunize immunized immunizes immunizing impaneled impaneling imperiled imperiling individualize individualized individualizes individualizing industrialize industrialized industrializes industrializing inflection inflections initialize initialized initializes initializing initialed initialing install installment installments installs instill instills institutionalization institutionalize institutionalized institutionalizes institutionalizing intellectualize intellectualized intellectualizes intellectualizing internalization internalize internalized internalizes internalizing internationalization internationalize internationalized internationalizes internationalizing ionization ionize ionized ionizer ionizers ionizes ionizing italicize italicized italicizes italicizing itemize itemized itemizes itemizing jeopardize jeopardized jeopardizes jeopardizing jeweled jeweler jewelers jewelry judgment kilogram kilograms kilometer kilometers labeled labeling labor labored laborer laborers laboring labors lackluster legalization legalize legalized legalizes legalizing legitimize legitimized legitimizes legitimizing leukemia leveled leveler levelers leveling libeled libeling libelous liberalization liberalize liberalized liberalizes liberalizing license licensed licenses licensing likable lionization lionize lionized lionizes lionizing liquidize liquidized liquidizer liquidizers liquidizes liquidizing liter liters localize localized localizes localizing louver louvered louvers luster magnetize magnetized magnetizes magnetizing maneuverability maneuverable maneuver maneuvered maneuvers maneuvering maneuverings marginalization marginalize marginalized marginalizes marginalizing marshaled marshaling marveled marveling marvelous marvelously materialization materialize materialized materializes materializing maximization maximize maximized maximizes maximizing meager mechanization mechanize mechanized mechanizes mechanizing medieval memorialize memorialized memorializes memorializing memorize memorized memorizes memorizing mesmerize mesmerized mesmerizes mesmerizing metabolize metabolized metabolizes metabolizing meter meters micrometer micrometers militarize militarized militarizes militarizing milligram milligrams milliliter milliliters millimeter millimeters miniaturization miniaturize miniaturized miniaturizes miniaturizing minibusses minimize minimized minimizes minimizing misbehavior misdemeanor misdemeanors misspelled miter miters mobilization mobilize mobilized mobilizes mobilizing modeled modeler modelers modeling modernize modernized modernizes modernizing moisturize moisturized moisturizer moisturizers moisturizes moisturizing monolog monologs monopolization monopolize monopolized monopolizes monopolizing moralize moralized moralizes moralizing motorized mold molded molder moldered moldering molders moldier moldiest molding moldings molds moldy molt molted molting molts mustache mustached mustaches mustachioed multicolored nationalization nationalizations nationalize nationalized nationalizes nationalizing naturalization naturalize naturalized naturalizes naturalizing neighbor neighborhood neighborhoods neighboring neighborliness neighborly neighbors neutralization neutralize neutralized neutralizes neutralizing normalization normalize normalized normalizes normalizing odor odorless odors esophagus esophaguses estrogen offense offenses omelet omelets optimize optimized optimizes optimizing organization organizational organizations organize organized organizer organizers organizes organizing orthopedic orthopedics ostracize ostracized ostracizes ostracizing outmaneuver outmaneuvered outmaneuvers outmaneuvering overemphasize overemphasized overemphasizes overemphasizing oxidization oxidize oxidized oxidizes oxidizing pederast pederasts pediatric pediatrician pediatricians pediatrics pedophile pedophiles pedophilia paleolithic paleontologist paleontologists paleontology paneled paneling panelist panelists paralyze paralyzed paralyzes paralyzing parceled parceling parlor parlors particularize particularized particularizes particularizing passivization passivize passivized passivizes passivizing pasteurization pasteurize pasteurized pasteurizes pasteurizing patronize patronized patronizes patronizing patronizingly pedaled pedaling pedestrianization pedestrianize pedestrianized pedestrianizes pedestrianizing penalize penalized penalizes penalizing penciled penciling personalize personalized personalizes personalizing pharmacopeia pharmacopeias philosophize philosophized philosophizes philosophizing filter filters phony plagiarize plagiarized plagiarizes plagiarizing plow plowed plowing plowman plowmen plows plowshare plowshares polarization polarize polarized polarizes polarizing politicization politicize politicized politicizes politicizing popularization popularize popularized popularizes popularizing pouf poufs practice practiced practices practicing presidium presidiums pressurization pressurize pressurized pressurizes pressurizing pretense pretenses primeval prioritization prioritize prioritized prioritizes prioritizing privatization privatizations privatize privatized privatizes privatizing professionalization professionalize professionalized professionalizes professionalizing program programs prolog prologs propagandize propagandized propagandizes propagandizing proselytize proselytized proselytizer proselytizers proselytizes proselytizing psychoanalyze psychoanalyzed psychoanalyzes psychoanalyzing publicize publicized publicizes publicizing pulverization pulverize pulverized pulverizes pulverizing pummel pummeled pajama pajamas pizzazz quarreled quarreling radicalize radicalized radicalizes radicalizing rancor randomize randomized randomizes randomizing rationalization rationalizations rationalize rationalized rationalizes rationalizing raveled raveling realizable realization realizations realize realized realizes realizing recognizable recognizably recognizance recognize recognized recognizes recognizing reconnoiter reconnoitered reconnoiters reconnoitering refueled refueling regularization regularize regularized regularizes regularizing remodeled remodeling remold remolded remolding remolds reorganization reorganizations reorganize reorganized reorganizes reorganizing reveled reveler revelers reveling revitalize revitalized revitalizes revitalizing revolutionize revolutionized revolutionizes revolutionizing rhapsodize rhapsodized rhapsodizes rhapsodizing rigor rigors ritualized rivaled rivaling romanticize romanticized romanticizes romanticizing rumor rumored rumors saber sabers saltpeter sanitize sanitized sanitizes sanitizing satirize satirized satirizes satirizing savior saviors savor savored savories savoring savors savory scandalize scandalized scandalizes scandalizing skeptic skeptical skeptically skepticism skeptics scepter scepters scrutinize scrutinized scrutinizes scrutinizing secularization secularize secularized secularizes secularizing sensationalize sensationalized sensationalizes sensationalizing sensitize sensitized sensitizes sensitizing sentimentalize sentimentalized sentimentalizes sentimentalizing sepulcher sepulchers serialization serializations serialize serialized serializes serializing sermonize sermonized sermonizes sermonizing sheik shoveled shoveling shriveled shriveling signalize signalized signalizes signalizing signaled signaling smolder smoldered smoldering smolders sniveled sniveling snorkeled snorkeling snowplow snowplow socialization socialize socialized socializes socializing sodomize sodomized sodomizes sodomizing solemnize solemnized solemnizes solemnizing somber specialization specializations specialize specialized specializes specializing specter specters spiraled spiraling splendor splendors squirreled squirreling stabilization stabilize stabilized stabilizer stabilizers stabilizes stabilizing standardization standardize standardized standardizes standardizing stenciled stenciling sterilization sterilizations sterilize sterilized sterilizer sterilizers sterilizes sterilizing stigmatization stigmatize stigmatized stigmatizes stigmatizing story stories subsidization subsidize subsidized subsidizer subsidizers subsidizes subsidizing succor succored succoring succors sulfate sulfates sulfide sulfides sulfur sulfurous summarize summarized summarizes summarizing swiveled swiveling symbolize symbolized symbolizes symbolizing sympathize sympathized sympathizer sympathizers sympathizes sympathizing synchronization synchronize synchronized synchronizes synchronizing synthesize synthesized synthesizer synthesizers synthesizes synthesizing siphon siphoned siphoning siphons systematization systematize systematized systematizes systematizing tantalize tantalized tantalizes tantalizing tantalizingly tasseled technicolor temporize temporized temporizes temporizing tenderize tenderized tenderizes tenderizing terrorize terrorized terrorizes terrorizing theater theatergoer theatergoers theaters theorize theorized theorizes theorizing ton tons toweled toweling toxemia tranquilize tranquilized tranquilizer tranquilizers tranquilizes tranquilizing tranquility tranquilize tranquilized tranquilizer tranquilizers tranquilizes tranquilizing tranquility transistorized traumatize traumatized traumatizes traumatizing traveled traveler travelers traveling travelog travelogs trialed trialing tricolor tricolors trivialize trivialized trivializes trivializing tumor tumors tunneled tunneling tyrannize tyrannized tyrannizes tyrannizing tire tires unauthorized uncivilized underutilized unequaled unfavorable unfavorably unionization unionize unionized unionizes unionizing unorganized unraveled unraveling unrecognizable unrecognized unrivaled unsavory untrammeled urbanization urbanize urbanized urbanizes urbanizing utilizable utilization utilize utilized utilizes utilizing valor vandalize vandalized vandalizes vandalizing vaporization vaporize vaporized vaporizes vaporizing vapor vapors verbalize verbalized verbalizes verbalizing victimization victimize victimized victimizes victimizing videodisk videodisks vigor visualization visualizations visualize visualized visualizes visualizing vocalization vocalizations vocalize vocalized vocalizes vocalizing vulcanized vulgarization vulgarize vulgarized vulgarizes vulgarizing wagon wagons watercolor watercolors weaseled weaseling westernization westernize westernized westernizes westernizing womanize womanized womanizer womanizers womanizes womanizing woolen woolens woolies wooly worshiped worshiping worshiper yodeled yodeling yogurt yogurts yogurt yogurts".lower().split()
ukUS = {}
usUK = {}
loopN = 0
for x in UK:
ukUS[x] = US[loopN]
loopN += 1
loopN = 0
for y in US:
usUK[y] = UK[loopN]
loopN += 1 |
s = [[int(i) for i in input().split(' ')] for j in range(3)]
n = [s[i][j] for i in range(3) for j in range(3)]
all_n = [[8,1,6,3,5,7,4,9,2],[6,1,8,7,5,3,2,9,4],[4,9,2,3,5,7,8,1,6],[2,9,4,7,5,3,6,1,8],[8,3,4,1,5,9,6,7,2],[4,3,8,9,5,1,2,7,6],[6,7,2,1,5,9,8,3,4],[2,7,6,9,5,1,4,3,8]]
allsum=[]
for l in all_n:
summ=0
for i in range(9):
summ+=abs(n[i]-l[i])
allsum.append(summ)
# print([abs(n[i]-l[i]) for i in range(9)])
# allsum.append(sum([abs(n[i]-l[i]) for i in range(9)]))
print(min(allsum)) |
BUILTIN_ENGINES = {"spark": "feaflow.engine.spark.SparkEngine"}
BUILTIN_SOURCES = {
"query": "feaflow.source.query.QuerySource",
"pandas": "feaflow.source.pandas.PandasDataFrameSource",
}
BUILTIN_COMPUTES = {"sql": "feaflow.compute.sql.SqlCompute"}
BUILTIN_SINKS = {
"table": "feaflow.sink.table.TableSink",
"redis": "feaflow.sink.redis.RedisSink",
"feature_view": "feaflow.sink.feature_view.FeatureViewSink",
}
|
"""
This module contains everything that calls command line calls.
"""
class Command(object):
base_cmd = ['transmission-remote']
args = []
def run_command(self):
return subprocess.check_output(self.base_cmd + self.args, stderr=subprocess.STDOUT)
class ListCommand(Command):
args = ['-l']
class RemoveCommand(Command):
def __init__(self, torrent_id):
self.args = ['--remove={0}'.format(torrent_id)]
|
APP_ID = '390093838084850'
DOMAIN = 'https://ef1ac6ba.ngrok.io'
COMMENTS_CALLBACK = DOMAIN + \
'/webhook_handler/'
MESSENGER_CALLBACK = DOMAIN + \
'/webhook_handler/'
VERIFY_TOKEN = '19990402'
APP_SECRET = 'e3d24fecd0c82e3c558d9cca9c6edad7'
|
# Copyright 2017 Ryan D. Williams
#
# 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.
"""Module containing helper functions for common tasks related to interacting
with the FeedLogs DB
Functions:
add_nulls_to_vals - replace values that evaluate to false with None
build_ins_query - builds an insert query
"""
def add_nulls_to_vals(columns, vals):
"""Takes a list of columns to be inserted/updated and a value dictionary. Any columns
that are not present in the dictionary keys will be added with a None value, translating
to Null in the db. Used to help input dictionarys
Args:
columns (list of str): column names
vals: (dict of str): keys = column names, values = their values
Returns:
dict: where columns not found in vals.keys() are added with a None value
"""
new_vals = vals.copy()
new_vals.update({col: None for col in columns if col not in vals})
return new_vals
def build_ins_query(table, columns, returns=None):
"""Takes a table name, a list of columns and optional colunns to return after the
insert is complete
Args:
table (str): table to insert into
columns (list of str): ordered list of column names
return (list of str): inserted column values you wish to return
Returns:
str: formated query
"""
qry = 'INSERT INTO {table} {columns_str} VALUES {values_str}'
qry_strs = {
'columns_str': '(' + ','.join(columns) + ')',
'values_str': '(' + ','.join(('%(' + col + ')s' for col in columns)) + ')'
}
if returns:
qry += ' RETURNING {returns_str}'
qry_strs['returns_str'] = '(' + ','.join(returns) + ')'
fmtd_qry = qry.format(table=table, **qry_strs)
return fmtd_qry
|
#!/usr/bin/python
#coding=utf-8
'''
@author: sheng
@license:
'''
SPELL=u'yìshè'
CN=u'意舍'
NAME=u'yishe44'
CHANNEL='bladder'
CHANNEL_FULLNAME='BladderChannelofFoot-Taiyang'
SEQ='BL49'
if __name__ == '__main__':
pass
|
bind = '0.0.0.0:5000'
workers = 1
backlog = 2048
worker_class = "sync"
debug = True
proc_name = 'gunicorn.proc'
pidfile = '/tmp/gunicorn.pid'
logfile = '/var/log/gunicorn/debug.log'
loglevel = 'error' |
def fizzbuzz(i):
''' int -> str
If i is divisible by 3, return "Fizz".
If i is divisible by 5, return "Buzz".
If i is divisible by 3 and 5, return "FizzBuzz".'''
if i % 3 == 0 and i % 5 == 0:
return ("FizzBuzz")
elif i % 3 == 0:
return ("Fizz")
elif i % 5 == 0:
return ("Buzz")
else:
return (str(i))
numlist = range(1, 101)
for i in numlist:
print(fizzbuzz(i))
|
# Configuration file for the Sphinx documentation builder.
# -- Project information
project = 'ChemW'
copyright = '2022, Andrew Philip Freiburger'
author = 'Andrew Philip Freiburger'
release = '1'
version = '0.3.1' |
"""
Quoridor Online
Quentin Deschamps, 2020
"""
class Game:
"""Create a game"""
def __init__(self, game_id, nb_players):
self.game_id = game_id
self.nb_players = nb_players
self.connected = [False] * nb_players
self.names = [''] * nb_players
self.run = False
self.current_player = -1
self.last_play = ''
self.winner = ''
self.wanted_restart = []
def add_player(self, num_player):
"""Add a player"""
self.connected[num_player] = True
print(f"[Game {self.game_id}]: player {num_player} added")
def add_name(self, data):
"""Add a player's name"""
num_player = int(data.split(';')[1])
name = data.split(';')[2]
self.names[num_player] = name
print(f"[Game {self.game_id}]: {name} added as player {num_player}")
def remove_player(self, num_player):
"""Remove a player"""
self.connected[num_player] = False
self.names[num_player] = ''
if self.nb_players_connected() == 1:
self.run = False
self.current_player == -1
else:
if num_player == self.current_player:
self.current_player = self.next_player(self.current_player)
self.last_play = ';'.join(['D', str(num_player)])
print(f"[Game {self.game_id}]: player {num_player} removed")
def nb_players_connected(self):
"""Return the number of players connected"""
return self.connected.count(True)
def players_missing(self):
"""Return the number of players missing to start"""
return self.nb_players - self.nb_players_connected()
def ready(self):
"""Return True if the game can start"""
return self.nb_players_connected() == self.nb_players
def next_player(self, current):
"""Return the new current player"""
current = (current + 1) % self.nb_players
while not self.connected[current]:
current = (current + 1) % self.nb_players
return current
def get_name_current(self):
"""Return the name of the current player"""
return self.names[self.current_player]
def start(self):
"""Start the game"""
self.winner = ''
self.current_player = self.next_player(-1)
self.run = True
print(f"[Game {self.game_id}]: started")
def play(self, data):
"""Get a move"""
print(f"[Game {self.game_id}]: move {data}")
self.last_play = data
if data.split(';')[-1] == 'w':
print(f"[Game {self.game_id}]: {self.get_name_current()} wins!")
self.winner = self.get_name_current()
self.current_player = -1
self.run = False
self.wanted_restart = []
else:
self.current_player = self.next_player(self.current_player)
def restart(self, data):
"""Restart the game if there are enough players"""
num_player = int(data.split(';')[1])
self.wanted_restart.append(num_player)
print(f"[Game {self.game_id}]: {self.names[num_player]} asked restart",
end=' ')
print(f"{len(self.wanted_restart)}/{self.nb_players}")
if len(self.wanted_restart) == self.nb_players:
self.start()
class Games:
"""Manage games"""
def __init__(self, nb_players):
self.games = {}
self.nb_players = nb_players
self.num_player = 0
self.game_id = 0
def find_game(self, game_id):
"""Find a game"""
if game_id in self.games:
return self.games[game_id]
return None
def add_game(self):
"""Create a new game"""
if self.game_id not in self.games:
self.num_player = 0
self.games[self.game_id] = Game(self.game_id, self.nb_players)
print(f"[Game {self.game_id}]: created")
def del_game(self, game_id):
"""Delete a game"""
if game_id in self.games:
del self.games[game_id]
print(f"[Game {game_id}]: closed")
if game_id == self.game_id:
self.num_player = 0
def accept_player(self):
"""Accept a player"""
if self.game_id not in self.games:
self.add_game()
self.games[self.game_id].add_player(self.num_player)
return self.game_id, self.num_player
def launch_game(self):
"""Lauch a game"""
if self.games[self.game_id].ready():
self.games[self.game_id].start()
self.game_id += 1
else:
self.num_player += 1
def remove_player(self, game_id, num_player):
"""Remove a player"""
game = self.find_game(game_id)
if game is not None:
game.remove_player(num_player)
if not game.run:
self.del_game(game_id)
|
'''
Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation.
Note:
The given integer is guaranteed to fit within the range of a 32-bit signed integer.
You could assume no leading zero bit in the integer’s binary representation.
Example 1:
Input: 5
Output: 2
Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2.
Example 2:
Input: 1
Output: 0
Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0.
'''
class Solution(object):
def findComplement(self, num):
r = ""
num = bin(num)
num = num.lstrip("0b")
for x in range(len(num)):
if num[x] == "0":
r = r + "1"
else:
r = r + "0"
return int(r,2)
solution = Solution()
print(solution.findComplement(5)) |
"""
>>> bus1 = HountedBus(['Alice', 'Bill'])
>>> bus1.passengers
['Alice', 'Bill']
>>> bus1.pick('Charlie')
>>> bus1.drop('Alice')
>>> bus1.passengers
['Bill', 'Charlie']
>>> bus2 = HountedBus()
>>> bus2.pick('Carrie')
>>> bus2.passengers
['Carrie']
>>> bus3 = HountedBus()
>>> bus3.passengers
['Carrie']
>>> bus3.pick('Dave')
>>> bus2.passengers
['Carrie', 'Dave']
>>> bus2.passengers is bus3.passengers
True
>>> bus1.passengers
['Bill', 'Charlie']
>>> dir(HountedBus.__init__) # doctest: +ELLIPSIS
['__annotations__', '__call__', ..., '__defaults__', ...]
>>> HountedBus.__init__.__defaults__
(['Carrie', 'Dave'],)
>>> HountedBus.__init__.__defaults__[0] is bus2.passengers
True
"""
# BEGIN HAUNTED_BUS_CLASS
class HountedBus:
"""A bus model hounted by ghost passengers"""
def __init__(self, passengers=[]): # <1>
self.passengers = passengers # <2>
def pick(self, name):
self.passengers.append(name) # <3>
def drop(self, name):
self.passengers.remove(name)
# END HAUNTED_BUS_CLASS
|
"""
File: caesar.py
Name: Isabelle
------------------------------
This program demonstrates the idea of caesar cipher.
Users will be asked to input a number to produce shifted
ALPHABET as the cipher table. After that, any strings typed
in will be encrypted.
"""
# This constant shows the original order of alphabetic sequence
ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
def main():
"""
User input the secret number and the string.
The program will shift ALPHABET as cipher table and then encrypt the string.
"""
n=int(input('Secret number: '))
s=input("What's the ciphered string? ").upper()
new_alphabet=alphabet(n)
decipher(s,new_alphabet)
def alphabet(n):
"""
Shift the ALPHABET as cipher table.
:param n: int, necessary number to shift ALPHABET as cipher table
:return: str, cipher table
"""
a=''
for i in range((26-n),26):
a+=ALPHABET[i]
for i in range(26-n):
a+=ALPHABET[i]
return a
def decipher(s,x):
"""
Encrypt the string the user input
:param s: str, string being encrypted
:param x: str, cipher table
"""
b=''
for i in s:
ch=x.find(i)
if ch==-1:
# When there is ' ' in the string.
b+=i
else:
b+=ALPHABET[ch]
print('The deciphered string is: '+b)
##### DO NOT EDIT THE CODE BELOW THIS LINE #####
if __name__ == '__main__':
main()
|
#URL: https://www.hackerrank.com/challenges/two-characters/problem
def alternate(l, s):
chars = list(set(s))
n = len(chars)
maxlen = 0
#print(chars)
for i in range(n):
for j in range(i+1,n):
ch1 = chars[i]
ch2 = chars[j]
tempans = ""
ansl = 0
f = True
for ch in s:
if ch ==ch1:
if (ansl==0) or tempans[-1]==ch2:
tempans+=ch
ansl+=1
else:
f= False
break
elif ch == ch2:
if (ansl==0) or tempans[-1]==ch1:
tempans+=ch
ansl+=1
else:
f=False
break
if f:
maxlen = max(maxlen, ansl)
return maxlen
|
def arithmetic_arranger(problems, answer=False):
# check to see if the list is too long
num_problems = len(problems)
answers_list = []
top_operand = []
operator = []
bottom_operand = []
# calculate answers, create a list of answers
# check to see if there are too many problems
if num_problems > 5:
return "Error: Too many problems."
for problem in problems:
problem_list = problem.split()
# if too many problems, return error
if (len(problem_list[0]) > 4) or (len(problem_list[2]) > 4):
return "Error: Numbers cannot be more than four digits."
# try/except to look for ValueErrors
try:
if problem_list[1] == '+':
result = int(problem_list[0]) + int(problem_list[2])
elif problem_list[1] == '-':
result = int(problem_list[0]) - int(problem_list[2])
# return error if wrong operator
else:
return "Error: Operator must be '+' or '-'."
except ValueError:
return "Error: Numbers must only contain digits."
answers_list.append(str(result))
top_operand.append(problem_list[0])
operator.append(problem_list[1])
bottom_operand.append(problem_list[2])
# determine lengths
# get lengths of all operands, append to list, then determine which to use for spacing purposes
top_lengths = []
bottom_lengths = []
actual_lengths = []
for value in top_operand:
top_lengths.append(len(value))
for value in bottom_operand:
bottom_lengths.append(len(value))
# determine which to use for spacing purposes
for i in range(0, len(top_lengths)):
if top_lengths[i] >= bottom_lengths[i]:
actual_lengths.append(top_lengths[i])
else:
actual_lengths.append(bottom_lengths[i])
actual_length_int = (int(actual_lengths[i]) + 2) # is for space/operator
actual_lengths[i] = actual_length_int
# build string
arranged_problems = ""
# top row
i = 0
for value in top_lengths:
space_length = actual_lengths[i] - value
spacing = " " * space_length
arranged_problems = arranged_problems + spacing
arranged_problems = arranged_problems + top_operand[i]
arranged_problems = arranged_problems + " "
i += 1
arranged_problems = arranged_problems.rstrip()
arranged_problems = arranged_problems + "\n"
# bottom operands and operators
i = 0
for value in bottom_lengths:
arranged_problems = arranged_problems + operator[i] + " "
space_length = (actual_lengths[i] - 2) - value
if space_length > 0:
spacing = " " * space_length
arranged_problems = arranged_problems + spacing
arranged_problems = arranged_problems + bottom_operand[i]
arranged_problems = arranged_problems + " "
i += 1
arranged_problems = arranged_problems.rstrip()
arranged_problems = arranged_problems + "\n"
# dashes
i = 0
for value in actual_lengths:
arranged_problems = arranged_problems + ("-" * actual_lengths[i])
arranged_problems = arranged_problems + " "
i += 1
arranged_problems = arranged_problems.rstrip()
if answer is True:
arranged_problems = arranged_problems + "\n"
i = 0
for answer in answers_list:
space_length = actual_lengths[i] - len(answer)
arranged_problems = arranged_problems + (" " * space_length)
arranged_problems = arranged_problems + answer
arranged_problems = arranged_problems + " "
i += 1
arranged_problems = arranged_problems.rstrip()
return arranged_problems |
#
# PySNMP MIB module OUTBOUNDTELNET-PRIVATE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/OUTBOUNDTELNET-PRIVATE-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:35:45 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueRangeConstraint, SingleValueConstraint, ConstraintsIntersection, ValueSizeConstraint, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "SingleValueConstraint", "ConstraintsIntersection", "ValueSizeConstraint", "ConstraintsUnion")
switch, = mibBuilder.importSymbols("QUANTA-SWITCH-MIB", "switch")
NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance")
MibScalar, MibTable, MibTableRow, MibTableColumn, NotificationType, ObjectIdentity, Unsigned32, Gauge32, MibIdentifier, iso, IpAddress, Counter32, Bits, Integer32, TimeTicks, Counter64, ModuleIdentity = mibBuilder.importSymbols("SNMPv2-SMI", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "NotificationType", "ObjectIdentity", "Unsigned32", "Gauge32", "MibIdentifier", "iso", "IpAddress", "Counter32", "Bits", "Integer32", "TimeTicks", "Counter64", "ModuleIdentity")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
outboundTelnetPrivate = ModuleIdentity((1, 3, 6, 1, 4, 1, 7244, 2, 19))
if mibBuilder.loadTexts: outboundTelnetPrivate.setLastUpdated('201108310000Z')
if mibBuilder.loadTexts: outboundTelnetPrivate.setOrganization('QCI')
if mibBuilder.loadTexts: outboundTelnetPrivate.setContactInfo(' Customer Support Postal: Quanta Computer Inc. 4, Wen Ming 1 St., Kuei Shan Hsiang, Tao Yuan Shien, Taiwan, R.O.C. Tel: +886 3 328 0050 E-Mail: strong.chen@quantatw.com')
if mibBuilder.loadTexts: outboundTelnetPrivate.setDescription('The QCI Private MIB for Outbound Telnet')
agentOutboundTelnetGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 7244, 2, 19, 1))
agentOutboundTelnetAdminMode = MibScalar((1, 3, 6, 1, 4, 1, 7244, 2, 19, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone('enable')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: agentOutboundTelnetAdminMode.setStatus('current')
if mibBuilder.loadTexts: agentOutboundTelnetAdminMode.setDescription(' Admin-mode of the Outbound Telnet.')
agentOutboundTelnetMaxNoOfSessions = MibScalar((1, 3, 6, 1, 4, 1, 7244, 2, 19, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 5)).clone(5)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: agentOutboundTelnetMaxNoOfSessions.setStatus('current')
if mibBuilder.loadTexts: agentOutboundTelnetMaxNoOfSessions.setDescription(' The maximum no. of Outbound Telnet sessions allowed.')
agentOutboundTelnetTimeout = MibScalar((1, 3, 6, 1, 4, 1, 7244, 2, 19, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 160)).clone(5)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: agentOutboundTelnetTimeout.setStatus('current')
if mibBuilder.loadTexts: agentOutboundTelnetTimeout.setDescription(' The login inactivity timeout value for Outbound Telnet.')
mibBuilder.exportSymbols("OUTBOUNDTELNET-PRIVATE-MIB", outboundTelnetPrivate=outboundTelnetPrivate, agentOutboundTelnetAdminMode=agentOutboundTelnetAdminMode, agentOutboundTelnetTimeout=agentOutboundTelnetTimeout, agentOutboundTelnetGroup=agentOutboundTelnetGroup, agentOutboundTelnetMaxNoOfSessions=agentOutboundTelnetMaxNoOfSessions, PYSNMP_MODULE_ID=outboundTelnetPrivate)
|
# automatically generated by the FlatBuffers compiler, do not modify
# namespace: FBOutput
class PassMask(object):
_img = 1
_id = 2
_category = 4
_mask = 8
_depth = 16
_normals = 32
_flow = 64
|
class Config():
def __init__(self):
self.api_token = None
self.module_name = None
self.port = None
self.enable_2fa = None
self.creds = None
self.seen = set()
self.verbose = False
|
board=[" "]*9
def draw_board(board):
print("|----|----|----|")
print("| | | |")
print("| "+board[0]+"| "+board[1]+" | "+board[2]+" |")
print("| | | |")
print("|----|----|----|")
print("| | | |")
print("| "+board[3]+"| "+board[4]+" | "+board[5]+" |")
print("| | | |")
print("|----|----|----|")
print("| | | |")
print("| "+board[6]+"| "+board[7]+" | "+board[8]+" |")
print("| | | |")
print("|----|----|----|")
def check_win(player_mark,board):
return(
(board[0]==board[1]==board[2]==player_mark) or
(board[3]==board[4]==board[5]==player_mark) or
(board[6]==board[7]==board[8]==player_mark) or
(board[0]==board[3]==board[6]==player_mark) or
(board[1]==board[4]==board[7]==player_mark) or
(board[2]==board[5]==board[8]==player_mark) or
(board[0]==board[4]==board[8]==player_mark) or
(board[6]==board[4]==board[2]==player_mark)
)
def check_draw(board):
return " " not in board
def duplicate_board(board):
dup=[]
for j in board:
dup.append(j)
return dup
def test_win_move(board,player_mark,move):
bcopy=duplicate_board(board)
bcopy[move]=player_mark
return check_win(player_mark,bcopy)
def win_strategy(board):
#If no place is there to win
#then it comes here
#Usually person wins by playing
#in the corners
for i in [0,8,2,6]:
if board[i]==" ":
return i
#next best chance is in the middle
if board[4]== " ":
return 4
for i in [1,3,5,7]:
if board[i]==" ":
return i
def fork_move(board, player_mark, move):
#checking ahead in time if that position
#can cause a fork move
bcopy=duplicate_board(board)
bcopy[move]=player_mark
#If winning moves that is,
#The player or agent plays in that position
# 2 places in which he can play to win
winning_moves=0
for i in range(0,9):
if bcopy[i]==" " and test_win_move(bcopy,player_mark,i):
winning_moves+=1
return winning_moves>=2
def get_agent_move(board):
#Return agent move
#If there exist a move which will make the agent win
for i in range(0,9):
if board[i]== " " and test_win_move(board,'X',i):
return i
#Return player win move
#Blocks the player from winning
for i in range(0,9):
if board[i]== " " and test_win_move(board,"O",i):
return i
#Return position of fork move
#Agent to try and make a fork move
for i in range(0,9):
if board[i]== " " and fork_move(board,"X",i):
return i
#Return position of fork move
#To block the player from making a fork move
for i in range(0,9):
if board[i]== " " and fork_move(board,"O",i):
return i
#if none of these positions are available
#then return the best postion to place the agent move
return win_strategy(board)
def tic_tac_toe():
Playing=True
while Playing:
InGame=True
board=[" "]*9
#X is fixed as agent marker
#O is fixed as player marker
player_mark="X"
print("Playing 1st or 2nd??(Enter 1 or 2)")
pref=input()
if pref=="1":
player_mark="O"
while InGame:
if player_mark=="O":
print("Player's turn")
move=int(input())
if board[move]!=" ":
print("Invalid move")
continue
else:
move=get_agent_move(board)
board[move]=player_mark
if check_win(player_mark,board):
InGame= False
draw_board(board)
if player_mark=="X":
print("Agent wins")
else:
print("Player wins")
continue
if check_draw(board):
InGame=False
draw_board(board)
print("Its a draw")
continue
draw_board(board)
if player_mark=="O":
player_mark="X"
else:
player_mark="O"
print("Do you want to continue playing??(Y or N)")
inp=input()
if inp!= "Y" or inp!="y":
Playing=False
tic_tac_toe()
|
"""
Script testing 3.4.1 control from OWASP ASVS 4.0:
'Verify that cookie-based session tokens have the 'Secure' attribute set.'
The script will raise an alert if 'Secure' attribute is not present.
"""
def scan(ps, msg, src):
#find "Set-Cookie" header
headerCookie = str(msg.getResponseHeader().getHeader("Set-Cookie"))
#alert parameters
alertRisk= 1
alertConfidence = 2
alertTitle = "3.4.1 Verify that cookie-based session tokens have the 'Secure' attribute set."
alertDescription = "The secure attribute is an option that can be set by the application server when sending a new cookie to the user within an HTTP Response. The purpose of the secure attribute is to prevent cookies from being observed by unauthorized parties due to the transmission of the cookie in clear text. To accomplish this goal, browsers which support the secure attribute will only send cookies with the secure attribute when the request is going to an HTTPS page. Said in another way, the browser will not send a cookie with the secure attribute set over an unencrypted HTTP request. By setting the secure attribute, the browser will prevent the transmission of a cookie over an unencrypted channel."
url = msg.getRequestHeader().getURI().toString()
alertParam = ""
alertAttack = ""
alertInfo = "https://owasp.org/www-community/controls/SecureCookieAttribute"
alertSolution = "Add 'Secure' attribute when sending cookie."
alertEvidence = ""
cweID = 614
wascID = 0
#if "Set-Cookie" header does not have "secure" attribute, raise alert
if ((headerCookie != "None") and "secure" not in headerCookie.lower()):
ps.raiseAlert(alertRisk, alertConfidence, alertTitle, alertDescription,
url, alertParam, alertAttack, alertInfo, alertSolution, alertEvidence, cweID, wascID, msg);
|
__example_payload__ = "AND 1=1"
__type__ = "putting the payload in-between a comment with obfuscation in it"
def tamper(payload, **kwargs):
return "/*!00000{}*/".format(payload)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.