content
stringlengths 7
1.05M
| fixed_cases
stringlengths 1
1.28M
|
|---|---|
# coding=utf-8
"""
Manages a UDP socket and does two things:
1. Retrieve incoming messages from DCS and update :py:class:`esst.core.status.status`
2. Sends command to the DCS application via the socket
"""
|
"""
Manages a UDP socket and does two things:
1. Retrieve incoming messages from DCS and update :py:class:`esst.core.status.status`
2. Sends command to the DCS application via the socket
"""
|
'''
Find missing no. in array.
'''
def missingNo(arr):
n = len(arr)
sumOfArr = 0
for num in range(0,n):
sumOfArr = sumOfArr + arr[num]
sumOfNno = (n * (n+1)) // 2
missNumber = sumOfNno - sumOfArr
print(missNumber)
arr = [3,0,1]
missingNo(arr)
|
"""
Find missing no. in array.
"""
def missing_no(arr):
n = len(arr)
sum_of_arr = 0
for num in range(0, n):
sum_of_arr = sumOfArr + arr[num]
sum_of_nno = n * (n + 1) // 2
miss_number = sumOfNno - sumOfArr
print(missNumber)
arr = [3, 0, 1]
missing_no(arr)
|
a = "python"
b = "is"
c = "excellent"
d = a[0] + c[0] + a[len(a)-1] + b
print(d)
|
a = 'python'
b = 'is'
c = 'excellent'
d = a[0] + c[0] + a[len(a) - 1] + b
print(d)
|
# weekdays buttons
WEEKDAY_BUTTON = 'timetable_%(weekday)s_button'
TIMETABLE_BUTTON = 'timetable_%(attendance)s_%(week_parity)s_%(weekday)s_button'
# parameters buttons
NAME = 'name_button'
MAILING = 'mailing_parameters_button'
ATTENDANCE = 'attendance_button'
COURSES = 'courses_parameters_button'
PARAMETERS_RETURN = 'return_parameters_button'
EXIT_PARAMETERS = 'exit_parameters_button'
MAIN_SET = {NAME, MAILING, COURSES, ATTENDANCE, PARAMETERS_RETURN}
# attendance buttons
ATTENDANCE_ONLINE = 'online_attendance_button'
ATTENDANCE_OFFLINE = 'offline_attendance_button'
ATTENDANCE_BOTH = 'both_attendance_button'
ATTENDANCE_SET = {ATTENDANCE_BOTH, ATTENDANCE_OFFLINE, ATTENDANCE_ONLINE}
# everyday message buttons
ALLOW_MAILING = 'allowed_mailing_button'
FORBID_MAILING = 'forbidden_mailing_button'
ENABLE_MAILING_NOTIFICATIONS = 'enabled_notification_mailing_button'
DISABLE_MAILING_NOTIFICATIONS = 'disabled_notification_mailing_button'
TZINFO = 'tz_info_button'
MESSAGE_TIME = 'message_time_button'
MAILING_SET = {ALLOW_MAILING, FORBID_MAILING, ENABLE_MAILING_NOTIFICATIONS, DISABLE_MAILING_NOTIFICATIONS,
MESSAGE_TIME, TZINFO}
# courses buttons
OS_TYPE = 'os_type_button'
SP_TYPE = 'sp_type_button'
ENG_GROUP = 'eng_group_button'
HISTORY_GROUP = 'history_group_button'
COURSES_RETURN = 'return_courses_button'
COURSES_SET = {OS_TYPE, SP_TYPE, HISTORY_GROUP, ENG_GROUP, COURSES_RETURN}
# os buttons
OS_ADV = 'os_adv_button'
OS_LITE = 'os_lite_button'
OS_ALL = 'os_all_button'
OS_SET = {OS_ADV, OS_LITE, OS_ALL}
# sp buttons
SP_KOTLIN = 'sp_kotlin_button'
SP_IOS = 'sp_ios_button'
SP_ANDROID = 'sp_android_button'
SP_WEB = 'sp_web_button'
SP_CPP = 'sp_cpp_button'
SP_ALL = 'sp_all_button'
SP_SET = {SP_CPP, SP_IOS, SP_WEB, SP_KOTLIN, SP_ANDROID, SP_ALL}
# eng buttons
ENG_C2_1 = 'eng_c2_1_button'
ENG_C2_2 = 'eng_c2_2_button'
ENG_C2_3 = 'eng_c2_3_button'
ENG_C1_1 = 'eng_c1_1_button'
ENG_C1_2 = 'eng_c1_2_button'
ENG_B2_1 = 'eng_b2_1_button'
ENG_B2_2 = 'eng_b2_2_button'
ENG_B2_3 = 'eng_b2_3_button'
ENG_B11_1 = 'eng_b11_1_button'
ENG_B11_2 = 'eng_b11_2_button'
ENG_B12_1 = 'eng_b12_1_button'
ENG_B12_2 = 'eng_b12_2_button'
ENG_ALL = 'eng_all_button'
ENG_NEXT = 'eng_next_button'
ENG_PREV = 'eng_prev_button'
ENG_SET = {ENG_C2_1, ENG_C2_3, ENG_C1_1, ENG_C1_2, ENG_B2_1, ENG_B2_2, ENG_B2_3, ENG_C2_2, ENG_B11_1, ENG_B11_2,
ENG_B12_1, ENG_B12_2, ENG_ALL, ENG_NEXT, ENG_PREV}
# history buttons
HISTORY_INTERNATIONAL = 'history_international_button'
HISTORY_SCIENCE = 'history_science_button'
HISTORY_EU_PROBLEMS = 'history_eu_problems_button'
HISTORY_CULTURE = 'history_culture_button'
HISTORY_REFORMS = 'history_reforms_button'
HISTORY_STATEHOOD = 'history_statehood_button'
HISTORY_ALL = 'history_all_button'
HISTORY_SET = {HISTORY_CULTURE, HISTORY_EU_PROBLEMS, HISTORY_INTERNATIONAL, HISTORY_REFORMS, HISTORY_SCIENCE,
HISTORY_STATEHOOD, HISTORY_ALL}
def is_course_update(button):
return button in HISTORY_SET or button in ENG_SET or button in OS_SET or button in SP_SET
# SUBJECTS change page
SUBJECT = 'subject_%(subject)s_%(attendance)s_%(page)s_button'
# HELP change page
HELP_MAIN = 'help_main_button'
HELP_ADDITIONAL = 'help_additional_button'
# other
CANCEL = 'cancel_button'
CANCEL_CALLBACK = 'cancel_%(data)s_button'
# admin ls button
ADMIN_LS = 'admin_ls_%(page_number)d_button'
NEXT_PAGE = 'admin_ls_next_button'
PREV_PAGE = 'admin_ls_prev_button'
UPDATE_PAGE = 'admin_ls_update_button'
DEADLINE = 'deadline_%(day_id)s_button'
|
weekday_button = 'timetable_%(weekday)s_button'
timetable_button = 'timetable_%(attendance)s_%(week_parity)s_%(weekday)s_button'
name = 'name_button'
mailing = 'mailing_parameters_button'
attendance = 'attendance_button'
courses = 'courses_parameters_button'
parameters_return = 'return_parameters_button'
exit_parameters = 'exit_parameters_button'
main_set = {NAME, MAILING, COURSES, ATTENDANCE, PARAMETERS_RETURN}
attendance_online = 'online_attendance_button'
attendance_offline = 'offline_attendance_button'
attendance_both = 'both_attendance_button'
attendance_set = {ATTENDANCE_BOTH, ATTENDANCE_OFFLINE, ATTENDANCE_ONLINE}
allow_mailing = 'allowed_mailing_button'
forbid_mailing = 'forbidden_mailing_button'
enable_mailing_notifications = 'enabled_notification_mailing_button'
disable_mailing_notifications = 'disabled_notification_mailing_button'
tzinfo = 'tz_info_button'
message_time = 'message_time_button'
mailing_set = {ALLOW_MAILING, FORBID_MAILING, ENABLE_MAILING_NOTIFICATIONS, DISABLE_MAILING_NOTIFICATIONS, MESSAGE_TIME, TZINFO}
os_type = 'os_type_button'
sp_type = 'sp_type_button'
eng_group = 'eng_group_button'
history_group = 'history_group_button'
courses_return = 'return_courses_button'
courses_set = {OS_TYPE, SP_TYPE, HISTORY_GROUP, ENG_GROUP, COURSES_RETURN}
os_adv = 'os_adv_button'
os_lite = 'os_lite_button'
os_all = 'os_all_button'
os_set = {OS_ADV, OS_LITE, OS_ALL}
sp_kotlin = 'sp_kotlin_button'
sp_ios = 'sp_ios_button'
sp_android = 'sp_android_button'
sp_web = 'sp_web_button'
sp_cpp = 'sp_cpp_button'
sp_all = 'sp_all_button'
sp_set = {SP_CPP, SP_IOS, SP_WEB, SP_KOTLIN, SP_ANDROID, SP_ALL}
eng_c2_1 = 'eng_c2_1_button'
eng_c2_2 = 'eng_c2_2_button'
eng_c2_3 = 'eng_c2_3_button'
eng_c1_1 = 'eng_c1_1_button'
eng_c1_2 = 'eng_c1_2_button'
eng_b2_1 = 'eng_b2_1_button'
eng_b2_2 = 'eng_b2_2_button'
eng_b2_3 = 'eng_b2_3_button'
eng_b11_1 = 'eng_b11_1_button'
eng_b11_2 = 'eng_b11_2_button'
eng_b12_1 = 'eng_b12_1_button'
eng_b12_2 = 'eng_b12_2_button'
eng_all = 'eng_all_button'
eng_next = 'eng_next_button'
eng_prev = 'eng_prev_button'
eng_set = {ENG_C2_1, ENG_C2_3, ENG_C1_1, ENG_C1_2, ENG_B2_1, ENG_B2_2, ENG_B2_3, ENG_C2_2, ENG_B11_1, ENG_B11_2, ENG_B12_1, ENG_B12_2, ENG_ALL, ENG_NEXT, ENG_PREV}
history_international = 'history_international_button'
history_science = 'history_science_button'
history_eu_problems = 'history_eu_problems_button'
history_culture = 'history_culture_button'
history_reforms = 'history_reforms_button'
history_statehood = 'history_statehood_button'
history_all = 'history_all_button'
history_set = {HISTORY_CULTURE, HISTORY_EU_PROBLEMS, HISTORY_INTERNATIONAL, HISTORY_REFORMS, HISTORY_SCIENCE, HISTORY_STATEHOOD, HISTORY_ALL}
def is_course_update(button):
return button in HISTORY_SET or button in ENG_SET or button in OS_SET or (button in SP_SET)
subject = 'subject_%(subject)s_%(attendance)s_%(page)s_button'
help_main = 'help_main_button'
help_additional = 'help_additional_button'
cancel = 'cancel_button'
cancel_callback = 'cancel_%(data)s_button'
admin_ls = 'admin_ls_%(page_number)d_button'
next_page = 'admin_ls_next_button'
prev_page = 'admin_ls_prev_button'
update_page = 'admin_ls_update_button'
deadline = 'deadline_%(day_id)s_button'
|
class SearchParams(object):
def __init__(self):
self.maxTweets = 0
def set_username(self, username):
self.username = username
return self
def set_since(self, since):
self.since = since
return self
def set_until(self, until):
self.until = until
return self
def set_search(self, query_search):
self.querySearch = query_search
return self
def set_max_tweets(self, max_tweets):
self.maxTweets = max_tweets
return self
def set_lang(self, lang):
self.lang = lang
return self
|
class Searchparams(object):
def __init__(self):
self.maxTweets = 0
def set_username(self, username):
self.username = username
return self
def set_since(self, since):
self.since = since
return self
def set_until(self, until):
self.until = until
return self
def set_search(self, query_search):
self.querySearch = query_search
return self
def set_max_tweets(self, max_tweets):
self.maxTweets = max_tweets
return self
def set_lang(self, lang):
self.lang = lang
return self
|
x = int(input("Please enter any number!"))
if x >= 0:
print( "Positive")
else:
print( "Negative")
|
x = int(input('Please enter any number!'))
if x >= 0:
print('Positive')
else:
print('Negative')
|
# IF
# In this program, we check if the number is positive or negative or zero and
# display an appropriate message
# Flow Control
x=7
if x>10:
print("x is big.")
elif x > 0:
print("x is small.")
else:
print("x is not positive.")
# Array
# Variabel array
genap = [14,24,56,80]
ganjil = [13,55,73,23]
nap = 0
jil = 0
# Buat looping for menggunakanvariable dari array yang udah dibuat
for val in genap:
nap = nap+val
for val in ganjil:
jil = jil+val
print("Ini adalah bilangan Genap", nap )
print("Ini adalah bilangan Ganjil", jil )
|
x = 7
if x > 10:
print('x is big.')
elif x > 0:
print('x is small.')
else:
print('x is not positive.')
genap = [14, 24, 56, 80]
ganjil = [13, 55, 73, 23]
nap = 0
jil = 0
for val in genap:
nap = nap + val
for val in ganjil:
jil = jil + val
print('Ini adalah bilangan Genap', nap)
print('Ini adalah bilangan Ganjil', jil)
|
# Remember that everything in python is
# pass by reference
if __name__ == '__main__':
a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
print('First four: ', a[:4]) # same as a[0:4]
# -ve list index starts at position 1
print('Last four: ', a[-4:])
print('Middle two: ', a[3:-3])
# when used in assignments, lists will grow/shrink to accomodate the new
# values
# remember a[x:y] is index x inclusive, y not inclusive
print('Before : ', a) # ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
# list items from index 2:7 will shrink to fit 3 items
a[2:7] = [99, 22, 14]
print('After : ', a) # ['a', 'b', 99, 22, 14, 'h']
# same applies to assignment of a slice with no start/end index
# if you leave out the start/end index in a slice
# you create a copy of the list
b = a[:]
assert b is not a
# but if we were to assign b to a
# a and b are references to the same object
b = a
a[:] = [100, 101, 102]
assert a is b # still the same object
print('Second assignment : ', a) # ['a', 'b', 99, 22, 14, 'h']
|
if __name__ == '__main__':
a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
print('First four: ', a[:4])
print('Last four: ', a[-4:])
print('Middle two: ', a[3:-3])
print('Before : ', a)
a[2:7] = [99, 22, 14]
print('After : ', a)
b = a[:]
assert b is not a
b = a
a[:] = [100, 101, 102]
assert a is b
print('Second assignment : ', a)
|
## This script contains useful functions to generate a html page given a
## blog post txt file. It also creates meta data for the blog posts to be
## used to make summaries.
## Input should be a txt file of specific format
def read_file(infile):
metadata = []
post = []
with open(infile, 'r') as f:
for line in f:
if line[0] == '#':
metadata.append(line.strip('\n'))
else:
post.append(line)
return {'metadata':metadata, 'post':post}
def get_title(metadata):
title = filter(lambda x: '##title' in x, metadata)
title = title[0][8: len(title[0])]
return title
def get_subtitle(metadata):
subtitle = filter(lambda x: '##subtitle' in x, metadata)
subtitle = subtitle[0][11: len(subtitle[0])]
return subtitle
def get_author(metadata):
author = filter(lambda x: '##author' in x, metadata)
author = author[0][9: len(author[0])]
return author
def get_date(metadata):
date = filter(lambda x: '##date' in x, metadata)
date = date[0][7: len(date[0])]
return date
def get_topic(metadata):
topic = filter(lambda x: '##topic' in x, metadata)
topic = topic[0][8: len(topic[0])]
return topic
def modify_template(file_to_modify, string2find, replace_value, outfile):
# Read in the file
with open(file_to_modify, 'r') as file:
filedata = file.read()
# Replace the target string
for i in range(len(string2find)):
filedata = filedata.replace(string2find[i], str(replace_value[i]))
# Write the file out
with open(outfile, 'w') as file:
file.write(filedata)
|
def read_file(infile):
metadata = []
post = []
with open(infile, 'r') as f:
for line in f:
if line[0] == '#':
metadata.append(line.strip('\n'))
else:
post.append(line)
return {'metadata': metadata, 'post': post}
def get_title(metadata):
title = filter(lambda x: '##title' in x, metadata)
title = title[0][8:len(title[0])]
return title
def get_subtitle(metadata):
subtitle = filter(lambda x: '##subtitle' in x, metadata)
subtitle = subtitle[0][11:len(subtitle[0])]
return subtitle
def get_author(metadata):
author = filter(lambda x: '##author' in x, metadata)
author = author[0][9:len(author[0])]
return author
def get_date(metadata):
date = filter(lambda x: '##date' in x, metadata)
date = date[0][7:len(date[0])]
return date
def get_topic(metadata):
topic = filter(lambda x: '##topic' in x, metadata)
topic = topic[0][8:len(topic[0])]
return topic
def modify_template(file_to_modify, string2find, replace_value, outfile):
with open(file_to_modify, 'r') as file:
filedata = file.read()
for i in range(len(string2find)):
filedata = filedata.replace(string2find[i], str(replace_value[i]))
with open(outfile, 'w') as file:
file.write(filedata)
|
#!/usr/bin/env python
"""
check out chapter 2 of cam
"""
|
"""
check out chapter 2 of cam
"""
|
#!/usr/bin/env python3
#chmod +x hello.py
#It will insert space and newline in preset
print ("Hello", "World!")
|
print('Hello', 'World!')
|
"""Django Asana integration project"""
# :copyright: (c) 2017-2021 by Stephen Bywater.
# :license: MIT, see LICENSE for more details.
VERSION = (1, 4, 8)
__version__ = '.'.join(map(str, VERSION[0:3])) + ''.join(VERSION[3:])
__author__ = 'Steve Bywater'
__contact__ = 'steve@regionalhelpwanted.com'
__homepage__ = 'https://github.com/sbywater/django-asana'
__docformat__ = 'restructuredtext'
__license__ = 'MIT'
# -eof meta-
default_app_config = 'djasana.apps.DjsanaConfig'
|
"""Django Asana integration project"""
version = (1, 4, 8)
__version__ = '.'.join(map(str, VERSION[0:3])) + ''.join(VERSION[3:])
__author__ = 'Steve Bywater'
__contact__ = 'steve@regionalhelpwanted.com'
__homepage__ = 'https://github.com/sbywater/django-asana'
__docformat__ = 'restructuredtext'
__license__ = 'MIT'
default_app_config = 'djasana.apps.DjsanaConfig'
|
def final_pos():
x = y = 0
with open("input.txt") as inp:
while True:
instr = inp.readline()
try:
cmd, val = instr.split()
except ValueError:
break
else:
if cmd == "forward":
x += int(val)
elif cmd == "down":
y += int(val)
elif cmd == "up":
y -= int(val)
print(f"Final Val: {x * y}")
if __name__ == '__main__':
final_pos()
|
def final_pos():
x = y = 0
with open('input.txt') as inp:
while True:
instr = inp.readline()
try:
(cmd, val) = instr.split()
except ValueError:
break
else:
if cmd == 'forward':
x += int(val)
elif cmd == 'down':
y += int(val)
elif cmd == 'up':
y -= int(val)
print(f'Final Val: {x * y}')
if __name__ == '__main__':
final_pos()
|
class zoo:
def __init__(self,stock,cuidadores,animales):
pass
class cuidador:
def __init__(self,animales,vacaciones):
pass
class animal:
def __init__(self,dieta):
pass
class vacaciones:
def __init__(self):
pass
class comida:
def __init__(self,dieta):
pass
class stock:
def __init__(self,comida):
pass
class carnivoros:
def __init__(self):
pass
class herbivoros:
def __init__(self):
pass
class insectivoros:
def __init__(self):
pass
print("puerca")
|
class Zoo:
def __init__(self, stock, cuidadores, animales):
pass
class Cuidador:
def __init__(self, animales, vacaciones):
pass
class Animal:
def __init__(self, dieta):
pass
class Vacaciones:
def __init__(self):
pass
class Comida:
def __init__(self, dieta):
pass
class Stock:
def __init__(self, comida):
pass
class Carnivoros:
def __init__(self):
pass
class Herbivoros:
def __init__(self):
pass
class Insectivoros:
def __init__(self):
pass
print('puerca')
|
PROLOGUE = '''module smcauth(clk, rst, g_input, e_input, o);
input clk;
input [255:0] e_input;
input [255:0] g_input;
output o;
input rst;
'''
EPILOGUE = 'endmodule\n'
OR_CIRCUIT = '''
OR {} (
.A({}),
.B({}),
.Z({})
);
'''
AND_CIRCUIT = '''
ANDN {} (
.A({}),
.B({}),
.Z({})
);
'''
XOR_CIRCUIT = '''
XOR {} (
.A({}),
.B({}),
.Z({})
);
'''
circuit_counter = 0
wire_counter = 0
def circuit():
global circuit_counter
circuit_counter += 1
return 'C%d' % circuit_counter
def wire():
global wire_counter
wire_counter += 1
return 'W%d' % wire_counter
def new_circuit(circuit_template, in1, in2, out=None):
global payload
if out is None:
out = wire()
payload += circuit_template.format(
circuit(),
in1,
in2,
out
)
return out
payload = ''
now = new_circuit(XOR_CIRCUIT, 'g_input[0]', 'e_input[0]')
for i in range(1, 255):
now = new_circuit(XOR_CIRCUIT, 'g_input[%d]' % i, now)
now = new_circuit(XOR_CIRCUIT, 'e_input[%d]' % i, now)
now = new_circuit(XOR_CIRCUIT, 'g_input[255]', now)
now = new_circuit(XOR_CIRCUIT, 'e_input[255]', now, 'o')
payload += EPILOGUE
wires = ''
for i in range(1, wire_counter+1):
wires += ' wire W%d;\n' % i
payload = PROLOGUE + wires + payload
with open('test.v', 'w') as f:
f.write(payload)
|
prologue = 'module smcauth(clk, rst, g_input, e_input, o);\n input clk;\n input [255:0] e_input;\n input [255:0] g_input;\n output o;\n input rst;\n'
epilogue = 'endmodule\n'
or_circuit = '\n OR {} (\n .A({}),\n .B({}),\n .Z({})\n );\n'
and_circuit = '\n ANDN {} (\n .A({}),\n .B({}),\n .Z({})\n );\n'
xor_circuit = '\n XOR {} (\n .A({}),\n .B({}),\n .Z({})\n );\n'
circuit_counter = 0
wire_counter = 0
def circuit():
global circuit_counter
circuit_counter += 1
return 'C%d' % circuit_counter
def wire():
global wire_counter
wire_counter += 1
return 'W%d' % wire_counter
def new_circuit(circuit_template, in1, in2, out=None):
global payload
if out is None:
out = wire()
payload += circuit_template.format(circuit(), in1, in2, out)
return out
payload = ''
now = new_circuit(XOR_CIRCUIT, 'g_input[0]', 'e_input[0]')
for i in range(1, 255):
now = new_circuit(XOR_CIRCUIT, 'g_input[%d]' % i, now)
now = new_circuit(XOR_CIRCUIT, 'e_input[%d]' % i, now)
now = new_circuit(XOR_CIRCUIT, 'g_input[255]', now)
now = new_circuit(XOR_CIRCUIT, 'e_input[255]', now, 'o')
payload += EPILOGUE
wires = ''
for i in range(1, wire_counter + 1):
wires += ' wire W%d;\n' % i
payload = PROLOGUE + wires + payload
with open('test.v', 'w') as f:
f.write(payload)
|
SINGLE_MATCHING_ITEM = """
<rss version="2.0">
<channel>
<item>
<title>testshow S02E03 720p</title>
<link>testlink</link>
</item>
</channel>
</rss>
"""
SINGLE_ITEM_CAPITALISATION = """
<rss version="2.0">
<channel>
<item>
<title>TestShow S02E03 720p</title>
<link>testlink</link>
</item>
</channel>
</rss>
"""
SINGLE_ITEM_SPECIAL_CHARS = """
<rss version="2.0">
<channel>
<item>
<title>Mr Robot S02E03 720p</title>
<link>testlink</link>
</item>
</channel>
</rss>
"""
MULTIPLE_MATCHING_ITEMS = """
<rss version="2.0">
<channel>
<item>
<title>testshow S02E03 720p</title>
<link>testlink</link>
</item>
<item>
<title>testshow S2E3 1080i</title>
<link>testlink</link>
</item>
<item>
<title>testshow 02x03 720i</title>
<link>testlink</link>
</item>
</channel>
</rss>
"""
SINGLE_ITEM_LOW_QUALITY = """
<rss version="2.0">
<channel>
<item>
<title>testshow S02E03 480p</title>
<link>testlink</link>
</item>
</channel>
</rss>
"""
|
single_matching_item = '\n<rss version="2.0">\n <channel>\n <item>\n <title>testshow S02E03 720p</title>\n <link>testlink</link>\n </item>\n </channel>\n</rss>\n'
single_item_capitalisation = '\n<rss version="2.0">\n <channel>\n <item>\n <title>TestShow S02E03 720p</title>\n <link>testlink</link>\n </item>\n </channel>\n</rss>\n'
single_item_special_chars = '\n<rss version="2.0">\n <channel>\n <item>\n <title>Mr Robot S02E03 720p</title>\n <link>testlink</link>\n </item>\n </channel>\n</rss>\n'
multiple_matching_items = '\n<rss version="2.0">\n <channel>\n <item>\n <title>testshow S02E03 720p</title>\n <link>testlink</link>\n </item>\n <item>\n <title>testshow S2E3 1080i</title>\n <link>testlink</link>\n </item>\n <item>\n <title>testshow 02x03 720i</title>\n <link>testlink</link>\n </item>\n </channel>\n</rss>\n'
single_item_low_quality = '\n<rss version="2.0">\n <channel>\n <item>\n <title>testshow S02E03 480p</title>\n <link>testlink</link>\n </item>\n </channel>\n</rss>\n'
|
"""
Loop control version 1.1.10.20
Copyright (c) 2020 Shahibur Rahaman
Licensed under MIT
"""
# Pass
# Continue
# break
# A runner is practicing in a stadium and the coach is giving orders.
t = 180
for i in range(t, 1, -1):
t = t - 5
if t > 150:
print("Time:", t, "| Do another lap.")
continue
if t > 120:
print("Time:", t, "| You are improving your laptime!")
pass
if t < 105:
print("Time:", t, "| Excellent, you have beaten the best runner's record!")
break
print("")
|
"""
Loop control version 1.1.10.20
Copyright (c) 2020 Shahibur Rahaman
Licensed under MIT
"""
t = 180
for i in range(t, 1, -1):
t = t - 5
if t > 150:
print('Time:', t, '| Do another lap.')
continue
if t > 120:
print('Time:', t, '| You are improving your laptime!')
pass
if t < 105:
print('Time:', t, "| Excellent, you have beaten the best runner's record!")
break
print('')
|
"""
Profile ../profile-datasets-py/div83/040.py
file automaticaly created by prof_gen.py script
"""
self["ID"] = "../profile-datasets-py/div83/040.py"
self["Q"] = numpy.array([ 1.890026, 2.119776, 2.622053, 3.246729,
3.667537, 4.216342, 4.862296, 5.531749,
6.100783, 6.376119, 6.376069, 6.30519 ,
6.187932, 5.998564, 5.778127, 5.603999,
5.44443 , 5.194473, 4.915426, 4.653008,
4.45 , 4.296832, 4.148003, 4.015564,
3.910205, 3.839615, 3.790106, 3.753656,
3.721226, 3.693996, 3.677826, 3.674526,
3.655867, 3.640757, 3.644617, 3.663107,
3.679716, 3.683656, 3.678676, 3.667877,
3.655367, 3.648067, 3.646037, 3.644827,
3.651267, 3.691236, 3.765886, 3.858565,
3.940824, 3.994534, 4.097813, 4.351141,
4.794867, 5.49314 , 6.497828, 8.015136,
10.60419 , 15.81985 , 21.16895 , 24.30741 ,
23.60504 , 24.79699 , 27.87162 , 33.67817 ,
42.22522 , 52.68792 , 65.67979 , 82.04257 ,
102.6225 , 116.7384 , 124.9514 , 131.6637 ,
137.0252 , 130.226 , 119.7127 , 105.9718 ,
104.862 , 125.6962 , 167.5619 , 234.0722 ,
297.3785 , 359.7445 , 423.0569 , 497.9349 ,
552.8482 , 569.9959 , 545.77 , 535.4481 ,
711.82 , 1148.918 , 1499.767 , 1580.109 ,
1531.92 , 1436.304 , 1228.928 , 1011.186 ,
845.8809 , 853.3132 , 830.1563 , 807.9197 , 786.5588 ])
self["P"] = numpy.array([ 5.00000000e-03, 1.61000000e-02, 3.84000000e-02,
7.69000000e-02, 1.37000000e-01, 2.24400000e-01,
3.45400000e-01, 5.06400000e-01, 7.14000000e-01,
9.75300000e-01, 1.29720000e+00, 1.68720000e+00,
2.15260000e+00, 2.70090000e+00, 3.33980000e+00,
4.07700000e+00, 4.92040000e+00, 5.87760000e+00,
6.95670000e+00, 8.16550000e+00, 9.51190000e+00,
1.10038000e+01, 1.26492000e+01, 1.44559000e+01,
1.64318000e+01, 1.85847000e+01, 2.09224000e+01,
2.34526000e+01, 2.61829000e+01, 2.91210000e+01,
3.22744000e+01, 3.56505000e+01, 3.92566000e+01,
4.31001000e+01, 4.71882000e+01, 5.15278000e+01,
5.61260000e+01, 6.09895000e+01, 6.61253000e+01,
7.15398000e+01, 7.72396000e+01, 8.32310000e+01,
8.95204000e+01, 9.61138000e+01, 1.03017000e+02,
1.10237000e+02, 1.17778000e+02, 1.25646000e+02,
1.33846000e+02, 1.42385000e+02, 1.51266000e+02,
1.60496000e+02, 1.70078000e+02, 1.80018000e+02,
1.90320000e+02, 2.00989000e+02, 2.12028000e+02,
2.23442000e+02, 2.35234000e+02, 2.47408000e+02,
2.59969000e+02, 2.72919000e+02, 2.86262000e+02,
3.00000000e+02, 3.14137000e+02, 3.28675000e+02,
3.43618000e+02, 3.58966000e+02, 3.74724000e+02,
3.90893000e+02, 4.07474000e+02, 4.24470000e+02,
4.41882000e+02, 4.59712000e+02, 4.77961000e+02,
4.96630000e+02, 5.15720000e+02, 5.35232000e+02,
5.55167000e+02, 5.75525000e+02, 5.96306000e+02,
6.17511000e+02, 6.39140000e+02, 6.61192000e+02,
6.83667000e+02, 7.06565000e+02, 7.29886000e+02,
7.53628000e+02, 7.77790000e+02, 8.02371000e+02,
8.27371000e+02, 8.52788000e+02, 8.78620000e+02,
9.04866000e+02, 9.31524000e+02, 9.58591000e+02,
9.86067000e+02, 1.01395000e+03, 1.04223000e+03,
1.07092000e+03, 1.10000000e+03])
self["CO2"] = numpy.array([ 370.8133, 370.8152, 370.819 , 370.8248, 370.8346, 370.8484,
370.8592, 370.8579, 370.8967, 370.9416, 370.9656, 370.9707,
371.0187, 371.0558, 371.0859, 371.1189, 371.164 , 371.2181,
371.2882, 371.3753, 371.4853, 371.5974, 371.7105, 371.8065,
371.8855, 371.9556, 371.9716, 371.9786, 371.9036, 371.8306,
371.8296, 371.8286, 371.9816, 372.1516, 372.3736, 372.6286,
372.8946, 373.1656, 373.4526, 373.8036, 374.1786, 374.5586,
374.9416, 375.3396, 375.6096, 375.8926, 376.1336, 376.3425,
376.5465, 376.6605, 376.7785, 376.8464, 376.8902, 376.9449,
377.0346, 377.128 , 377.324 , 377.549 , 377.852 , 378.2698,
378.7031, 379.2006, 379.7134, 380.1292, 380.5039, 380.8129,
380.989 , 381.1627, 381.2329, 381.3075, 381.3593, 381.4038,
381.4637, 381.5393, 381.6193, 381.7075, 381.794 , 381.882 ,
381.973 , 382.0935, 382.2253, 382.3864, 382.5441, 382.6894,
382.8332, 382.9886, 383.1448, 383.2917, 383.3489, 383.3001,
383.2863, 383.3892, 383.5445, 383.7251, 383.9945, 384.3599,
385.021 , 385.4928, 385.8484, 386.0688, 386.149 ])
self["CO"] = numpy.array([ 5.07834 , 4.978429 , 4.783627 , 4.465066 , 4.009665 ,
3.428986 , 2.1168 , 0.7107151 , 0.3604568 , 0.1722319 ,
0.09253791, 0.06835487, 0.06619429, 0.06226643, 0.05921646,
0.05582889, 0.05210092, 0.04852775, 0.04563088, 0.0435902 ,
0.04266791, 0.04196062, 0.04131023, 0.04063314, 0.03983114,
0.03892895, 0.03783966, 0.03667146, 0.03530527, 0.03391147,
0.03270558, 0.03146188, 0.03095409, 0.03045309, 0.03021789,
0.03010279, 0.03018719, 0.03073179, 0.03131748, 0.03369348,
0.03659667, 0.04005435, 0.04421134, 0.04900962, 0.05320021,
0.05796649, 0.06307856, 0.06862024, 0.07462111, 0.07899018,
0.08380636, 0.08758932, 0.09090566, 0.09480198, 0.1001443 ,
0.1059952 , 0.1139498 , 0.1231891 , 0.1334292 , 0.1447495 ,
0.1573193 , 0.1683598 , 0.180545 , 0.1902606 , 0.1989896 ,
0.2064601 , 0.2107932 , 0.2151723 , 0.2166698 , 0.2182195 ,
0.2193496 , 0.220384 , 0.2215356 , 0.222791 , 0.2240452 ,
0.2252751 , 0.2264323 , 0.2273394 , 0.2281768 , 0.2287195 ,
0.2293438 , 0.2301862 , 0.2313281 , 0.2330089 , 0.234985 ,
0.2372327 , 0.2394283 , 0.2416156 , 0.2436684 , 0.2454167 ,
0.2468103 , 0.2475702 , 0.2474194 , 0.2469778 , 0.2469551 ,
0.2485434 , 0.2532306 , 0.2569715 , 0.255173 , 0.2553855 ,
0.2556078 ])
self["T"] = numpy.array([ 201.756, 208.959, 221.236, 232.895, 242.747, 248.786,
248.329, 240.903, 229.68 , 220.741, 219.585, 222.314,
223.457, 223.196, 222.551, 222.843, 222.789, 222.21 ,
221.367, 220.664, 220.666, 221.42 , 221.862, 221.833,
221.445, 221.116, 221.34 , 221.609, 221.876, 222.239,
222.762, 223.15 , 223.03 , 222.598, 221.894, 221.35 ,
221.172, 221.079, 220.7 , 220.162, 219.576, 219.085,
218.821, 218.548, 218.069, 217.619, 217.047, 216.42 ,
215.951, 215.682, 215.498, 215.293, 215.002, 214.535,
213.791, 212.72 , 211.396, 210.082, 209.266, 208.907,
209.051, 209.749, 211.078, 212.777, 214.68 , 216.699,
218.741, 220.833, 222.97 , 225.147, 227.187, 229.093,
230.856, 232.34 , 233.77 , 235.146, 236.509, 237.94 ,
239.449, 241.132, 242.895, 244.697, 246.497, 248.304,
250.093, 251.797, 253.356, 254.716, 255.748, 256.257,
256.617, 256.449, 255.921, 255.521, 254.315, 252.591,
250.969, 251.339, 251.339, 251.339, 251.339])
self["N2O"] = numpy.array([ 1.59999700e-04, 6.39998600e-04, 9.99997400e-04,
1.28999600e-03, 3.35998800e-03, 3.46998500e-03,
2.00999000e-03, 9.29994900e-04, 7.69995300e-04,
1.55999000e-03, 3.49997800e-03, 4.09997400e-03,
3.60997800e-03, 3.51997900e-03, 3.85997800e-03,
5.33997000e-03, 7.33996000e-03, 1.04899500e-02,
1.34499300e-02, 1.60199300e-02, 1.84799200e-02,
2.20899100e-02, 2.61798900e-02, 3.00898800e-02,
5.58597800e-02, 8.34796800e-02, 1.10069600e-01,
1.41009500e-01, 1.72649400e-01, 2.03189200e-01,
2.29059200e-01, 2.39769100e-01, 2.50139100e-01,
2.60199100e-01, 2.68909000e-01, 2.72829000e-01,
2.76629000e-01, 2.80329000e-01, 2.79099000e-01,
2.77989000e-01, 2.76929000e-01, 2.78389000e-01,
2.81049000e-01, 2.83589000e-01, 2.87389000e-01,
2.91148900e-01, 2.94858900e-01, 2.98488800e-01,
3.01988800e-01, 3.05358800e-01, 3.08538700e-01,
3.11508600e-01, 3.14228500e-01, 3.16658300e-01,
3.18747900e-01, 3.19607400e-01, 3.20386600e-01,
3.21084900e-01, 3.21683200e-01, 3.22162200e-01,
3.22532400e-01, 3.22752000e-01, 3.22831000e-01,
3.22829100e-01, 3.22826400e-01, 3.22823000e-01,
3.22818800e-01, 3.22813500e-01, 3.22806900e-01,
3.22802300e-01, 3.22799700e-01, 3.22797500e-01,
3.22795800e-01, 3.22798000e-01, 3.22801400e-01,
3.22805800e-01, 3.22806100e-01, 3.22799400e-01,
3.22785900e-01, 3.22764400e-01, 3.22744000e-01,
3.22723900e-01, 3.22703400e-01, 3.22679200e-01,
3.22661500e-01, 3.22656000e-01, 3.22663800e-01,
3.22667100e-01, 3.22610200e-01, 3.22469100e-01,
3.22355800e-01, 3.22329900e-01, 3.22345400e-01,
3.22376300e-01, 3.22443300e-01, 3.22513500e-01,
3.22566900e-01, 3.22564500e-01, 3.22572000e-01,
3.22579200e-01, 3.22586100e-01])
self["O3"] = numpy.array([ 0.510174 , 0.5621888 , 0.6514743 , 0.7822175 , 0.9318276 ,
1.063576 , 1.310564 , 1.76503 , 2.535005 , 3.648507 ,
4.547261 , 4.78841 , 4.92361 , 5.275468 , 5.694327 ,
5.762868 , 5.783319 , 5.893709 , 6.03422 , 6.160551 ,
6.228622 , 6.203113 , 6.153684 , 6.089276 , 6.012956 ,
5.923467 , 5.849328 , 5.783048 , 5.734829 , 5.679589 ,
5.574619 , 5.39368 , 5.244621 , 5.120821 , 4.922902 ,
4.727543 , 4.524263 , 4.246424 , 3.923376 , 3.604037 ,
3.319568 , 3.047309 , 2.75112 , 2.482241 , 2.317652 ,
2.148792 , 1.885393 , 1.603124 , 1.397604 , 1.272585 ,
1.146755 , 0.9980887 , 0.8611839 , 0.729153 , 0.5870622 ,
0.4483724 , 0.3575272 , 0.2652448 , 0.1737753 , 0.1178921 ,
0.09092905, 0.07172082, 0.05827958, 0.05142367, 0.04863645,
0.04841805, 0.04816644, 0.04715373, 0.04594748, 0.04495205,
0.0455781 , 0.04686353, 0.04873582, 0.04975662, 0.0501041 ,
0.04979462, 0.04934463, 0.04914342, 0.04915406, 0.04921568,
0.04915478, 0.04893549, 0.04849328, 0.04805416, 0.04794348,
0.04790108, 0.0476205 , 0.04700432, 0.04654844, 0.04632991,
0.04646221, 0.04573811, 0.04403783, 0.04091335, 0.03254705,
0.02640277, 0.02501912, 0.02442054, 0.02442111, 0.02442165,
0.02442218])
self["CH4"] = numpy.array([ 0.04183322, 0.07070085, 0.09215896, 0.1150766 , 0.1600424 ,
0.1895992 , 0.203706 , 0.2216318 , 0.2513385 , 0.2618113 ,
0.2802002 , 0.3011591 , 0.323238 , 0.3478319 , 0.3743778 ,
0.4088557 , 0.4408626 , 0.4700776 , 0.4956766 , 0.5058676 ,
0.5155767 , 0.5382237 , 0.5665796 , 0.5937466 , 0.6694654 ,
0.7486761 , 0.8249039 , 0.9082426 , 0.9919303 , 1.046986 ,
1.106076 , 1.169336 , 1.236905 , 1.290275 , 1.341695 ,
1.390245 , 1.434895 , 1.474525 , 1.496414 , 1.519504 ,
1.543804 , 1.569344 , 1.596164 , 1.637644 , 1.659294 ,
1.681934 , 1.697794 , 1.708283 , 1.718413 , 1.722753 ,
1.727263 , 1.729712 , 1.731132 , 1.7327 , 1.734659 ,
1.736686 , 1.740032 , 1.743762 , 1.748043 , 1.753067 ,
1.758228 , 1.763046 , 1.768011 , 1.77186 , 1.775215 ,
1.778026 , 1.779713 , 1.781404 , 1.782387 , 1.783412 ,
1.784227 , 1.784995 , 1.785885 , 1.786897 , 1.788006 ,
1.78924 , 1.790502 , 1.791825 , 1.793189 , 1.79475 ,
1.796366 , 1.798093 , 1.799748 , 1.801223 , 1.802603 ,
1.803951 , 1.805294 , 1.806622 , 1.807672 , 1.80842 ,
1.809452 , 1.811134 , 1.812978 , 1.815059 , 1.817833 ,
1.821496 , 1.829131 , 1.834953 , 1.839252 , 1.841891 ,
1.842819 ])
self["CTP"] = 500.0
self["CFRACTION"] = 0.0
self["IDG"] = 0
self["ISH"] = 0
self["ELEVATION"] = 0.0
self["S2M"]["T"] = 251.339
self["S2M"]["Q"] = 786.558838187
self["S2M"]["O"] = 0.0244221754008
self["S2M"]["P"] = 1007.16998
self["S2M"]["U"] = 0.0
self["S2M"]["V"] = 0.0
self["S2M"]["WFETC"] = 100000.0
self["SKIN"]["SURFTYPE"] = 1
self["SKIN"]["WATERTYPE"] = 1
self["SKIN"]["T"] = 251.339
self["SKIN"]["SALINITY"] = 35.0
self["SKIN"]["FOAM_FRACTION"] = 0.0
self["SKIN"]["FASTEM"] = numpy.array([ 3. , 5. , 15. , 0.1, 0.3])
self["ZENANGLE"] = 0.0
self["AZANGLE"] = 0.0
self["SUNZENANGLE"] = 0.0
self["SUNAZANGLE"] = 0.0
self["LATITUDE"] = 72.967
self["GAS_UNITS"] = 2
self["BE"] = 0.0
self["COSBK"] = 0.0
self["DATE"] = numpy.array([2007, 1, 20])
self["TIME"] = numpy.array([0, 0, 0])
|
"""
Profile ../profile-datasets-py/div83/040.py
file automaticaly created by prof_gen.py script
"""
self['ID'] = '../profile-datasets-py/div83/040.py'
self['Q'] = numpy.array([1.890026, 2.119776, 2.622053, 3.246729, 3.667537, 4.216342, 4.862296, 5.531749, 6.100783, 6.376119, 6.376069, 6.30519, 6.187932, 5.998564, 5.778127, 5.603999, 5.44443, 5.194473, 4.915426, 4.653008, 4.45, 4.296832, 4.148003, 4.015564, 3.910205, 3.839615, 3.790106, 3.753656, 3.721226, 3.693996, 3.677826, 3.674526, 3.655867, 3.640757, 3.644617, 3.663107, 3.679716, 3.683656, 3.678676, 3.667877, 3.655367, 3.648067, 3.646037, 3.644827, 3.651267, 3.691236, 3.765886, 3.858565, 3.940824, 3.994534, 4.097813, 4.351141, 4.794867, 5.49314, 6.497828, 8.015136, 10.60419, 15.81985, 21.16895, 24.30741, 23.60504, 24.79699, 27.87162, 33.67817, 42.22522, 52.68792, 65.67979, 82.04257, 102.6225, 116.7384, 124.9514, 131.6637, 137.0252, 130.226, 119.7127, 105.9718, 104.862, 125.6962, 167.5619, 234.0722, 297.3785, 359.7445, 423.0569, 497.9349, 552.8482, 569.9959, 545.77, 535.4481, 711.82, 1148.918, 1499.767, 1580.109, 1531.92, 1436.304, 1228.928, 1011.186, 845.8809, 853.3132, 830.1563, 807.9197, 786.5588])
self['P'] = numpy.array([0.005, 0.0161, 0.0384, 0.0769, 0.137, 0.2244, 0.3454, 0.5064, 0.714, 0.9753, 1.2972, 1.6872, 2.1526, 2.7009, 3.3398, 4.077, 4.9204, 5.8776, 6.9567, 8.1655, 9.5119, 11.0038, 12.6492, 14.4559, 16.4318, 18.5847, 20.9224, 23.4526, 26.1829, 29.121, 32.2744, 35.6505, 39.2566, 43.1001, 47.1882, 51.5278, 56.126, 60.9895, 66.1253, 71.5398, 77.2396, 83.231, 89.5204, 96.1138, 103.017, 110.237, 117.778, 125.646, 133.846, 142.385, 151.266, 160.496, 170.078, 180.018, 190.32, 200.989, 212.028, 223.442, 235.234, 247.408, 259.969, 272.919, 286.262, 300.0, 314.137, 328.675, 343.618, 358.966, 374.724, 390.893, 407.474, 424.47, 441.882, 459.712, 477.961, 496.63, 515.72, 535.232, 555.167, 575.525, 596.306, 617.511, 639.14, 661.192, 683.667, 706.565, 729.886, 753.628, 777.79, 802.371, 827.371, 852.788, 878.62, 904.866, 931.524, 958.591, 986.067, 1013.95, 1042.23, 1070.92, 1100.0])
self['CO2'] = numpy.array([370.8133, 370.8152, 370.819, 370.8248, 370.8346, 370.8484, 370.8592, 370.8579, 370.8967, 370.9416, 370.9656, 370.9707, 371.0187, 371.0558, 371.0859, 371.1189, 371.164, 371.2181, 371.2882, 371.3753, 371.4853, 371.5974, 371.7105, 371.8065, 371.8855, 371.9556, 371.9716, 371.9786, 371.9036, 371.8306, 371.8296, 371.8286, 371.9816, 372.1516, 372.3736, 372.6286, 372.8946, 373.1656, 373.4526, 373.8036, 374.1786, 374.5586, 374.9416, 375.3396, 375.6096, 375.8926, 376.1336, 376.3425, 376.5465, 376.6605, 376.7785, 376.8464, 376.8902, 376.9449, 377.0346, 377.128, 377.324, 377.549, 377.852, 378.2698, 378.7031, 379.2006, 379.7134, 380.1292, 380.5039, 380.8129, 380.989, 381.1627, 381.2329, 381.3075, 381.3593, 381.4038, 381.4637, 381.5393, 381.6193, 381.7075, 381.794, 381.882, 381.973, 382.0935, 382.2253, 382.3864, 382.5441, 382.6894, 382.8332, 382.9886, 383.1448, 383.2917, 383.3489, 383.3001, 383.2863, 383.3892, 383.5445, 383.7251, 383.9945, 384.3599, 385.021, 385.4928, 385.8484, 386.0688, 386.149])
self['CO'] = numpy.array([5.07834, 4.978429, 4.783627, 4.465066, 4.009665, 3.428986, 2.1168, 0.7107151, 0.3604568, 0.1722319, 0.09253791, 0.06835487, 0.06619429, 0.06226643, 0.05921646, 0.05582889, 0.05210092, 0.04852775, 0.04563088, 0.0435902, 0.04266791, 0.04196062, 0.04131023, 0.04063314, 0.03983114, 0.03892895, 0.03783966, 0.03667146, 0.03530527, 0.03391147, 0.03270558, 0.03146188, 0.03095409, 0.03045309, 0.03021789, 0.03010279, 0.03018719, 0.03073179, 0.03131748, 0.03369348, 0.03659667, 0.04005435, 0.04421134, 0.04900962, 0.05320021, 0.05796649, 0.06307856, 0.06862024, 0.07462111, 0.07899018, 0.08380636, 0.08758932, 0.09090566, 0.09480198, 0.1001443, 0.1059952, 0.1139498, 0.1231891, 0.1334292, 0.1447495, 0.1573193, 0.1683598, 0.180545, 0.1902606, 0.1989896, 0.2064601, 0.2107932, 0.2151723, 0.2166698, 0.2182195, 0.2193496, 0.220384, 0.2215356, 0.222791, 0.2240452, 0.2252751, 0.2264323, 0.2273394, 0.2281768, 0.2287195, 0.2293438, 0.2301862, 0.2313281, 0.2330089, 0.234985, 0.2372327, 0.2394283, 0.2416156, 0.2436684, 0.2454167, 0.2468103, 0.2475702, 0.2474194, 0.2469778, 0.2469551, 0.2485434, 0.2532306, 0.2569715, 0.255173, 0.2553855, 0.2556078])
self['T'] = numpy.array([201.756, 208.959, 221.236, 232.895, 242.747, 248.786, 248.329, 240.903, 229.68, 220.741, 219.585, 222.314, 223.457, 223.196, 222.551, 222.843, 222.789, 222.21, 221.367, 220.664, 220.666, 221.42, 221.862, 221.833, 221.445, 221.116, 221.34, 221.609, 221.876, 222.239, 222.762, 223.15, 223.03, 222.598, 221.894, 221.35, 221.172, 221.079, 220.7, 220.162, 219.576, 219.085, 218.821, 218.548, 218.069, 217.619, 217.047, 216.42, 215.951, 215.682, 215.498, 215.293, 215.002, 214.535, 213.791, 212.72, 211.396, 210.082, 209.266, 208.907, 209.051, 209.749, 211.078, 212.777, 214.68, 216.699, 218.741, 220.833, 222.97, 225.147, 227.187, 229.093, 230.856, 232.34, 233.77, 235.146, 236.509, 237.94, 239.449, 241.132, 242.895, 244.697, 246.497, 248.304, 250.093, 251.797, 253.356, 254.716, 255.748, 256.257, 256.617, 256.449, 255.921, 255.521, 254.315, 252.591, 250.969, 251.339, 251.339, 251.339, 251.339])
self['N2O'] = numpy.array([0.0001599997, 0.0006399986, 0.0009999974, 0.001289996, 0.003359988, 0.003469985, 0.00200999, 0.0009299949, 0.0007699953, 0.00155999, 0.003499978, 0.004099974, 0.003609978, 0.003519979, 0.003859978, 0.00533997, 0.00733996, 0.01048995, 0.01344993, 0.01601993, 0.01847992, 0.02208991, 0.02617989, 0.03008988, 0.05585978, 0.08347968, 0.1100696, 0.1410095, 0.1726494, 0.2031892, 0.2290592, 0.2397691, 0.2501391, 0.2601991, 0.268909, 0.272829, 0.276629, 0.280329, 0.279099, 0.277989, 0.276929, 0.278389, 0.281049, 0.283589, 0.287389, 0.2911489, 0.2948589, 0.2984888, 0.3019888, 0.3053588, 0.3085387, 0.3115086, 0.3142285, 0.3166583, 0.3187479, 0.3196074, 0.3203866, 0.3210849, 0.3216832, 0.3221622, 0.3225324, 0.322752, 0.322831, 0.3228291, 0.3228264, 0.322823, 0.3228188, 0.3228135, 0.3228069, 0.3228023, 0.3227997, 0.3227975, 0.3227958, 0.322798, 0.3228014, 0.3228058, 0.3228061, 0.3227994, 0.3227859, 0.3227644, 0.322744, 0.3227239, 0.3227034, 0.3226792, 0.3226615, 0.322656, 0.3226638, 0.3226671, 0.3226102, 0.3224691, 0.3223558, 0.3223299, 0.3223454, 0.3223763, 0.3224433, 0.3225135, 0.3225669, 0.3225645, 0.322572, 0.3225792, 0.3225861])
self['O3'] = numpy.array([0.510174, 0.5621888, 0.6514743, 0.7822175, 0.9318276, 1.063576, 1.310564, 1.76503, 2.535005, 3.648507, 4.547261, 4.78841, 4.92361, 5.275468, 5.694327, 5.762868, 5.783319, 5.893709, 6.03422, 6.160551, 6.228622, 6.203113, 6.153684, 6.089276, 6.012956, 5.923467, 5.849328, 5.783048, 5.734829, 5.679589, 5.574619, 5.39368, 5.244621, 5.120821, 4.922902, 4.727543, 4.524263, 4.246424, 3.923376, 3.604037, 3.319568, 3.047309, 2.75112, 2.482241, 2.317652, 2.148792, 1.885393, 1.603124, 1.397604, 1.272585, 1.146755, 0.9980887, 0.8611839, 0.729153, 0.5870622, 0.4483724, 0.3575272, 0.2652448, 0.1737753, 0.1178921, 0.09092905, 0.07172082, 0.05827958, 0.05142367, 0.04863645, 0.04841805, 0.04816644, 0.04715373, 0.04594748, 0.04495205, 0.0455781, 0.04686353, 0.04873582, 0.04975662, 0.0501041, 0.04979462, 0.04934463, 0.04914342, 0.04915406, 0.04921568, 0.04915478, 0.04893549, 0.04849328, 0.04805416, 0.04794348, 0.04790108, 0.0476205, 0.04700432, 0.04654844, 0.04632991, 0.04646221, 0.04573811, 0.04403783, 0.04091335, 0.03254705, 0.02640277, 0.02501912, 0.02442054, 0.02442111, 0.02442165, 0.02442218])
self['CH4'] = numpy.array([0.04183322, 0.07070085, 0.09215896, 0.1150766, 0.1600424, 0.1895992, 0.203706, 0.2216318, 0.2513385, 0.2618113, 0.2802002, 0.3011591, 0.323238, 0.3478319, 0.3743778, 0.4088557, 0.4408626, 0.4700776, 0.4956766, 0.5058676, 0.5155767, 0.5382237, 0.5665796, 0.5937466, 0.6694654, 0.7486761, 0.8249039, 0.9082426, 0.9919303, 1.046986, 1.106076, 1.169336, 1.236905, 1.290275, 1.341695, 1.390245, 1.434895, 1.474525, 1.496414, 1.519504, 1.543804, 1.569344, 1.596164, 1.637644, 1.659294, 1.681934, 1.697794, 1.708283, 1.718413, 1.722753, 1.727263, 1.729712, 1.731132, 1.7327, 1.734659, 1.736686, 1.740032, 1.743762, 1.748043, 1.753067, 1.758228, 1.763046, 1.768011, 1.77186, 1.775215, 1.778026, 1.779713, 1.781404, 1.782387, 1.783412, 1.784227, 1.784995, 1.785885, 1.786897, 1.788006, 1.78924, 1.790502, 1.791825, 1.793189, 1.79475, 1.796366, 1.798093, 1.799748, 1.801223, 1.802603, 1.803951, 1.805294, 1.806622, 1.807672, 1.80842, 1.809452, 1.811134, 1.812978, 1.815059, 1.817833, 1.821496, 1.829131, 1.834953, 1.839252, 1.841891, 1.842819])
self['CTP'] = 500.0
self['CFRACTION'] = 0.0
self['IDG'] = 0
self['ISH'] = 0
self['ELEVATION'] = 0.0
self['S2M']['T'] = 251.339
self['S2M']['Q'] = 786.558838187
self['S2M']['O'] = 0.0244221754008
self['S2M']['P'] = 1007.16998
self['S2M']['U'] = 0.0
self['S2M']['V'] = 0.0
self['S2M']['WFETC'] = 100000.0
self['SKIN']['SURFTYPE'] = 1
self['SKIN']['WATERTYPE'] = 1
self['SKIN']['T'] = 251.339
self['SKIN']['SALINITY'] = 35.0
self['SKIN']['FOAM_FRACTION'] = 0.0
self['SKIN']['FASTEM'] = numpy.array([3.0, 5.0, 15.0, 0.1, 0.3])
self['ZENANGLE'] = 0.0
self['AZANGLE'] = 0.0
self['SUNZENANGLE'] = 0.0
self['SUNAZANGLE'] = 0.0
self['LATITUDE'] = 72.967
self['GAS_UNITS'] = 2
self['BE'] = 0.0
self['COSBK'] = 0.0
self['DATE'] = numpy.array([2007, 1, 20])
self['TIME'] = numpy.array([0, 0, 0])
|
class Base(object):
def __init__(self, *args, **kwargs):
pass
def dispose(self, *args, **kwargs):
pass
def prepare(self, *args, **kwargs):
pass
def prepare_page(self, *args, **kwargs):
pass
def cleanup(self, *args, **kwargs):
pass
|
class Base(object):
def __init__(self, *args, **kwargs):
pass
def dispose(self, *args, **kwargs):
pass
def prepare(self, *args, **kwargs):
pass
def prepare_page(self, *args, **kwargs):
pass
def cleanup(self, *args, **kwargs):
pass
|
"""Creates the train class"""
class Train:
"""
Each train in the metro is an instance of the Train class.
Methods:
__init__: creates a new train in the station
"""
def __init__(self):
self.cars = None
self.board_rate = 8
self.pop = None
self.travelers_exiting = None
self.dwell_time = None
self.car_capacity = 125
@property
def cap(self):
return self.cars * self.car_capacity
|
"""Creates the train class"""
class Train:
"""
Each train in the metro is an instance of the Train class.
Methods:
__init__: creates a new train in the station
"""
def __init__(self):
self.cars = None
self.board_rate = 8
self.pop = None
self.travelers_exiting = None
self.dwell_time = None
self.car_capacity = 125
@property
def cap(self):
return self.cars * self.car_capacity
|
n1 = float(input("Write the average of the first student "))
n2 = float(input("Write the average of the second student "))
m = (n1+n2)/2
print("The average of the two students is {}".format(m))
|
n1 = float(input('Write the average of the first student '))
n2 = float(input('Write the average of the second student '))
m = (n1 + n2) / 2
print('The average of the two students is {}'.format(m))
|
"""
https://www.codewars.com/kata/52742f58faf5485cae000b9a/train/python
Given an int that is a number of seconds, return a string.
If int is 0, return 'now'.
Otherwise,
return string in an ordered combination of years, days, hours, minutes, and seconds.
Examples:
format_duration(62) # returns "1 minute and 2 seconds"
format_duration(3662) # returns "1 hour, 1 minute and 2 seconds"
"""
def format_duration(seconds: int) -> str:
if seconds == 0:
return 'now'
time_amounts = {'years': 0, 'days': 0,
'hours': 0, 'minutes': 0, 'seconds': 0}
output = ''
if seconds >= 31536000:
time_amounts['years'] = seconds//31536000
output += str(time_amounts['years'])
output += " years, " if time_amounts['years'] > 1 else " year, "
seconds = seconds % 31536000
if seconds >= 86400:
time_amounts['days'] = seconds//86400
output += str(time_amounts['days'])
output += " days, " if time_amounts['days'] > 1 else " day, "
seconds = seconds % 86400
if seconds >= 3600:
time_amounts['hours'] = seconds//3600
output += str(time_amounts['hours'])
output += " hours, " if time_amounts['hours'] > 1 else " hour, "
seconds = seconds % 3600
if seconds >= 60:
time_amounts['minutes'] = seconds//60
output += str(time_amounts['minutes'])
output += " minutes, " if time_amounts['minutes'] > 1 else " minute, "
seconds = seconds % 60
time_amounts['seconds'] = seconds
# Find left-most comma and replace it with ' and'
num_of_digits = sum(c.isdigit() for c in output)
if num_of_digits > 1:
output = ' and'.join(output.rsplit(',', 1))
else:
output = output[:-2]
# Handle seconds
if num_of_digits == 1 and time_amounts['seconds'] > 0:
output += ' and '
if time_amounts['seconds'] == 1:
output += str(time_amounts['seconds']) + ' second'
elif time_amounts['seconds'] > 1:
output += str(time_amounts['seconds']) + ' seconds'
elif num_of_digits > 1 and time_amounts['seconds'] == 0:
output = output[:-5]
output = ' and'.join(output.rsplit(',', 1))
# print(seconds, time_amounts)
return output
print(format_duration(31536100))
print(format_duration(62))
print(format_duration(3662))
print(format_duration(120))
print(format_duration(1))
print(format_duration(132030240))
|
"""
https://www.codewars.com/kata/52742f58faf5485cae000b9a/train/python
Given an int that is a number of seconds, return a string.
If int is 0, return 'now'.
Otherwise,
return string in an ordered combination of years, days, hours, minutes, and seconds.
Examples:
format_duration(62) # returns "1 minute and 2 seconds"
format_duration(3662) # returns "1 hour, 1 minute and 2 seconds"
"""
def format_duration(seconds: int) -> str:
if seconds == 0:
return 'now'
time_amounts = {'years': 0, 'days': 0, 'hours': 0, 'minutes': 0, 'seconds': 0}
output = ''
if seconds >= 31536000:
time_amounts['years'] = seconds // 31536000
output += str(time_amounts['years'])
output += ' years, ' if time_amounts['years'] > 1 else ' year, '
seconds = seconds % 31536000
if seconds >= 86400:
time_amounts['days'] = seconds // 86400
output += str(time_amounts['days'])
output += ' days, ' if time_amounts['days'] > 1 else ' day, '
seconds = seconds % 86400
if seconds >= 3600:
time_amounts['hours'] = seconds // 3600
output += str(time_amounts['hours'])
output += ' hours, ' if time_amounts['hours'] > 1 else ' hour, '
seconds = seconds % 3600
if seconds >= 60:
time_amounts['minutes'] = seconds // 60
output += str(time_amounts['minutes'])
output += ' minutes, ' if time_amounts['minutes'] > 1 else ' minute, '
seconds = seconds % 60
time_amounts['seconds'] = seconds
num_of_digits = sum((c.isdigit() for c in output))
if num_of_digits > 1:
output = ' and'.join(output.rsplit(',', 1))
else:
output = output[:-2]
if num_of_digits == 1 and time_amounts['seconds'] > 0:
output += ' and '
if time_amounts['seconds'] == 1:
output += str(time_amounts['seconds']) + ' second'
elif time_amounts['seconds'] > 1:
output += str(time_amounts['seconds']) + ' seconds'
elif num_of_digits > 1 and time_amounts['seconds'] == 0:
output = output[:-5]
output = ' and'.join(output.rsplit(',', 1))
return output
print(format_duration(31536100))
print(format_duration(62))
print(format_duration(3662))
print(format_duration(120))
print(format_duration(1))
print(format_duration(132030240))
|
"""
Takes BUY/SELL/HOLD decision on stocks based on some metrics
"""
def decision(ticker):
pass
|
"""
Takes BUY/SELL/HOLD decision on stocks based on some metrics
"""
def decision(ticker):
pass
|
"""
Module containing LinkedList class and Node class.
"""
class LinkedList():
"""
Class to generate and modify linked list.
"""
def __init__(self, arg=None):
self.head = None
if arg is not None:
if hasattr(arg, '__iter__') and not isinstance(arg, str):
for i in arg:
self.append(i)
else:
self.append(arg)
def insert(self, new_data):
"""
Method to create a node in the linked list with a .data value
of *new_data* at the beginning of the list.
"""
node = Node(new_data)
if not self.head:
self.head = node
else:
current = self.head
self.head = node
self.head.nxt = current
def includes(self, lookup):
"""
Method to see if there is a node in the linked list with
a .data value of *lookup*.
"""
current = self.head
try:
while current.nxt:
if current.data == lookup:
print('included!')
return True
else:
current = current.nxt
if current.data == lookup:
print('included!')
return True
except:
print('no .nxt')
def print(self):
"""
Method to print a string containing the
.data value in every node.
"""
output = ''
current = self.head
while current:
if current == self.head:
output += current.data
else:
output += ', ' + current.data
current = current.nxt
return output
def append(self, new_data):
"""
Method to create a node in the linked list with a
.data value of *new_data* at the end of the list.
"""
node = Node(new_data)
if not self.head:
self.head = node
else:
current = self.head
while current.nxt:
current = current.nxt
current.nxt = node
def add_before(self, lookup, new_data):
"""
Method to create a node in the linked list with a .data
value of *new_data* before the node with the .data
value of *lookup* in the list.
"""
node = Node(new_data)
if self.includes(lookup):
if self.head.data == lookup:
self.insert(new_data)
else:
current = self.head
while current.nxt.data != lookup:
current = current.nxt
node.nxt = current.nxt
current.nxt = node
else:
print('Lookup data not found in list.')
def add_after(self, lookup, new_data):
"""
Method to create a node in the linked list with a .data value
of *new_data* after the node with the .data
value of *lookup* in the list.
"""
node = Node(new_data)
if self.includes(lookup):
current = self.head
while current.data != lookup:
current = current.nxt
node.nxt = current.nxt
current.nxt = node
else:
print('Lookup data not found in list.')
def k_from_end(self, k):
"""
Method to return the data of the kth node in a linked list.
"""
total_nodes = 0
position = 0
current = self.head
while current and current.nxt:
total_nodes += 1
current = current.nxt
if current and not current.nxt:
total_nodes += 1
else:
return 'Empty Linked List'
if k < total_nodes:
position = total_nodes - k
else:
return 'Exception'
current = self.head
for i in range(1, position):
current = current.nxt
return current.data
def __iter__(self):
current = self.head
while current:
yield current.data
current = current.nxt
def __next__(self):
current = self.head
if current:
yield current.nxt
def __add__(self, val):
output = LinkedList()
for i in self:
output.append(i)
if hasattr(val, '__iter__') and not isinstance(val, str):
for i in val:
output.append(i)
else:
output.append(val)
return output
def __iadd__(self, val):
if hasattr(val, '__iter__') and not isinstance(val, str):
for i in val:
self.append(i)
else:
self.append(val)
return self
class Node():
def __init__(self, data):
"""
Initializes an instance of a node with a
.data value equal to *data*.
"""
self.data = data
self.nxt = None
|
"""
Module containing LinkedList class and Node class.
"""
class Linkedlist:
"""
Class to generate and modify linked list.
"""
def __init__(self, arg=None):
self.head = None
if arg is not None:
if hasattr(arg, '__iter__') and (not isinstance(arg, str)):
for i in arg:
self.append(i)
else:
self.append(arg)
def insert(self, new_data):
"""
Method to create a node in the linked list with a .data value
of *new_data* at the beginning of the list.
"""
node = node(new_data)
if not self.head:
self.head = node
else:
current = self.head
self.head = node
self.head.nxt = current
def includes(self, lookup):
"""
Method to see if there is a node in the linked list with
a .data value of *lookup*.
"""
current = self.head
try:
while current.nxt:
if current.data == lookup:
print('included!')
return True
else:
current = current.nxt
if current.data == lookup:
print('included!')
return True
except:
print('no .nxt')
def print(self):
"""
Method to print a string containing the
.data value in every node.
"""
output = ''
current = self.head
while current:
if current == self.head:
output += current.data
else:
output += ', ' + current.data
current = current.nxt
return output
def append(self, new_data):
"""
Method to create a node in the linked list with a
.data value of *new_data* at the end of the list.
"""
node = node(new_data)
if not self.head:
self.head = node
else:
current = self.head
while current.nxt:
current = current.nxt
current.nxt = node
def add_before(self, lookup, new_data):
"""
Method to create a node in the linked list with a .data
value of *new_data* before the node with the .data
value of *lookup* in the list.
"""
node = node(new_data)
if self.includes(lookup):
if self.head.data == lookup:
self.insert(new_data)
else:
current = self.head
while current.nxt.data != lookup:
current = current.nxt
node.nxt = current.nxt
current.nxt = node
else:
print('Lookup data not found in list.')
def add_after(self, lookup, new_data):
"""
Method to create a node in the linked list with a .data value
of *new_data* after the node with the .data
value of *lookup* in the list.
"""
node = node(new_data)
if self.includes(lookup):
current = self.head
while current.data != lookup:
current = current.nxt
node.nxt = current.nxt
current.nxt = node
else:
print('Lookup data not found in list.')
def k_from_end(self, k):
"""
Method to return the data of the kth node in a linked list.
"""
total_nodes = 0
position = 0
current = self.head
while current and current.nxt:
total_nodes += 1
current = current.nxt
if current and (not current.nxt):
total_nodes += 1
else:
return 'Empty Linked List'
if k < total_nodes:
position = total_nodes - k
else:
return 'Exception'
current = self.head
for i in range(1, position):
current = current.nxt
return current.data
def __iter__(self):
current = self.head
while current:
yield current.data
current = current.nxt
def __next__(self):
current = self.head
if current:
yield current.nxt
def __add__(self, val):
output = linked_list()
for i in self:
output.append(i)
if hasattr(val, '__iter__') and (not isinstance(val, str)):
for i in val:
output.append(i)
else:
output.append(val)
return output
def __iadd__(self, val):
if hasattr(val, '__iter__') and (not isinstance(val, str)):
for i in val:
self.append(i)
else:
self.append(val)
return self
class Node:
def __init__(self, data):
"""
Initializes an instance of a node with a
.data value equal to *data*.
"""
self.data = data
self.nxt = None
|
# -*- coding: utf-8 -*-
# Copyright (c) 2014, Elvis Tombini <elvis@mapom.me>
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
WLCONF = 'wlister.conf'
WLPREFIX = 'wlister.log_prefix'
WLACTION = 'wlister.default_action'
WLMAXPOST = 'wlister.max_post_read'
WLMAXPOST_VALUE = 2048
class WLConfig(object):
def __init__(self, request, log):
options = request.get_options()
self.log = log
if WLCONF in options:
self.conf = options[WLCONF]
else:
self.conf = None
if WLPREFIX in options:
self.prefix = options[WLPREFIX].strip() + ' '
else:
self.prefix = ''
self.default_action = 'block'
if WLACTION in options:
if options[WLACTION] in \
['block', 'pass', 'logpass', 'logblock']:
self.default_action = options[WLACTION]
else:
self.log('WARNING - unknown value for ' + WLACTION +
', set to block')
else:
self.log('WARNING - ' + WLACTION + ' not defined, set to block')
if WLMAXPOST in options:
self.max_post_read = options[WLMAXPOST]
else:
self.max_post_read = WLMAXPOST_VALUE
self.log('WARNING - default request body to be read set to ' +
str(WLMAXPOST_VALUE))
rules_schema = \
{
"$schema": "http://json-schema.org/draft-04/schema#",
"description": "Conservative json schema defining wlrule format",
"type": "object",
"required": ["id"],
"additionalProperties": False,
"properties": {
"id": {
"type": "string"
},
"prerequisite": {
"type": "object",
"additionalProperties": False,
"properties": {
"has_tag": {
"type": "array",
"items": {"type": "string"}
},
"has_not_tag": {
"type": "array",
"items": {"type": "string"}
}
}
},
"match": {
"type": "object",
"additionalProperties": False,
"properties": {
"order": {
"type": "array",
"items": {
"type": "string"
}
},
"uri": {
"type": "string"
},
"protocol": {
"type": "string"
},
"method": {
"type": "string"
},
"host": {
"type": "string"
},
"args": {
"type": "string"
},
"parameters": {
"type": "array",
"items": {
"type": "array",
"minItems": 2,
"maxItems": 2,
"items": {
"type": "string"
}
}
},
"headers": {
"type": "array",
"items": {
"type": "array",
"minItems": 2,
"maxItems": 2,
"items": {
"type": "string"
}
}
},
"content_url_encoded": {
"type": "array",
"items": {
"type": "array",
"minItems": 2,
"maxItems": 2,
"items": {
"type": "string"
}
}
},
"content_json": {
"type": "object"
},
"parameters_in": {
"type": "array",
"items": {
"type": "array",
"minItems": 2,
"maxItems": 2,
"items": {
"type": "string"
}
}
},
"headers_in": {
"type": "array",
"items": {
"type": "array",
"minItems": 2,
"maxItems": 2,
"items": {
"type": "string"
}
}
},
"content_url_encoded_in": {
"type": "array",
"items": {
"type": "array",
"minItems": 2,
"maxItems": 2,
"items": {
"type": "string"
}
}
},
"parameters_list": {
"type": "array",
"items": {
"type": "string"
}
},
"headers_list": {
"type": "array",
"items": {
"type": "string"
}
},
"content_url_encoded_list": {
"type": "array",
"items": {
"type": "string"
}
},
"parameters_list_in": {
"type": "array",
"items": {
"type": "string"
}
},
"headers_list_in": {
"type": "array",
"items": {
"type": "string"
}
},
"content_url_encoded_list_in": {
"type": "array",
"items": {
"type": "string"
}
},
"parameters_unique": {
"type": "array",
"items": {
"type": "string"
}
},
"headers_unique": {
"type": "array",
"items": {
"type": "string"
}
},
"content_url_encoded_unique": {
"type": "array",
"items": {
"type": "string"
}
},
"parameters_all_unique": {
"type": "string",
"enum": ["True", "False"]
},
"headers_all_unique": {
"type": "string",
"enum": ["True", "False"]
},
"content_url_encoded_all_unique": {
"type": "string",
"enum": ["True", "False"]
},
}
},
"action_if_match": {
"type": "object",
"additionalProperties": False,
"properties": {
"whitelist": {
"type": "string",
"enum": ["True", "False"]
},
"set_tag": {
"type": "array",
"items": {
"type": "string"
}
},
"unset_tag": {
"type": "array",
"items": {
"type": "string"
}
},
"log": {
"type": "array",
"items": {
"type": "array",
"items": {
"type": "string"
}
}
},
"set_header": {
"type": "array",
"items": {
"type": "string"
}
}
}
},
"action_if_mismatch": {
"type": "object",
"additionalProperties": False,
"properties": {
"whitelist": {
"type": "string",
"enum": ["True", "False"]
},
"set_tag": {
"type": "array",
"items": {
"type": "string"
}
},
"log": {
"type": "array",
"items": {
"type": "array",
"items": {
"type": "string"
}
}
},
"unset_tag": {
"type": "array",
"items": {
"type": "string"
}
}
}
}
}
}
|
wlconf = 'wlister.conf'
wlprefix = 'wlister.log_prefix'
wlaction = 'wlister.default_action'
wlmaxpost = 'wlister.max_post_read'
wlmaxpost_value = 2048
class Wlconfig(object):
def __init__(self, request, log):
options = request.get_options()
self.log = log
if WLCONF in options:
self.conf = options[WLCONF]
else:
self.conf = None
if WLPREFIX in options:
self.prefix = options[WLPREFIX].strip() + ' '
else:
self.prefix = ''
self.default_action = 'block'
if WLACTION in options:
if options[WLACTION] in ['block', 'pass', 'logpass', 'logblock']:
self.default_action = options[WLACTION]
else:
self.log('WARNING - unknown value for ' + WLACTION + ', set to block')
else:
self.log('WARNING - ' + WLACTION + ' not defined, set to block')
if WLMAXPOST in options:
self.max_post_read = options[WLMAXPOST]
else:
self.max_post_read = WLMAXPOST_VALUE
self.log('WARNING - default request body to be read set to ' + str(WLMAXPOST_VALUE))
rules_schema = {'$schema': 'http://json-schema.org/draft-04/schema#', 'description': 'Conservative json schema defining wlrule format', 'type': 'object', 'required': ['id'], 'additionalProperties': False, 'properties': {'id': {'type': 'string'}, 'prerequisite': {'type': 'object', 'additionalProperties': False, 'properties': {'has_tag': {'type': 'array', 'items': {'type': 'string'}}, 'has_not_tag': {'type': 'array', 'items': {'type': 'string'}}}}, 'match': {'type': 'object', 'additionalProperties': False, 'properties': {'order': {'type': 'array', 'items': {'type': 'string'}}, 'uri': {'type': 'string'}, 'protocol': {'type': 'string'}, 'method': {'type': 'string'}, 'host': {'type': 'string'}, 'args': {'type': 'string'}, 'parameters': {'type': 'array', 'items': {'type': 'array', 'minItems': 2, 'maxItems': 2, 'items': {'type': 'string'}}}, 'headers': {'type': 'array', 'items': {'type': 'array', 'minItems': 2, 'maxItems': 2, 'items': {'type': 'string'}}}, 'content_url_encoded': {'type': 'array', 'items': {'type': 'array', 'minItems': 2, 'maxItems': 2, 'items': {'type': 'string'}}}, 'content_json': {'type': 'object'}, 'parameters_in': {'type': 'array', 'items': {'type': 'array', 'minItems': 2, 'maxItems': 2, 'items': {'type': 'string'}}}, 'headers_in': {'type': 'array', 'items': {'type': 'array', 'minItems': 2, 'maxItems': 2, 'items': {'type': 'string'}}}, 'content_url_encoded_in': {'type': 'array', 'items': {'type': 'array', 'minItems': 2, 'maxItems': 2, 'items': {'type': 'string'}}}, 'parameters_list': {'type': 'array', 'items': {'type': 'string'}}, 'headers_list': {'type': 'array', 'items': {'type': 'string'}}, 'content_url_encoded_list': {'type': 'array', 'items': {'type': 'string'}}, 'parameters_list_in': {'type': 'array', 'items': {'type': 'string'}}, 'headers_list_in': {'type': 'array', 'items': {'type': 'string'}}, 'content_url_encoded_list_in': {'type': 'array', 'items': {'type': 'string'}}, 'parameters_unique': {'type': 'array', 'items': {'type': 'string'}}, 'headers_unique': {'type': 'array', 'items': {'type': 'string'}}, 'content_url_encoded_unique': {'type': 'array', 'items': {'type': 'string'}}, 'parameters_all_unique': {'type': 'string', 'enum': ['True', 'False']}, 'headers_all_unique': {'type': 'string', 'enum': ['True', 'False']}, 'content_url_encoded_all_unique': {'type': 'string', 'enum': ['True', 'False']}}}, 'action_if_match': {'type': 'object', 'additionalProperties': False, 'properties': {'whitelist': {'type': 'string', 'enum': ['True', 'False']}, 'set_tag': {'type': 'array', 'items': {'type': 'string'}}, 'unset_tag': {'type': 'array', 'items': {'type': 'string'}}, 'log': {'type': 'array', 'items': {'type': 'array', 'items': {'type': 'string'}}}, 'set_header': {'type': 'array', 'items': {'type': 'string'}}}}, 'action_if_mismatch': {'type': 'object', 'additionalProperties': False, 'properties': {'whitelist': {'type': 'string', 'enum': ['True', 'False']}, 'set_tag': {'type': 'array', 'items': {'type': 'string'}}, 'log': {'type': 'array', 'items': {'type': 'array', 'items': {'type': 'string'}}}, 'unset_tag': {'type': 'array', 'items': {'type': 'string'}}}}}}
|
# This programs aasks for your name and says hello
print('Hello world!')
print('What is your name?') #Ask for their name
myName = input()
print('It is good to meet you, ' + myName)
print('The lenght of your name is : ')
print(len(myName))
print('What is your age?') #Ask for their age
yourAge = input()
print('You will be ' + str(int(yourAge) + 1) + ' in a year.' )
|
print('Hello world!')
print('What is your name?')
my_name = input()
print('It is good to meet you, ' + myName)
print('The lenght of your name is : ')
print(len(myName))
print('What is your age?')
your_age = input()
print('You will be ' + str(int(yourAge) + 1) + ' in a year.')
|
# coding=utf8
"""all possible exceptions"""
class LilacException(Exception):
"""There was an ambiguous exception that occurred while
handling lilac process"""
pass
class SourceDirectoryNotFound(LilacException):
"""Source directory was not found"""
pass
class ParseException(LilacException):
"""There was an exception occurred while parsing the source"""
pass
class RenderException(LilacException):
"""There was an exception occurred while rendering to html"""
pass
class SeparatorNotFound(ParseException):
"""There was no separator found in post's source"""
pass
class PostDateTimeNotFound(ParseException):
"""There was no datetime found in post's source"""
pass
class PostTitleNotFound(ParseException):
"""There was no title found in post's source"""
pass
class PostDateTimeInvalid(ParseException):
"""Invalid datetime format, should like '2012-04-05 10:10'"""
pass
class PostTagsTypeInvalid(ParseException):
"""Invalid tags datatype, should be a array"""
pass
class PostHeaderSyntaxError(ParseException):
"""TomlSyntaxError occurred in post's header"""
pass
class ConfigSyntaxError(LilacException):
"""TomlSyntaxError occurred in config.toml"""
pass
class JinjaTemplateNotFound(RenderException):
"""Jinja2 template was not found"""
pass
|
"""all possible exceptions"""
class Lilacexception(Exception):
"""There was an ambiguous exception that occurred while
handling lilac process"""
pass
class Sourcedirectorynotfound(LilacException):
"""Source directory was not found"""
pass
class Parseexception(LilacException):
"""There was an exception occurred while parsing the source"""
pass
class Renderexception(LilacException):
"""There was an exception occurred while rendering to html"""
pass
class Separatornotfound(ParseException):
"""There was no separator found in post's source"""
pass
class Postdatetimenotfound(ParseException):
"""There was no datetime found in post's source"""
pass
class Posttitlenotfound(ParseException):
"""There was no title found in post's source"""
pass
class Postdatetimeinvalid(ParseException):
"""Invalid datetime format, should like '2012-04-05 10:10'"""
pass
class Posttagstypeinvalid(ParseException):
"""Invalid tags datatype, should be a array"""
pass
class Postheadersyntaxerror(ParseException):
"""TomlSyntaxError occurred in post's header"""
pass
class Configsyntaxerror(LilacException):
"""TomlSyntaxError occurred in config.toml"""
pass
class Jinjatemplatenotfound(RenderException):
"""Jinja2 template was not found"""
pass
|
# project/tests/test_ping.py
def test_ping(test_app):
response = test_app.get("/ping")
assert response.status_code == 200
assert response.json() == {"environment": "dev", "ping": "pong!", "testing": True}
|
def test_ping(test_app):
response = test_app.get('/ping')
assert response.status_code == 200
assert response.json() == {'environment': 'dev', 'ping': 'pong!', 'testing': True}
|
#!/usr/bin/env python
# coding=utf-8
__version__ = "2.1.4"
|
__version__ = '2.1.4'
|
label_name = []
with open("label_name.txt",encoding='utf-8') as file:
for line in file.readlines():
line = line.strip()
name = (line.split('-')[-1])
if name.count('|') > 0:
name = name.split('|')[-1]
print(name)
label_name.append((name))
for item in label_name:
with open('label_name_1.txt','a') as file:
file.write(item+'\n')
|
label_name = []
with open('label_name.txt', encoding='utf-8') as file:
for line in file.readlines():
line = line.strip()
name = line.split('-')[-1]
if name.count('|') > 0:
name = name.split('|')[-1]
print(name)
label_name.append(name)
for item in label_name:
with open('label_name_1.txt', 'a') as file:
file.write(item + '\n')
|
class Library(object):
def __init__(self):
self.dictionary = {
"Micah": ["Judgement on Samaria and Judah", "Reason for the judgement", "Judgement on wicked leaders",
"Messianic Kingdom", "Birth of the Messiah", "Indictment 1, 2", "Promise of salvation"]
}
def get(self, book):
return self.dictionary.get(book)
|
class Library(object):
def __init__(self):
self.dictionary = {'Micah': ['Judgement on Samaria and Judah', 'Reason for the judgement', 'Judgement on wicked leaders', 'Messianic Kingdom', 'Birth of the Messiah', 'Indictment 1, 2', 'Promise of salvation']}
def get(self, book):
return self.dictionary.get(book)
|
def split_full_name(string: str) -> list:
"""Takes a full name and splits it into first and last.
Parameters
----------
string : str
The full name to be parsed.
Returns
-------
list
The first and the last name.
"""
return string.split(" ")
# Test it out.
print(split_full_name(string=100000000))
|
def split_full_name(string: str) -> list:
"""Takes a full name and splits it into first and last.
Parameters
----------
string : str
The full name to be parsed.
Returns
-------
list
The first and the last name.
"""
return string.split(' ')
print(split_full_name(string=100000000))
|
AESEncryptParam = "Key (32 Hex characters)"
S_BOX = (
0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76,
0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0,
0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15,
0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75,
0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0, 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84,
0x53, 0xD1, 0x00, 0xED, 0x20, 0xFC, 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF,
0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, 0x45, 0xF9, 0x02, 0x7F, 0x50, 0x3C, 0x9F, 0xA8,
0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5, 0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2,
0xCD, 0x0C, 0x13, 0xEC, 0x5F, 0x97, 0x44, 0x17, 0xC4, 0xA7, 0x7E, 0x3D, 0x64, 0x5D, 0x19, 0x73,
0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88, 0x46, 0xEE, 0xB8, 0x14, 0xDE, 0x5E, 0x0B, 0xDB,
0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C, 0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79,
0xE7, 0xC8, 0x37, 0x6D, 0x8D, 0xD5, 0x4E, 0xA9, 0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A, 0xAE, 0x08,
0xBA, 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6, 0xE8, 0xDD, 0x74, 0x1F, 0x4B, 0xBD, 0x8B, 0x8A,
0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E, 0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E,
0xE1, 0xF8, 0x98, 0x11, 0x69, 0xD9, 0x8E, 0x94, 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF,
0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68, 0x41, 0x99, 0x2D, 0x0F, 0xB0, 0x54, 0xBB, 0x16,
)
S_BOX_INVERSE = (
0x52, 0x09, 0x6A, 0xD5, 0x30, 0x36, 0xA5, 0x38, 0xBF, 0x40, 0xA3, 0x9E, 0x81, 0xF3, 0xD7, 0xFB,
0x7C, 0xE3, 0x39, 0x82, 0x9B, 0x2F, 0xFF, 0x87, 0x34, 0x8E, 0x43, 0x44, 0xC4, 0xDE, 0xE9, 0xCB,
0x54, 0x7B, 0x94, 0x32, 0xA6, 0xC2, 0x23, 0x3D, 0xEE, 0x4C, 0x95, 0x0B, 0x42, 0xFA, 0xC3, 0x4E,
0x08, 0x2E, 0xA1, 0x66, 0x28, 0xD9, 0x24, 0xB2, 0x76, 0x5B, 0xA2, 0x49, 0x6D, 0x8B, 0xD1, 0x25,
0x72, 0xF8, 0xF6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xD4, 0xA4, 0x5C, 0xCC, 0x5D, 0x65, 0xB6, 0x92,
0x6C, 0x70, 0x48, 0x50, 0xFD, 0xED, 0xB9, 0xDA, 0x5E, 0x15, 0x46, 0x57, 0xA7, 0x8D, 0x9D, 0x84,
0x90, 0xD8, 0xAB, 0x00, 0x8C, 0xBC, 0xD3, 0x0A, 0xF7, 0xE4, 0x58, 0x05, 0xB8, 0xB3, 0x45, 0x06,
0xD0, 0x2C, 0x1E, 0x8F, 0xCA, 0x3F, 0x0F, 0x02, 0xC1, 0xAF, 0xBD, 0x03, 0x01, 0x13, 0x8A, 0x6B,
0x3A, 0x91, 0x11, 0x41, 0x4F, 0x67, 0xDC, 0xEA, 0x97, 0xF2, 0xCF, 0xCE, 0xF0, 0xB4, 0xE6, 0x73,
0x96, 0xAC, 0x74, 0x22, 0xE7, 0xAD, 0x35, 0x85, 0xE2, 0xF9, 0x37, 0xE8, 0x1C, 0x75, 0xDF, 0x6E,
0x47, 0xF1, 0x1A, 0x71, 0x1D, 0x29, 0xC5, 0x89, 0x6F, 0xB7, 0x62, 0x0E, 0xAA, 0x18, 0xBE, 0x1B,
0xFC, 0x56, 0x3E, 0x4B, 0xC6, 0xD2, 0x79, 0x20, 0x9A, 0xDB, 0xC0, 0xFE, 0x78, 0xCD, 0x5A, 0xF4,
0x1F, 0xDD, 0xA8, 0x33, 0x88, 0x07, 0xC7, 0x31, 0xB1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xEC, 0x5F,
0x60, 0x51, 0x7F, 0xA9, 0x19, 0xB5, 0x4A, 0x0D, 0x2D, 0xE5, 0x7A, 0x9F, 0x93, 0xC9, 0x9C, 0xEF,
0xA0, 0xE0, 0x3B, 0x4D, 0xAE, 0x2A, 0xF5, 0xB0, 0xC8, 0xEB, 0xBB, 0x3C, 0x83, 0x53, 0x99, 0x61,
0x17, 0x2B, 0x04, 0x7E, 0xBA, 0x77, 0xD6, 0x26, 0xE1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0C, 0x7D,
)
R_CON = (
0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40,
0x80, 0x1B, 0x36, 0x6C, 0xD8, 0xAB, 0x4D, 0x9A,
0x2F, 0x5E, 0xBC, 0x63, 0xC6, 0x97, 0x35, 0x6A,
0xD4, 0xB3, 0x7D, 0xFA, 0xEF, 0xC5, 0x91, 0x39,
)
KEYSIZE_ROUNDS_MAP = {16: 10, 24: 12, 32: 14}
def shiftRows(s):
s[0][1], s[1][1], s[2][1], s[3][1] = s[1][1], s[2][1], s[3][1], s[0][1]
s[0][2], s[1][2], s[2][2], s[3][2] = s[2][2], s[3][2], s[0][2], s[1][2]
s[0][3], s[1][3], s[2][3], s[3][3] = s[3][3], s[0][3], s[1][3], s[2][3]
def shiftRowsInvert(s):
s[0][1], s[1][1], s[2][1], s[3][1] = s[3][1], s[0][1], s[1][1], s[2][1]
s[0][2], s[1][2], s[2][2], s[3][2] = s[2][2], s[3][2], s[0][2], s[1][2]
s[0][3], s[1][3], s[2][3], s[3][3] = s[1][3], s[2][3], s[3][3], s[0][3]
def addRoundKey(input, roundKey):
for i in range(4):
for j in range(4):
input[i][j] ^= roundKey[i][j]
def substituteGeneric(input, subTable):
for i in range(4):
for j in range(4):
input[i][j] = subTable[input[i][j]]
def substitute(input):
substituteGeneric(input, S_BOX)
def substituteInverse(input):
substituteGeneric(input, S_BOX_INVERSE)
def xtime(a):
return (((a << 1) ^ 0x1B) & 0xFF) if (a & 0x80) else (a << 1)
def mixSingleCol(input):
t = input[0] ^ input[1] ^ input[2] ^ input[3]
u = input[0]
input[0] ^= t ^ xtime(input[0] ^ input[1])
input[1] ^= t ^ xtime(input[1] ^ input[2])
input[2] ^= t ^ xtime(input[2] ^ input[3])
input[3] ^= t ^ xtime(input[3] ^ u)
def mixColumns(input):
for i in range(4):
mixSingleCol(input[i])
def mixColumnsInverse(input):
for i in range(4):
u, v = xtime(xtime(input[i][0] ^ input[i][2])), xtime(
xtime(input[i][1] ^ input[i][3]))
input[i][0] ^= u
input[i][1] ^= v
input[i][2] ^= u
input[i][3] ^= v
mixColumns(input)
def bytesToMatrix(input):
return [list(input[i:i+4]) for i in range(0, len(input), 4)]
def matrixToBytes(matrix):
return bytes(sum(matrix, []))
def xor(a, b):
return bytes(a[i] ^ b[i] for i in range(len(a)))
def expandKey(key, numberOfRounds):
keyColumns = bytesToMatrix(key)
iteration_size = len(key) // 4
i = 1
while len(keyColumns) < ((numberOfRounds + 1) * 4):
word = list(keyColumns[-1])
if len(keyColumns) % iteration_size == 0:
word = word[1:] + [word[0]]
word = [S_BOX[b] for b in word]
word[0] ^= R_CON[i]
i += 1
elif len(key) == 32 and len(keyColumns) % iteration_size == 4:
word = [S_BOX[b] for b in word]
word = xor(word, keyColumns[-iteration_size])
keyColumns.append(word)
return [keyColumns[4*i: 4*(i+1)] for i in range(len(keyColumns) // 4)]
def getInitalInfo(param):
key = bytearray.fromhex(param[0])
numberOfRounds = KEYSIZE_ROUNDS_MAP[len(key)]
keyMatrices = expandKey(key, numberOfRounds)
return numberOfRounds, keyMatrices
def prepareInput(input):
return bytesToMatrix(bytearray.fromhex(input[0].strip()))
def prepareOutput(output):
return [matrixToBytes(output).hex().upper()]
def AESEncrypt(input, param):
numberOfRounds, keyMatrices = getInitalInfo(param)
output = prepareInput(input)
addRoundKey(output, keyMatrices[0])
for i in range(1, numberOfRounds):
substitute(output)
shiftRows(output)
mixColumns(output)
addRoundKey(output, keyMatrices[i])
substitute(output)
shiftRows(output)
addRoundKey(output, keyMatrices[-1])
return prepareOutput(output)
def AESDecrypt(input, param):
numberOfRounds, keyMatrices = getInitalInfo(param)
output = prepareInput(input)
addRoundKey(output, keyMatrices[-1])
shiftRowsInvert(output)
substituteInverse(output)
for i in range(numberOfRounds - 1, 0, -1):
addRoundKey(output, keyMatrices[i])
mixColumnsInverse(output)
shiftRowsInvert(output)
substituteInverse(output)
addRoundKey(output, keyMatrices[0])
return prepareOutput(output)
|
aes_encrypt_param = 'Key (32 Hex characters)'
s_box = (99, 124, 119, 123, 242, 107, 111, 197, 48, 1, 103, 43, 254, 215, 171, 118, 202, 130, 201, 125, 250, 89, 71, 240, 173, 212, 162, 175, 156, 164, 114, 192, 183, 253, 147, 38, 54, 63, 247, 204, 52, 165, 229, 241, 113, 216, 49, 21, 4, 199, 35, 195, 24, 150, 5, 154, 7, 18, 128, 226, 235, 39, 178, 117, 9, 131, 44, 26, 27, 110, 90, 160, 82, 59, 214, 179, 41, 227, 47, 132, 83, 209, 0, 237, 32, 252, 177, 91, 106, 203, 190, 57, 74, 76, 88, 207, 208, 239, 170, 251, 67, 77, 51, 133, 69, 249, 2, 127, 80, 60, 159, 168, 81, 163, 64, 143, 146, 157, 56, 245, 188, 182, 218, 33, 16, 255, 243, 210, 205, 12, 19, 236, 95, 151, 68, 23, 196, 167, 126, 61, 100, 93, 25, 115, 96, 129, 79, 220, 34, 42, 144, 136, 70, 238, 184, 20, 222, 94, 11, 219, 224, 50, 58, 10, 73, 6, 36, 92, 194, 211, 172, 98, 145, 149, 228, 121, 231, 200, 55, 109, 141, 213, 78, 169, 108, 86, 244, 234, 101, 122, 174, 8, 186, 120, 37, 46, 28, 166, 180, 198, 232, 221, 116, 31, 75, 189, 139, 138, 112, 62, 181, 102, 72, 3, 246, 14, 97, 53, 87, 185, 134, 193, 29, 158, 225, 248, 152, 17, 105, 217, 142, 148, 155, 30, 135, 233, 206, 85, 40, 223, 140, 161, 137, 13, 191, 230, 66, 104, 65, 153, 45, 15, 176, 84, 187, 22)
s_box_inverse = (82, 9, 106, 213, 48, 54, 165, 56, 191, 64, 163, 158, 129, 243, 215, 251, 124, 227, 57, 130, 155, 47, 255, 135, 52, 142, 67, 68, 196, 222, 233, 203, 84, 123, 148, 50, 166, 194, 35, 61, 238, 76, 149, 11, 66, 250, 195, 78, 8, 46, 161, 102, 40, 217, 36, 178, 118, 91, 162, 73, 109, 139, 209, 37, 114, 248, 246, 100, 134, 104, 152, 22, 212, 164, 92, 204, 93, 101, 182, 146, 108, 112, 72, 80, 253, 237, 185, 218, 94, 21, 70, 87, 167, 141, 157, 132, 144, 216, 171, 0, 140, 188, 211, 10, 247, 228, 88, 5, 184, 179, 69, 6, 208, 44, 30, 143, 202, 63, 15, 2, 193, 175, 189, 3, 1, 19, 138, 107, 58, 145, 17, 65, 79, 103, 220, 234, 151, 242, 207, 206, 240, 180, 230, 115, 150, 172, 116, 34, 231, 173, 53, 133, 226, 249, 55, 232, 28, 117, 223, 110, 71, 241, 26, 113, 29, 41, 197, 137, 111, 183, 98, 14, 170, 24, 190, 27, 252, 86, 62, 75, 198, 210, 121, 32, 154, 219, 192, 254, 120, 205, 90, 244, 31, 221, 168, 51, 136, 7, 199, 49, 177, 18, 16, 89, 39, 128, 236, 95, 96, 81, 127, 169, 25, 181, 74, 13, 45, 229, 122, 159, 147, 201, 156, 239, 160, 224, 59, 77, 174, 42, 245, 176, 200, 235, 187, 60, 131, 83, 153, 97, 23, 43, 4, 126, 186, 119, 214, 38, 225, 105, 20, 99, 85, 33, 12, 125)
r_con = (0, 1, 2, 4, 8, 16, 32, 64, 128, 27, 54, 108, 216, 171, 77, 154, 47, 94, 188, 99, 198, 151, 53, 106, 212, 179, 125, 250, 239, 197, 145, 57)
keysize_rounds_map = {16: 10, 24: 12, 32: 14}
def shift_rows(s):
(s[0][1], s[1][1], s[2][1], s[3][1]) = (s[1][1], s[2][1], s[3][1], s[0][1])
(s[0][2], s[1][2], s[2][2], s[3][2]) = (s[2][2], s[3][2], s[0][2], s[1][2])
(s[0][3], s[1][3], s[2][3], s[3][3]) = (s[3][3], s[0][3], s[1][3], s[2][3])
def shift_rows_invert(s):
(s[0][1], s[1][1], s[2][1], s[3][1]) = (s[3][1], s[0][1], s[1][1], s[2][1])
(s[0][2], s[1][2], s[2][2], s[3][2]) = (s[2][2], s[3][2], s[0][2], s[1][2])
(s[0][3], s[1][3], s[2][3], s[3][3]) = (s[1][3], s[2][3], s[3][3], s[0][3])
def add_round_key(input, roundKey):
for i in range(4):
for j in range(4):
input[i][j] ^= roundKey[i][j]
def substitute_generic(input, subTable):
for i in range(4):
for j in range(4):
input[i][j] = subTable[input[i][j]]
def substitute(input):
substitute_generic(input, S_BOX)
def substitute_inverse(input):
substitute_generic(input, S_BOX_INVERSE)
def xtime(a):
return (a << 1 ^ 27) & 255 if a & 128 else a << 1
def mix_single_col(input):
t = input[0] ^ input[1] ^ input[2] ^ input[3]
u = input[0]
input[0] ^= t ^ xtime(input[0] ^ input[1])
input[1] ^= t ^ xtime(input[1] ^ input[2])
input[2] ^= t ^ xtime(input[2] ^ input[3])
input[3] ^= t ^ xtime(input[3] ^ u)
def mix_columns(input):
for i in range(4):
mix_single_col(input[i])
def mix_columns_inverse(input):
for i in range(4):
(u, v) = (xtime(xtime(input[i][0] ^ input[i][2])), xtime(xtime(input[i][1] ^ input[i][3])))
input[i][0] ^= u
input[i][1] ^= v
input[i][2] ^= u
input[i][3] ^= v
mix_columns(input)
def bytes_to_matrix(input):
return [list(input[i:i + 4]) for i in range(0, len(input), 4)]
def matrix_to_bytes(matrix):
return bytes(sum(matrix, []))
def xor(a, b):
return bytes((a[i] ^ b[i] for i in range(len(a))))
def expand_key(key, numberOfRounds):
key_columns = bytes_to_matrix(key)
iteration_size = len(key) // 4
i = 1
while len(keyColumns) < (numberOfRounds + 1) * 4:
word = list(keyColumns[-1])
if len(keyColumns) % iteration_size == 0:
word = word[1:] + [word[0]]
word = [S_BOX[b] for b in word]
word[0] ^= R_CON[i]
i += 1
elif len(key) == 32 and len(keyColumns) % iteration_size == 4:
word = [S_BOX[b] for b in word]
word = xor(word, keyColumns[-iteration_size])
keyColumns.append(word)
return [keyColumns[4 * i:4 * (i + 1)] for i in range(len(keyColumns) // 4)]
def get_inital_info(param):
key = bytearray.fromhex(param[0])
number_of_rounds = KEYSIZE_ROUNDS_MAP[len(key)]
key_matrices = expand_key(key, numberOfRounds)
return (numberOfRounds, keyMatrices)
def prepare_input(input):
return bytes_to_matrix(bytearray.fromhex(input[0].strip()))
def prepare_output(output):
return [matrix_to_bytes(output).hex().upper()]
def aes_encrypt(input, param):
(number_of_rounds, key_matrices) = get_inital_info(param)
output = prepare_input(input)
add_round_key(output, keyMatrices[0])
for i in range(1, numberOfRounds):
substitute(output)
shift_rows(output)
mix_columns(output)
add_round_key(output, keyMatrices[i])
substitute(output)
shift_rows(output)
add_round_key(output, keyMatrices[-1])
return prepare_output(output)
def aes_decrypt(input, param):
(number_of_rounds, key_matrices) = get_inital_info(param)
output = prepare_input(input)
add_round_key(output, keyMatrices[-1])
shift_rows_invert(output)
substitute_inverse(output)
for i in range(numberOfRounds - 1, 0, -1):
add_round_key(output, keyMatrices[i])
mix_columns_inverse(output)
shift_rows_invert(output)
substitute_inverse(output)
add_round_key(output, keyMatrices[0])
return prepare_output(output)
|
# -*- coding: utf-8 -*-
"""
Top-level package for Los Angeles
CDP instance backend.
"""
__author__ = "Matt Webster"
__version__ = "1.0.0"
def get_module_version() -> str:
return __version__
|
"""
Top-level package for Los Angeles
CDP instance backend.
"""
__author__ = 'Matt Webster'
__version__ = '1.0.0'
def get_module_version() -> str:
return __version__
|
### Sherlock and The Beast - Solution
def findDecentNumber(n):
temp = n
while temp > 0:
if temp%3 == 0:
break
else:
temp -= 5
if temp < 0:
return -1
final_str = ""
rep_count = temp // 3
while rep_count:
final_str += "555"
rep_count -= 1
rep_count = (n-temp) // 5
while rep_count:
final_str += "33333"
rep_count -= 1
return final_str
def main():
t = int(input())
while t:
n = int(input())
result = findDecentNumber(n)
print(result)
t -= 1
main()
|
def find_decent_number(n):
temp = n
while temp > 0:
if temp % 3 == 0:
break
else:
temp -= 5
if temp < 0:
return -1
final_str = ''
rep_count = temp // 3
while rep_count:
final_str += '555'
rep_count -= 1
rep_count = (n - temp) // 5
while rep_count:
final_str += '33333'
rep_count -= 1
return final_str
def main():
t = int(input())
while t:
n = int(input())
result = find_decent_number(n)
print(result)
t -= 1
main()
|
#!/bin/env python3
class Car:
''' A car description '''
NUMBER_OF_WHEELS = 4 # Class variable.
def __init__(self, name):
self.name = name
self.distance = 0
def drive(self, distance):
''' incrises distance '''
self.distance += distance
def reverse(distance):
''' Class method '''
print("distance %d" % distance)
mycar = Car("Fiat 126p")
print(mycar.__dict__)
mycar.drive(5)
print(mycar.__dict__)
Car.reverse(7)
|
class Car:
""" A car description """
number_of_wheels = 4
def __init__(self, name):
self.name = name
self.distance = 0
def drive(self, distance):
""" incrises distance """
self.distance += distance
def reverse(distance):
""" Class method """
print('distance %d' % distance)
mycar = car('Fiat 126p')
print(mycar.__dict__)
mycar.drive(5)
print(mycar.__dict__)
Car.reverse(7)
|
# LeetCode 953. Verifying an Alien Dictionary `E`
# 1sk | 97% | 22'
# A~0v21
class Solution:
def isAlienSorted(self, words: List[str], order: str) -> bool:
dic = {c: i for i, c in enumerate(order)}
def cmp(s1, s2):
for i in range(min(len(s1), len(s2))):
if s1[i] != s2[i]:
return dic[s1[i]] <= dic[s2[i]]
return len(s1) <= len(s2)
return all(cmp(words[i], words[i+1]) for i in range(len(words)-1))
|
class Solution:
def is_alien_sorted(self, words: List[str], order: str) -> bool:
dic = {c: i for (i, c) in enumerate(order)}
def cmp(s1, s2):
for i in range(min(len(s1), len(s2))):
if s1[i] != s2[i]:
return dic[s1[i]] <= dic[s2[i]]
return len(s1) <= len(s2)
return all((cmp(words[i], words[i + 1]) for i in range(len(words) - 1)))
|
def beautifulTriplets(d, arr):
t = 0
for i in range(len(arr)):
if arr[i] + d in arr and arr[i] + 2*d in arr:
t += 1
return t
|
def beautiful_triplets(d, arr):
t = 0
for i in range(len(arr)):
if arr[i] + d in arr and arr[i] + 2 * d in arr:
t += 1
return t
|
prime_numbers = [True for x in range(1001)]
prime_numbers[1] = False
for i in range(2, 1001):
for j in range(2*i, 1001, i):
prime_numbers[j] = False
input()
count = 0
for i in map(int, input().split()):
if prime_numbers[i] is True:
count += 1
print(count)
|
prime_numbers = [True for x in range(1001)]
prime_numbers[1] = False
for i in range(2, 1001):
for j in range(2 * i, 1001, i):
prime_numbers[j] = False
input()
count = 0
for i in map(int, input().split()):
if prime_numbers[i] is True:
count += 1
print(count)
|
def intersection(right=[], left=[]):
return list(set(right).intersection(set(left)))
def union(right=[], left=[]):
return list(set(right).union(set(left)))
def union(right=[], left=[]):
return list(set(right).difference(set(left))) # not have in left
|
def intersection(right=[], left=[]):
return list(set(right).intersection(set(left)))
def union(right=[], left=[]):
return list(set(right).union(set(left)))
def union(right=[], left=[]):
return list(set(right).difference(set(left)))
|
class Book:
"""The Book object contains all the information about a book"""
def __init__(self, title, author, date, genre):
"""Object constructor
:param title: title of the Book
:type title: str
:param author: author of the book
:type author: str
:param data: the date at which the book has been published
:param date: str
:param genre: the subject/type of the book
:type genre: str
"""
self.title = title
self.author = author
self.date = date
self.genre = genre
def to_json(self):
"""
to_json converts the object into a json object
:var json_dict: contains information about the book
:type json_dict: dict
:returns: a dict (json) containing of the information of the book
:rtype: dict
"""
json_dict = {
'title': self.title,
'author': self.author,
'date': self.date,
'genre': self.genre
}
return json_dict
def __eq__(self, other):
return (self.to_json() == other.to_json())
def __repr__(self):
return str(self.to_json())
def __str__(self):
return str(self.to_json())
|
class Book:
"""The Book object contains all the information about a book"""
def __init__(self, title, author, date, genre):
"""Object constructor
:param title: title of the Book
:type title: str
:param author: author of the book
:type author: str
:param data: the date at which the book has been published
:param date: str
:param genre: the subject/type of the book
:type genre: str
"""
self.title = title
self.author = author
self.date = date
self.genre = genre
def to_json(self):
"""
to_json converts the object into a json object
:var json_dict: contains information about the book
:type json_dict: dict
:returns: a dict (json) containing of the information of the book
:rtype: dict
"""
json_dict = {'title': self.title, 'author': self.author, 'date': self.date, 'genre': self.genre}
return json_dict
def __eq__(self, other):
return self.to_json() == other.to_json()
def __repr__(self):
return str(self.to_json())
def __str__(self):
return str(self.to_json())
|
########
# Copyright (c) 2014 GigaSpaces Technologies Ltd. All rights reserved
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# * See the License for the specific language governing permissions and
# * limitations under the License.
class EvaluatedFunctions(dict):
"""
Evaluated functions.
"""
def __init__(self, evaluated_functions):
self.update(evaluated_functions)
@property
def deployment_id(self):
"""
:return: The deployment id this request belongs to.
"""
return self['deployment_id']
@property
def payload(self):
"""
:return: The evaluation payload.
"""
return self['payload']
class EvaluateClient(object):
def __init__(self, api):
self.api = api
def functions(self, deployment_id, context, payload):
"""Evaluate intrinsic functions in payload in respect to the
provided context.
:param deployment_id: The deployment's id of the node.
:param context: The processing context
(dict with optional self, source, target).
:param payload: The payload to process.
:return: The payload with its intrinsic functions references
evaluated.
:rtype: EvaluatedFunctions
"""
assert deployment_id
result = self.api.post('/evaluate/functions', data={
'deployment_id': deployment_id,
'context': context,
'payload': payload
})
return EvaluatedFunctions(result)
|
class Evaluatedfunctions(dict):
"""
Evaluated functions.
"""
def __init__(self, evaluated_functions):
self.update(evaluated_functions)
@property
def deployment_id(self):
"""
:return: The deployment id this request belongs to.
"""
return self['deployment_id']
@property
def payload(self):
"""
:return: The evaluation payload.
"""
return self['payload']
class Evaluateclient(object):
def __init__(self, api):
self.api = api
def functions(self, deployment_id, context, payload):
"""Evaluate intrinsic functions in payload in respect to the
provided context.
:param deployment_id: The deployment's id of the node.
:param context: The processing context
(dict with optional self, source, target).
:param payload: The payload to process.
:return: The payload with its intrinsic functions references
evaluated.
:rtype: EvaluatedFunctions
"""
assert deployment_id
result = self.api.post('/evaluate/functions', data={'deployment_id': deployment_id, 'context': context, 'payload': payload})
return evaluated_functions(result)
|
"""Workspace rules (Nixpkgs)"""
load("@bazel_skylib//lib:dicts.bzl", "dicts")
load(
"@io_tweag_rules_nixpkgs//nixpkgs:nixpkgs.bzl",
"nixpkgs_package",
)
def haskell_nixpkgs_package(
name,
attribute_path,
nix_file_deps = [],
repositories = {},
build_file_content = None,
build_file = None,
**kwargs):
"""Load a single haskell package.
The package is expected to be in the form of the packages generated by
`genBazelBuild.nix`
"""
repositories = dicts.add(
{"bazel_haskell_wrapper": "@io_tweag_rules_haskell//haskell:nix/default.nix"},
repositories,
)
nixpkgs_args = dict(
name = name,
attribute_path = attribute_path,
build_file_content = build_file_content,
nix_file_deps = nix_file_deps + ["@io_tweag_rules_haskell//haskell:nix/default.nix"],
repositories = repositories,
**kwargs
)
if build_file_content:
nixpkgs_args["build_file_content"] = build_file_content
elif build_file:
nixpkgs_args["build_file"] = build_file
else:
nixpkgs_args["build_file_content"] = """
package(default_visibility = ["//visibility:public"])
load("@io_tweag_rules_haskell//haskell:import.bzl", haskell_import_new = "haskell_import")
load(":BUILD.bzl", "targets")
targets()
"""
nixpkgs_package(
**nixpkgs_args
)
def _bundle_impl(repository_ctx):
build_file_content = """
package(default_visibility = ["//visibility:public"])
"""
for package in repository_ctx.attr.packages:
build_file_content += """
alias(
name = "{package}",
actual = "@{base_repo}-{package}//:pkg",
)
""".format(
package = package,
base_repo = repository_ctx.attr.base_repository,
)
repository_ctx.file("BUILD", build_file_content)
_bundle = repository_rule(
attrs = {
"packages": attr.string_list(),
"base_repository": attr.string(),
},
implementation = _bundle_impl,
)
"""
Generate an alias from `@base_repo//:package` to `@base_repo-package//:pkg` for
each one of the input package
"""
def haskell_nixpkgs_packages(name, base_attribute_path, packages, **kwargs):
"""Import a set of haskell packages from nixpkgs.
This takes as input the same arguments as
[nixpkgs_package](https://github.com/tweag/rules_nixpkgs#nixpkgs_package),
expecting the `attribute_path` to resolve to a set of haskell packages
(such as `haskellPackages` or `haskell.packages.ghc822`) preprocessed by
the `genBazelBuild` function. It also takes as input a list of packages to
import (which can be generated by the `gen_packages_list` function).
"""
for package in packages:
haskell_nixpkgs_package(
name = name + "-" + package,
attribute_path = base_attribute_path + "." + package,
**kwargs
)
_bundle(
name = name,
packages = packages,
base_repository = name,
)
def _is_nix_platform(repository_ctx):
return repository_ctx.which("nix-build") != None
def _gen_imports_impl(repository_ctx):
repository_ctx.file("BUILD", "")
extra_args_raw = ""
for foo, bar in repository_ctx.attr.extra_args.items():
extra_args_raw += foo + " = " + bar + ", "
bzl_file_content = """
load("{repo_name}", "packages")
load("@io_tweag_rules_haskell//haskell:nixpkgs.bzl", "haskell_nixpkgs_packages")
def import_packages(name):
haskell_nixpkgs_packages(
name = name,
packages = packages,
{extra_args_raw}
)
""".format(
repo_name = repository_ctx.attr.packages_list_file,
extra_args_raw = extra_args_raw,
)
# A dummy 'packages.bzl' file with a no-op 'import_packages()' on unsupported platforms
bzl_file_content_unsupported_platform = """
def import_packages(name):
return
"""
if _is_nix_platform(repository_ctx):
repository_ctx.file("packages.bzl", bzl_file_content)
else:
repository_ctx.file("packages.bzl", bzl_file_content_unsupported_platform)
_gen_imports_str = repository_rule(
implementation = _gen_imports_impl,
attrs = dict(
packages_list_file = attr.label(doc = "A list containing the list of packages to import"),
# We pass the extra arguments to `haskell_nixpkgs_packages` as strings
# since we can't forward arbitrary arguments in a rule and they will be
# converted to strings anyways.
extra_args = attr.string_dict(doc = "Extra arguments for `haskell_nixpkgs_packages`"),
),
)
"""
Generate a repository containing a file `packages.bzl` which imports the given
packages list.
"""
def _gen_imports(name, packages_list_file, extra_args):
"""
A wrapper around `_gen_imports_str` which allows passing an arbitrary set of
`extra_args` instead of a set of strings
"""
extra_args_str = {label: repr(value) for (label, value) in extra_args.items()}
_gen_imports_str(
name = name,
packages_list_file = packages_list_file,
extra_args = extra_args_str,
)
def haskell_nixpkgs_packageset(name, base_attribute_path, repositories = {}, **kwargs):
"""Import all the available haskell packages.
The arguments are the same as the arguments of ``nixpkgs_package``, except
for the ``base_attribute_path`` which should point to an `haskellPackages`
set in the nix expression
Example:
In `haskellPackages.nix`:
```nix
with import <nixpkgs> {};
let wrapPackages = callPackage <bazel_haskell_wrapper> { }; in
{ haskellPackages = wrapPackages haskell.packages.ghc822; }
```
In your `WORKSPACE`
```bazel
# Define a nix repository to fetch the packages from
load("@io_tweag_rules_nixpkgs//nixpkgs:nixpkgs.bzl",
"nixpkgs_git_repository")
nixpkgs_git_repository(
name = "nixpkgs",
revision = "9a787af6bc75a19ac9f02077ade58ddc248e674a",
)
load("@io_tweag_rules_haskell//haskell:nixpkgs.bzl",
"haskell_nixpkgs_packageset",
# Generate a list of all the available haskell packages
haskell_nixpkgs_packageset(
name = "hackage-packages",
repositories = {"@nixpkgs": "nixpkgs"},
nix_file = "//haskellPackages.nix",
base_attribute_path = "haskellPackages",
)
load("@hackage-packages//:packages.bzl", "import_packages")
import_packages(name = "hackage")
```
Then in your `BUILD` files, you can access to the whole of hackage as
`@hackage//:{your-package-name}`
"""
repositories = dicts.add(
{"bazel_haskell_wrapper": "@io_tweag_rules_haskell//haskell:nix/default.nix"},
repositories,
)
nixpkgs_package(
name = name + "-packages-list",
attribute_path = base_attribute_path + ".packageNames",
repositories = repositories,
build_file_content = """
exports_files(["all-haskell-packages.bzl"])
""",
fail_not_supported = False,
**kwargs
)
_gen_imports(
name = name,
packages_list_file = "@" + name + "-packages-list//:all-haskell-packages.bzl",
extra_args = dict(
repositories = repositories,
base_attribute_path = base_attribute_path,
**kwargs
),
)
def _ghc_nixpkgs_toolchain_impl(repository_ctx):
# These constraints might look tautological, because they always
# match the host platform if it is the same as the target
# platform. But they are important to state because Bazel
# toolchain resolution prefers other toolchains with more specific
# constraints otherwise.
target_constraints = ["@bazel_tools//platforms:x86_64"]
if repository_ctx.os.name == "linux":
target_constraints.append("@bazel_tools//platforms:linux")
elif repository_ctx.os.name == "mac os x":
target_constraints.append("@bazel_tools//platforms:osx")
exec_constraints = list(target_constraints)
exec_constraints.append("@io_tweag_rules_haskell//haskell/platforms:nixpkgs")
repository_ctx.file(
"BUILD",
executable = False,
content = """
load("@io_tweag_rules_haskell//haskell:toolchain.bzl", "haskell_toolchain")
haskell_toolchain(
name = "toolchain",
tools = "{tools}",
version = "{version}",
compiler_flags = {compiler_flags},
haddock_flags = {haddock_flags},
repl_ghci_args = {repl_ghci_args},
# On Darwin we don't need a locale archive. It's a Linux-specific
# hack in Nixpkgs.
locale_archive = "{locale_archive}",
exec_compatible_with = {exec_constraints},
target_compatible_with = {target_constraints},
)
""".format(
tools = "@io_tweag_rules_haskell_ghc-nixpkgs//:bin",
version = repository_ctx.attr.version,
compiler_flags = str(repository_ctx.attr.compiler_flags),
haddock_flags = str(repository_ctx.attr.haddock_flags),
repl_ghci_args = str(repository_ctx.attr.repl_ghci_args),
locale_archive = repository_ctx.attr.locale_archive,
exec_constraints = exec_constraints,
target_constraints = target_constraints,
),
)
_ghc_nixpkgs_toolchain = repository_rule(
_ghc_nixpkgs_toolchain_impl,
local = False,
attrs = {
# These attributes just forward to haskell_toolchain.
# They are documented there.
"version": attr.string(),
"compiler_flags": attr.string_list(),
"haddock_flags": attr.string_list(),
"repl_ghci_args": attr.string_list(),
"locale_archive": attr.string(),
},
)
def haskell_register_ghc_nixpkgs(
version,
compiler_flags = None,
haddock_flags = None,
repl_ghci_args = None,
locale_archive = None,
attribute_path = "haskellPackages.ghc",
nix_file = None,
nix_file_deps = [],
repositories = {}):
"""Register a package from Nixpkgs as a toolchain.
Toolchains can be used to compile Haskell code. To have this
toolchain selected during [toolchain
resolution][toolchain-resolution], set a host platform that
includes the `@io_tweag_rules_haskell//haskell/platforms:nixpkgs`
constraint value.
[toolchain-resolution]: https://docs.bazel.build/versions/master/toolchains.html#toolchain-resolution
Example:
```
haskell_register_ghc_nixpkgs(
locale_archive = "@glibc_locales//:locale-archive",
atttribute_path = "haskellPackages.ghc",
version = "1.2.3", # The version of GHC
)
```
Setting the host platform can be done on the command-line like
in the following:
```
--host_platform=@io_tweag_rules_haskell//haskell/platforms:linux_x86_64_nixpkgs
```
"""
haskell_nixpkgs_package(
name = "io_tweag_rules_haskell_ghc-nixpkgs",
attribute_path = attribute_path,
build_file = "//haskell:ghc.BUILD",
nix_file = nix_file,
nix_file_deps = nix_file_deps,
repositories = repositories,
)
_ghc_nixpkgs_toolchain(
name = "io_tweag_rules_haskell_ghc-nixpkgs-toolchain",
version = version,
compiler_flags = compiler_flags,
haddock_flags = haddock_flags,
repl_ghci_args = repl_ghci_args,
locale_archive = locale_archive,
)
native.register_toolchains("@io_tweag_rules_haskell_ghc-nixpkgs-toolchain//:toolchain")
|
"""Workspace rules (Nixpkgs)"""
load('@bazel_skylib//lib:dicts.bzl', 'dicts')
load('@io_tweag_rules_nixpkgs//nixpkgs:nixpkgs.bzl', 'nixpkgs_package')
def haskell_nixpkgs_package(name, attribute_path, nix_file_deps=[], repositories={}, build_file_content=None, build_file=None, **kwargs):
"""Load a single haskell package.
The package is expected to be in the form of the packages generated by
`genBazelBuild.nix`
"""
repositories = dicts.add({'bazel_haskell_wrapper': '@io_tweag_rules_haskell//haskell:nix/default.nix'}, repositories)
nixpkgs_args = dict(name=name, attribute_path=attribute_path, build_file_content=build_file_content, nix_file_deps=nix_file_deps + ['@io_tweag_rules_haskell//haskell:nix/default.nix'], repositories=repositories, **kwargs)
if build_file_content:
nixpkgs_args['build_file_content'] = build_file_content
elif build_file:
nixpkgs_args['build_file'] = build_file
else:
nixpkgs_args['build_file_content'] = '\npackage(default_visibility = ["//visibility:public"])\nload("@io_tweag_rules_haskell//haskell:import.bzl", haskell_import_new = "haskell_import")\n\nload(":BUILD.bzl", "targets")\ntargets()\n'
nixpkgs_package(**nixpkgs_args)
def _bundle_impl(repository_ctx):
build_file_content = '\npackage(default_visibility = ["//visibility:public"])\n '
for package in repository_ctx.attr.packages:
build_file_content += '\nalias(\n name = "{package}",\n actual = "@{base_repo}-{package}//:pkg",\n)\n '.format(package=package, base_repo=repository_ctx.attr.base_repository)
repository_ctx.file('BUILD', build_file_content)
_bundle = repository_rule(attrs={'packages': attr.string_list(), 'base_repository': attr.string()}, implementation=_bundle_impl)
'\nGenerate an alias from `@base_repo//:package` to `@base_repo-package//:pkg` for\neach one of the input package\n'
def haskell_nixpkgs_packages(name, base_attribute_path, packages, **kwargs):
"""Import a set of haskell packages from nixpkgs.
This takes as input the same arguments as
[nixpkgs_package](https://github.com/tweag/rules_nixpkgs#nixpkgs_package),
expecting the `attribute_path` to resolve to a set of haskell packages
(such as `haskellPackages` or `haskell.packages.ghc822`) preprocessed by
the `genBazelBuild` function. It also takes as input a list of packages to
import (which can be generated by the `gen_packages_list` function).
"""
for package in packages:
haskell_nixpkgs_package(name=name + '-' + package, attribute_path=base_attribute_path + '.' + package, **kwargs)
_bundle(name=name, packages=packages, base_repository=name)
def _is_nix_platform(repository_ctx):
return repository_ctx.which('nix-build') != None
def _gen_imports_impl(repository_ctx):
repository_ctx.file('BUILD', '')
extra_args_raw = ''
for (foo, bar) in repository_ctx.attr.extra_args.items():
extra_args_raw += foo + ' = ' + bar + ', '
bzl_file_content = '\nload("{repo_name}", "packages")\nload("@io_tweag_rules_haskell//haskell:nixpkgs.bzl", "haskell_nixpkgs_packages")\n\ndef import_packages(name):\n haskell_nixpkgs_packages(\n name = name,\n packages = packages,\n {extra_args_raw}\n )\n '.format(repo_name=repository_ctx.attr.packages_list_file, extra_args_raw=extra_args_raw)
bzl_file_content_unsupported_platform = '\ndef import_packages(name):\n return\n '
if _is_nix_platform(repository_ctx):
repository_ctx.file('packages.bzl', bzl_file_content)
else:
repository_ctx.file('packages.bzl', bzl_file_content_unsupported_platform)
_gen_imports_str = repository_rule(implementation=_gen_imports_impl, attrs=dict(packages_list_file=attr.label(doc='A list containing the list of packages to import'), extra_args=attr.string_dict(doc='Extra arguments for `haskell_nixpkgs_packages`')))
'\nGenerate a repository containing a file `packages.bzl` which imports the given\npackages list.\n'
def _gen_imports(name, packages_list_file, extra_args):
"""
A wrapper around `_gen_imports_str` which allows passing an arbitrary set of
`extra_args` instead of a set of strings
"""
extra_args_str = {label: repr(value) for (label, value) in extra_args.items()}
_gen_imports_str(name=name, packages_list_file=packages_list_file, extra_args=extra_args_str)
def haskell_nixpkgs_packageset(name, base_attribute_path, repositories={}, **kwargs):
"""Import all the available haskell packages.
The arguments are the same as the arguments of ``nixpkgs_package``, except
for the ``base_attribute_path`` which should point to an `haskellPackages`
set in the nix expression
Example:
In `haskellPackages.nix`:
```nix
with import <nixpkgs> {};
let wrapPackages = callPackage <bazel_haskell_wrapper> { }; in
{ haskellPackages = wrapPackages haskell.packages.ghc822; }
```
In your `WORKSPACE`
```bazel
# Define a nix repository to fetch the packages from
load("@io_tweag_rules_nixpkgs//nixpkgs:nixpkgs.bzl",
"nixpkgs_git_repository")
nixpkgs_git_repository(
name = "nixpkgs",
revision = "9a787af6bc75a19ac9f02077ade58ddc248e674a",
)
load("@io_tweag_rules_haskell//haskell:nixpkgs.bzl",
"haskell_nixpkgs_packageset",
# Generate a list of all the available haskell packages
haskell_nixpkgs_packageset(
name = "hackage-packages",
repositories = {"@nixpkgs": "nixpkgs"},
nix_file = "//haskellPackages.nix",
base_attribute_path = "haskellPackages",
)
load("@hackage-packages//:packages.bzl", "import_packages")
import_packages(name = "hackage")
```
Then in your `BUILD` files, you can access to the whole of hackage as
`@hackage//:{your-package-name}`
"""
repositories = dicts.add({'bazel_haskell_wrapper': '@io_tweag_rules_haskell//haskell:nix/default.nix'}, repositories)
nixpkgs_package(name=name + '-packages-list', attribute_path=base_attribute_path + '.packageNames', repositories=repositories, build_file_content='\nexports_files(["all-haskell-packages.bzl"])\n ', fail_not_supported=False, **kwargs)
_gen_imports(name=name, packages_list_file='@' + name + '-packages-list//:all-haskell-packages.bzl', extra_args=dict(repositories=repositories, base_attribute_path=base_attribute_path, **kwargs))
def _ghc_nixpkgs_toolchain_impl(repository_ctx):
target_constraints = ['@bazel_tools//platforms:x86_64']
if repository_ctx.os.name == 'linux':
target_constraints.append('@bazel_tools//platforms:linux')
elif repository_ctx.os.name == 'mac os x':
target_constraints.append('@bazel_tools//platforms:osx')
exec_constraints = list(target_constraints)
exec_constraints.append('@io_tweag_rules_haskell//haskell/platforms:nixpkgs')
repository_ctx.file('BUILD', executable=False, content='\nload("@io_tweag_rules_haskell//haskell:toolchain.bzl", "haskell_toolchain")\n\nhaskell_toolchain(\n name = "toolchain",\n tools = "{tools}",\n version = "{version}",\n compiler_flags = {compiler_flags},\n haddock_flags = {haddock_flags},\n repl_ghci_args = {repl_ghci_args},\n # On Darwin we don\'t need a locale archive. It\'s a Linux-specific\n # hack in Nixpkgs.\n locale_archive = "{locale_archive}",\n exec_compatible_with = {exec_constraints},\n target_compatible_with = {target_constraints},\n)\n '.format(tools='@io_tweag_rules_haskell_ghc-nixpkgs//:bin', version=repository_ctx.attr.version, compiler_flags=str(repository_ctx.attr.compiler_flags), haddock_flags=str(repository_ctx.attr.haddock_flags), repl_ghci_args=str(repository_ctx.attr.repl_ghci_args), locale_archive=repository_ctx.attr.locale_archive, exec_constraints=exec_constraints, target_constraints=target_constraints))
_ghc_nixpkgs_toolchain = repository_rule(_ghc_nixpkgs_toolchain_impl, local=False, attrs={'version': attr.string(), 'compiler_flags': attr.string_list(), 'haddock_flags': attr.string_list(), 'repl_ghci_args': attr.string_list(), 'locale_archive': attr.string()})
def haskell_register_ghc_nixpkgs(version, compiler_flags=None, haddock_flags=None, repl_ghci_args=None, locale_archive=None, attribute_path='haskellPackages.ghc', nix_file=None, nix_file_deps=[], repositories={}):
"""Register a package from Nixpkgs as a toolchain.
Toolchains can be used to compile Haskell code. To have this
toolchain selected during [toolchain
resolution][toolchain-resolution], set a host platform that
includes the `@io_tweag_rules_haskell//haskell/platforms:nixpkgs`
constraint value.
[toolchain-resolution]: https://docs.bazel.build/versions/master/toolchains.html#toolchain-resolution
Example:
```
haskell_register_ghc_nixpkgs(
locale_archive = "@glibc_locales//:locale-archive",
atttribute_path = "haskellPackages.ghc",
version = "1.2.3", # The version of GHC
)
```
Setting the host platform can be done on the command-line like
in the following:
```
--host_platform=@io_tweag_rules_haskell//haskell/platforms:linux_x86_64_nixpkgs
```
"""
haskell_nixpkgs_package(name='io_tweag_rules_haskell_ghc-nixpkgs', attribute_path=attribute_path, build_file='//haskell:ghc.BUILD', nix_file=nix_file, nix_file_deps=nix_file_deps, repositories=repositories)
_ghc_nixpkgs_toolchain(name='io_tweag_rules_haskell_ghc-nixpkgs-toolchain', version=version, compiler_flags=compiler_flags, haddock_flags=haddock_flags, repl_ghci_args=repl_ghci_args, locale_archive=locale_archive)
native.register_toolchains('@io_tweag_rules_haskell_ghc-nixpkgs-toolchain//:toolchain')
|
{
"target_defaults":
{
"cflags" : ["-Wall", "-Wextra", "-Wno-unused-parameter"],
"include_dirs": ["<!(node -e \"require('..')\")", "<!(node -e \"require('nan')\")",]
},
"targets": [
{
"target_name" : "primeNumbers",
"sources" : [ "cpp/primeNumbers.cpp" ],
"target_conditions": [
['OS=="mac"', {
'xcode_settings': {
'GCC_ENABLE_CPP_EXCEPTIONS': 'YES',
'GCC_ENABLE_CPP_RTTI': 'YES',
'OTHER_CFLAGS': [ '-g', '-mmacosx-version-min=10.7', '-std=c++11', '-stdlib=libc++' ],
'OTHER_CPLUSPLUSFLAGS': [ '-g', '-mmacosx-version-min=10.7', '-std=c++11', '-stdlib=libc++' ]
}
}],
['OS=="linux" or OS=="freebsd" or OS=="openbsd" or OS=="solaris"', {
'libraries!': [ '-undefined dynamic_lookup' ],
'cflags_cc!': [ '-fno-exceptions', '-fno-rtti' ],
"cflags": [ '-std=c++11', '-fexceptions', '-frtti' ],
}]
]
}
]}
|
{'target_defaults': {'cflags': ['-Wall', '-Wextra', '-Wno-unused-parameter'], 'include_dirs': ['<!(node -e "require(\'..\')")', '<!(node -e "require(\'nan\')")']}, 'targets': [{'target_name': 'primeNumbers', 'sources': ['cpp/primeNumbers.cpp'], 'target_conditions': [['OS=="mac"', {'xcode_settings': {'GCC_ENABLE_CPP_EXCEPTIONS': 'YES', 'GCC_ENABLE_CPP_RTTI': 'YES', 'OTHER_CFLAGS': ['-g', '-mmacosx-version-min=10.7', '-std=c++11', '-stdlib=libc++'], 'OTHER_CPLUSPLUSFLAGS': ['-g', '-mmacosx-version-min=10.7', '-std=c++11', '-stdlib=libc++']}}], ['OS=="linux" or OS=="freebsd" or OS=="openbsd" or OS=="solaris"', {'libraries!': ['-undefined dynamic_lookup'], 'cflags_cc!': ['-fno-exceptions', '-fno-rtti'], 'cflags': ['-std=c++11', '-fexceptions', '-frtti']}]]}]}
|
line = input()
a, b = line.split()
a = int(a)
b = int(b)
if a < b:
print(a, b)
else:
print(b, a)
"""nums = [int(i) for i in input().split()]
print(f"{min(nums)} {max(nums)}")"""
|
line = input()
(a, b) = line.split()
a = int(a)
b = int(b)
if a < b:
print(a, b)
else:
print(b, a)
'nums = [int(i) for i in input().split()]\nprint(f"{min(nums)} {max(nums)}")'
|
#!/usr/bin/python3
# -*- coding: utf-8 -*-
def main():
print(add(5,10))
print(add(5))
print(add(5,6))
print(add(x=5, y=2))
# print(add(x=5, 2)) # Error we need to use the both with name if you use the first one as named argument
print(add(5,y=2))
print(1,2,3,4,5, sep=" - ")
def add(x, y=3):
total = x + y
return total
if __name__ == "__main__":
main()
|
def main():
print(add(5, 10))
print(add(5))
print(add(5, 6))
print(add(x=5, y=2))
print(add(5, y=2))
print(1, 2, 3, 4, 5, sep=' - ')
def add(x, y=3):
total = x + y
return total
if __name__ == '__main__':
main()
|
"""Created by sgoswami on 7/3/17."""
"""Given two binary strings, return their sum (also a binary string).
For example,
a = \"11\"
b = \"1\"
Return \"100\"."""
class Solution(object):
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
return bin(int(a, 2) + int(b, 2))[2:]
if __name__ == '__main__':
solution = Solution()
print(solution.addBinary('11', '1'))
|
"""Created by sgoswami on 7/3/17."""
'Given two binary strings, return their sum (also a binary string).\nFor example,\na = "11"\nb = "1"\nReturn "100".'
class Solution(object):
def add_binary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
return bin(int(a, 2) + int(b, 2))[2:]
if __name__ == '__main__':
solution = solution()
print(solution.addBinary('11', '1'))
|
# 59. Spiral Matrix II
# O(n) time | O(n) space
class Solution:
def fillMatrix(self, spiralMatrix: [[int]], startIter: int, endIter: int, runningValue=1) -> None:
if startIter > endIter:
return
for index in range(startIter, endIter + 1):
spiralMatrix[startIter][index] = runningValue
runningValue += 1
for index in range(startIter + 1, endIter + 1):
spiralMatrix[index][endIter] = runningValue
runningValue += 1
for index in reversed(range(startIter, endIter)):
spiralMatrix[endIter][index] = runningValue
runningValue += 1
for index in reversed(range(startIter + 1, endIter)):
spiralMatrix[index][startIter] = runningValue
runningValue += 1
self.fillMatrix(spiralMatrix, startIter + 1, endIter - 1, runningValue)
def generateMatrix(self, n: int) -> [[int]]:
"""
Given a positive integer n, generate a square matrix filled with elements from 1 to n^2 in spiral order.
"""
matrix = [[None for _ in range(n)] for _ in range(n)]
self.fillMatrix(matrix, 0, n - 1)
print(matrix)
return matrix
|
class Solution:
def fill_matrix(self, spiralMatrix: [[int]], startIter: int, endIter: int, runningValue=1) -> None:
if startIter > endIter:
return
for index in range(startIter, endIter + 1):
spiralMatrix[startIter][index] = runningValue
running_value += 1
for index in range(startIter + 1, endIter + 1):
spiralMatrix[index][endIter] = runningValue
running_value += 1
for index in reversed(range(startIter, endIter)):
spiralMatrix[endIter][index] = runningValue
running_value += 1
for index in reversed(range(startIter + 1, endIter)):
spiralMatrix[index][startIter] = runningValue
running_value += 1
self.fillMatrix(spiralMatrix, startIter + 1, endIter - 1, runningValue)
def generate_matrix(self, n: int) -> [[int]]:
"""
Given a positive integer n, generate a square matrix filled with elements from 1 to n^2 in spiral order.
"""
matrix = [[None for _ in range(n)] for _ in range(n)]
self.fillMatrix(matrix, 0, n - 1)
print(matrix)
return matrix
|
"""
Space = O(1)
Time = O(n log n)
"""
class Solution:
def removeCoveredIntervals(self, intervals: List[List[int]]) -> int:
ans = 0
intervals.sort(key=lambda a: (a[0], -a[1]))
end = 0
for i, j in intervals:
if j > end:
ans += 1
end = max(end, j)
return ans
|
"""
Space = O(1)
Time = O(n log n)
"""
class Solution:
def remove_covered_intervals(self, intervals: List[List[int]]) -> int:
ans = 0
intervals.sort(key=lambda a: (a[0], -a[1]))
end = 0
for (i, j) in intervals:
if j > end:
ans += 1
end = max(end, j)
return ans
|
AgentID = str
""" Assigned by Kentik """
TestID = str
""" Assigned by Kentik """
Threshold = float
""" latency and jitter in milliseconds, packet_loss in percent (0-100) """
MetricValue = float
""" latency and jitter in milliseconds, packet_loss in percent (0-100) """
|
agent_id = str
' Assigned by Kentik '
test_id = str
' Assigned by Kentik '
threshold = float
' latency and jitter in milliseconds, packet_loss in percent (0-100) '
metric_value = float
' latency and jitter in milliseconds, packet_loss in percent (0-100) '
|
#!/usr/bin/python3
class VectorFeeder:
def __init__(self, vectors, words, cursor=0):
self.data = vectors
self.cursor = cursor
self.words = words
print('len words', len(self.words), 'len data', len(self.data))
def get_next_batch(self, size):
batch = self.data[self.cursor:(self.cursor+size)]
word_batch = self.words[self.cursor:(self.cursor+size)]
self.cursor += size
return batch, word_batch
def has_next(self):
return self.cursor < len(self.data)
def get_cursor(self):
return self.cursor
|
class Vectorfeeder:
def __init__(self, vectors, words, cursor=0):
self.data = vectors
self.cursor = cursor
self.words = words
print('len words', len(self.words), 'len data', len(self.data))
def get_next_batch(self, size):
batch = self.data[self.cursor:self.cursor + size]
word_batch = self.words[self.cursor:self.cursor + size]
self.cursor += size
return (batch, word_batch)
def has_next(self):
return self.cursor < len(self.data)
def get_cursor(self):
return self.cursor
|
expected_output = {
"instance": {
"default": {
"vrf": {
"VRF1": {
"address_family": {
"vpnv4 unicast RD 100:100": {
"default_vrf": "VRF1",
"prefixes": {
"10.229.11.11/32": {
"available_path": "1",
"best_path": "1",
"index": {
1: {
"gateway": "0.0.0.0",
"inaccessible": False,
"localpref": 100,
"metric": 0,
"next_hop": "0.0.0.0",
"next_hop_via": "vrf VRF1",
"origin_codes": "?",
"originator": "10.1.1.1",
"recipient_pathid": "0",
"refresh_epoch": 1,
"route_info": "Local",
"status_codes": "*>",
"transfer_pathid": "0x0",
"weight": "32768",
}
},
"paths": "1 available, best #1, table VRF1",
"table_version": "2",
}
},
"route_distinguisher": "100:100",
},
"vpnv6 unicast RD 100:100": {
"default_vrf": "VRF1",
"prefixes": {
"2001:11:11::11/128": {
"available_path": "1",
"best_path": "1",
"index": {
1: {
"gateway": "0.0.0.0",
"inaccessible": False,
"localpref": 100,
"metric": 0,
"next_hop": "::",
"next_hop_via": "vrf VRF1",
"origin_codes": "?",
"originator": "10.1.1.1",
"recipient_pathid": "0",
"refresh_epoch": 1,
"route_info": "Local",
"status_codes": "*>",
"transfer_pathid": "0x0",
"weight": "32768",
}
},
"paths": "1 available, best #1, table VRF1",
"table_version": "2",
}
},
"route_distinguisher": "100:100",
},
}
},
"default": {
"address_family": {
"ipv4 unicast": {
"prefixes": {
"10.4.1.1/32": {
"available_path": "1",
"best_path": "1",
"index": {
1: {
"gateway": "0.0.0.0",
"localpref": 100,
"metric": 0,
"next_hop": "0.0.0.0",
"origin_codes": "?",
"originator": "10.1.1.1",
"recipient_pathid": "0",
"refresh_epoch": 1,
"route_info": "Local",
"status_codes": "*>",
"transfer_pathid": "0x0",
"update_group": 3,
"weight": "32768",
}
},
"paths": "1 available, best #1, table default, RIB-failure(17)",
"table_version": "4",
},
"10.1.1.0/24": {
"available_path": "2",
"best_path": "1",
"index": {
1: {
"gateway": "0.0.0.0",
"localpref": 100,
"metric": 0,
"next_hop": "0.0.0.0",
"origin_codes": "?",
"originator": "10.1.1.1",
"recipient_pathid": "0",
"refresh_epoch": 1,
"route_info": "Local",
"status_codes": "*>",
"transfer_pathid": "0x0",
"update_group": 3,
"weight": "32768",
},
2: {
"gateway": "10.1.1.2",
"localpref": 100,
"metric": 0,
"next_hop": "10.1.1.2",
"origin_codes": "?",
"originator": "10.1.1.2",
"recipient_pathid": "0",
"transfer_pathid": "0",
"refresh_epoch": 1,
"route_info": "Local",
"status_codes": "* i",
"update_group": 3,
},
},
"paths": "2 available, best #1, table default",
"table_version": "5",
},
"10.16.2.2/32": {
"available_path": "1",
"best_path": "1",
"index": {
1: {
"gateway": "10.1.1.2",
"localpref": 100,
"metric": 0,
"next_hop": "10.1.1.2",
"origin_codes": "?",
"originator": "10.1.1.2",
"recipient_pathid": "0",
"refresh_epoch": 1,
"route_info": "Local",
"status_codes": "*>",
"transfer_pathid": "0x0",
}
},
"paths": "1 available, best #1, table default",
"table_version": "2",
},
}
},
"ipv6 unicast": {
"prefixes": {
"2001:1:1:1::1/128": {
"available_path": "1",
"best_path": "1",
"index": {
1: {
"gateway": "0.0.0.0",
"localpref": 100,
"metric": 0,
"next_hop": "::",
"origin_codes": "?",
"originator": "10.1.1.1",
"recipient_pathid": "0",
"refresh_epoch": 1,
"route_info": "Local",
"status_codes": "*>",
"transfer_pathid": "0x0",
"update_group": 1,
"weight": "32768",
}
},
"paths": "1 available, best #1, table default",
"table_version": "4",
},
"2001:2:2:2::2/128": {
"available_path": "2",
"best_path": "1",
"index": {
1: {
"gateway": "2001:DB8:1:1::2",
"localpref": 100,
"metric": 0,
"next_hop": "2001:DB8:1:1::2",
"origin_codes": "?",
"originator": "10.1.1.2",
"recipient_pathid": "0",
"refresh_epoch": 1,
"route_info": "Local",
"status_codes": "*>",
"transfer_pathid": "0x0",
},
2: {
"gateway": "10.1.1.2",
"localpref": 100,
"metric": 0,
"next_hop": "::FFFF:10.1.1.2",
"origin_codes": "?",
"originator": "10.1.1.2",
"recipient_pathid": "0",
"transfer_pathid": "0",
"refresh_epoch": 1,
"route_info": "Local",
"status_codes": "* i",
},
},
"paths": "2 available, best #1, table default",
"table_version": "2",
},
"2001:DB8:1:1::/64": {
"available_path": "3",
"best_path": "1",
"index": {
1: {
"gateway": "0.0.0.0",
"localpref": 100,
"metric": 0,
"next_hop": "::",
"origin_codes": "?",
"originator": "10.1.1.1",
"recipient_pathid": "0",
"refresh_epoch": 1,
"route_info": "Local",
"status_codes": "*>",
"transfer_pathid": "0x0",
"update_group": 1,
"weight": "32768",
},
2: {
"gateway": "2001:DB8:1:1::2",
"localpref": 100,
"metric": 0,
"next_hop": "2001:DB8:1:1::2",
"origin_codes": "?",
"originator": "10.1.1.2",
"recipient_pathid": "0",
"transfer_pathid": "0",
"refresh_epoch": 1,
"route_info": "Local",
"status_codes": "* i",
"update_group": 1,
},
3: {
"gateway": "10.1.1.2",
"localpref": 100,
"metric": 0,
"next_hop": "::FFFF:10.1.1.2",
"origin_codes": "?",
"originator": "10.1.1.2",
"recipient_pathid": "0",
"transfer_pathid": "0",
"refresh_epoch": 1,
"route_info": "Local",
"status_codes": "* i",
"update_group": 1,
},
},
"paths": "3 available, best #1, table default",
"table_version": "5",
},
}
},
}
},
}
}
}
}
|
expected_output = {'instance': {'default': {'vrf': {'VRF1': {'address_family': {'vpnv4 unicast RD 100:100': {'default_vrf': 'VRF1', 'prefixes': {'10.229.11.11/32': {'available_path': '1', 'best_path': '1', 'index': {1: {'gateway': '0.0.0.0', 'inaccessible': False, 'localpref': 100, 'metric': 0, 'next_hop': '0.0.0.0', 'next_hop_via': 'vrf VRF1', 'origin_codes': '?', 'originator': '10.1.1.1', 'recipient_pathid': '0', 'refresh_epoch': 1, 'route_info': 'Local', 'status_codes': '*>', 'transfer_pathid': '0x0', 'weight': '32768'}}, 'paths': '1 available, best #1, table VRF1', 'table_version': '2'}}, 'route_distinguisher': '100:100'}, 'vpnv6 unicast RD 100:100': {'default_vrf': 'VRF1', 'prefixes': {'2001:11:11::11/128': {'available_path': '1', 'best_path': '1', 'index': {1: {'gateway': '0.0.0.0', 'inaccessible': False, 'localpref': 100, 'metric': 0, 'next_hop': '::', 'next_hop_via': 'vrf VRF1', 'origin_codes': '?', 'originator': '10.1.1.1', 'recipient_pathid': '0', 'refresh_epoch': 1, 'route_info': 'Local', 'status_codes': '*>', 'transfer_pathid': '0x0', 'weight': '32768'}}, 'paths': '1 available, best #1, table VRF1', 'table_version': '2'}}, 'route_distinguisher': '100:100'}}}, 'default': {'address_family': {'ipv4 unicast': {'prefixes': {'10.4.1.1/32': {'available_path': '1', 'best_path': '1', 'index': {1: {'gateway': '0.0.0.0', 'localpref': 100, 'metric': 0, 'next_hop': '0.0.0.0', 'origin_codes': '?', 'originator': '10.1.1.1', 'recipient_pathid': '0', 'refresh_epoch': 1, 'route_info': 'Local', 'status_codes': '*>', 'transfer_pathid': '0x0', 'update_group': 3, 'weight': '32768'}}, 'paths': '1 available, best #1, table default, RIB-failure(17)', 'table_version': '4'}, '10.1.1.0/24': {'available_path': '2', 'best_path': '1', 'index': {1: {'gateway': '0.0.0.0', 'localpref': 100, 'metric': 0, 'next_hop': '0.0.0.0', 'origin_codes': '?', 'originator': '10.1.1.1', 'recipient_pathid': '0', 'refresh_epoch': 1, 'route_info': 'Local', 'status_codes': '*>', 'transfer_pathid': '0x0', 'update_group': 3, 'weight': '32768'}, 2: {'gateway': '10.1.1.2', 'localpref': 100, 'metric': 0, 'next_hop': '10.1.1.2', 'origin_codes': '?', 'originator': '10.1.1.2', 'recipient_pathid': '0', 'transfer_pathid': '0', 'refresh_epoch': 1, 'route_info': 'Local', 'status_codes': '* i', 'update_group': 3}}, 'paths': '2 available, best #1, table default', 'table_version': '5'}, '10.16.2.2/32': {'available_path': '1', 'best_path': '1', 'index': {1: {'gateway': '10.1.1.2', 'localpref': 100, 'metric': 0, 'next_hop': '10.1.1.2', 'origin_codes': '?', 'originator': '10.1.1.2', 'recipient_pathid': '0', 'refresh_epoch': 1, 'route_info': 'Local', 'status_codes': '*>', 'transfer_pathid': '0x0'}}, 'paths': '1 available, best #1, table default', 'table_version': '2'}}}, 'ipv6 unicast': {'prefixes': {'2001:1:1:1::1/128': {'available_path': '1', 'best_path': '1', 'index': {1: {'gateway': '0.0.0.0', 'localpref': 100, 'metric': 0, 'next_hop': '::', 'origin_codes': '?', 'originator': '10.1.1.1', 'recipient_pathid': '0', 'refresh_epoch': 1, 'route_info': 'Local', 'status_codes': '*>', 'transfer_pathid': '0x0', 'update_group': 1, 'weight': '32768'}}, 'paths': '1 available, best #1, table default', 'table_version': '4'}, '2001:2:2:2::2/128': {'available_path': '2', 'best_path': '1', 'index': {1: {'gateway': '2001:DB8:1:1::2', 'localpref': 100, 'metric': 0, 'next_hop': '2001:DB8:1:1::2', 'origin_codes': '?', 'originator': '10.1.1.2', 'recipient_pathid': '0', 'refresh_epoch': 1, 'route_info': 'Local', 'status_codes': '*>', 'transfer_pathid': '0x0'}, 2: {'gateway': '10.1.1.2', 'localpref': 100, 'metric': 0, 'next_hop': '::FFFF:10.1.1.2', 'origin_codes': '?', 'originator': '10.1.1.2', 'recipient_pathid': '0', 'transfer_pathid': '0', 'refresh_epoch': 1, 'route_info': 'Local', 'status_codes': '* i'}}, 'paths': '2 available, best #1, table default', 'table_version': '2'}, '2001:DB8:1:1::/64': {'available_path': '3', 'best_path': '1', 'index': {1: {'gateway': '0.0.0.0', 'localpref': 100, 'metric': 0, 'next_hop': '::', 'origin_codes': '?', 'originator': '10.1.1.1', 'recipient_pathid': '0', 'refresh_epoch': 1, 'route_info': 'Local', 'status_codes': '*>', 'transfer_pathid': '0x0', 'update_group': 1, 'weight': '32768'}, 2: {'gateway': '2001:DB8:1:1::2', 'localpref': 100, 'metric': 0, 'next_hop': '2001:DB8:1:1::2', 'origin_codes': '?', 'originator': '10.1.1.2', 'recipient_pathid': '0', 'transfer_pathid': '0', 'refresh_epoch': 1, 'route_info': 'Local', 'status_codes': '* i', 'update_group': 1}, 3: {'gateway': '10.1.1.2', 'localpref': 100, 'metric': 0, 'next_hop': '::FFFF:10.1.1.2', 'origin_codes': '?', 'originator': '10.1.1.2', 'recipient_pathid': '0', 'transfer_pathid': '0', 'refresh_epoch': 1, 'route_info': 'Local', 'status_codes': '* i', 'update_group': 1}}, 'paths': '3 available, best #1, table default', 'table_version': '5'}}}}}}}}}
|
n=6
x=1
for i in range(1,n+1):
for j in range(i,0,-1):
ch=chr(ord('Z')-j+1)
print(ch,end="")
x=x+1
print()
for i in range(n,0,-1):
for j in range(i,0,-1):
ch=chr(ord('Z')-j+1)
print(ch,end="")
x=x+1
print()
|
n = 6
x = 1
for i in range(1, n + 1):
for j in range(i, 0, -1):
ch = chr(ord('Z') - j + 1)
print(ch, end='')
x = x + 1
print()
for i in range(n, 0, -1):
for j in range(i, 0, -1):
ch = chr(ord('Z') - j + 1)
print(ch, end='')
x = x + 1
print()
|
name1_1_0_0_0_0_0 = None
name1_1_0_0_0_0_1 = None
name1_1_0_0_0_0_2 = None
name1_1_0_0_0_0_3 = None
name1_1_0_0_0_0_4 = None
|
name1_1_0_0_0_0_0 = None
name1_1_0_0_0_0_1 = None
name1_1_0_0_0_0_2 = None
name1_1_0_0_0_0_3 = None
name1_1_0_0_0_0_4 = None
|
def soma(*args):
total = 0
for n in args:
total += n
return total
print(__name__)
print(soma())
print(soma(1))
print(soma(1, 2))
print(soma(1, 2, 5))
|
def soma(*args):
total = 0
for n in args:
total += n
return total
print(__name__)
print(soma())
print(soma(1))
print(soma(1, 2))
print(soma(1, 2, 5))
|
infty = 999999
def whitespace(words, i, j):
return (L-(j-i)-sum([len(word) for word in words[i:j+1]]))
def cost(words,i,j):
total_char_length = sum([len(word) for word in words[i:j+1]])
if total_char_length > L-(j-i):
return infty
if j==len(words)-1:
return 0
return whitespace(words,i,j)**3
#words = ["one","two","three","four","five","six","seven"]
#L = 10
words = ["alpha", "beta", "gamma", "delta", "epsilon", "zeta", "eta", "theta", "iota", "kappa"]
L=15
# Setting up tables
costs = [[None for i in range(len(words))] for j in range(len(words))]
optimum_costs = [[None for i in range(len(words))] for j in range(len(words))]
break_table = [[None for i in range(len(words))] for j in range(len(words))]
for i in range(len(costs)):
for j in range(len(costs[i])):
costs[i][j] = cost(words,i,j)
def get_opt_cost(words,i,j):
# If this subproblem is already solved, return result
if(optimum_costs[i][j] != None):
return optimum_costs[i][j]
# There are now two main classes of ways we could get the optimum
# 1) The best choice is that we put all the words on one line
canidate_costs = [costs[i][j]]
canidate_list = [None]
if i!=j:
for k in range(i,j):
# Calculate optimum of words before line split
left_optimum = get_opt_cost(words,i,k)
optimum_costs[i][k] = left_optimum
# Calculate optimum of words after line split
right_optimum = get_opt_cost(words,k+1,j)
optimum_costs[k+1][j] = right_optimum
total_optimum = left_optimum+right_optimum
canidate_costs.append(total_optimum)
canidate_list.append(k)
min_cost= infty
min_canidate = None
for n, cost in enumerate(canidate_costs):
if cost < min_cost:
min_cost = cost
min_canidate = canidate_list[n]
break_table[i][j] = min_canidate
return min_cost
# Calculate the line breaks
def get_line_breaks(i,j):
if break_table[i][j] != None:
opt_break = get_line_breaks(break_table[i][j]+1,j)
return [break_table[i][j]]+opt_break
else:
return []
final_cost = get_opt_cost(words,0,len(words)-1)
breaks = get_line_breaks(0,len(words)-1)
def print_final_paragraph(words,breaks):
final_str = ""
cur_break_point = 0
for n, word in enumerate(words):
final_str = final_str+word+" "
if cur_break_point < len(breaks) and n==breaks[cur_break_point]:
final_str+="\n"
cur_break_point+=1
print(final_str)
print("Final Cost: ",final_cost)
print("Break Locations: ",breaks)
print("----")
print_final_paragraph(words,breaks)
|
infty = 999999
def whitespace(words, i, j):
return L - (j - i) - sum([len(word) for word in words[i:j + 1]])
def cost(words, i, j):
total_char_length = sum([len(word) for word in words[i:j + 1]])
if total_char_length > L - (j - i):
return infty
if j == len(words) - 1:
return 0
return whitespace(words, i, j) ** 3
words = ['alpha', 'beta', 'gamma', 'delta', 'epsilon', 'zeta', 'eta', 'theta', 'iota', 'kappa']
l = 15
costs = [[None for i in range(len(words))] for j in range(len(words))]
optimum_costs = [[None for i in range(len(words))] for j in range(len(words))]
break_table = [[None for i in range(len(words))] for j in range(len(words))]
for i in range(len(costs)):
for j in range(len(costs[i])):
costs[i][j] = cost(words, i, j)
def get_opt_cost(words, i, j):
if optimum_costs[i][j] != None:
return optimum_costs[i][j]
canidate_costs = [costs[i][j]]
canidate_list = [None]
if i != j:
for k in range(i, j):
left_optimum = get_opt_cost(words, i, k)
optimum_costs[i][k] = left_optimum
right_optimum = get_opt_cost(words, k + 1, j)
optimum_costs[k + 1][j] = right_optimum
total_optimum = left_optimum + right_optimum
canidate_costs.append(total_optimum)
canidate_list.append(k)
min_cost = infty
min_canidate = None
for (n, cost) in enumerate(canidate_costs):
if cost < min_cost:
min_cost = cost
min_canidate = canidate_list[n]
break_table[i][j] = min_canidate
return min_cost
def get_line_breaks(i, j):
if break_table[i][j] != None:
opt_break = get_line_breaks(break_table[i][j] + 1, j)
return [break_table[i][j]] + opt_break
else:
return []
final_cost = get_opt_cost(words, 0, len(words) - 1)
breaks = get_line_breaks(0, len(words) - 1)
def print_final_paragraph(words, breaks):
final_str = ''
cur_break_point = 0
for (n, word) in enumerate(words):
final_str = final_str + word + ' '
if cur_break_point < len(breaks) and n == breaks[cur_break_point]:
final_str += '\n'
cur_break_point += 1
print(final_str)
print('Final Cost: ', final_cost)
print('Break Locations: ', breaks)
print('----')
print_final_paragraph(words, breaks)
|
class MinStack:
# Update Min every pop (Accepted), O(1) push, pop, top, min
def __init__(self):
self.stack = []
self.min = None
def push(self, val: int) -> None:
if self.stack:
self.min = min(self.min, val)
self.stack.append((val, self.min))
else:
self.min = val
self.stack.append((val, self.min))
def pop(self) -> None:
val, min_ = self.stack.pop()
if self.stack:
self.min = self.stack[-1][1]
else:
self.min = None
def top(self) -> int:
if self.stack:
return self.stack[-1][0]
def getMin(self) -> int:
return self.min
class MinStack:
# Find min in last elem (Top Voted), O(1) push, pop, top, min
def __init__(self):
self.q = []
def push(self, x: int) -> None:
curMin = self.getMin()
if curMin == None or x < curMin:
curMin = x
self.q.append((x, curMin))
def pop(self) -> None:
self.q.pop()
def top(self) -> int:
if len(self.q) == 0:
return None
else:
return self.q[len(self.q) - 1][0]
def getMin(self) -> int:
if len(self.q) == 0:
return None
else:
return self.q[len(self.q) - 1][1]
# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(val)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.getMin()
|
class Minstack:
def __init__(self):
self.stack = []
self.min = None
def push(self, val: int) -> None:
if self.stack:
self.min = min(self.min, val)
self.stack.append((val, self.min))
else:
self.min = val
self.stack.append((val, self.min))
def pop(self) -> None:
(val, min_) = self.stack.pop()
if self.stack:
self.min = self.stack[-1][1]
else:
self.min = None
def top(self) -> int:
if self.stack:
return self.stack[-1][0]
def get_min(self) -> int:
return self.min
class Minstack:
def __init__(self):
self.q = []
def push(self, x: int) -> None:
cur_min = self.getMin()
if curMin == None or x < curMin:
cur_min = x
self.q.append((x, curMin))
def pop(self) -> None:
self.q.pop()
def top(self) -> int:
if len(self.q) == 0:
return None
else:
return self.q[len(self.q) - 1][0]
def get_min(self) -> int:
if len(self.q) == 0:
return None
else:
return self.q[len(self.q) - 1][1]
|
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 24 13:09:04 2020
@author: 766810
"""
tab = []
loop = 'loop'
# tab will hold all Kaprekar numbers found
# loop is just for better wording
def asc(n):
# puts the number's digits in ascending...
return int(''.join(sorted(str(n))))
def desc(n):
# ...and descending order
return int(''.join(sorted(str(n))[::-1]))
n = input("Specify a number: ")
try:
n = int(n)
except:
# assuming n = 2016 to prevent program from crashing
print("\nInvalid number specified!!!\nAssuming n = 2020.")
n = "2020"
print("\nTransforming", str(n) + ":")
while True:
# iterates, assigns the new diff
print(desc(n), "-", asc(n), "=", desc(n)-asc(n))
n = desc(n) - asc(n)
if n not in tab:
# checks if already hit that number
tab.append(n)
else:
if tab.index(n) == len(tab)-1:
# if found as the last, it is a constant...
tab = []
tab.append(n)
loop = 'constant'
else:
# ...otherwise it is a loop
tab = tab[tab.index(n):]
# strip the first, non-looping items
break
print('Kaprekar', loop, 'reached:', tab)
|
"""
Created on Mon Feb 24 13:09:04 2020
@author: 766810
"""
tab = []
loop = 'loop'
def asc(n):
return int(''.join(sorted(str(n))))
def desc(n):
return int(''.join(sorted(str(n))[::-1]))
n = input('Specify a number: ')
try:
n = int(n)
except:
print('\nInvalid number specified!!!\nAssuming n = 2020.')
n = '2020'
print('\nTransforming', str(n) + ':')
while True:
print(desc(n), '-', asc(n), '=', desc(n) - asc(n))
n = desc(n) - asc(n)
if n not in tab:
tab.append(n)
else:
if tab.index(n) == len(tab) - 1:
tab = []
tab.append(n)
loop = 'constant'
else:
tab = tab[tab.index(n):]
break
print('Kaprekar', loop, 'reached:', tab)
|
def main():
try:
with open('cat_200_300.jpg', 'rb') as fs1:
data = fs1.read()
print(type(data))
with open('cat1.jpg', 'wb') as fs2:
fs2.write(data)
except FileNotFoundError as e:
print(e)
if __name__ == '__main__':
main()
|
def main():
try:
with open('cat_200_300.jpg', 'rb') as fs1:
data = fs1.read()
print(type(data))
with open('cat1.jpg', 'wb') as fs2:
fs2.write(data)
except FileNotFoundError as e:
print(e)
if __name__ == '__main__':
main()
|
#!/usr/bin/env python3
class Point:
def __init__(self, x, y, t, err):
"""
This class represents a gaze point
@param x:
@param y:
@param t:
@param err:
"""
self.error = err
self.timestamp = t
self.coord = []
self.coord.append(x)
self.coord.append(y)
def at(self, k):
"""
index into the coords of this Point
@param k: x if 0, y if 1
@return: coordinate
"""
return self.coord[k]
def set(self, x, y):
"""
set coords
@param x:
@param y:
"""
self.coord[0] = x
self.coord[1] = y
def get_status(self):
"""
Get error status of point
@return:
"""
return self.error
def valid(self):
"""
a gaze point is valid if it's normalized coordinates are in the range [0,1] and both eyes are present
@return:
"""
if self.error == "None" and \
self.coord[0] > 0 and self.coord[1] > 0 and \
self.coord[0] < 1 and self.coord[1] < 1:
return True
else:
return False
def get_timestamp(self):
return self.timestamp
|
class Point:
def __init__(self, x, y, t, err):
"""
This class represents a gaze point
@param x:
@param y:
@param t:
@param err:
"""
self.error = err
self.timestamp = t
self.coord = []
self.coord.append(x)
self.coord.append(y)
def at(self, k):
"""
index into the coords of this Point
@param k: x if 0, y if 1
@return: coordinate
"""
return self.coord[k]
def set(self, x, y):
"""
set coords
@param x:
@param y:
"""
self.coord[0] = x
self.coord[1] = y
def get_status(self):
"""
Get error status of point
@return:
"""
return self.error
def valid(self):
"""
a gaze point is valid if it's normalized coordinates are in the range [0,1] and both eyes are present
@return:
"""
if self.error == 'None' and self.coord[0] > 0 and (self.coord[1] > 0) and (self.coord[0] < 1) and (self.coord[1] < 1):
return True
else:
return False
def get_timestamp(self):
return self.timestamp
|
"""
*AbstractProperty*
"""
__all__ = ["AbstractProperty"]
class AbstractProperty:
pass
|
"""
*AbstractProperty*
"""
__all__ = ['AbstractProperty']
class Abstractproperty:
pass
|
# -*- coding: utf-8 -*-
"""Conventions for data, coordinate and attribute names."""
measurement_type = 'measurement'
peak_coord = 'peak'
"""Index coordinate denoting passband peaks of the FPI."""
number_of_peaks = 'npeaks'
"""Number of passband peaks included in a given image."""
setpoint_coord = 'setpoint_index'
"""Coordinate denoting the the setpoint (which voltage it denotes)"""
setpoint_data = 'setpoint'
"""Values of the setpoints."""
sinv_data = 'sinvs'
"""Inversion coefficients for radiance calculation."""
colour_coord = 'colour'
"""Colour coordinate for values indexed w.r.t. CFA colours."""
radiance_data = 'radiance'
"""DataArray containing a stack of radiance images."""
reflectance_data = 'reflectance'
"""DataArray containing a stack of reflectance images."""
cfa_data = 'dn'
"""DataArray containing a stack of raw CFA images."""
dark_corrected_cfa_data = 'dn_dark_corrected'
"""DataArray containing a stack of raw images with dark current corrected"""
rgb_data = 'rgb'
"""DataArray containing a stack of RGB images."""
dark_reference_data = 'dark'
"""DataArray containing a dark current reference."""
wavelength_data = 'wavelength'
"""Passband center wavelength values."""
fwhm_data = 'fwhm'
"""Full Width at Half Maximum values"""
camera_gain = 'gain'
"""Camera analog gain value."""
camera_exposure = 'exposure'
"""Camera exposure time in milliseconds."""
genicam_exposure = 'ExposureTime'
"""Camera exposure time in microseconds as defined by GenICam."""
cfa_pattern_data = 'bayer_pattern'
"""String denoting the pattern (e.g. RGGB) of the colour filter array."""
genicam_pattern_data = 'PixelColorFilter'
"""String denoting the pattern (e.g. BayerGB) of the colour filter array."""
image_index = 'index'
"""Index number of the image in a given stack."""
band_index = 'band'
"""Index for wavelength band data."""
image_width = 'width'
image_height = 'height'
height_coord = 'y'
width_coord = 'x'
cfa_dims = (image_index, height_coord, width_coord)
"""Convention for CFA image stacks."""
dark_ref_dims = (height_coord, width_coord)
"""Convention for dark reference image dimensions."""
radiance_dims = (band_index, height_coord, width_coord)
"""Convention for radiance image stacks."""
RGB_dims = (height_coord, width_coord, colour_coord)
"""Convention for RGB images."""
sinv_dims = (image_index, peak_coord, colour_coord)
"""Convention for inversion coefficient dimensions."""
|
"""Conventions for data, coordinate and attribute names."""
measurement_type = 'measurement'
peak_coord = 'peak'
'Index coordinate denoting passband peaks of the FPI.'
number_of_peaks = 'npeaks'
'Number of passband peaks included in a given image.'
setpoint_coord = 'setpoint_index'
'Coordinate denoting the the setpoint (which voltage it denotes)'
setpoint_data = 'setpoint'
'Values of the setpoints.'
sinv_data = 'sinvs'
'Inversion coefficients for radiance calculation.'
colour_coord = 'colour'
'Colour coordinate for values indexed w.r.t. CFA colours.'
radiance_data = 'radiance'
'DataArray containing a stack of radiance images.'
reflectance_data = 'reflectance'
'DataArray containing a stack of reflectance images.'
cfa_data = 'dn'
'DataArray containing a stack of raw CFA images.'
dark_corrected_cfa_data = 'dn_dark_corrected'
'DataArray containing a stack of raw images with dark current corrected'
rgb_data = 'rgb'
'DataArray containing a stack of RGB images.'
dark_reference_data = 'dark'
'DataArray containing a dark current reference.'
wavelength_data = 'wavelength'
'Passband center wavelength values.'
fwhm_data = 'fwhm'
'Full Width at Half Maximum values'
camera_gain = 'gain'
'Camera analog gain value.'
camera_exposure = 'exposure'
'Camera exposure time in milliseconds.'
genicam_exposure = 'ExposureTime'
'Camera exposure time in microseconds as defined by GenICam.'
cfa_pattern_data = 'bayer_pattern'
'String denoting the pattern (e.g. RGGB) of the colour filter array.'
genicam_pattern_data = 'PixelColorFilter'
'String denoting the pattern (e.g. BayerGB) of the colour filter array.'
image_index = 'index'
'Index number of the image in a given stack.'
band_index = 'band'
'Index for wavelength band data.'
image_width = 'width'
image_height = 'height'
height_coord = 'y'
width_coord = 'x'
cfa_dims = (image_index, height_coord, width_coord)
'Convention for CFA image stacks.'
dark_ref_dims = (height_coord, width_coord)
'Convention for dark reference image dimensions.'
radiance_dims = (band_index, height_coord, width_coord)
'Convention for radiance image stacks.'
rgb_dims = (height_coord, width_coord, colour_coord)
'Convention for RGB images.'
sinv_dims = (image_index, peak_coord, colour_coord)
'Convention for inversion coefficient dimensions.'
|
while True:
a = input()
if a == '-1':
break
L = list(map(int, a.split()))[:-1]
cnt = 0
for i in L:
if i*2 in L:
cnt += 1
print(cnt)
|
while True:
a = input()
if a == '-1':
break
l = list(map(int, a.split()))[:-1]
cnt = 0
for i in L:
if i * 2 in L:
cnt += 1
print(cnt)
|
# -*- coding: utf-8 -*-
__all__=['glottal', 'phonation', 'articulation', 'prosody', 'replearning']
|
__all__ = ['glottal', 'phonation', 'articulation', 'prosody', 'replearning']
|
# creating a function to calculate the density.
def calc_density(mass, volume):
# arithmetic calculation to determine the density.
density = mass / volume
density = round(density, 2)
# returning the value of the density.
return density
# receiving input from the user regarding the mass and volume of the substance.
mass = float(input("Enter the mass of the substance in grams please: "))
volume = float(input("Enter the volume of the substance please: "))
# printing the final output which indicates the density.
print("The density of the object is:", calc_density(mass, volume), "g/cm^3")
|
def calc_density(mass, volume):
density = mass / volume
density = round(density, 2)
return density
mass = float(input('Enter the mass of the substance in grams please: '))
volume = float(input('Enter the volume of the substance please: '))
print('The density of the object is:', calc_density(mass, volume), 'g/cm^3')
|
class documentmodel:
def getDocuments(self):
document_tokens1 = "China has a strong economy that is growing at a rapid pace. However politically it differs greatly from the US Economy."
document_tokens2 = "At last, China seems serious about confronting an endemic problem: domestic violence and corruption."
document_tokens3 = "Japan's prime minister, Shinzo Abe, is working towards healing the economic turmoil in his own country for his view on the future of his people."
document_tokens4 = "Vladimir Putin is working hard to fix the economy in Russia as the Ruble has tumbled."
document_tokens5 = "What's the future of Abenomics? We asked Shinzo Abe for his views"
document_tokens6 = "Obama has eased sanctions on Cuba while accelerating those against the Russian Economy, even as the Ruble's value falls almost daily."
document_tokens7 = "Vladimir Putin is riding a horse while hunting deer. Vladimir Putin always seems so serious about things - even riding horses. Is he crazy?"
documents = []
documents.append(document_tokens1)
documents.append(document_tokens2)
documents.append(document_tokens3)
documents.append(document_tokens4)
documents.append(document_tokens5)
documents.append(document_tokens6)
documents.append(document_tokens7)
return documents
|
class Documentmodel:
def get_documents(self):
document_tokens1 = 'China has a strong economy that is growing at a rapid pace. However politically it differs greatly from the US Economy.'
document_tokens2 = 'At last, China seems serious about confronting an endemic problem: domestic violence and corruption.'
document_tokens3 = "Japan's prime minister, Shinzo Abe, is working towards healing the economic turmoil in his own country for his view on the future of his people."
document_tokens4 = 'Vladimir Putin is working hard to fix the economy in Russia as the Ruble has tumbled.'
document_tokens5 = "What's the future of Abenomics? We asked Shinzo Abe for his views"
document_tokens6 = "Obama has eased sanctions on Cuba while accelerating those against the Russian Economy, even as the Ruble's value falls almost daily."
document_tokens7 = 'Vladimir Putin is riding a horse while hunting deer. Vladimir Putin always seems so serious about things - even riding horses. Is he crazy?'
documents = []
documents.append(document_tokens1)
documents.append(document_tokens2)
documents.append(document_tokens3)
documents.append(document_tokens4)
documents.append(document_tokens5)
documents.append(document_tokens6)
documents.append(document_tokens7)
return documents
|
# For internal use. Please do not modify this file.
def setup():
return
def extra_make_option():
return ""
|
def setup():
return
def extra_make_option():
return ''
|
def collatz(number):
if number%2==0:
number=number//2
else:
number=3*number+1
print(number)
return number
print('enter an integer')
num=int(input())
a=0
a=collatz(num)
while a!=1:
a=collatz(a)
|
def collatz(number):
if number % 2 == 0:
number = number // 2
else:
number = 3 * number + 1
print(number)
return number
print('enter an integer')
num = int(input())
a = 0
a = collatz(num)
while a != 1:
a = collatz(a)
|
# CONVERSION OF UNITS
# Python 3
# Using Jupyter Notebook
# If using Visual Studio then change .ipynb to .py
# This program aims to convert units from miles to km and from km to ft.
# 1 inch = 2.54 cm, 1 km = 1000m, 1 m = 100 cm, 12 inches = 1 ft, 1 mile = 5280 ft
# ------- Start -------
# Known Standard Units of Conversion
# Refer to a conversion table if you don't know where to find it.
# But I placed it at the top for reference
inToCm = 2.54
kmToM = 1000
mToCm = 100
inToFt = 1/12
miToFt = 5280
# Input your number to be converted using this command
num = float(input("Enter your number (in miles): "))
# Conversion formula
# Don't get overwhelmed, if you have the conversion table you'll be fine.
# Otherwise get your pen and paper, and write before coding!
miToFt = num * miToFt
inToFt = miToFt * (1/inToFt)
inToCm = inToFt * inToCm
mToCm = inToCm * (1/mToCm)
kmToM = mToCm * (1/kmToM)
# Print the answer
print()
print(num, " mile(s) is",miToFt," feet")
print(miToFt, " feet(s) is",inToFt," inch(es)")
print(inToFt, " inch(es) is",inToCm," centimeter(s)")
print(inToCm, " centmeter(s) is",mToCm," meter(s)")
print(mToCm, " meter(s) is",kmToM," kilometer(s)")
# ------- End -------
# For a shorter version
#CONVERSION OF UNITS
#This program aims to convert units from miles to km and from km to ft.
# 1 inch = 2.54 cm, 1 km = 1000m, 1 m = 100 cm, 12 inches = 1 ft, 1 mile = 5280 ft
inToCm = 2.54
kmToM = 1000
mToCm = 100
inToFt = 1/12
miToFt = 5280
num = float(input("Enter your number (in miles): "))
convertedNum = num * miToFt * (1/inToFt) * inToCm * (1/mToCm) * (1/kmToM)
print(num, " mile(s) is",convertedNum,"kilometers")
|
in_to_cm = 2.54
km_to_m = 1000
m_to_cm = 100
in_to_ft = 1 / 12
mi_to_ft = 5280
num = float(input('Enter your number (in miles): '))
mi_to_ft = num * miToFt
in_to_ft = miToFt * (1 / inToFt)
in_to_cm = inToFt * inToCm
m_to_cm = inToCm * (1 / mToCm)
km_to_m = mToCm * (1 / kmToM)
print()
print(num, ' mile(s) is', miToFt, ' feet')
print(miToFt, ' feet(s) is', inToFt, ' inch(es)')
print(inToFt, ' inch(es) is', inToCm, ' centimeter(s)')
print(inToCm, ' centmeter(s) is', mToCm, ' meter(s)')
print(mToCm, ' meter(s) is', kmToM, ' kilometer(s)')
in_to_cm = 2.54
km_to_m = 1000
m_to_cm = 100
in_to_ft = 1 / 12
mi_to_ft = 5280
num = float(input('Enter your number (in miles): '))
converted_num = num * miToFt * (1 / inToFt) * inToCm * (1 / mToCm) * (1 / kmToM)
print(num, ' mile(s) is', convertedNum, 'kilometers')
|
'''constants.py
Various constants that are utilized in different modules across the whole program'''
#Unicode characters for suits
SUITS = [
'\u2660',
'\u2663',
'\u2665',
'\u2666'
]
#A calculation value and a face value for the cards
VALUE_PAIRS = [
(1, 'A'),
(2, '2'),
(3, '3'),
(4, '4'),
(5, '5'),
(6, '6'),
(7, '7'),
(8, '8'),
(9, '9'),
(10, '10'),
(11, 'J'),
(12, 'Q'),
(13, 'K')
]
#Colors: Tuples with RGB values from 0 to 255
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
BLUE = (50, 150, 255)
GRAY = (115, 115, 115)
GREEN = (0, 255, 0)
|
"""constants.py
Various constants that are utilized in different modules across the whole program"""
suits = ['♠', '♣', '♥', '♦']
value_pairs = [(1, 'A'), (2, '2'), (3, '3'), (4, '4'), (5, '5'), (6, '6'), (7, '7'), (8, '8'), (9, '9'), (10, '10'), (11, 'J'), (12, 'Q'), (13, 'K')]
black = (0, 0, 0)
white = (255, 255, 255)
red = (255, 0, 0)
blue = (50, 150, 255)
gray = (115, 115, 115)
green = (0, 255, 0)
|
def is_overlap(arr1, arr2):
if arr2[0] <= arr1[0] <= arr2[1]:
return True
if arr2[0] <= arr1[1] <= arr2[1]:
return True
if arr1[0] <= arr2[0] <= arr1[1]:
return True
if arr1[0] <= arr2[1] <= arr1[1]:
return True
return False
def merge_2_arrays(arr1, arr2):
l = min(min(arr1), min(arr2))
r = max(max(arr1), max(arr2))
return [l, r]
def rain_drop(rain):
if not rain:
return -1
r = sorted(rain)
covered = r[0]
for i in range(1, len(r)):
if not is_overlap(covered, r[i]):
return -1
covered = merge_2_arrays(covered, r[i])
print(covered)
if covered[1] >= 1:
return i + 1
return -1
if __name__ == '__main__':
rains = [[0, 0.3],[0.3, 0.6],[0.5, 0.8], [0.67, 1], [0, 0.4] ,[0.5, 0.75]]
print(rain_drop(rains))
|
def is_overlap(arr1, arr2):
if arr2[0] <= arr1[0] <= arr2[1]:
return True
if arr2[0] <= arr1[1] <= arr2[1]:
return True
if arr1[0] <= arr2[0] <= arr1[1]:
return True
if arr1[0] <= arr2[1] <= arr1[1]:
return True
return False
def merge_2_arrays(arr1, arr2):
l = min(min(arr1), min(arr2))
r = max(max(arr1), max(arr2))
return [l, r]
def rain_drop(rain):
if not rain:
return -1
r = sorted(rain)
covered = r[0]
for i in range(1, len(r)):
if not is_overlap(covered, r[i]):
return -1
covered = merge_2_arrays(covered, r[i])
print(covered)
if covered[1] >= 1:
return i + 1
return -1
if __name__ == '__main__':
rains = [[0, 0.3], [0.3, 0.6], [0.5, 0.8], [0.67, 1], [0, 0.4], [0.5, 0.75]]
print(rain_drop(rains))
|
def fib(n):
if n == 1 or n == 2:
return 1
else:
return fib(n - 1) + fib(n - 2)
def fib3(n):
if n == 1 or n == 2 or n == 3:
return 1
else:
return fib3(n - 1) + fib3(n - 2) + fib3(n - 3)
def fib_mult(n):
if n == 1:
return 1
if n == 2:
return 2
else:
return fib_mult(n - 1) * fib_mult(n - 2)
def fib_skip(n):
if n == 1 or n == 2 or n == 3:
return 1
else:
return fib_skip(n - 1) + fib_skip(n - 3)
def joynernacci(n):
if n == 1 or n == 2:
return 1
else:
if n % 2 ==0:
return joynernacci(n - 1) + joynernacci(n - 2)
else:
return abs(joynernacci(n - 1) - joynernacci(n - 2))
|
def fib(n):
if n == 1 or n == 2:
return 1
else:
return fib(n - 1) + fib(n - 2)
def fib3(n):
if n == 1 or n == 2 or n == 3:
return 1
else:
return fib3(n - 1) + fib3(n - 2) + fib3(n - 3)
def fib_mult(n):
if n == 1:
return 1
if n == 2:
return 2
else:
return fib_mult(n - 1) * fib_mult(n - 2)
def fib_skip(n):
if n == 1 or n == 2 or n == 3:
return 1
else:
return fib_skip(n - 1) + fib_skip(n - 3)
def joynernacci(n):
if n == 1 or n == 2:
return 1
elif n % 2 == 0:
return joynernacci(n - 1) + joynernacci(n - 2)
else:
return abs(joynernacci(n - 1) - joynernacci(n - 2))
|
"""Given a linked list of co-ordinates where adjacent points either form a vertical line or a horizontal line.
Delete points from the linked list which are in the middle of a horizontal or vertical line."""
"""Input: (0,10)->(1,10)->(5,10)->(7,10)
|
(7,5)->(20,5)->(40,5)
Output: Linked List should be changed to following
(0,10)->(7,10)
|
(7,5)->(40,5) """
# Node class
class Node:
# Constructor to initialise (x, y) coordinates and next
def __init__(self, x=None, y=None):
self.x = x
self.y = y
self.next = None
class SinglyLinkedList:
# Constructor to initialise head
def __init__(self):
self.head = None
# Function to find middle node of a linked list
def delete_middle_nodes(self):
current = self.head
# iterate while the next of the next node is not none
while current and current.next and current.next.next is not None:
# assign variables for next and next of next nodes
next = current.next
next_next = current.next.next
# if x coordinates are equal of current and next node i.e. horizontal line
if current.x == next.x:
# check if there are more than 2 nodes in the horizontal line
# if yes then delete the middle node and update next and next_next
while next_next is not None and next.x == next_next.x:
current.next = next_next
next = next_next
next_next = next_next.next
# if y coordinates are equal of current and next node i.e. vertical line
elif current.y == next.y:
# check if there are more than 2 nodes in the vertical line
# if yes then delete the middle node and update next and next_next
while next_next is not None and next.y == next_next.y:
current.next = next_next
next = next_next
next_next = next_next.next
# updated the current node to next node for checking the next line nodes
current = current.next
# Function to Insert data at the beginning of the linked list
def insert_at_beg(self, x, y):
node = Node(x, y)
node.next = self.head
self.head = node
# Function to print the linked list
def print_data(self):
current = self.head
while current is not None:
print('(',current.x, ',', current.y, ') -> ', end='')
current = current.next
print('None')
if __name__ == '__main__':
linked_list = SinglyLinkedList()
linked_list.insert_at_beg(40,5)
linked_list.insert_at_beg(20,5)
linked_list.insert_at_beg(7,5)
linked_list.insert_at_beg(7,10)
linked_list.insert_at_beg(5,10)
linked_list.insert_at_beg(1,10)
linked_list.insert_at_beg(0,10)
# print the linked list representing vertical and horizontal lines
linked_list.print_data()
# call the delete_middle_nodes function
linked_list.delete_middle_nodes()
# print the new linked list
linked_list.print_data()
|
"""Given a linked list of co-ordinates where adjacent points either form a vertical line or a horizontal line.
Delete points from the linked list which are in the middle of a horizontal or vertical line."""
'Input: (0,10)->(1,10)->(5,10)->(7,10)\n |\n (7,5)->(20,5)->(40,5)\nOutput: Linked List should be changed to following\n (0,10)->(7,10)\n |\n (7,5)->(40,5) '
class Node:
def __init__(self, x=None, y=None):
self.x = x
self.y = y
self.next = None
class Singlylinkedlist:
def __init__(self):
self.head = None
def delete_middle_nodes(self):
current = self.head
while current and current.next and (current.next.next is not None):
next = current.next
next_next = current.next.next
if current.x == next.x:
while next_next is not None and next.x == next_next.x:
current.next = next_next
next = next_next
next_next = next_next.next
elif current.y == next.y:
while next_next is not None and next.y == next_next.y:
current.next = next_next
next = next_next
next_next = next_next.next
current = current.next
def insert_at_beg(self, x, y):
node = node(x, y)
node.next = self.head
self.head = node
def print_data(self):
current = self.head
while current is not None:
print('(', current.x, ',', current.y, ') -> ', end='')
current = current.next
print('None')
if __name__ == '__main__':
linked_list = singly_linked_list()
linked_list.insert_at_beg(40, 5)
linked_list.insert_at_beg(20, 5)
linked_list.insert_at_beg(7, 5)
linked_list.insert_at_beg(7, 10)
linked_list.insert_at_beg(5, 10)
linked_list.insert_at_beg(1, 10)
linked_list.insert_at_beg(0, 10)
linked_list.print_data()
linked_list.delete_middle_nodes()
linked_list.print_data()
|
"""
==========
Exceptions
==========
Module containing framework-wide exception definitions. Exceptions for
particular subsystems are defined in their respective modules.
"""
class VivariumError(Exception):
"""Generic exception raised for errors in ``vivarium`` simulations."""
pass
|
"""
==========
Exceptions
==========
Module containing framework-wide exception definitions. Exceptions for
particular subsystems are defined in their respective modules.
"""
class Vivariumerror(Exception):
"""Generic exception raised for errors in ``vivarium`` simulations."""
pass
|
"""
Python program to find the n'th number in the tribonacci series
Tribonacci series is a generalization of the Fibonacci sequence, in which the current term
is the sum of the previous three terms.
"""
def find_tribonacci(n):
dp = [0] * n
dp[0] = 0
dp[1] = 0
dp[2] = 1
# Compute the sum of the previous three terms
for i in range(3,n):
dp[i] = dp[i-1] + dp[i-2] + dp[i-3]
return dp[n-1]
if __name__ == '__main__':
print("Enter the value of n?, where you need the n'th number in the tribonacci sequence. ", end="")
n = int(input())
if (n <= 0):
print("The given value of n is invalid.", end="")
exit()
res = find_tribonacci(n)
print("The {}'th term in the tribonacci series is {}.".format(n, res))
"""
Time Complexity - O(n)
Space Complexity - O(n)
SAMPLE INPUT AND OUTPUT
SAMPLE I
Enter the value of n?, where you need the n'th number in the tribonacci sequence. 12
The 12'th term in the tribonacci series is 149.
SAMPLE II
Enter the value of n?, where you need the n'th number in the tribonacci sequence. 1254
The 1254'th term in the tribonacci series is 4020147461713125140.
"""
|
"""
Python program to find the n'th number in the tribonacci series
Tribonacci series is a generalization of the Fibonacci sequence, in which the current term
is the sum of the previous three terms.
"""
def find_tribonacci(n):
dp = [0] * n
dp[0] = 0
dp[1] = 0
dp[2] = 1
for i in range(3, n):
dp[i] = dp[i - 1] + dp[i - 2] + dp[i - 3]
return dp[n - 1]
if __name__ == '__main__':
print("Enter the value of n?, where you need the n'th number in the tribonacci sequence. ", end='')
n = int(input())
if n <= 0:
print('The given value of n is invalid.', end='')
exit()
res = find_tribonacci(n)
print("The {}'th term in the tribonacci series is {}.".format(n, res))
"\nTime Complexity - O(n)\nSpace Complexity - O(n)\n\nSAMPLE INPUT AND OUTPUT\n\nSAMPLE I\nEnter the value of n?, where you need the n'th number in the tribonacci sequence. 12\nThe 12'th term in the tribonacci series is 149.\n\nSAMPLE II\nEnter the value of n?, where you need the n'th number in the tribonacci sequence. 1254\nThe 1254'th term in the tribonacci series is 4020147461713125140.\n"
|
__author__ = 'Dmitriy Korsakov'
def main():
pass
|
__author__ = 'Dmitriy Korsakov'
def main():
pass
|
# Python - 3.4.3
def problem(a):
try:
return float(a) * 50 + 6
except:
return 'Error'
|
def problem(a):
try:
return float(a) * 50 + 6
except:
return 'Error'
|
"""
bluew.daemon
~~~~~~~~~~~~~~~~~
This module provides a Daemon object that tries its best to keep connections
alive, and has the ability to reproduce certain steps when a reconnection is
needed.
:copyright: (c) 2017 by Ahmed Alsharif.
:license: MIT, see LICENSE for more details.
"""
def daemonize(func):
"""
A function wrapper that checks daemon flags. This wrapper as it is assumes
that the calling class has a daemon attribute.
"""
def _wrapper(self, *args, d_init=False, **kwargs):
if d_init:
self.daemon.d_init.append((func, self, args, kwargs))
return func(self, *args, **kwargs)
return _wrapper
class Daemon(object):
"""The bluew daemon."""
def __init__(self):
self.d_init = []
def run_init_funcs(self):
"""
This function iterates through the functions added to d_init, and
runs them in the same order they were added in.
"""
for func, self_, args, kwargs in self.d_init:
func(self_, *args, **kwargs)
|
"""
bluew.daemon
~~~~~~~~~~~~~~~~~
This module provides a Daemon object that tries its best to keep connections
alive, and has the ability to reproduce certain steps when a reconnection is
needed.
:copyright: (c) 2017 by Ahmed Alsharif.
:license: MIT, see LICENSE for more details.
"""
def daemonize(func):
"""
A function wrapper that checks daemon flags. This wrapper as it is assumes
that the calling class has a daemon attribute.
"""
def _wrapper(self, *args, d_init=False, **kwargs):
if d_init:
self.daemon.d_init.append((func, self, args, kwargs))
return func(self, *args, **kwargs)
return _wrapper
class Daemon(object):
"""The bluew daemon."""
def __init__(self):
self.d_init = []
def run_init_funcs(self):
"""
This function iterates through the functions added to d_init, and
runs them in the same order they were added in.
"""
for (func, self_, args, kwargs) in self.d_init:
func(self_, *args, **kwargs)
|
# current = -4.036304473876953
def convert(time):
pos = True if time >= 0 else False
time = abs(time)
time_hours = time/3600
time_h = int(time_hours)
time_remaining = time_hours - time_h
time_m = int(time_remaining*60)
time_sec = time_remaining - time_m/60
time_s = int(time_sec*3600)
time_format = f'{time_m}:{time_s}' if pos else f'-{time_m}:{time_s}'
if abs(time_h) > 0:
time_format = f'{time_h}:{time_m}:{time_s}' if pos else f'-{time_h}:{time_m}:{time_s}'
return time_format
# time = convert(current)
# print(time)
|
def convert(time):
pos = True if time >= 0 else False
time = abs(time)
time_hours = time / 3600
time_h = int(time_hours)
time_remaining = time_hours - time_h
time_m = int(time_remaining * 60)
time_sec = time_remaining - time_m / 60
time_s = int(time_sec * 3600)
time_format = f'{time_m}:{time_s}' if pos else f'-{time_m}:{time_s}'
if abs(time_h) > 0:
time_format = f'{time_h}:{time_m}:{time_s}' if pos else f'-{time_h}:{time_m}:{time_s}'
return time_format
|
"""
Define redistricting.management as a Python package.
This file serves the purpose of defining a Python package for
this folder. It is intentionally left empty.
This file is part of The Public Mapping Project
https://github.com/PublicMapping/
License:
Copyright 2010-2012 Micah Altman, Michael McDonald
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.
Author:
Andrew Jennings, David Zwarg
"""
|
"""
Define redistricting.management as a Python package.
This file serves the purpose of defining a Python package for
this folder. It is intentionally left empty.
This file is part of The Public Mapping Project
https://github.com/PublicMapping/
License:
Copyright 2010-2012 Micah Altman, Michael McDonald
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.
Author:
Andrew Jennings, David Zwarg
"""
|
def composite_value(value):
if ';' in value:
items = []
first = True
for tmp in value.split(';'):
if not first and tmp.startswith(' '):
tmp = tmp[1:]
items.append(tmp)
first = False
else:
items = [value]
return items
|
def composite_value(value):
if ';' in value:
items = []
first = True
for tmp in value.split(';'):
if not first and tmp.startswith(' '):
tmp = tmp[1:]
items.append(tmp)
first = False
else:
items = [value]
return items
|
# MIT License
# (C) Copyright 2021 Hewlett Packard Enterprise Development LP.
#
# actionLog : Get Action/Audit Logs
def get_audit_log(
self,
start_time: int,
end_time: int,
limit: int,
log_level: int = 1,
ne_pk: str = None,
username: str = None,
) -> list:
"""Get audit log details filtered by specified query parameters
.. list-table::
:header-rows: 1
* - Swagger Section
- Method
- Endpoint
* - actionLog
- GET
- /action
:param start_time: Long(Signed 64 bits) value of seconds since EPOCH
time indicating the starting time boundary of data time range
:type start_time: int
:param end_time: Long(Signed 64 bits) value of seconds since EPOCH
time indicating the ending time boundary of data time range
:type end_time: int
:param limit: Limit the number of rows to retrieve from audit log
:type limit: int
:param log_level: ``0`` for Debug, ``1`` for Info, ``2`` for Error.
Defaults to 1
:type log_level: int, optional
:param ne_pk: Filter for specific appliance with Network Primary Key
(nePk) of appliance, e.g. ``3.NE``
:type ne_pk: str, optional
:param username: Filter for specific user
:type username: str, optional
:return: Returns list of dictionaries \n
[`dict`]: Audit log line \n
* keyword **id** (`int`): Id of the log entry
* keyword **user** (`str`): User who performed this action
* keyword **ipAddress** (`str`): IP Address who performed
this action
* keyword **nepk** (`str`): Primary key of the appliance on
which this action was performed
* keyword **name** (`str`): Name of the action
* keyword **description** (`str`): Description of the action
* keyword **taskStatus** (`str`): Status of the action
* keyword **startTime** (`int`): Start time of the action in
milliseconds since epoch
* keyword **endTime** (`int`): End time of the action in
milliseconds since epoch
* keyword **queuedTime** (`int`): Original queued time of
the action in milliseconds since epoch
* keyword **percentComplete** (`int`): Percentage completion
of the action
* keyword **completionStatus** (boolean): Show if action
succeeded or failed
* keyword **result** (`str`): Opaque blob of data related to
action. Typically, this is the result of the action.
* keyword **intTaskStatus** (`int`): Status of the action in
integer enum format
* keyword **guid** (`str`): GUID of a group of related
actions
:rtype: list
"""
path = "/action?startTime={}&endTime={}&limit={}&logLevel={}".format(
start_time, end_time, limit, log_level
)
if ne_pk is not None:
path = path + "&appliance={}".format(ne_pk)
if username is not None:
path = path + "&username={}".format(username)
return self._get(path)
def get_audit_log_task_status(
self,
action_key: str,
) -> dict:
"""Certain actions like appliance upgrade, appliance restore etc.,
return a key as in response. Check for status of such operations
using the key
.. list-table::
:header-rows: 1
* - Swagger Section
- Method
- Endpoint
* - actionLog
- GET
- /action/status
:param action_key: GUID of task to retrieve status for
:type action_key: str
:return: Returns dictionary of specified task details \n
* keyword **id** (`int`): Id of the log entry
* keyword **user** (`str`): User who performed this action
* keyword **ipAddress** (`str`): IP Address who performed
this action
* keyword **nepk** (`str`): Primary key of the appliance on
which this action was performed
* keyword **name** (`str`): Name of the action
* keyword **description** (`str`): Description of the action
* keyword **taskStatus** (`str`): Status of the action
* keyword **startTime** (`int`): Start time of the action in
milliseconds since epoch
* keyword **endTime** (`int`): End time of the action in
milliseconds since epoch
* keyword **queuedTime** (`int`): Original queued time of
the action in milliseconds since epoch
* keyword **percentComplete** (`int`): Percentage completion
of the action
* keyword **completionStatus** (boolean): Show if action
succeeded or failed
* keyword **result** (`str`): Opaque blob of data related to
action. Typically, this is the result of the action.
* keyword **intTaskStatus** (`int`): Status of the action in
integer enum format
* keyword **guid** (`str`): GUID of a group of related
actions
:rtype: list
"""
return self._get("/action/status?key={}".format(action_key))
def cancel_audit_log_task(
self,
action_key: str,
) -> bool:
"""Certain actions like appliance upgrade, appliance restore etc.,
return a key as in response. Cancel the action referenced by
provided key.
.. list-table::
:header-rows: 1
* - Swagger Section
- Method
- Endpoint
* - actionLog
- POST
- /action/cancel
:param action_key: GUID of task to retrieve status for
:type action_key: str
:return: Returns True/False based on successful call
:rtype: bool
"""
return self._get("/action/status?key={}".format(action_key))
|
def get_audit_log(self, start_time: int, end_time: int, limit: int, log_level: int=1, ne_pk: str=None, username: str=None) -> list:
"""Get audit log details filtered by specified query parameters
.. list-table::
:header-rows: 1
* - Swagger Section
- Method
- Endpoint
* - actionLog
- GET
- /action
:param start_time: Long(Signed 64 bits) value of seconds since EPOCH
time indicating the starting time boundary of data time range
:type start_time: int
:param end_time: Long(Signed 64 bits) value of seconds since EPOCH
time indicating the ending time boundary of data time range
:type end_time: int
:param limit: Limit the number of rows to retrieve from audit log
:type limit: int
:param log_level: ``0`` for Debug, ``1`` for Info, ``2`` for Error.
Defaults to 1
:type log_level: int, optional
:param ne_pk: Filter for specific appliance with Network Primary Key
(nePk) of appliance, e.g. ``3.NE``
:type ne_pk: str, optional
:param username: Filter for specific user
:type username: str, optional
:return: Returns list of dictionaries
[`dict`]: Audit log line
* keyword **id** (`int`): Id of the log entry
* keyword **user** (`str`): User who performed this action
* keyword **ipAddress** (`str`): IP Address who performed
this action
* keyword **nepk** (`str`): Primary key of the appliance on
which this action was performed
* keyword **name** (`str`): Name of the action
* keyword **description** (`str`): Description of the action
* keyword **taskStatus** (`str`): Status of the action
* keyword **startTime** (`int`): Start time of the action in
milliseconds since epoch
* keyword **endTime** (`int`): End time of the action in
milliseconds since epoch
* keyword **queuedTime** (`int`): Original queued time of
the action in milliseconds since epoch
* keyword **percentComplete** (`int`): Percentage completion
of the action
* keyword **completionStatus** (boolean): Show if action
succeeded or failed
* keyword **result** (`str`): Opaque blob of data related to
action. Typically, this is the result of the action.
* keyword **intTaskStatus** (`int`): Status of the action in
integer enum format
* keyword **guid** (`str`): GUID of a group of related
actions
:rtype: list
"""
path = '/action?startTime={}&endTime={}&limit={}&logLevel={}'.format(start_time, end_time, limit, log_level)
if ne_pk is not None:
path = path + '&appliance={}'.format(ne_pk)
if username is not None:
path = path + '&username={}'.format(username)
return self._get(path)
def get_audit_log_task_status(self, action_key: str) -> dict:
"""Certain actions like appliance upgrade, appliance restore etc.,
return a key as in response. Check for status of such operations
using the key
.. list-table::
:header-rows: 1
* - Swagger Section
- Method
- Endpoint
* - actionLog
- GET
- /action/status
:param action_key: GUID of task to retrieve status for
:type action_key: str
:return: Returns dictionary of specified task details
* keyword **id** (`int`): Id of the log entry
* keyword **user** (`str`): User who performed this action
* keyword **ipAddress** (`str`): IP Address who performed
this action
* keyword **nepk** (`str`): Primary key of the appliance on
which this action was performed
* keyword **name** (`str`): Name of the action
* keyword **description** (`str`): Description of the action
* keyword **taskStatus** (`str`): Status of the action
* keyword **startTime** (`int`): Start time of the action in
milliseconds since epoch
* keyword **endTime** (`int`): End time of the action in
milliseconds since epoch
* keyword **queuedTime** (`int`): Original queued time of
the action in milliseconds since epoch
* keyword **percentComplete** (`int`): Percentage completion
of the action
* keyword **completionStatus** (boolean): Show if action
succeeded or failed
* keyword **result** (`str`): Opaque blob of data related to
action. Typically, this is the result of the action.
* keyword **intTaskStatus** (`int`): Status of the action in
integer enum format
* keyword **guid** (`str`): GUID of a group of related
actions
:rtype: list
"""
return self._get('/action/status?key={}'.format(action_key))
def cancel_audit_log_task(self, action_key: str) -> bool:
"""Certain actions like appliance upgrade, appliance restore etc.,
return a key as in response. Cancel the action referenced by
provided key.
.. list-table::
:header-rows: 1
* - Swagger Section
- Method
- Endpoint
* - actionLog
- POST
- /action/cancel
:param action_key: GUID of task to retrieve status for
:type action_key: str
:return: Returns True/False based on successful call
:rtype: bool
"""
return self._get('/action/status?key={}'.format(action_key))
|
#!/usr/bin/env python
# iGoBot - a GO game playing robot
#
# ##############################
# # GO stone board coordinates #
# ##############################
#
# Project website: http://www.springwald.de/hi/igobot
#
# Licensed under MIT License (MIT)
#
# Copyright (c) 2018 Daniel Springwald | daniel@springwald.de
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
class Board():
_released = False
Empty = 0;
Black = 1;
White = 2;
_boardSize = 0; # 9, 13, 19
_fields = [];
# Stepper motor positions
_13x13_xMin = 735;
_13x13_xMax = 3350;
_13x13_yMin = 100;
_13x13_yMax = 2890;
_9x9_xMin = 1120;
_9x9_xMax = 2940;
_9x9_yMin = 560;
_9x9_yMax = 2400;
StepperMinX = 0;
StepperMaxX = 0;
StepperMinY = 0;
StepperMaxY = 0;
def __init__(self, boardSize):
self._boardSize = boardSize;
if (boardSize == 13):
#print("Board: size " , boardSize, "x", boardSize);
self.StepperMinX = self._13x13_xMin;
self.StepperMaxX = self._13x13_xMax
self.StepperMinY = self._13x13_yMin;
self.StepperMaxY = self._13x13_yMax;
else:
if (boardSize == 9):
#print("Board: size " , boardSize, "x", boardSize);
self.StepperMinX = self._9x9_xMin;
self.StepperMaxX = self._9x9_xMax
self.StepperMinY = self._9x9_yMin;
self.StepperMaxY = self._9x9_yMax;
else:
throw ("unknown board size " , boardSize, "x", boardSize);
# init board dimensions with 0 values (0=empty, 1=black, 2= white)
self._fields = [[0 for i in range(boardSize)] for j in range(boardSize)]
@staticmethod
def FromStones(boardSize, blackStones, whiteStones):
# create a new board and fill it with the given black and white stones
board = Board(boardSize)
if (blackStones != None and len(blackStones) > 0 and blackStones[0] != ''):
for black in Board.EnsureXyNotation(blackStones):
board.SetField(black[0],black[1],Board.Black);
if (whiteStones != None and len(whiteStones) > 0 and whiteStones[0] != ''):
for white in Board.EnsureXyNotation(whiteStones):
board.SetField(white[0],white[1],Board.White);
return board;
@staticmethod
def Differences(board1, board2):
# find all coordinates, where the second board is other
if (board1 == None): throw ("board1 == None");
if (board2 == None): throw ("board2 == None");
if (board1._boardSize != board2._boardSize): throw ("different board sizes: " , board1._boardSize, " vs. ", board2._boardSize);
result = [];
for x in range(0, board1._boardSize):
for y in range(0, board1._boardSize):
if (board1.GetField(x,y) != board2.GetField(x,y)):
result.extend([[x,y]])
return result;
def RemovedStones(board1, board2):
# find all coordinates, where the stones from board1 are not on board2
if (board1 == None): throw ("board1 == None");
if (board2 == None): throw ("board2 == None");
if (board1._boardSize != board2._boardSize): throw ("different board sizes: " , board1._boardSize, " vs. ", board2._boardSize);
result = [];
for x in range(0, board1._boardSize):
for y in range(0, board1._boardSize):
if (board1.GetField(x,y) != Board.Empty):
if (board2.GetField(x,y) == Board.Empty):
result.extend([[x,y]])
return result;
@staticmethod
def EnsureXyNotation(stones):
#ensures that this is a list of [[x,y],[x,y]] and not like ["A1","G2]
result = [];
for stone in stones:
#print(">>>1>>>", stone);
if (isinstance(stone, str) and stone !=''):
#print(">>>2>>>", Board.AzToXy(stone));
result.extend([Board.AzToXy(stone)])
else:
#print(">>>3>>>", stones);
return stones; # already [x,y] format
return result;
@staticmethod
def XyToAz(x,y):
# converts x=1,y=2 to A1
if (x > 7):
x=x+1; # i is not defined, jump to j
return chr(65+x)+str(y+1);
@staticmethod
def AzToXy(azNotation):
# converts A1 to [0,0]
if (len(azNotation) != 2 and len(azNotation) != 3):
print ("board.AzToXy for '" + azNotation + "' is not exact 2-3 chars long");
return None;
x = ord(azNotation[0])-65;
if (x > 7):
x=x-1; # i is not defined, jump to h
y = int(azNotation[1:])-1;
return [x,y]
def Print(self):
# draw the board to console
for y in range(0, self._boardSize):
line = "";
for x in range(0, self._boardSize):
stone = self.GetField(x,y);
if (stone==0):
line = line + "."
elif (stone==Board.Black):
line = line + "*";
elif (stone==Board.White):
line = line + "O";
print(line);
def GetField(self,x,y):
return self._fields[x][y];
def SetField(self,x,y, value):
self._fields[x][y] = value;
def GetNewStones(self, detectedStones, color=Black):
# what are the new black/whites stones in the list, not still on the board?
newStones = [];
for stone in detectedStones:
if (self.GetField(stone[0],stone[1]) != color):
newStones.extend([[stone[0],stone[1]]])
return newStones;
def GetStepperXPos(self, fieldX):
return self.StepperMinX + int(fieldX * 1.0 * ((self.StepperMaxX-self.StepperMinX) / (self._boardSize-1.0)));
def GetStepperYPos(self, fieldY):
return self.StepperMinY + int(fieldY * 1.0 * ((self.StepperMaxY-self.StepperMinY) / (self._boardSize-1.0)));
if __name__ == '__main__':
board = Board(13)
print (board._fields)
print (Board.AzToXy("A1"))
board.SetField(0,0,board.Black);
board.SetField(12,12,board.Black);
print(board.GetField(0,0));
print(board.GetField(0,0) == board.Black);
for x in range(0,13):
f = board.XyToAz(x,x);
print([x,x],f, Board.AzToXy(f));
board2 = Board.FromStones(boardSize=13, blackStones=[[0,0],[1,1]], whiteStones=[[2,0],[2,1]]);
board2.Print();
print(Board.Differences(board,board2));
print(Board.RemovedStones(board,board2));
|
class Board:
_released = False
empty = 0
black = 1
white = 2
_board_size = 0
_fields = []
_13x13_x_min = 735
_13x13_x_max = 3350
_13x13_y_min = 100
_13x13_y_max = 2890
_9x9_x_min = 1120
_9x9_x_max = 2940
_9x9_y_min = 560
_9x9_y_max = 2400
stepper_min_x = 0
stepper_max_x = 0
stepper_min_y = 0
stepper_max_y = 0
def __init__(self, boardSize):
self._boardSize = boardSize
if boardSize == 13:
self.StepperMinX = self._13x13_xMin
self.StepperMaxX = self._13x13_xMax
self.StepperMinY = self._13x13_yMin
self.StepperMaxY = self._13x13_yMax
elif boardSize == 9:
self.StepperMinX = self._9x9_xMin
self.StepperMaxX = self._9x9_xMax
self.StepperMinY = self._9x9_yMin
self.StepperMaxY = self._9x9_yMax
else:
throw('unknown board size ', boardSize, 'x', boardSize)
self._fields = [[0 for i in range(boardSize)] for j in range(boardSize)]
@staticmethod
def from_stones(boardSize, blackStones, whiteStones):
board = board(boardSize)
if blackStones != None and len(blackStones) > 0 and (blackStones[0] != ''):
for black in Board.EnsureXyNotation(blackStones):
board.SetField(black[0], black[1], Board.Black)
if whiteStones != None and len(whiteStones) > 0 and (whiteStones[0] != ''):
for white in Board.EnsureXyNotation(whiteStones):
board.SetField(white[0], white[1], Board.White)
return board
@staticmethod
def differences(board1, board2):
if board1 == None:
throw('board1 == None')
if board2 == None:
throw('board2 == None')
if board1._boardSize != board2._boardSize:
throw('different board sizes: ', board1._boardSize, ' vs. ', board2._boardSize)
result = []
for x in range(0, board1._boardSize):
for y in range(0, board1._boardSize):
if board1.GetField(x, y) != board2.GetField(x, y):
result.extend([[x, y]])
return result
def removed_stones(board1, board2):
if board1 == None:
throw('board1 == None')
if board2 == None:
throw('board2 == None')
if board1._boardSize != board2._boardSize:
throw('different board sizes: ', board1._boardSize, ' vs. ', board2._boardSize)
result = []
for x in range(0, board1._boardSize):
for y in range(0, board1._boardSize):
if board1.GetField(x, y) != Board.Empty:
if board2.GetField(x, y) == Board.Empty:
result.extend([[x, y]])
return result
@staticmethod
def ensure_xy_notation(stones):
result = []
for stone in stones:
if isinstance(stone, str) and stone != '':
result.extend([Board.AzToXy(stone)])
else:
return stones
return result
@staticmethod
def xy_to_az(x, y):
if x > 7:
x = x + 1
return chr(65 + x) + str(y + 1)
@staticmethod
def az_to_xy(azNotation):
if len(azNotation) != 2 and len(azNotation) != 3:
print("board.AzToXy for '" + azNotation + "' is not exact 2-3 chars long")
return None
x = ord(azNotation[0]) - 65
if x > 7:
x = x - 1
y = int(azNotation[1:]) - 1
return [x, y]
def print(self):
for y in range(0, self._boardSize):
line = ''
for x in range(0, self._boardSize):
stone = self.GetField(x, y)
if stone == 0:
line = line + '.'
elif stone == Board.Black:
line = line + '*'
elif stone == Board.White:
line = line + 'O'
print(line)
def get_field(self, x, y):
return self._fields[x][y]
def set_field(self, x, y, value):
self._fields[x][y] = value
def get_new_stones(self, detectedStones, color=Black):
new_stones = []
for stone in detectedStones:
if self.GetField(stone[0], stone[1]) != color:
newStones.extend([[stone[0], stone[1]]])
return newStones
def get_stepper_x_pos(self, fieldX):
return self.StepperMinX + int(fieldX * 1.0 * ((self.StepperMaxX - self.StepperMinX) / (self._boardSize - 1.0)))
def get_stepper_y_pos(self, fieldY):
return self.StepperMinY + int(fieldY * 1.0 * ((self.StepperMaxY - self.StepperMinY) / (self._boardSize - 1.0)))
if __name__ == '__main__':
board = board(13)
print(board._fields)
print(Board.AzToXy('A1'))
board.SetField(0, 0, board.Black)
board.SetField(12, 12, board.Black)
print(board.GetField(0, 0))
print(board.GetField(0, 0) == board.Black)
for x in range(0, 13):
f = board.XyToAz(x, x)
print([x, x], f, Board.AzToXy(f))
board2 = Board.FromStones(boardSize=13, blackStones=[[0, 0], [1, 1]], whiteStones=[[2, 0], [2, 1]])
board2.Print()
print(Board.Differences(board, board2))
print(Board.RemovedStones(board, board2))
|
def compare(a: int, b: int):
printNums(a, b)
if a > b:
msg = "a > b"
a += 1
elif a < b:
msg = "a < b"
b += 1
else:
msg = "a == b"
a += 1
b += 1
print(msg)
printNums(a, b)
print()
def printNums(a, b):
print(f"{a = }, {b = }")
def main():
for a in range(1, 4):
for b in range(1, 4):
compare(a, b)
if __name__ == "__main__":
main()
|
def compare(a: int, b: int):
print_nums(a, b)
if a > b:
msg = 'a > b'
a += 1
elif a < b:
msg = 'a < b'
b += 1
else:
msg = 'a == b'
a += 1
b += 1
print(msg)
print_nums(a, b)
print()
def print_nums(a, b):
print(f'a = {a!r}, b = {b!r}')
def main():
for a in range(1, 4):
for b in range(1, 4):
compare(a, b)
if __name__ == '__main__':
main()
|
#!/usr/bin/env python
"""quicksort.py: Program to implement quicksort"""
__author__ = 'Rohit Sinha'
def quick_sort(alist):
quick_sort_helper(alist, 0, len(alist) - 1)
def quick_sort_helper(alist, start, end):
if start < end:
pivot = partition(alist, start, end)
quick_sort_helper(alist, start, pivot - 1)
quick_sort_helper(alist, pivot + 1, end)
def partition(alist, start, end):
pivot_value = alist[start]
left_pointer = start+1
right_pointer = end
done = False
while not done:
while left_pointer <= right_pointer and alist[left_pointer] <= pivot_value:
left_pointer += 1
while right_pointer >= left_pointer and alist[right_pointer] >= pivot_value:
right_pointer -= 1
if left_pointer > right_pointer:
done = True
else:
alist[left_pointer], alist[right_pointer] = alist[right_pointer], alist[left_pointer]
alist[right_pointer], alist[start] = alist[start], alist[right_pointer]
return right_pointer
if __name__ == '__main__':
alist = [84, 69, 76, 86, 94, 91]
quick_sort(alist)
print(alist)
|
"""quicksort.py: Program to implement quicksort"""
__author__ = 'Rohit Sinha'
def quick_sort(alist):
quick_sort_helper(alist, 0, len(alist) - 1)
def quick_sort_helper(alist, start, end):
if start < end:
pivot = partition(alist, start, end)
quick_sort_helper(alist, start, pivot - 1)
quick_sort_helper(alist, pivot + 1, end)
def partition(alist, start, end):
pivot_value = alist[start]
left_pointer = start + 1
right_pointer = end
done = False
while not done:
while left_pointer <= right_pointer and alist[left_pointer] <= pivot_value:
left_pointer += 1
while right_pointer >= left_pointer and alist[right_pointer] >= pivot_value:
right_pointer -= 1
if left_pointer > right_pointer:
done = True
else:
(alist[left_pointer], alist[right_pointer]) = (alist[right_pointer], alist[left_pointer])
(alist[right_pointer], alist[start]) = (alist[start], alist[right_pointer])
return right_pointer
if __name__ == '__main__':
alist = [84, 69, 76, 86, 94, 91]
quick_sort(alist)
print(alist)
|
latest_block_redis_key = "latest_block_from_chain"
latest_block_hash_redis_key = "latest_blockhash_from_chain"
most_recent_indexed_block_redis_key = "most_recently_indexed_block_from_db"
most_recent_indexed_block_hash_redis_key = "most_recently_indexed_block_hash_from_db"
most_recent_indexed_ipld_block_redis_key = "most_recent_indexed_ipld_block_redis_key"
most_recent_indexed_ipld_block_hash_redis_key = (
"most_recent_indexed_ipld_block_hash_redis_key"
)
trending_tracks_last_completion_redis_key = "trending:tracks:last-completion"
trending_playlists_last_completion_redis_key = "trending-playlists:last-completion"
challenges_last_processed_event_redis_key = "challenges:last-processed-event"
user_balances_refresh_last_completion_redis_key = "user_balances:last-completion"
latest_sol_play_tx_key = "latest_sol_play_tx_key"
index_eth_last_completion_redis_key = "index_eth:last-completion"
|
latest_block_redis_key = 'latest_block_from_chain'
latest_block_hash_redis_key = 'latest_blockhash_from_chain'
most_recent_indexed_block_redis_key = 'most_recently_indexed_block_from_db'
most_recent_indexed_block_hash_redis_key = 'most_recently_indexed_block_hash_from_db'
most_recent_indexed_ipld_block_redis_key = 'most_recent_indexed_ipld_block_redis_key'
most_recent_indexed_ipld_block_hash_redis_key = 'most_recent_indexed_ipld_block_hash_redis_key'
trending_tracks_last_completion_redis_key = 'trending:tracks:last-completion'
trending_playlists_last_completion_redis_key = 'trending-playlists:last-completion'
challenges_last_processed_event_redis_key = 'challenges:last-processed-event'
user_balances_refresh_last_completion_redis_key = 'user_balances:last-completion'
latest_sol_play_tx_key = 'latest_sol_play_tx_key'
index_eth_last_completion_redis_key = 'index_eth:last-completion'
|
a = 'abcdefghijklmnopqrstuvwxyz'
b = 'pvwdgazxubqfsnrhocitlkeymj'
trans = str.maketrans(b, a)
src = 'Wxgcg txgcg ui p ixgff, txgcg ui p epm. I gyhgwt mrl lig txg ixgff wrsspnd tr irfkg txui hcrvfgs, nre, hfgpig tcm liunz txg crt13 ra "ixgff" tr gntgc ngyt fgkgf.'
print(src.translate(trans))
|
a = 'abcdefghijklmnopqrstuvwxyz'
b = 'pvwdgazxubqfsnrhocitlkeymj'
trans = str.maketrans(b, a)
src = 'Wxgcg txgcg ui p ixgff, txgcg ui p epm. I gyhgwt mrl lig txg ixgff wrsspnd tr irfkg txui hcrvfgs, nre, hfgpig tcm liunz txg crt13 ra "ixgff" tr gntgc ngyt fgkgf.'
print(src.translate(trans))
|
def get_level_1_news():
news1 = 'Stars Wars movie filming is canceled due to high electrical energy used. Turns out' \
'those lasers don\'t power themselves'
news2 = 'Pink Floyd Tour canceled after first show used up the whole energy city had for' \
'the whole month. The band says they\'ll be happy to play on the dark side of the town'
news3 = 'A public poll shows people are spending more energy on electric heaters after the ' \
'start of the cold war'
news4 = "9 in 10 people of your country do not know what the cold war is. The one who knows " \
"is in the military"
news5 = "Scientists says that world temperatures are rising due to high number of home " \
"refrigerators being used worldwide. According to Mr. Midgley, all the earth's" \
" cold is being trapped inside 4 billion refrigerators"
news6 = "Mr. Midgley published a new research where he's proved that ceiling and wall fans" \
" are causing hurricanes"
news7 = "Mr. Midgley, again, says he's discovered a way to revert climate change: everybody" \
" should throw their refrigerator's ice cubes into the ocean"
news8 = "After a whole year of snow falling almost in every corner of the world, Mr. " \
"Midgley says he knows nothing and announced his retirement"
news9 = "Free nuclear fusion energy is a reality, says scientist, we just need to learn " \
"how to do it"
news10 = "RMS Titanic reaches its destiny safely after hitting a small chunk of ice in" \
" the ocean"
news11 = "All the Ice Sculptures business worldwide have declared bankruptcy, says" \
" World Bank"
news12 = "After 'Star Wars: The Phantom Menace' script was leaked people are happy the " \
"franchise got canceled 30 years ago"
news13 = "Microsoft's head says Windows95 will be the last one to ever be launched due to its" \
" low energy use"
news14 = "Programmers for Climate Change Convention ends in confusion after fight over using" \
" tabs or spaces"
news15 = "The series finale of Game of Thrones lowered the Public Well being index of your" \
" nation by x%"
news16 = "Drake's song 'Hotline Bling' is under investigation for being related to higher" \
" temperatures in the US this year"
news17 = "The blockbuster 'Mad Max: Fury Road' shows a sequel of the world we live in, " \
"says director"
news18 = "Lost's last episode is an homage to our own world, which will also have a crappy " \
"ending, says fan"
news19 = "Pearl Harbor movie filming canceled due to the harbor being flooded by the " \
"advancing ocean"
news20 = "Award winning Dwight Schrute's movie 'Recyclops' to gain sequels: 'Recyclops " \
"Reloaded' and 'Recyclops Revolution'"
news21 = "The Simpsons predicted nuclear power scandal in episode where Homer pushes big" \
" red button for no reason"
news = {
'news1': news1,
'news2': news2,
'news3': news3,
'news4': news4,
'news5': news5,
'news6': news6,
'news7': news7,
'news8': news8,
'news9': news9,
'news10': news10,
'news11': news11,
'news12': news12,
'news13': news13,
'news14': news14,
'news15': news15,
'news16': news16,
'news17': news17,
'news18': news18,
'news19': news19,
'news20': news20,
'news21': news21
}
return news
def get_level_2_news():
news1 = "Your X index is up Y% and your N index is down because of Z"
news2 = "President PLAYER_NAME canceled Formula 1 race to save fuel, Public well being, " \
"acceptance and co2 emissions are down x%"
news = {
'news1': news1,
'news2': news2
}
return news
def get_level_3_news():
news1 = "Your X index is down Y% because of Z"
news2 = "In order to save energy, President PLAYER_NAME sanctions law that prohibits people " \
"of ever ironing their clothes. People are so happy that public well being index is" \
" up x% and energy use is down y%"
news = {
'news1': news1,
'news2': news2
}
return news
def get_level_4_news():
news1 = "Your X index is down Y% and it also affected your Z index which is down N%"
news = {
'news1': news1
}
return news
def get_level_5_news():
news1 = "Your X index is down X%, XYZ thing just happened"
news2 = "The Amazon River, the biggest in the world, dries up and becomes the world's " \
"biggest desert"
news3 = "Plants can no longer recognize what season we are on. They now bloom at random " \
"moments of the year"
news = {
'news1': news1,
'news2': news2,
'news3': news3
}
return news
|
def get_level_1_news():
news1 = "Stars Wars movie filming is canceled due to high electrical energy used. Turns outthose lasers don't power themselves"
news2 = "Pink Floyd Tour canceled after first show used up the whole energy city had forthe whole month. The band says they'll be happy to play on the dark side of the town"
news3 = 'A public poll shows people are spending more energy on electric heaters after the start of the cold war'
news4 = '9 in 10 people of your country do not know what the cold war is. The one who knows is in the military'
news5 = "Scientists says that world temperatures are rising due to high number of home refrigerators being used worldwide. According to Mr. Midgley, all the earth's cold is being trapped inside 4 billion refrigerators"
news6 = "Mr. Midgley published a new research where he's proved that ceiling and wall fans are causing hurricanes"
news7 = "Mr. Midgley, again, says he's discovered a way to revert climate change: everybody should throw their refrigerator's ice cubes into the ocean"
news8 = 'After a whole year of snow falling almost in every corner of the world, Mr. Midgley says he knows nothing and announced his retirement'
news9 = 'Free nuclear fusion energy is a reality, says scientist, we just need to learn how to do it'
news10 = 'RMS Titanic reaches its destiny safely after hitting a small chunk of ice in the ocean'
news11 = 'All the Ice Sculptures business worldwide have declared bankruptcy, says World Bank'
news12 = "After 'Star Wars: The Phantom Menace' script was leaked people are happy the franchise got canceled 30 years ago"
news13 = "Microsoft's head says Windows95 will be the last one to ever be launched due to its low energy use"
news14 = 'Programmers for Climate Change Convention ends in confusion after fight over using tabs or spaces'
news15 = 'The series finale of Game of Thrones lowered the Public Well being index of your nation by x%'
news16 = "Drake's song 'Hotline Bling' is under investigation for being related to higher temperatures in the US this year"
news17 = "The blockbuster 'Mad Max: Fury Road' shows a sequel of the world we live in, says director"
news18 = "Lost's last episode is an homage to our own world, which will also have a crappy ending, says fan"
news19 = 'Pearl Harbor movie filming canceled due to the harbor being flooded by the advancing ocean'
news20 = "Award winning Dwight Schrute's movie 'Recyclops' to gain sequels: 'Recyclops Reloaded' and 'Recyclops Revolution'"
news21 = 'The Simpsons predicted nuclear power scandal in episode where Homer pushes big red button for no reason'
news = {'news1': news1, 'news2': news2, 'news3': news3, 'news4': news4, 'news5': news5, 'news6': news6, 'news7': news7, 'news8': news8, 'news9': news9, 'news10': news10, 'news11': news11, 'news12': news12, 'news13': news13, 'news14': news14, 'news15': news15, 'news16': news16, 'news17': news17, 'news18': news18, 'news19': news19, 'news20': news20, 'news21': news21}
return news
def get_level_2_news():
news1 = 'Your X index is up Y% and your N index is down because of Z'
news2 = 'President PLAYER_NAME canceled Formula 1 race to save fuel, Public well being, acceptance and co2 emissions are down x%'
news = {'news1': news1, 'news2': news2}
return news
def get_level_3_news():
news1 = 'Your X index is down Y% because of Z'
news2 = 'In order to save energy, President PLAYER_NAME sanctions law that prohibits people of ever ironing their clothes. People are so happy that public well being index is up x% and energy use is down y%'
news = {'news1': news1, 'news2': news2}
return news
def get_level_4_news():
news1 = 'Your X index is down Y% and it also affected your Z index which is down N%'
news = {'news1': news1}
return news
def get_level_5_news():
news1 = 'Your X index is down X%, XYZ thing just happened'
news2 = "The Amazon River, the biggest in the world, dries up and becomes the world's biggest desert"
news3 = 'Plants can no longer recognize what season we are on. They now bloom at random moments of the year'
news = {'news1': news1, 'news2': news2, 'news3': news3}
return news
|
user_num = int(input("which number would you like to check?"))
def devisible_by_both():
if user_num %3 == 0 and user_num %5 == 0:
print("your number is divisible by both")
else:
print("your number is not divisible by both")
|
user_num = int(input('which number would you like to check?'))
def devisible_by_both():
if user_num % 3 == 0 and user_num % 5 == 0:
print('your number is divisible by both')
else:
print('your number is not divisible by both')
|
class PyQtSociusError(Exception):
pass
class WrongInputFileTypeError(PyQtSociusError):
__module__ = 'pyqtsocius'
def __init__(self, input_file: str, expected_file_extension: str, extra_message: str = None):
self.file = input_file
self.file_ext = '.' + input_file.split('.')[-1]
self.expected_ext = expected_file_extension
self.message = f"File '{self.file}' with extension '{self.file_ext}', has wrong File type. expected extension --> '{self.expected_ext}'\n"
if extra_message is not None:
self.message += extra_message
super().__init__(self.message)
class FeatureNotYetImplemented(PyQtSociusError):
__module__ = 'pyqtsocius'
def __init__(self, requested_feature):
super().__init__(f"the feature '{requested_feature}' is currently not yet implemented")
|
class Pyqtsociuserror(Exception):
pass
class Wronginputfiletypeerror(PyQtSociusError):
__module__ = 'pyqtsocius'
def __init__(self, input_file: str, expected_file_extension: str, extra_message: str=None):
self.file = input_file
self.file_ext = '.' + input_file.split('.')[-1]
self.expected_ext = expected_file_extension
self.message = f"File '{self.file}' with extension '{self.file_ext}', has wrong File type. expected extension --> '{self.expected_ext}'\n"
if extra_message is not None:
self.message += extra_message
super().__init__(self.message)
class Featurenotyetimplemented(PyQtSociusError):
__module__ = 'pyqtsocius'
def __init__(self, requested_feature):
super().__init__(f"the feature '{requested_feature}' is currently not yet implemented")
|
base_rf.fit(X_train, y_train)
under_rf.fit(X_train, y_train)
over_rf.fit(X_train, y_train)
plot_roc_and_precision_recall_curves([
("original", base_rf),
("undersampling", under_rf),
("oversampling", over_rf),
])
|
base_rf.fit(X_train, y_train)
under_rf.fit(X_train, y_train)
over_rf.fit(X_train, y_train)
plot_roc_and_precision_recall_curves([('original', base_rf), ('undersampling', under_rf), ('oversampling', over_rf)])
|
# The view that is shown for normal use of this app
# Button name for front page
SUPERUSER_SETTINGS_VIEW = 'twitterapp.views.site_setup'
|
superuser_settings_view = 'twitterapp.views.site_setup'
|
class TrieNode:
def __init__(self):
self.children = {}
self.is_word = False
self.word = str
class Trie:
def __init__(self):
self.root = TrieNode()
def add_word(self, word):
node = self.root
for c in word:
if c not in node.children:
node.children[c] = TrieNode()
node = node.children[c]
node.is_word = True
node.word = word
class Solution:
"""
@param words: a set of stirngs
@param target: a target string
@param k: An integer
@return: output all the strings that meet the requirements
"""
def kDistance(self, words, target, k):
trie = Trie()
for word in words:
trie.add_word(word)
n = len(target)
dp = [i for i in range(n + 1)]
result = []
self.find(trie.root, target, k, dp, result)
return result
def find(self, node, target, k, dp, result):
n = len(target)
if node.is_word:
print(node.word, dp[n])
if node.is_word and dp[n] <= k:
result.append(node.word)
next = [0 for i in range(n + 1)]
for c in node.children:
next[0] = dp[0] + 1
for i in range(1, n + 1):
if target[i - 1] == c:
# print(target[i - 1], c)
next[i] = min(dp[i - 1], min(dp[i] + 1, next[i - 1] + 1))
else:
next[i] = min(dp[i - 1] + 1, dp[i] + 1, next[i - 1] + 1)
self.find(node.children[c], target, k, next, result)
|
class Trienode:
def __init__(self):
self.children = {}
self.is_word = False
self.word = str
class Trie:
def __init__(self):
self.root = trie_node()
def add_word(self, word):
node = self.root
for c in word:
if c not in node.children:
node.children[c] = trie_node()
node = node.children[c]
node.is_word = True
node.word = word
class Solution:
"""
@param words: a set of stirngs
@param target: a target string
@param k: An integer
@return: output all the strings that meet the requirements
"""
def k_distance(self, words, target, k):
trie = trie()
for word in words:
trie.add_word(word)
n = len(target)
dp = [i for i in range(n + 1)]
result = []
self.find(trie.root, target, k, dp, result)
return result
def find(self, node, target, k, dp, result):
n = len(target)
if node.is_word:
print(node.word, dp[n])
if node.is_word and dp[n] <= k:
result.append(node.word)
next = [0 for i in range(n + 1)]
for c in node.children:
next[0] = dp[0] + 1
for i in range(1, n + 1):
if target[i - 1] == c:
next[i] = min(dp[i - 1], min(dp[i] + 1, next[i - 1] + 1))
else:
next[i] = min(dp[i - 1] + 1, dp[i] + 1, next[i - 1] + 1)
self.find(node.children[c], target, k, next, result)
|
class MoonBoard():
"""
Class that encapsulates Moonboard layout info for a specific year.
:param year_layout: Year in which this board layout was published
:type year_layout: int
:param image: Path to the image file for this board layout
:type image: str
:param rows: Number of rows of the board. Defaults to 18
:type rows: int, optional
:param cols: Number of columns of the board. Defaults to 11
:type cols: int, optional
"""
def __init__(self, year_layout: int, image: str, rows: int = 18, cols: int = 11) -> None:
"""
Initialize a MoonBoard object.
"""
self._year_layout = year_layout
self._image = image
self._rows = rows
self._cols = cols
def __str__(self) -> str:
"""Get a user friendly string representation of the MoonBoard class
:return: User firendly string representation if this Moonboard object
:rtype: str
"""
return f"{__class__.__name__} for {self._moonboard.get_year_layout()} layout"
def __hash__(self) -> int:
"""
Compute hash from the year, image path
"""
return hash(self._year_layout) ^ hash(self._image) ^ hash(self._rows) ^ hash(self._cols)
def __eq__(self, __o: object) -> bool:
"""
Test for equality between two MoonBoard objects
"""
if hash(self) != hash(__o): # if hashes are not equal, objects cannot be equal
return False
return self._year_layout == __o._year_layout and self._image == __o._image and self._rows == __o._rows and self._cols == __o._cols
def get_rows(self) -> int:
"""
Get number of rows of the board
:return: Number of rows of the board
:rtype: int
"""
return self._rows
def get_cols(self) -> int:
"""
Get number of columns of the board
:return: Number of columns of the board
:rtype: int
"""
return self._cols
def get_year_layout(self) -> int:
"""
Get the year in which this board layout was published
:return: Year in which this board layout was published
:rtype: int
"""
return self._year_layout
def get_image(self) -> str:
"""
Get the path to the image file for this board layout
:return: Image path
:rtype: str
"""
return self._image
def get_moonboard(year: int) -> MoonBoard:
"""
Factory function. Given a year, return a Moonboard object encapsulating the
Moonboard layout info of that year.
:param year: Year of the desired Moonboard layout
:type year: int
:return: Moonboard object encapsulating the Moonboard layout info
:rtype: MoonBoard
:raises ValueError: Year is not a valid Moonboard year
"""
if year == 2016:
return MoonBoard(2016, 'moonboards/2016.jpg')
elif year == 2017:
return MoonBoard(2017, 'moonboards/2017.jpg')
elif year == 2019:
return MoonBoard(2019, 'moonboards/2019.jpg')
elif year == 2020:
return MoonBoard(2020, 'moonboards/2020.jpg', rows=12)
raise ValueError('Invalid year')
|
class Moonboard:
"""
Class that encapsulates Moonboard layout info for a specific year.
:param year_layout: Year in which this board layout was published
:type year_layout: int
:param image: Path to the image file for this board layout
:type image: str
:param rows: Number of rows of the board. Defaults to 18
:type rows: int, optional
:param cols: Number of columns of the board. Defaults to 11
:type cols: int, optional
"""
def __init__(self, year_layout: int, image: str, rows: int=18, cols: int=11) -> None:
"""
Initialize a MoonBoard object.
"""
self._year_layout = year_layout
self._image = image
self._rows = rows
self._cols = cols
def __str__(self) -> str:
"""Get a user friendly string representation of the MoonBoard class
:return: User firendly string representation if this Moonboard object
:rtype: str
"""
return f'{__class__.__name__} for {self._moonboard.get_year_layout()} layout'
def __hash__(self) -> int:
"""
Compute hash from the year, image path
"""
return hash(self._year_layout) ^ hash(self._image) ^ hash(self._rows) ^ hash(self._cols)
def __eq__(self, __o: object) -> bool:
"""
Test for equality between two MoonBoard objects
"""
if hash(self) != hash(__o):
return False
return self._year_layout == __o._year_layout and self._image == __o._image and (self._rows == __o._rows) and (self._cols == __o._cols)
def get_rows(self) -> int:
"""
Get number of rows of the board
:return: Number of rows of the board
:rtype: int
"""
return self._rows
def get_cols(self) -> int:
"""
Get number of columns of the board
:return: Number of columns of the board
:rtype: int
"""
return self._cols
def get_year_layout(self) -> int:
"""
Get the year in which this board layout was published
:return: Year in which this board layout was published
:rtype: int
"""
return self._year_layout
def get_image(self) -> str:
"""
Get the path to the image file for this board layout
:return: Image path
:rtype: str
"""
return self._image
def get_moonboard(year: int) -> MoonBoard:
"""
Factory function. Given a year, return a Moonboard object encapsulating the
Moonboard layout info of that year.
:param year: Year of the desired Moonboard layout
:type year: int
:return: Moonboard object encapsulating the Moonboard layout info
:rtype: MoonBoard
:raises ValueError: Year is not a valid Moonboard year
"""
if year == 2016:
return moon_board(2016, 'moonboards/2016.jpg')
elif year == 2017:
return moon_board(2017, 'moonboards/2017.jpg')
elif year == 2019:
return moon_board(2019, 'moonboards/2019.jpg')
elif year == 2020:
return moon_board(2020, 'moonboards/2020.jpg', rows=12)
raise value_error('Invalid year')
|
'''Write a Python program to empty a variable without destroying it.
Sample data: n=20
d = {"x":200}
Expected Output : 0
{}'''
n = 20
d = {"x":200}
print(type(n)())
print(type(d)())
|
"""Write a Python program to empty a variable without destroying it.
Sample data: n=20
d = {"x":200}
Expected Output : 0
{}"""
n = 20
d = {'x': 200}
print(type(n)())
print(type(d)())
|
{
"name": "Module Wordpess Mysql",
"author": "Tedezed",
"version": "0.1",
"frontend": "wordpress",
"backend": "mysql",
"check_app": True,
"update_app_password": True,
"update_secret": True,
"executable": False,
}
|
{'name': 'Module Wordpess Mysql', 'author': 'Tedezed', 'version': '0.1', 'frontend': 'wordpress', 'backend': 'mysql', 'check_app': True, 'update_app_password': True, 'update_secret': True, 'executable': False}
|
"""
@author : udisinghania
@date : 24/12/2018
"""
string1 = input()
string2 = input()
a = 0
if len(string1)!=len(string2):
print("Strings are of different length")
else:
for i in range (len(string1)):
if string1[i]!=string2[i]:
a+=1
print(a)
|
"""
@author : udisinghania
@date : 24/12/2018
"""
string1 = input()
string2 = input()
a = 0
if len(string1) != len(string2):
print('Strings are of different length')
else:
for i in range(len(string1)):
if string1[i] != string2[i]:
a += 1
print(a)
|
"""Minimize_sum_Of_array!!!, CodeWars Kata, level 7."""
def minimize_sum(arr):
"""Minimize sum of array.
Find pairs of to multiply then add the product of those multiples
to find the minimum possible sum
input = integers, in a list
output = integer, the minimum sum of those products
ex: minSum(5,4,2,3) should return 22, 5*2 +3*4 = 22
ex: minSum(12,6,10,26,3,24) should return 342, 26*3 + 24*6 + 12*10 = 342
"""
x = len(arr)
res = []
arr1 = sorted(arr)
for i in range(x // 2):
minprod = arr1[0] * arr1[-1]
arr1.pop()
arr1.pop(0)
res.append(minprod)
return sum(res)
|
"""Minimize_sum_Of_array!!!, CodeWars Kata, level 7."""
def minimize_sum(arr):
"""Minimize sum of array.
Find pairs of to multiply then add the product of those multiples
to find the minimum possible sum
input = integers, in a list
output = integer, the minimum sum of those products
ex: minSum(5,4,2,3) should return 22, 5*2 +3*4 = 22
ex: minSum(12,6,10,26,3,24) should return 342, 26*3 + 24*6 + 12*10 = 342
"""
x = len(arr)
res = []
arr1 = sorted(arr)
for i in range(x // 2):
minprod = arr1[0] * arr1[-1]
arr1.pop()
arr1.pop(0)
res.append(minprod)
return sum(res)
|
# Copyright (c) 2011-2020 Eric Froemling
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
# -----------------------------------------------------------------------------
# This file was automatically generated from "doom_shroom.ma"
# pylint: disable=all
points = {}
# noinspection PyDictCreation
boxes = {}
boxes['area_of_interest_bounds'] = (0.4687647786, 2.320345088,
-3.219423694) + (0.0, 0.0, 0.0) + (
21.34898078, 10.25529817, 14.67298352)
points['ffa_spawn1'] = (-5.828122667, 2.301094498,
-3.445694701) + (1.0, 1.0, 2.682935578)
points['ffa_spawn2'] = (6.496252674, 2.397778847, -3.573241388) + (1.0, 1.0,
2.682935578)
points['ffa_spawn3'] = (0.8835145921, 2.307217208,
-0.3552854962) + (4.455517747, 1.0, 0.2723037175)
points['ffa_spawn4'] = (0.8835145921, 2.307217208,
-7.124335491) + (4.455517747, 1.0, 0.2723037175)
points['flag1'] = (-7.153737138, 2.251993091, -3.427368878)
points['flag2'] = (8.103769491, 2.320591215, -3.548878069)
points['flag_default'] = (0.5964565429, 2.373456481, -4.241969517)
boxes['map_bounds'] = (0.4566560559, 1.332051421, -3.80651373) + (
0.0, 0.0, 0.0) + (27.75073129, 14.44528216, 22.9896617)
points['powerup_spawn1'] = (5.180858712, 4.278900266, -7.282758712)
points['powerup_spawn2'] = (-3.236908759, 4.159702067, -0.3232556512)
points['powerup_spawn3'] = (5.082843398, 4.159702067, -0.3232556512)
points['powerup_spawn4'] = (-3.401729203, 4.278900266, -7.425891191)
points['shadow_lower_bottom'] = (0.5964565429, -0.2279530265, 3.368035253)
points['shadow_lower_top'] = (0.5964565429, 0.6982784189, 3.368035253)
points['shadow_upper_bottom'] = (0.5964565429, 5.413250948, 3.368035253)
points['shadow_upper_top'] = (0.5964565429, 7.891484473, 3.368035253)
points['spawn1'] = (-5.828122667, 2.301094498, -3.445694701) + (1.0, 1.0,
2.682935578)
points['spawn2'] = (6.496252674, 2.397778847, -3.573241388) + (1.0, 1.0,
2.682935578)
|
points = {}
boxes = {}
boxes['area_of_interest_bounds'] = (0.4687647786, 2.320345088, -3.219423694) + (0.0, 0.0, 0.0) + (21.34898078, 10.25529817, 14.67298352)
points['ffa_spawn1'] = (-5.828122667, 2.301094498, -3.445694701) + (1.0, 1.0, 2.682935578)
points['ffa_spawn2'] = (6.496252674, 2.397778847, -3.573241388) + (1.0, 1.0, 2.682935578)
points['ffa_spawn3'] = (0.8835145921, 2.307217208, -0.3552854962) + (4.455517747, 1.0, 0.2723037175)
points['ffa_spawn4'] = (0.8835145921, 2.307217208, -7.124335491) + (4.455517747, 1.0, 0.2723037175)
points['flag1'] = (-7.153737138, 2.251993091, -3.427368878)
points['flag2'] = (8.103769491, 2.320591215, -3.548878069)
points['flag_default'] = (0.5964565429, 2.373456481, -4.241969517)
boxes['map_bounds'] = (0.4566560559, 1.332051421, -3.80651373) + (0.0, 0.0, 0.0) + (27.75073129, 14.44528216, 22.9896617)
points['powerup_spawn1'] = (5.180858712, 4.278900266, -7.282758712)
points['powerup_spawn2'] = (-3.236908759, 4.159702067, -0.3232556512)
points['powerup_spawn3'] = (5.082843398, 4.159702067, -0.3232556512)
points['powerup_spawn4'] = (-3.401729203, 4.278900266, -7.425891191)
points['shadow_lower_bottom'] = (0.5964565429, -0.2279530265, 3.368035253)
points['shadow_lower_top'] = (0.5964565429, 0.6982784189, 3.368035253)
points['shadow_upper_bottom'] = (0.5964565429, 5.413250948, 3.368035253)
points['shadow_upper_top'] = (0.5964565429, 7.891484473, 3.368035253)
points['spawn1'] = (-5.828122667, 2.301094498, -3.445694701) + (1.0, 1.0, 2.682935578)
points['spawn2'] = (6.496252674, 2.397778847, -3.573241388) + (1.0, 1.0, 2.682935578)
|
#!/usr/bin/python
# -*- utf-8 -*-
class Solution:
# @param nums, a list of integer
# @param k, num of steps
# @return nothing, please modify the nums list in-place.
def rotate(self, nums, k):
copy = [e for e in nums]
l = len(nums)
k = l - k % l
for i in range(l):
nums[i] = copy[(k + i) % l]
def rotate2(self, nums, k):
if not nums:
return
l = len(nums)
for i in range(k % l):
last = nums[-1]
for j in range(l-1, 0, -1):
nums[j] = nums[j-1]
nums[0] = last
def rotate3(self, nums, k):
# Todo third method
# Fixme rotate([1, 2, 3, 4, 5, 6], 2)
if not nums:
return
l = len(nums)
k = k % l
if k == 0:
return
last = nums[0]
cur = k
for e in nums:
nums[cur], last = last, nums[cur]
cur = (cur + k) % l
if __name__ == '__main__':
s = Solution()
l = [1, 2, 3, 4, 5, 6, 7]
print(l)
l = [1, 2, 3, 4, 5, 6, 7]
s.rotate(l, 0)
print(l)
l = [1, 2, 3, 4, 5, 6, 7]
s.rotate(l, 3)
print(l)
l = [1, 2, 3, 4, 5, 6, 7]
s.rotate(l, 6)
print(l)
l = [1, 2, 3, 4, 5, 6, 7]
s.rotate(l, 9)
print(l)
l = [1, 2, 3, 4, 5, 6]
s.rotate(l, 2)
print(l)
|
class Solution:
def rotate(self, nums, k):
copy = [e for e in nums]
l = len(nums)
k = l - k % l
for i in range(l):
nums[i] = copy[(k + i) % l]
def rotate2(self, nums, k):
if not nums:
return
l = len(nums)
for i in range(k % l):
last = nums[-1]
for j in range(l - 1, 0, -1):
nums[j] = nums[j - 1]
nums[0] = last
def rotate3(self, nums, k):
if not nums:
return
l = len(nums)
k = k % l
if k == 0:
return
last = nums[0]
cur = k
for e in nums:
(nums[cur], last) = (last, nums[cur])
cur = (cur + k) % l
if __name__ == '__main__':
s = solution()
l = [1, 2, 3, 4, 5, 6, 7]
print(l)
l = [1, 2, 3, 4, 5, 6, 7]
s.rotate(l, 0)
print(l)
l = [1, 2, 3, 4, 5, 6, 7]
s.rotate(l, 3)
print(l)
l = [1, 2, 3, 4, 5, 6, 7]
s.rotate(l, 6)
print(l)
l = [1, 2, 3, 4, 5, 6, 7]
s.rotate(l, 9)
print(l)
l = [1, 2, 3, 4, 5, 6]
s.rotate(l, 2)
print(l)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.