content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
class Const:
GITHUB = "https://github.com/ayvytr/PythonBox"
ISSUE = "https://github.com/Ayvytr/PythonBox/issues"
MAIL = "mailto:ayvytr@163.com?subject=Bug-Report&body={}"
| class Const:
github = 'https://github.com/ayvytr/PythonBox'
issue = 'https://github.com/Ayvytr/PythonBox/issues'
mail = 'mailto:ayvytr@163.com?subject=Bug-Report&body={}' |
def prediction(image_path):
img = tf.keras.utils.load_img(
image_path, target_size=(img_height, img_width))
img = tf.keras.utils.img_to_array(img)
plt.title('Image')
plt.axis('off')
plt.imshow((img/255.0).squeeze())
predict = model.predict(img[np.newaxis , ...])
predicted_class = labels[np.argmax(predict[0] , axis = -1)]
print('Prediction Value: ' , np.max(predict[0] , axis = -1))
print("Classified:",predicted_class) | def prediction(image_path):
img = tf.keras.utils.load_img(image_path, target_size=(img_height, img_width))
img = tf.keras.utils.img_to_array(img)
plt.title('Image')
plt.axis('off')
plt.imshow((img / 255.0).squeeze())
predict = model.predict(img[np.newaxis, ...])
predicted_class = labels[np.argmax(predict[0], axis=-1)]
print('Prediction Value: ', np.max(predict[0], axis=-1))
print('Classified:', predicted_class) |
target_str = "hello python world"
# reverse encrypt
print(target_str[-1::-1])
| target_str = 'hello python world'
print(target_str[-1::-1]) |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# Copyright (c) The Lab of Professor Weiwei Lin (linww@scut.edu.cn),
# School of Computer Science and Engineering, South China University of Technology.
# A-Tune is licensed under the Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
# http://license.coscl.org.cn/MulanPSL2
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
# PURPOSE.
# See the Mulan PSL v2 for more details.
# Create: 2020-01-04
x1 = 3
x2 = 1
x3 = 5
x4 = 3
x5 = 3
x6 = 3
x7 = 3
x8 = 3
x9 = 3
x10 = 2
x11 = 2
x12 = 4
x13 = 4
x14 = 2
x15 = 2
x16 = 1
x17 = 2
x18 = 5
x19 = 1
x20 = 1
x21 = 1
x22 = 1
x23 = 1
x24 = 2
x25 = 4
x26 = 2
x27 = 3
x28 = 1
x29 = 2
x30 = 4
x31 = 4
x32 = 1
x33 = 4
x34 = 1
x35 = 2
x36 = 1
x37 = 3
x38 = 2
x39 = 1
x40 = 2
x41 = 3
x42 = 3
x43 = 2
x44 = 2
x45 = 2
x46 = 4
x47 = 4
x48 = 2
x49 = 2
x50 = 2
x51 = 2
x52 = 1
x53 = 4
x54 = 3
x55 = 3
x56 = 1
x57 = 2
x58 = 3
x59 = 3
x60 = 3
x61 = 1
x62 = 3
x63 = 3
x64 = 4
x65 = 3
x66 = 2
x67 = 3
x68 = 3
x69 = 3
x70 = 2
x71 = 4
x72 = 1
x73 = 3
x74 = 2
x75 = 3
x76 = 1
x77 = 3
x78 = 1
x79 = 4
x80 = 2
x81 = 1
x82 = 1
x83 = 2
x84 = 4
x85 = 5
x86 = 3
x87 = 4
x88 = 2
x89 = 2
x90 = 1
x91 = 2
x92 = 1
x93 = 2
x94 = 1
x95 = 2
x96 = 3
x97 = 3
x98 = 2
x99 = 2
x100 = 3
x101 = 4
x102 = 3
x103 = 2
x104 = 2
x105 = 3
x106 = 5
x107 = 4
x108 = 2
x109 = 1
x110 = 4
x111 = 3
x112 = 4
x113 = 2
x114 = 2
x115 = 4
x116 = 4
x117 = 2
x118 = 3
x119 = 2
x120 = 4
x121 = 3
x122 = 2
x123 = 4
x124 = 4
x125 = 3
x126 = 4
x127 = 1
x128 = 3
x129 = 3
x130 = 5
x131 = 4
x132 = 3
x133 = 1
x134 = 2
x135 = 1
x136 = 1
x137 = 4
x138 = 4
x139 = 3
x140 = 1
x141 = 4
x142 = 1
x143 = 1
x144 = 4
x145 = 5
x146 = 4
x147 = 1
x148 = 4
x149 = 3
x150 = 3
y = 1 * x147 ** 1 + 2 * x80 ** 1 + 3 * x55 ** 1 + 4 * x81 ** 1 + 5 * x87 ** 1 + 1 * x82 ** 2 + 2 * x88 ** 2 + \
3 * x83 ** 2 + 4 * x144 ** 2 + 5 * x38 ** 2 + 1 * x135 ** 3 + 2 * x125 ** 3 + 3 * x14 ** 3 + 4 * x65 ** 3 + \
5 * x95 ** 3 + 1 * x73 ** 4 + 2 * x37 ** 4 + 3 * x105 ** 4 + 4 * x28 ** 4 + 5 * x121 ** 4 + 1 * x100 ** 5 + \
2 * x141 ** 5 + 3 * x69 ** 5 + 4 * x97 ** 5 + 5 * x53 ** 5 + 1 * x126 ** 6 + 2 * x104 ** 6 + 3 * x103 ** 6 + \
4 * x27 ** 6 + 5 * x10 ** 6 + 1 * x140 ** 7 + 2 * x54 ** 7 + 3 * x5 ** 7 + 4 * x70 ** 7 + 5 * x114 ** 7 + \
1 * x57 ** 8 + 2 * x74 ** 8 + 3 * x26 ** 8 + 4 * x19 ** 8 + 5 * x111 ** 8 + 1 * x108 ** 9 + 2 * x48 ** 9 + \
3 * x11 ** 9 + 4 * x59 ** 9 + 5 * x123 ** 9 + 1 * x61 ** 10 + 2 * x6 ** 10 + 3 * x79 ** 10 + 4 * x71 ** 10 + \
5 * x98 ** 10 + 1 * x34 ** 11 + 2 * x112 ** 11 + 3 * x25 ** 11 + 4 * x93 ** 11 + 5 * x86 ** 11 + 1 * x64 ** 12 + \
2 * x120 ** 12 + 3 * x20 ** 12 + 4 * x16 ** 12 + 5 * x94 ** 12 + 1 * x76 ** 13 + 2 * x21 ** 13 + 3 * x129 ** 13 + \
4 * x146 ** 13 + 5 * x77 ** 13 + 1 * x46 ** 14 + 2 * x91 ** 14 + 3 * x31 ** 14 + 4 * x67 ** 14 + 5 * x150 ** 14 + \
1 * x72 ** 15 + 2 * x84 ** 15 + 3 * x136 ** 15 + 4 * x15 ** 15 + 5 * x149 ** 15 + 1 * x2 ** 16 + 2 * x116 ** 16 + \
3 * x66 ** 16 + 4 * x42 ** 16 + 5 * x45 ** 16 + 1 * x63 ** 17 + 2 * x85 ** 17 + 3 * x143 ** 17 + 4 * x4 ** 17 + \
5 * x29 ** 17 + 1 * x113 ** 18 + 2 * x50 ** 18 + 3 * x132 ** 18 + 4 * x127 ** 18 + 5 * x30 ** 18 + 1 * x109 ** 19 +\
2 * x131 ** 19 + 3 * x36 ** 19 + 4 * x9 ** 19 + 5 * x43 ** 19 + 1 * x119 ** 20 + 2 * x8 ** 20 + 3 * x68 ** 20 + \
4 * x107 ** 20 + 5 * x12 ** 20 + 1 * x32 ** 21 + 2 * x122 ** 21 + 3 * x115 ** 21 + 4 * x75 ** 21 + 5 * x49 ** 21 + \
1 * x110 ** 22 + 2 * x40 ** 22 + 3 * x17 ** 22 + 4 * x134 ** 22 + 5 * x128 ** 22 + 1 * x18 ** 23 + 2 * x142 ** 23 +\
3 * x133 ** 23 + 4 * x24 ** 23 + 5 * x102 ** 23 + 1 * x145 ** 24 + 2 * x33 ** 24 + 3 * x106 ** 24 + 4 * x58 ** 24 +\
5 * x47 ** 24 + 1 * x22 ** 25 + 2 * x118 ** 25 + 3 * x44 ** 25 + 4 * x35 ** 25 + 5 * x90 ** 25 + 1 * x96 ** 26 + \
2 * x62 ** 26 + 3 * x78 ** 26 + 4 * x39 ** 26 + 5 * x99 ** 26 + 1 * x117 ** 27 + 2 * x1 ** 27 + 3 * x3 ** 27 + \
4 * x7 ** 27 + 5 * x52 ** 27 + 1 * x60 ** 28 + 2 * x124 ** 28 + 3 * x139 ** 28 + 4 * x101 ** 28 + 5 * x23 ** 28 + \
1 * x92 ** 29 + 2 * x148 ** 29 + 3 * x137 ** 29 + 4 * x89 ** 29 + 5 * x51 ** 29 + 1 * x41 ** 30 + 2 * x13 ** 30 + \
3 * x130 ** 30 + 4 * x138 ** 30 + 5 * x56 ** 30
print("y = %s" % y)
| x1 = 3
x2 = 1
x3 = 5
x4 = 3
x5 = 3
x6 = 3
x7 = 3
x8 = 3
x9 = 3
x10 = 2
x11 = 2
x12 = 4
x13 = 4
x14 = 2
x15 = 2
x16 = 1
x17 = 2
x18 = 5
x19 = 1
x20 = 1
x21 = 1
x22 = 1
x23 = 1
x24 = 2
x25 = 4
x26 = 2
x27 = 3
x28 = 1
x29 = 2
x30 = 4
x31 = 4
x32 = 1
x33 = 4
x34 = 1
x35 = 2
x36 = 1
x37 = 3
x38 = 2
x39 = 1
x40 = 2
x41 = 3
x42 = 3
x43 = 2
x44 = 2
x45 = 2
x46 = 4
x47 = 4
x48 = 2
x49 = 2
x50 = 2
x51 = 2
x52 = 1
x53 = 4
x54 = 3
x55 = 3
x56 = 1
x57 = 2
x58 = 3
x59 = 3
x60 = 3
x61 = 1
x62 = 3
x63 = 3
x64 = 4
x65 = 3
x66 = 2
x67 = 3
x68 = 3
x69 = 3
x70 = 2
x71 = 4
x72 = 1
x73 = 3
x74 = 2
x75 = 3
x76 = 1
x77 = 3
x78 = 1
x79 = 4
x80 = 2
x81 = 1
x82 = 1
x83 = 2
x84 = 4
x85 = 5
x86 = 3
x87 = 4
x88 = 2
x89 = 2
x90 = 1
x91 = 2
x92 = 1
x93 = 2
x94 = 1
x95 = 2
x96 = 3
x97 = 3
x98 = 2
x99 = 2
x100 = 3
x101 = 4
x102 = 3
x103 = 2
x104 = 2
x105 = 3
x106 = 5
x107 = 4
x108 = 2
x109 = 1
x110 = 4
x111 = 3
x112 = 4
x113 = 2
x114 = 2
x115 = 4
x116 = 4
x117 = 2
x118 = 3
x119 = 2
x120 = 4
x121 = 3
x122 = 2
x123 = 4
x124 = 4
x125 = 3
x126 = 4
x127 = 1
x128 = 3
x129 = 3
x130 = 5
x131 = 4
x132 = 3
x133 = 1
x134 = 2
x135 = 1
x136 = 1
x137 = 4
x138 = 4
x139 = 3
x140 = 1
x141 = 4
x142 = 1
x143 = 1
x144 = 4
x145 = 5
x146 = 4
x147 = 1
x148 = 4
x149 = 3
x150 = 3
y = 1 * x147 ** 1 + 2 * x80 ** 1 + 3 * x55 ** 1 + 4 * x81 ** 1 + 5 * x87 ** 1 + 1 * x82 ** 2 + 2 * x88 ** 2 + 3 * x83 ** 2 + 4 * x144 ** 2 + 5 * x38 ** 2 + 1 * x135 ** 3 + 2 * x125 ** 3 + 3 * x14 ** 3 + 4 * x65 ** 3 + 5 * x95 ** 3 + 1 * x73 ** 4 + 2 * x37 ** 4 + 3 * x105 ** 4 + 4 * x28 ** 4 + 5 * x121 ** 4 + 1 * x100 ** 5 + 2 * x141 ** 5 + 3 * x69 ** 5 + 4 * x97 ** 5 + 5 * x53 ** 5 + 1 * x126 ** 6 + 2 * x104 ** 6 + 3 * x103 ** 6 + 4 * x27 ** 6 + 5 * x10 ** 6 + 1 * x140 ** 7 + 2 * x54 ** 7 + 3 * x5 ** 7 + 4 * x70 ** 7 + 5 * x114 ** 7 + 1 * x57 ** 8 + 2 * x74 ** 8 + 3 * x26 ** 8 + 4 * x19 ** 8 + 5 * x111 ** 8 + 1 * x108 ** 9 + 2 * x48 ** 9 + 3 * x11 ** 9 + 4 * x59 ** 9 + 5 * x123 ** 9 + 1 * x61 ** 10 + 2 * x6 ** 10 + 3 * x79 ** 10 + 4 * x71 ** 10 + 5 * x98 ** 10 + 1 * x34 ** 11 + 2 * x112 ** 11 + 3 * x25 ** 11 + 4 * x93 ** 11 + 5 * x86 ** 11 + 1 * x64 ** 12 + 2 * x120 ** 12 + 3 * x20 ** 12 + 4 * x16 ** 12 + 5 * x94 ** 12 + 1 * x76 ** 13 + 2 * x21 ** 13 + 3 * x129 ** 13 + 4 * x146 ** 13 + 5 * x77 ** 13 + 1 * x46 ** 14 + 2 * x91 ** 14 + 3 * x31 ** 14 + 4 * x67 ** 14 + 5 * x150 ** 14 + 1 * x72 ** 15 + 2 * x84 ** 15 + 3 * x136 ** 15 + 4 * x15 ** 15 + 5 * x149 ** 15 + 1 * x2 ** 16 + 2 * x116 ** 16 + 3 * x66 ** 16 + 4 * x42 ** 16 + 5 * x45 ** 16 + 1 * x63 ** 17 + 2 * x85 ** 17 + 3 * x143 ** 17 + 4 * x4 ** 17 + 5 * x29 ** 17 + 1 * x113 ** 18 + 2 * x50 ** 18 + 3 * x132 ** 18 + 4 * x127 ** 18 + 5 * x30 ** 18 + 1 * x109 ** 19 + 2 * x131 ** 19 + 3 * x36 ** 19 + 4 * x9 ** 19 + 5 * x43 ** 19 + 1 * x119 ** 20 + 2 * x8 ** 20 + 3 * x68 ** 20 + 4 * x107 ** 20 + 5 * x12 ** 20 + 1 * x32 ** 21 + 2 * x122 ** 21 + 3 * x115 ** 21 + 4 * x75 ** 21 + 5 * x49 ** 21 + 1 * x110 ** 22 + 2 * x40 ** 22 + 3 * x17 ** 22 + 4 * x134 ** 22 + 5 * x128 ** 22 + 1 * x18 ** 23 + 2 * x142 ** 23 + 3 * x133 ** 23 + 4 * x24 ** 23 + 5 * x102 ** 23 + 1 * x145 ** 24 + 2 * x33 ** 24 + 3 * x106 ** 24 + 4 * x58 ** 24 + 5 * x47 ** 24 + 1 * x22 ** 25 + 2 * x118 ** 25 + 3 * x44 ** 25 + 4 * x35 ** 25 + 5 * x90 ** 25 + 1 * x96 ** 26 + 2 * x62 ** 26 + 3 * x78 ** 26 + 4 * x39 ** 26 + 5 * x99 ** 26 + 1 * x117 ** 27 + 2 * x1 ** 27 + 3 * x3 ** 27 + 4 * x7 ** 27 + 5 * x52 ** 27 + 1 * x60 ** 28 + 2 * x124 ** 28 + 3 * x139 ** 28 + 4 * x101 ** 28 + 5 * x23 ** 28 + 1 * x92 ** 29 + 2 * x148 ** 29 + 3 * x137 ** 29 + 4 * x89 ** 29 + 5 * x51 ** 29 + 1 * x41 ** 30 + 2 * x13 ** 30 + 3 * x130 ** 30 + 4 * x138 ** 30 + 5 * x56 ** 30
print('y = %s' % y) |
def solve():
n=int(input())
row,col=(n,n)
res=""
for i in range(row):
for j in range(col):
if i==j:
res+='1 '
elif i==j-1:
res+='1 '
elif i==j+1:
res+='1 '
else:
res+='0 '
if i!=n-1:
res+='\n'
print(res)
for _ in range(int(input())):
solve()
| def solve():
n = int(input())
(row, col) = (n, n)
res = ''
for i in range(row):
for j in range(col):
if i == j:
res += '1 '
elif i == j - 1:
res += '1 '
elif i == j + 1:
res += '1 '
else:
res += '0 '
if i != n - 1:
res += '\n'
print(res)
for _ in range(int(input())):
solve() |
tuple_a = 1, 2
tuple_b = (1, 2)
print(tuple_a == tuple_b)
print(tuple_a[1])
AngkorWat = (13.4125, 103.866667)
print(type(AngkorWat))
# <class 'tuple'="">
print("AngkorWat is at latitude: {}".format(AngkorWat[0]))
# AngkorWat is at latitude: 13.4125
print("AngkorWat is at longitude: {}".format(AngkorWat[1]))
# AngkorWat is at longitude: 103.866667 | tuple_a = (1, 2)
tuple_b = (1, 2)
print(tuple_a == tuple_b)
print(tuple_a[1])
angkor_wat = (13.4125, 103.866667)
print(type(AngkorWat))
print('AngkorWat is at latitude: {}'.format(AngkorWat[0]))
print('AngkorWat is at longitude: {}'.format(AngkorWat[1])) |
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
''' Battery runner classes and Report classes '''
class BatteryRunner(object):
def __init__(self, checks):
self._checks = checks
def check_only(self, obj):
reports = []
for check in self._checks:
reports.append(check(obj, False))
return reports
def check_fix(self, obj):
reports = []
for check in self._checks:
report = check(obj, True)
obj = report.obj
reports.append(report)
return obj, reports
def __len__(self):
return len(self._checks)
class Report(object):
def __init__(self,
obj=None,
error=None,
problem_level=0,
problem_msg='',
fix_msg=''):
''' Initialize report with values
Parameters
----------
obj : object
object tested, possibly fixed. Default is None
error : None or Exception
Error to raise if raising error for this check. If None,
no error can be raised for this check (it was probably
normal).
problem_level : int
level of problem. From 0 (no problem) to 50 (severe
problem). If the report originates from a fix, then this
is the level of the problem remaining after the fix.
Default is 0
problem_msg : string
String describing problem detected. Default is ''
fix_msg : string
String describing any fix applied. Default is ''.
Examples
--------
>>> rep = Report()
>>> rep.problem_level
0
>>> rep = Report((), TypeError, 10)
>>> rep.problem_level
10
'''
self.obj = obj
self.error = error
self.problem_level = problem_level
self.problem_msg = problem_msg
self.fix_msg = fix_msg
def __eq__(self, other):
''' Test for equality
Parameters
----------
other : object
report-like object to test equality
Examples
--------
>>> rep = Report(problem_level=10)
>>> rep2 = Report(problem_level=10)
>>> rep == rep2
True
>>> rep3 = Report(problem_level=20)
>>> rep == rep3
False
'''
return (self.__dict__ == other.__dict__)
def __ne__(self, other):
''' Test for equality
Parameters
----------
other : object
report-like object to test equality
See __eq__ docstring for examples
'''
return (self.__dict__ != other.__dict__)
def __str__(self):
''' Printable string for object '''
return self.__dict__.__str__()
@property
def message(self):
''' formatted message string, including fix message if present
'''
if self.fix_msg:
return '; '.join((self.problem_msg, self.fix_msg))
return self.problem_msg
def log_raise(self, logger, error_level=40):
''' Log problem, raise error if problem >= `error_level`
Parameters
----------
logger : log
log object, implementing ``log`` method
error_level : int, optional
If ``self.problem_level`` >= `error_level`, raise error
'''
logger.log(self.problem_level, self.message)
if self.problem_level and self.problem_level >= error_level:
if self.error:
raise self.error(self.problem_msg)
def write_raise(self, stream, error_level=40, log_level=30):
if self.problem_level >= log_level:
stream.write('Level %s: %s\n' %
(self.problem_level, self.message))
if self.problem_level and self.problem_level >= error_level:
if self.error:
raise self.error(self.problem_msg)
| """ Battery runner classes and Report classes """
class Batteryrunner(object):
def __init__(self, checks):
self._checks = checks
def check_only(self, obj):
reports = []
for check in self._checks:
reports.append(check(obj, False))
return reports
def check_fix(self, obj):
reports = []
for check in self._checks:
report = check(obj, True)
obj = report.obj
reports.append(report)
return (obj, reports)
def __len__(self):
return len(self._checks)
class Report(object):
def __init__(self, obj=None, error=None, problem_level=0, problem_msg='', fix_msg=''):
""" Initialize report with values
Parameters
----------
obj : object
object tested, possibly fixed. Default is None
error : None or Exception
Error to raise if raising error for this check. If None,
no error can be raised for this check (it was probably
normal).
problem_level : int
level of problem. From 0 (no problem) to 50 (severe
problem). If the report originates from a fix, then this
is the level of the problem remaining after the fix.
Default is 0
problem_msg : string
String describing problem detected. Default is ''
fix_msg : string
String describing any fix applied. Default is ''.
Examples
--------
>>> rep = Report()
>>> rep.problem_level
0
>>> rep = Report((), TypeError, 10)
>>> rep.problem_level
10
"""
self.obj = obj
self.error = error
self.problem_level = problem_level
self.problem_msg = problem_msg
self.fix_msg = fix_msg
def __eq__(self, other):
""" Test for equality
Parameters
----------
other : object
report-like object to test equality
Examples
--------
>>> rep = Report(problem_level=10)
>>> rep2 = Report(problem_level=10)
>>> rep == rep2
True
>>> rep3 = Report(problem_level=20)
>>> rep == rep3
False
"""
return self.__dict__ == other.__dict__
def __ne__(self, other):
""" Test for equality
Parameters
----------
other : object
report-like object to test equality
See __eq__ docstring for examples
"""
return self.__dict__ != other.__dict__
def __str__(self):
""" Printable string for object """
return self.__dict__.__str__()
@property
def message(self):
""" formatted message string, including fix message if present
"""
if self.fix_msg:
return '; '.join((self.problem_msg, self.fix_msg))
return self.problem_msg
def log_raise(self, logger, error_level=40):
""" Log problem, raise error if problem >= `error_level`
Parameters
----------
logger : log
log object, implementing ``log`` method
error_level : int, optional
If ``self.problem_level`` >= `error_level`, raise error
"""
logger.log(self.problem_level, self.message)
if self.problem_level and self.problem_level >= error_level:
if self.error:
raise self.error(self.problem_msg)
def write_raise(self, stream, error_level=40, log_level=30):
if self.problem_level >= log_level:
stream.write('Level %s: %s\n' % (self.problem_level, self.message))
if self.problem_level and self.problem_level >= error_level:
if self.error:
raise self.error(self.problem_msg) |
class Solution:
def spiralOrder(self, matrix) -> list:
result = []
m = len(matrix)
n = len(matrix[0])
flag = [[False] * n for _ in range(m)]
i = 0
j = 0
orient = (0, 1) # (0, 1)=left, (1, 0)=down, (0, -1)=right, (-1, 0)=up
while len(result) < m * n:
result.append(matrix[i][j])
flag[i][j] = True
next_i, next_j = i + orient[0], j + orient[1]
if 0 <= next_i < m and 0 <= next_j < n and not flag[next_i][next_j]:
i, j = next_i, next_j
else:
if orient == (0, 1):
orient = (1, 0)
elif orient == (1, 0):
orient = (0, -1)
elif orient == (0, -1):
orient = (-1, 0)
elif orient == (-1, 0):
orient = (0, 1)
i, j = i + orient[0], j + orient[1]
return result
| class Solution:
def spiral_order(self, matrix) -> list:
result = []
m = len(matrix)
n = len(matrix[0])
flag = [[False] * n for _ in range(m)]
i = 0
j = 0
orient = (0, 1)
while len(result) < m * n:
result.append(matrix[i][j])
flag[i][j] = True
(next_i, next_j) = (i + orient[0], j + orient[1])
if 0 <= next_i < m and 0 <= next_j < n and (not flag[next_i][next_j]):
(i, j) = (next_i, next_j)
else:
if orient == (0, 1):
orient = (1, 0)
elif orient == (1, 0):
orient = (0, -1)
elif orient == (0, -1):
orient = (-1, 0)
elif orient == (-1, 0):
orient = (0, 1)
(i, j) = (i + orient[0], j + orient[1])
return result |
class RequireTwoFactorException(Exception):
pass
class LoginFailedException(Exception):
pass
| class Requiretwofactorexception(Exception):
pass
class Loginfailedexception(Exception):
pass |
"""
python-social-auth application, allows OpenId or OAuth user
registration/authentication just adding a few configurations.
"""
version = (0, 1, 16)
extra = ''
__version__ = '.'.join(map(str, version)) + extra
| """
python-social-auth application, allows OpenId or OAuth user
registration/authentication just adding a few configurations.
"""
version = (0, 1, 16)
extra = ''
__version__ = '.'.join(map(str, version)) + extra |
### Default Pins M5Stack bzw. Mapping auf IoTKitV3.1 small
DEFAULT_IOTKIT_LED1 = 27 # ohne Funktion - internes Neopixel verwenden
DEFAULT_IOTKIT_BUZZER = 27 # ohne Funktion - internen Vibrationsmotor verwenden
DEFAULT_IOTKIT_BUTTON1 = 39 # Pushbotton A unter Touchscreen M5Stack
# Port A
DEFAULT_IOTKIT_I2C_SDA = 32
DEFAULT_IOTKIT_I2C_SCL = 33
# Port B
DEFAULT_IOTKIT_PORT_B_DAC = 26
DEFAULT_IOTKIT_PORT_B_ADC = 27
# Port C
DEFAULT_IOTKIT_PORT_C_TX = 14
DEFAULT_IOTKIT_PORT_C_RX = 13
# Port D - kann auf dem Shield bei Grove A4/A5 abgegriffen werden
DEFAULT_IOTKIT_PORT_C_TX = 1
DEFAULT_IOTKIT_PORT_C_RX = 3
# L293D mit 1 x DC Motor (zweiter ohne Funktion)
DEFAULT_IOTKIT_MOTOR1_FWD = 2
DEFAULT_IOTKIT_MOTOR1_PWM = 19
DEFAULT_IOTKIT_MOTOR1_REV = 0
DEFAULT_IOTKIT_MOTOR2_FWD = -1
DEFAULT_IOTKIT_MOTOR2_PWM = -1
DEFAULT_IOTKIT_MOTOR2_REW = -1
# SPI Bus inkl. SS Pin fuer RFID Reader
DEFAULT_IOTKIT_SPI_SCLK = 18
DEFAULT_IOTKIT_SPI_MISO = 38
DEFAULT_IOTKIT_SPI_MOSI = 23
DEFAULT_IOTKIT_SPI_SS = 25
# Servos gleich wie Port B
DEFAULT_IOTKIT_SERVO1 = 26
DEFAULT_IOTKIT_SERVO2 = 27
# ADC - Analog Pins
DEFAULT_IOTKIT_POTI = 35
DEFAULT_IOTKIT_HALL_SENSOR = 36
| default_iotkit_led1 = 27
default_iotkit_buzzer = 27
default_iotkit_button1 = 39
default_iotkit_i2_c_sda = 32
default_iotkit_i2_c_scl = 33
default_iotkit_port_b_dac = 26
default_iotkit_port_b_adc = 27
default_iotkit_port_c_tx = 14
default_iotkit_port_c_rx = 13
default_iotkit_port_c_tx = 1
default_iotkit_port_c_rx = 3
default_iotkit_motor1_fwd = 2
default_iotkit_motor1_pwm = 19
default_iotkit_motor1_rev = 0
default_iotkit_motor2_fwd = -1
default_iotkit_motor2_pwm = -1
default_iotkit_motor2_rew = -1
default_iotkit_spi_sclk = 18
default_iotkit_spi_miso = 38
default_iotkit_spi_mosi = 23
default_iotkit_spi_ss = 25
default_iotkit_servo1 = 26
default_iotkit_servo2 = 27
default_iotkit_poti = 35
default_iotkit_hall_sensor = 36 |
categories = [
(82, False, "player", "defense_ast", "Assist to a tackle."),
(91, False, "player", "defense_ffum", "Defensive player forced a fumble."),
(88, False, "player", "defense_fgblk", "Defensive player blocked a field goal."),
(60, False, "player", "defense_frec", "Defensive player recovered a fumble by the opposing team."),
(62, False, "player", "defense_frec_tds", "Defensive player scored a touchdown after recovering a fumble by the opposing team."),
(62, False, "player", "defense_frec_yds", "Yards gained by a defensive player after recovering a fumble by the opposing team."),
(26, False, "player", "defense_int", "An interception."),
(28, False, "player", "defense_int_tds", "A touchdown scored after an interception."),
(28, False, "player", "defense_int_yds", "Yards gained after an interception."),
(64, False, "player", "defense_misc_tds", "A touchdown scored on miscellaneous yardage (e.g., on a missed field goal or a blocked punt)."),
(64, False, "player", "defense_misc_yds", "Miscellaneous yards gained by a defensive player (e.g., yardage on a missed field goal or blocked punt)."),
(85, False, "player", "defense_pass_def", "Incomplete pass was due primarily to a defensive player's action."),
(86, False, "player", "defense_puntblk", "Defensive player blocked a punt."),
(110, False, "player", "defense_qbhit", "Defensive player knocked the quarterback to the ground and the quarterback was not the ball carrier."),
(89, False, "player", "defense_safe", "Tackle by a defensive player that resulted in a safety. This is in addition to a tackle."),
(84, True, "player", "defense_sk", "Defensive player sacked the quarterback. Note that this is the only field that is a floating point number. Namely, there can be half-credit sacks."),
(84, False, "player", "defense_sk_yds", "Yards lost as a result of a sack."),
(80, False, "player", "defense_tkl", "A defensive player tackle. (This include defense_tkl_primary.)"),
(120, False, "player", "defense_tkl_loss", "Defensive player tackled the runner behind the line of scrimmage. Play must have ended, player must have received a tackle stat, has to be an offensive player tackled."),
(402, False, "player", "defense_tkl_loss_yds", "The number of yards lost caused by a defensive tackle behind the line of scrimmage."),
(80, False, "player", "defense_tkl_primary", "Defensive player was the primary tackler."),
(87, False, "player", "defense_xpblk", "Defensive player blocked the extra point."),
(5, False, "play", "first_down", "A first down or TD occurred due to a penalty. A play can have a first down from a pass or rush and from a penalty."),
(9, False, "play", "fourth_down_att", "4th down play."),
(8, False, "play", "fourth_down_conv", "4th down play resulted in a first down or touchdown."),
(9, False, "play", "fourth_down_failed", "4th down play did not result in a first down or touchdown."),
(52, False, "player", "fumbles_forced", "Player fumbled the ball, fumble was forced by another player."),
(106, False, "player", "fumbles_lost", "Player fumbled the ball and the opposing team recovered it."),
(53, False, "player", "fumbles_notforced", "Player fumbled the ball that was not caused by a defensive player."),
(54, False, "player", "fumbles_oob", "Player fumbled the ball, and the ball went out of bounds."),
(56, False, "player", "fumbles_rec", "Fumble recovery from a player on the same team."),
(58, False, "player", "fumbles_rec_tds", "A touchdown after a fumble recovery from a player on the same team."),
(58, False, "player", "fumbles_rec_yds", "Yards gained after a fumble recovery from a player on the same team."),
(54, False, "player", "fumbles_tot", "Total number of fumbles by a player. Includes forced, not forced and out-of-bounds."),
(410, False, "player", "kicking_all_yds", "Kickoff and length of kick. Includes end zone yards for all kicks into the end zone, including kickoffs ending in a touchback."),
(102, False, "player", "kicking_downed", "A downed kickoff. A kickoff is downed when touched by an offensive player within the 10 yard free zone, and the ball is awarded to the receivers at the spot of the touch."),
(71, False, "player", "kicking_fga", "A field goal attempt, including blocked field goals. Unlike a punt, a field goal is statistically blocked even if the ball does go beyond the line of scrimmage."),
(71, False, "player", "kicking_fgb", "Field goal was blocked. Unlike a punt, a field goal is statistically blocked even if the ball does go beyond the line of scrimmage."),
(70, False, "player", "kicking_fgm", "A field goal."),
(70, False, "player", "kicking_fgm_yds", "The length of a successful field goal."),
(71, False, "player", "kicking_fgmissed", "The field goal was unsuccessful, including blocked field goals. Unlike a punt, a field goal is statistically blocked even if the ball does go beyond the line of scrimmage."),
(71, False, "player", "kicking_fgmissed_yds", "The length of an unsuccessful field goal, including blocked field goals. Unlike a punt, a field goal is statistically blocked even if the ball does go beyond the line of scrimmage."),
(42, False, "player", "kicking_i20", "Kickoff and length of kick, where return ended inside opponent's 20 yard line."),
(108, False, "player", "kicking_rec", "Recovery of own kickoff, whether or not the kickoff is onside."),
(108, False, "player", "kicking_rec_tds", "Touchdown resulting from direct recovery in endzone of own kickoff, whether or not the kickoff is onside."),
(44, False, "player", "kicking_tot", "A kickoff."),
(44, False, "player", "kicking_touchback", "A kickoff that resulted in a touchback."),
(74, False, "player", "kicking_xpa", "An extra point attempt."),
(74, False, "player", "kicking_xpb", "Extra point was blocked."),
(72, False, "player", "kicking_xpmade", "Extra point good."),
(74, False, "player", "kicking_xpmissed", "Extra point missed. This includes blocked extra points."),
(44, False, "player", "kicking_yds", "The length of a kickoff."),
(50, False, "player", "kickret_fair", "A fair catch kickoff return."),
(49, False, "player", "kickret_oob", "Kicked ball went out of bounds."),
(46, False, "player", "kickret_ret", "A kickoff return."),
(48, False, "player", "kickret_tds", "A kickoff return touchdown."),
(51, False, "player", "kickret_touchback", "A kickoff return that resulted in a touchback."),
(48, False, "player", "kickret_yds", "Yards gained by a kickoff return."),
(19, False, "player", "passing_att", "A pass attempt."),
(16, False, "player", "passing_cmp", "A pass completion."),
(111, False, "player", "passing_cmp_air_yds", "Length of a pass, not including the yards gained by the receiver after the catch."),
(4, False, "play", "passing_first_down", "A first down or TD occurred due to a pass."),
(19, False, "player", "passing_incmp", "Pass was incomplete."),
(112, False, "player", "passing_incmp_air_yds", "Length of the pass, if it would have been a completion."),
(19, False, "player", "passing_int", "Pass attempt that resulted in an interception."),
(20, False, "player", "passing_sk", "The player was sacked."),
(103, False, "player", "passing_sk_yds", "The yards lost by a player that was sacked."),
(16, False, "player", "passing_tds", "A pass completion that resulted in a touchdown."),
(78, False, "player", "passing_twopta", "A passing two-point conversion attempt."),
(77, False, "player", "passing_twoptm", "A successful passing two-point conversion."),
(78, False, "player", "passing_twoptmissed", "An unsuccessful passing two-point conversion."),
(16, False, "player", "passing_yds", "Total yards resulting from a pass completion."),
(93, False, "play", "penalty", "A penalty occurred."),
(5, False, "play", "penalty_first_down", "A first down or TD occurred due to a penalty."),
(93, False, "play", "penalty_yds", "The number of yards gained or lost from a penalty."),
(2, False, "player", "punting_blk", "Punt was blocked. A blocked punt is a punt that is touched behind the line of scrimmage, and is recovered, or goes out of bounds, behind the line of scrimmage. If the impetus of the punt takes it beyond the line of scrimmage, it is not a blocked punt."),
(30, False, "player", "punting_i20", "A punt where the punt return ended inside the opponent's 20 yard line."),
(32, False, "player", "punting_tot", "A punt."),
(32, False, "player", "punting_touchback", "A punt that results in a touchback."),
(32, False, "player", "punting_yds", "The length of a punt."),
(38, False, "player", "puntret_downed", "Punt return where the ball was downed by kicking team."),
(39, False, "player", "puntret_fair", "Punt return resulted in a fair catch."),
(37, False, "player", "puntret_oob", "Punt went out of bounds."),
(36, False, "player", "puntret_tds", "A punt return touchdown."),
(34, False, "player", "puntret_tot", "A punt return."),
(40, False, "player", "puntret_touchback", "A punt return that resulted in a touchback."),
(36, False, "player", "puntret_yds", "Yards gained by a punt return."),
(22, False, "player", "receiving_rec", "A reception."),
(115, False, "player", "receiving_tar", "Player was the target of a pass attempt."),
(24, False, "player", "receiving_tds", "A reception that results in a touchdown."),
(105, False, "player", "receiving_twopta", "A receiving two-point conversion attempt."),
(104, False, "player", "receiving_twoptm", "A successful receiving two-point conversion."),
(105, False, "player", "receiving_twoptmissed", "An unsuccessful receiving two-point conversion."),
(113, False, "player", "receiving_yac_yds", "Yardage from where the ball was caught until the player's action was over."),
(24, False, "player", "receiving_yds", "Yards resulting from a reception."),
(11, False, "player", "rushing_att", "A rushing attempt."),
(3, False, "play", "rushing_first_down", "A first down or TD occurred due to a rush."),
(95, False, "player", "rushing_loss", "Ball carrier was tackled for a loss behind the line of scrimmage, where at least one defensive player is credited with ending the rush with a tackle, or tackle assist."),
(95, False, "player", "rushing_loss_yds", "Yards lost from the ball carrier being tackled for a loss behind the line of scrimmage, where at least one defensive player is credited with ending the rush with a tackle, or tackle assist."),
(13, False, "player", "rushing_tds", "A touchdown resulting from a rush attempt."),
(76, False, "player", "rushing_twopta", "A rushing two-point conversion attempt."),
(75, False, "player", "rushing_twoptm", "A successful rushing two-point conversion."),
(76, False, "player", "rushing_twoptmissed", "An unsuccessful rushing two-point conversion."),
(13, False, "player", "rushing_yds", "Yards resulting from a rush."),
(7, False, "play", "third_down_att", "3rd down play."),
(6, False, "play", "third_down_conv", "3rd down play resulted in a first down or touchdown."),
(7, False, "play", "third_down_failed", "3rd down play did not result in a first down or touchdown."),
(68, False, "play", "timeout", "Team took a time out."),
(301, False, "play", "xp_aborted", "The extra point was aborted."),
]
| categories = [(82, False, 'player', 'defense_ast', 'Assist to a tackle.'), (91, False, 'player', 'defense_ffum', 'Defensive player forced a fumble.'), (88, False, 'player', 'defense_fgblk', 'Defensive player blocked a field goal.'), (60, False, 'player', 'defense_frec', 'Defensive player recovered a fumble by the opposing team.'), (62, False, 'player', 'defense_frec_tds', 'Defensive player scored a touchdown after recovering a fumble by the opposing team.'), (62, False, 'player', 'defense_frec_yds', 'Yards gained by a defensive player after recovering a fumble by the opposing team.'), (26, False, 'player', 'defense_int', 'An interception.'), (28, False, 'player', 'defense_int_tds', 'A touchdown scored after an interception.'), (28, False, 'player', 'defense_int_yds', 'Yards gained after an interception.'), (64, False, 'player', 'defense_misc_tds', 'A touchdown scored on miscellaneous yardage (e.g., on a missed field goal or a blocked punt).'), (64, False, 'player', 'defense_misc_yds', 'Miscellaneous yards gained by a defensive player (e.g., yardage on a missed field goal or blocked punt).'), (85, False, 'player', 'defense_pass_def', "Incomplete pass was due primarily to a defensive player's action."), (86, False, 'player', 'defense_puntblk', 'Defensive player blocked a punt.'), (110, False, 'player', 'defense_qbhit', 'Defensive player knocked the quarterback to the ground and the quarterback was not the ball carrier.'), (89, False, 'player', 'defense_safe', 'Tackle by a defensive player that resulted in a safety. This is in addition to a tackle.'), (84, True, 'player', 'defense_sk', 'Defensive player sacked the quarterback. Note that this is the only field that is a floating point number. Namely, there can be half-credit sacks.'), (84, False, 'player', 'defense_sk_yds', 'Yards lost as a result of a sack.'), (80, False, 'player', 'defense_tkl', 'A defensive player tackle. (This include defense_tkl_primary.)'), (120, False, 'player', 'defense_tkl_loss', 'Defensive player tackled the runner behind the line of scrimmage. Play must have ended, player must have received a tackle stat, has to be an offensive player tackled.'), (402, False, 'player', 'defense_tkl_loss_yds', 'The number of yards lost caused by a defensive tackle behind the line of scrimmage.'), (80, False, 'player', 'defense_tkl_primary', 'Defensive player was the primary tackler.'), (87, False, 'player', 'defense_xpblk', 'Defensive player blocked the extra point.'), (5, False, 'play', 'first_down', 'A first down or TD occurred due to a penalty. A play can have a first down from a pass or rush and from a penalty.'), (9, False, 'play', 'fourth_down_att', '4th down play.'), (8, False, 'play', 'fourth_down_conv', '4th down play resulted in a first down or touchdown.'), (9, False, 'play', 'fourth_down_failed', '4th down play did not result in a first down or touchdown.'), (52, False, 'player', 'fumbles_forced', 'Player fumbled the ball, fumble was forced by another player.'), (106, False, 'player', 'fumbles_lost', 'Player fumbled the ball and the opposing team recovered it.'), (53, False, 'player', 'fumbles_notforced', 'Player fumbled the ball that was not caused by a defensive player.'), (54, False, 'player', 'fumbles_oob', 'Player fumbled the ball, and the ball went out of bounds.'), (56, False, 'player', 'fumbles_rec', 'Fumble recovery from a player on the same team.'), (58, False, 'player', 'fumbles_rec_tds', 'A touchdown after a fumble recovery from a player on the same team.'), (58, False, 'player', 'fumbles_rec_yds', 'Yards gained after a fumble recovery from a player on the same team.'), (54, False, 'player', 'fumbles_tot', 'Total number of fumbles by a player. Includes forced, not forced and out-of-bounds.'), (410, False, 'player', 'kicking_all_yds', 'Kickoff and length of kick. Includes end zone yards for all kicks into the end zone, including kickoffs ending in a touchback.'), (102, False, 'player', 'kicking_downed', 'A downed kickoff. A kickoff is downed when touched by an offensive player within the 10 yard free zone, and the ball is awarded to the receivers at the spot of the touch.'), (71, False, 'player', 'kicking_fga', 'A field goal attempt, including blocked field goals. Unlike a punt, a field goal is statistically blocked even if the ball does go beyond the line of scrimmage.'), (71, False, 'player', 'kicking_fgb', 'Field goal was blocked. Unlike a punt, a field goal is statistically blocked even if the ball does go beyond the line of scrimmage.'), (70, False, 'player', 'kicking_fgm', 'A field goal.'), (70, False, 'player', 'kicking_fgm_yds', 'The length of a successful field goal.'), (71, False, 'player', 'kicking_fgmissed', 'The field goal was unsuccessful, including blocked field goals. Unlike a punt, a field goal is statistically blocked even if the ball does go beyond the line of scrimmage.'), (71, False, 'player', 'kicking_fgmissed_yds', 'The length of an unsuccessful field goal, including blocked field goals. Unlike a punt, a field goal is statistically blocked even if the ball does go beyond the line of scrimmage.'), (42, False, 'player', 'kicking_i20', "Kickoff and length of kick, where return ended inside opponent's 20 yard line."), (108, False, 'player', 'kicking_rec', 'Recovery of own kickoff, whether or not the kickoff is onside.'), (108, False, 'player', 'kicking_rec_tds', 'Touchdown resulting from direct recovery in endzone of own kickoff, whether or not the kickoff is onside.'), (44, False, 'player', 'kicking_tot', 'A kickoff.'), (44, False, 'player', 'kicking_touchback', 'A kickoff that resulted in a touchback.'), (74, False, 'player', 'kicking_xpa', 'An extra point attempt.'), (74, False, 'player', 'kicking_xpb', 'Extra point was blocked.'), (72, False, 'player', 'kicking_xpmade', 'Extra point good.'), (74, False, 'player', 'kicking_xpmissed', 'Extra point missed. This includes blocked extra points.'), (44, False, 'player', 'kicking_yds', 'The length of a kickoff.'), (50, False, 'player', 'kickret_fair', 'A fair catch kickoff return.'), (49, False, 'player', 'kickret_oob', 'Kicked ball went out of bounds.'), (46, False, 'player', 'kickret_ret', 'A kickoff return.'), (48, False, 'player', 'kickret_tds', 'A kickoff return touchdown.'), (51, False, 'player', 'kickret_touchback', 'A kickoff return that resulted in a touchback.'), (48, False, 'player', 'kickret_yds', 'Yards gained by a kickoff return.'), (19, False, 'player', 'passing_att', 'A pass attempt.'), (16, False, 'player', 'passing_cmp', 'A pass completion.'), (111, False, 'player', 'passing_cmp_air_yds', 'Length of a pass, not including the yards gained by the receiver after the catch.'), (4, False, 'play', 'passing_first_down', 'A first down or TD occurred due to a pass.'), (19, False, 'player', 'passing_incmp', 'Pass was incomplete.'), (112, False, 'player', 'passing_incmp_air_yds', 'Length of the pass, if it would have been a completion.'), (19, False, 'player', 'passing_int', 'Pass attempt that resulted in an interception.'), (20, False, 'player', 'passing_sk', 'The player was sacked.'), (103, False, 'player', 'passing_sk_yds', 'The yards lost by a player that was sacked.'), (16, False, 'player', 'passing_tds', 'A pass completion that resulted in a touchdown.'), (78, False, 'player', 'passing_twopta', 'A passing two-point conversion attempt.'), (77, False, 'player', 'passing_twoptm', 'A successful passing two-point conversion.'), (78, False, 'player', 'passing_twoptmissed', 'An unsuccessful passing two-point conversion.'), (16, False, 'player', 'passing_yds', 'Total yards resulting from a pass completion.'), (93, False, 'play', 'penalty', 'A penalty occurred.'), (5, False, 'play', 'penalty_first_down', 'A first down or TD occurred due to a penalty.'), (93, False, 'play', 'penalty_yds', 'The number of yards gained or lost from a penalty.'), (2, False, 'player', 'punting_blk', 'Punt was blocked. A blocked punt is a punt that is touched behind the line of scrimmage, and is recovered, or goes out of bounds, behind the line of scrimmage. If the impetus of the punt takes it beyond the line of scrimmage, it is not a blocked punt.'), (30, False, 'player', 'punting_i20', "A punt where the punt return ended inside the opponent's 20 yard line."), (32, False, 'player', 'punting_tot', 'A punt.'), (32, False, 'player', 'punting_touchback', 'A punt that results in a touchback.'), (32, False, 'player', 'punting_yds', 'The length of a punt.'), (38, False, 'player', 'puntret_downed', 'Punt return where the ball was downed by kicking team.'), (39, False, 'player', 'puntret_fair', 'Punt return resulted in a fair catch.'), (37, False, 'player', 'puntret_oob', 'Punt went out of bounds.'), (36, False, 'player', 'puntret_tds', 'A punt return touchdown.'), (34, False, 'player', 'puntret_tot', 'A punt return.'), (40, False, 'player', 'puntret_touchback', 'A punt return that resulted in a touchback.'), (36, False, 'player', 'puntret_yds', 'Yards gained by a punt return.'), (22, False, 'player', 'receiving_rec', 'A reception.'), (115, False, 'player', 'receiving_tar', 'Player was the target of a pass attempt.'), (24, False, 'player', 'receiving_tds', 'A reception that results in a touchdown.'), (105, False, 'player', 'receiving_twopta', 'A receiving two-point conversion attempt.'), (104, False, 'player', 'receiving_twoptm', 'A successful receiving two-point conversion.'), (105, False, 'player', 'receiving_twoptmissed', 'An unsuccessful receiving two-point conversion.'), (113, False, 'player', 'receiving_yac_yds', "Yardage from where the ball was caught until the player's action was over."), (24, False, 'player', 'receiving_yds', 'Yards resulting from a reception.'), (11, False, 'player', 'rushing_att', 'A rushing attempt.'), (3, False, 'play', 'rushing_first_down', 'A first down or TD occurred due to a rush.'), (95, False, 'player', 'rushing_loss', 'Ball carrier was tackled for a loss behind the line of scrimmage, where at least one defensive player is credited with ending the rush with a tackle, or tackle assist.'), (95, False, 'player', 'rushing_loss_yds', 'Yards lost from the ball carrier being tackled for a loss behind the line of scrimmage, where at least one defensive player is credited with ending the rush with a tackle, or tackle assist.'), (13, False, 'player', 'rushing_tds', 'A touchdown resulting from a rush attempt.'), (76, False, 'player', 'rushing_twopta', 'A rushing two-point conversion attempt.'), (75, False, 'player', 'rushing_twoptm', 'A successful rushing two-point conversion.'), (76, False, 'player', 'rushing_twoptmissed', 'An unsuccessful rushing two-point conversion.'), (13, False, 'player', 'rushing_yds', 'Yards resulting from a rush.'), (7, False, 'play', 'third_down_att', '3rd down play.'), (6, False, 'play', 'third_down_conv', '3rd down play resulted in a first down or touchdown.'), (7, False, 'play', 'third_down_failed', '3rd down play did not result in a first down or touchdown.'), (68, False, 'play', 'timeout', 'Team took a time out.'), (301, False, 'play', 'xp_aborted', 'The extra point was aborted.')] |
"""
https://leetcode.com/problems/container-with-most-water/
Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.
Note: You may not slant the container and n is at least 2.
Example:
Input: [1,8,6,2,5,4,8,3,7]
Output: 49
"""
class Solution(object):
def maxArea(self, height):
"""
:type height: List[int]
:rtype: int
"""
low, high = height[0], height[len(height)-1]
container_area = []
low_index = 0
high_index = len(height)-1
#print, low_index, high_index
while low_index < high_index:
#print "append"
container_area.append(min(low,high)*(high_index-low_index))
#print container_area
if low < high:
low_index += 1
low = height[low_index]
else:
high_index -=1
high = height[high_index]
return max(container_area)
| """
https://leetcode.com/problems/container-with-most-water/
Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.
Note: You may not slant the container and n is at least 2.
Example:
Input: [1,8,6,2,5,4,8,3,7]
Output: 49
"""
class Solution(object):
def max_area(self, height):
"""
:type height: List[int]
:rtype: int
"""
(low, high) = (height[0], height[len(height) - 1])
container_area = []
low_index = 0
high_index = len(height) - 1
while low_index < high_index:
container_area.append(min(low, high) * (high_index - low_index))
if low < high:
low_index += 1
low = height[low_index]
else:
high_index -= 1
high = height[high_index]
return max(container_area) |
# Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
"""
Stubs for testing cloudformation.py
"""
describe_stack = {
'Stacks': [{
'Outputs': [{
'OutputKey': "DeploymentFrameworkRegionalKMSKey",
'OutputValue': "some_key_arn"
}, {
'OutputKey': "DeploymentFrameworkRegionalS3Bucket",
'OutputValue': "some_bucket_name"
}],
'StackStatus': 'CREATE_IN_PROGRESS'
}]
}
| """
Stubs for testing cloudformation.py
"""
describe_stack = {'Stacks': [{'Outputs': [{'OutputKey': 'DeploymentFrameworkRegionalKMSKey', 'OutputValue': 'some_key_arn'}, {'OutputKey': 'DeploymentFrameworkRegionalS3Bucket', 'OutputValue': 'some_bucket_name'}], 'StackStatus': 'CREATE_IN_PROGRESS'}]} |
JAVA_EXEC_LABEL="//third_party/openjdk:java"
PHASICJ_AGENT_LABEL="//phasicj/agent:libpjagent"
RENAISSANCE_JAR_LABEL="//third_party/renaissance:jar"
RENAISSANCE_MAIN_CLASS="org.renaissance.core.Launcher"
PHASICJ_EXEC="//phasicj/cli"
EXTRA_PHASICJ_AGENT_OPTIONS="verbose"
def smoke_test_benchmark(name):
native.sh_test(
name = name,
srcs = ["test.sh"],
data = [
JAVA_EXEC_LABEL,
PHASICJ_AGENT_LABEL,
RENAISSANCE_JAR_LABEL,
PHASICJ_EXEC,
],
args = [
"$(rootpath {})".format(JAVA_EXEC_LABEL),
"$(rootpath {})".format(PHASICJ_AGENT_LABEL),
"$(rootpath {})".format(RENAISSANCE_JAR_LABEL),
RENAISSANCE_MAIN_CLASS,
"$(rootpath {})".format(PHASICJ_EXEC),
EXTRA_PHASICJ_AGENT_OPTIONS,
"--repetitions",
"1",
name
],
)
KNOWN_BENCHMARKS = [
"akka-uct",
"als",
"chi-square",
# TODO(dwtj): Figure out why this crashes.
# "db-shootout",
"dec-tree",
"dotty",
"finagle-chirper",
"finagle-http",
"fj-kmeans",
"future-genetic",
"gauss-mix",
"log-regression",
"mnemonics",
"movie-lens",
"naive-bayes",
"neo4j-analytics",
"page-rank",
"par-mnemonics",
"philosophers",
"reactors",
"rx-scrabble",
"scala-doku",
"scala-kmeans",
"scala-stm-bench7",
"scrabble",
]
def test_each_known_renaissance_benchmark():
for benchmark in KNOWN_BENCHMARKS:
smoke_test_benchmark(benchmark)
| java_exec_label = '//third_party/openjdk:java'
phasicj_agent_label = '//phasicj/agent:libpjagent'
renaissance_jar_label = '//third_party/renaissance:jar'
renaissance_main_class = 'org.renaissance.core.Launcher'
phasicj_exec = '//phasicj/cli'
extra_phasicj_agent_options = 'verbose'
def smoke_test_benchmark(name):
native.sh_test(name=name, srcs=['test.sh'], data=[JAVA_EXEC_LABEL, PHASICJ_AGENT_LABEL, RENAISSANCE_JAR_LABEL, PHASICJ_EXEC], args=['$(rootpath {})'.format(JAVA_EXEC_LABEL), '$(rootpath {})'.format(PHASICJ_AGENT_LABEL), '$(rootpath {})'.format(RENAISSANCE_JAR_LABEL), RENAISSANCE_MAIN_CLASS, '$(rootpath {})'.format(PHASICJ_EXEC), EXTRA_PHASICJ_AGENT_OPTIONS, '--repetitions', '1', name])
known_benchmarks = ['akka-uct', 'als', 'chi-square', 'dec-tree', 'dotty', 'finagle-chirper', 'finagle-http', 'fj-kmeans', 'future-genetic', 'gauss-mix', 'log-regression', 'mnemonics', 'movie-lens', 'naive-bayes', 'neo4j-analytics', 'page-rank', 'par-mnemonics', 'philosophers', 'reactors', 'rx-scrabble', 'scala-doku', 'scala-kmeans', 'scala-stm-bench7', 'scrabble']
def test_each_known_renaissance_benchmark():
for benchmark in KNOWN_BENCHMARKS:
smoke_test_benchmark(benchmark) |
__author__ = """Christopher Bevan Barnett"""
__email__ = 'chrisbarnettster@gmail.com'
__version__ = '0.3.7'
| __author__ = 'Christopher Bevan Barnett'
__email__ = 'chrisbarnettster@gmail.com'
__version__ = '0.3.7' |
def trace(func):
def wrapper():
func_name = func.__name__
print(f'Entering "{func_name}" function')
func()
print(f'Exiting from "{func_name}" function')
return wrapper
def say_hello():
print('Hello!')
say_hello = trace(say_hello)
say_hello()
| def trace(func):
def wrapper():
func_name = func.__name__
print(f'Entering "{func_name}" function')
func()
print(f'Exiting from "{func_name}" function')
return wrapper
def say_hello():
print('Hello!')
say_hello = trace(say_hello)
say_hello() |
# Copyright 2019 Erik Maciejewski
#
# 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.
"""system file creation rules"""
NOBODY = 65534
NONROOT = 65532
def _pad(max_len, text, extra = " "):
pad_spcs = max_len - len(text)
if pad_spcs <= 0:
return extra
return "".join([" " for i in range(0, pad_spcs)]) + extra
def _nsswitch_conf_file_impl(ctx):
doc = """# /etc/nsswitch.conf
#
# generated by bazel
#
# Example configuration of GNU Name Service Switch functionality.
# If you have the `glibc-doc-reference' and `info' packages installed, try:
# `info libc "Name Service Switch"' for information about this file.
\n"""
max_len = max([len(key) for key in ctx.attr.entries.keys()])
data = doc + "".join(["%s:%s%s\n" % (
entry[0], # db name
_pad(max_len, entry[0]),
entry[1], # db service spec
) for entry in ctx.attr.entries.items()])
nsswitch_file = ctx.actions.declare_file(ctx.attr.name)
ctx.actions.write(output = nsswitch_file, content = data)
return DefaultInfo(files = depset([nsswitch_file]))
nsswitch_conf_file = rule(
attrs = {
"entries": attr.string_dict(
allow_empty = False,
),
},
executable = False,
implementation = _nsswitch_conf_file_impl,
)
def _os_release_file_impl(ctx):
data = """PRETTY_NAME=\"%s\"
NAME=\"%s\"
VERSION_ID=\"%s\"
VERSION=\"%s\"
VERSION_CODENAME=%s
ID=%s
HOME_URL=\"%s\"
SUPPORT_URL=\"%s\"
BUG_REPORT_URL=\"%s\"\n""" % (
ctx.attr.pretty_name,
ctx.attr.release_name,
ctx.attr.version_id,
ctx.attr.version,
ctx.attr.version_codename,
ctx.attr.id,
ctx.attr.home_url,
ctx.attr.support_url,
ctx.attr.bug_report_url,
)
release_file = ctx.actions.declare_file(ctx.attr.name)
ctx.actions.write(output = release_file, content = data)
return DefaultInfo(files = depset([release_file]))
os_release_file = rule(
attrs = {
"pretty_name": attr.string(mandatory = True),
"release_name": attr.string(mandatory = True),
"version_id": attr.string(mandatory = True),
"version": attr.string(mandatory = True),
"version_codename": attr.string(mandatory = True),
"id": attr.string(mandatory = True),
"home_url": attr.string(default = ""),
"support_url": attr.string(default = ""),
"bug_report_url": attr.string(default = ""),
},
implementation = _os_release_file_impl,
)
| """system file creation rules"""
nobody = 65534
nonroot = 65532
def _pad(max_len, text, extra=' '):
pad_spcs = max_len - len(text)
if pad_spcs <= 0:
return extra
return ''.join([' ' for i in range(0, pad_spcs)]) + extra
def _nsswitch_conf_file_impl(ctx):
doc = '# /etc/nsswitch.conf\n#\n# generated by bazel\n#\n# Example configuration of GNU Name Service Switch functionality.\n# If you have the `glibc-doc-reference\' and `info\' packages installed, try:\n# `info libc "Name Service Switch"\' for information about this file.\n\n'
max_len = max([len(key) for key in ctx.attr.entries.keys()])
data = doc + ''.join(['%s:%s%s\n' % (entry[0], _pad(max_len, entry[0]), entry[1]) for entry in ctx.attr.entries.items()])
nsswitch_file = ctx.actions.declare_file(ctx.attr.name)
ctx.actions.write(output=nsswitch_file, content=data)
return default_info(files=depset([nsswitch_file]))
nsswitch_conf_file = rule(attrs={'entries': attr.string_dict(allow_empty=False)}, executable=False, implementation=_nsswitch_conf_file_impl)
def _os_release_file_impl(ctx):
data = 'PRETTY_NAME="%s"\nNAME="%s"\nVERSION_ID="%s"\nVERSION="%s"\nVERSION_CODENAME=%s\nID=%s\nHOME_URL="%s"\nSUPPORT_URL="%s"\nBUG_REPORT_URL="%s"\n' % (ctx.attr.pretty_name, ctx.attr.release_name, ctx.attr.version_id, ctx.attr.version, ctx.attr.version_codename, ctx.attr.id, ctx.attr.home_url, ctx.attr.support_url, ctx.attr.bug_report_url)
release_file = ctx.actions.declare_file(ctx.attr.name)
ctx.actions.write(output=release_file, content=data)
return default_info(files=depset([release_file]))
os_release_file = rule(attrs={'pretty_name': attr.string(mandatory=True), 'release_name': attr.string(mandatory=True), 'version_id': attr.string(mandatory=True), 'version': attr.string(mandatory=True), 'version_codename': attr.string(mandatory=True), 'id': attr.string(mandatory=True), 'home_url': attr.string(default=''), 'support_url': attr.string(default=''), 'bug_report_url': attr.string(default='')}, implementation=_os_release_file_impl) |
bitcoin = int(input())
yuans = float(input())
commission = float(input()) / 100
bitcoin_lv = bitcoin * 1168
yuans_dollars = yuans * (0.15 * 1.76)
sum_lv = bitcoin_lv + yuans_dollars
sum_eur = sum_lv / 1.95
sum_eur = round(sum_eur - (commission * sum_eur), 2)
print(sum_eur)
| bitcoin = int(input())
yuans = float(input())
commission = float(input()) / 100
bitcoin_lv = bitcoin * 1168
yuans_dollars = yuans * (0.15 * 1.76)
sum_lv = bitcoin_lv + yuans_dollars
sum_eur = sum_lv / 1.95
sum_eur = round(sum_eur - commission * sum_eur, 2)
print(sum_eur) |
"""The simplest data reader."""
for line in open('ice-cream.csv'):
row = line.split(',')
print(row)
| """The simplest data reader."""
for line in open('ice-cream.csv'):
row = line.split(',')
print(row) |
description = 'Neutron Grating Interferometer'
group = 'optional'
tango_base = 'tango://antareshw.antares.frm2.tum.de:10000/antares/'
devices = dict(
G0rz = device('nicos.devices.entangle.Motor',
speed = 1,
unit = 'deg',
description = 'Rotation of G0 grating around beam direction',
tangodevice = tango_base + 'fzjs7/G0rz',
abslimits = (-400, 400),
maxage = 5,
pollinterval = 3,
precision = 0.01,
),
G0ry = device('nicos.devices.entangle.Motor',
speed = 1,
unit = 'deg',
description = 'Rotation of G0 grating around vertical axis',
tangodevice = tango_base + 'fzjs7/G0ry',
abslimits = (-1, 400),
maxage = 5,
pollinterval = 3,
precision = 0.01,
),
G0tz = device('nicos.devices.entangle.Motor',
speed = 0.5,
unit = 'mm',
description = 'Stepping of G0 perpendicular to the beam direction',
tangodevice = tango_base + 'fzjs7/G0tx',
abslimits = (-2, 25),
maxage = 5,
pollinterval = 3,
precision = 0.01,
),
G1tx = device('nicos.devices.entangle.Motor',
speed = 50,
unit = 'mum',
description = 'Stepping of G1 perpendicular to the beam direction',
tangodevice = tango_base + 'copley/m09',
abslimits = (0, 25000),
userlimits = (0, 25000),
maxage = 5,
pollinterval = 3,
precision = 0.1,
),
G1tz = device('nicos.devices.entangle.Motor',
speed = 5,
unit = 'mm',
description = 'Translation of G1 parallel to the beam direction',
tangodevice = tango_base + 'copley/m12',
abslimits = (-1, 101),
userlimits = (0, 100),
maxage = 5,
pollinterval = 3,
precision = 0.001,
),
G1rz = device('nicos.devices.entangle.Motor',
speed = 5,
unit = 'deg',
description = 'Rotation of G1 around the beam axis',
tangodevice = tango_base + 'copley/m10',
abslimits = (-400, 400),
userlimits = (-400, 400),
maxage = 5,
pollinterval = 3,
precision = 0.001,
),
G1ry = device('nicos.devices.entangle.Motor',
speed = 5,
unit = 'deg',
description = 'Rotation of G1 around the y-axis',
tangodevice = tango_base + 'copley/m14',
abslimits = (-400,400),
userlimits = (-400,400),
maxage = 5,
pollinterval = 3,
precision = 0.001,
),
G1gx = device('nicos.devices.entangle.Motor',
speed = 5,
unit = 'deg',
description = 'Rotation of G1 around the x-axis',
tangodevice = tango_base + 'copley/m15',
abslimits = (-20, 20),
userlimits = (-20, 20),
maxage = 5,
pollinterval = 3,
precision = 0.001,
),
G2rz_p = device('nicos.devices.entangle.Motor',
speed = 0.2,
unit = 'deg',
description = 'Rotation of G1 grating around beam direction',
tangodevice = tango_base + 'fzjs7/G1rz',
abslimits = (-400, 400),
maxage = 5,
pollinterval = 3,
precision = 0.0005,
),
G2tz = device('nicos.devices.entangle.Motor',
speed = 1,
unit = 'mm',
description = 'Translation of G1 in beam direction. (Talbot distance)',
tangodevice = tango_base + 'fzjs7/G1tz',
abslimits = (0, 20),
maxage = 5,
pollinterval = 3,
precision = 0.05,
),
G2rz = device('nicos.devices.entangle.Motor',
speed = 1,
unit = 'deg',
description = 'Rotation of G2 and G1 around beam axis',
tangodevice = tango_base + 'fzjs7/G12rz',
abslimits = (-400, 400),
userlimits = (-250, 250),
maxage = 5,
pollinterval = 3,
precision = 0.01,
),
)
| description = 'Neutron Grating Interferometer'
group = 'optional'
tango_base = 'tango://antareshw.antares.frm2.tum.de:10000/antares/'
devices = dict(G0rz=device('nicos.devices.entangle.Motor', speed=1, unit='deg', description='Rotation of G0 grating around beam direction', tangodevice=tango_base + 'fzjs7/G0rz', abslimits=(-400, 400), maxage=5, pollinterval=3, precision=0.01), G0ry=device('nicos.devices.entangle.Motor', speed=1, unit='deg', description='Rotation of G0 grating around vertical axis', tangodevice=tango_base + 'fzjs7/G0ry', abslimits=(-1, 400), maxage=5, pollinterval=3, precision=0.01), G0tz=device('nicos.devices.entangle.Motor', speed=0.5, unit='mm', description='Stepping of G0 perpendicular to the beam direction', tangodevice=tango_base + 'fzjs7/G0tx', abslimits=(-2, 25), maxage=5, pollinterval=3, precision=0.01), G1tx=device('nicos.devices.entangle.Motor', speed=50, unit='mum', description='Stepping of G1 perpendicular to the beam direction', tangodevice=tango_base + 'copley/m09', abslimits=(0, 25000), userlimits=(0, 25000), maxage=5, pollinterval=3, precision=0.1), G1tz=device('nicos.devices.entangle.Motor', speed=5, unit='mm', description='Translation of G1 parallel to the beam direction', tangodevice=tango_base + 'copley/m12', abslimits=(-1, 101), userlimits=(0, 100), maxage=5, pollinterval=3, precision=0.001), G1rz=device('nicos.devices.entangle.Motor', speed=5, unit='deg', description='Rotation of G1 around the beam axis', tangodevice=tango_base + 'copley/m10', abslimits=(-400, 400), userlimits=(-400, 400), maxage=5, pollinterval=3, precision=0.001), G1ry=device('nicos.devices.entangle.Motor', speed=5, unit='deg', description='Rotation of G1 around the y-axis', tangodevice=tango_base + 'copley/m14', abslimits=(-400, 400), userlimits=(-400, 400), maxage=5, pollinterval=3, precision=0.001), G1gx=device('nicos.devices.entangle.Motor', speed=5, unit='deg', description='Rotation of G1 around the x-axis', tangodevice=tango_base + 'copley/m15', abslimits=(-20, 20), userlimits=(-20, 20), maxage=5, pollinterval=3, precision=0.001), G2rz_p=device('nicos.devices.entangle.Motor', speed=0.2, unit='deg', description='Rotation of G1 grating around beam direction', tangodevice=tango_base + 'fzjs7/G1rz', abslimits=(-400, 400), maxage=5, pollinterval=3, precision=0.0005), G2tz=device('nicos.devices.entangle.Motor', speed=1, unit='mm', description='Translation of G1 in beam direction. (Talbot distance)', tangodevice=tango_base + 'fzjs7/G1tz', abslimits=(0, 20), maxage=5, pollinterval=3, precision=0.05), G2rz=device('nicos.devices.entangle.Motor', speed=1, unit='deg', description='Rotation of G2 and G1 around beam axis', tangodevice=tango_base + 'fzjs7/G12rz', abslimits=(-400, 400), userlimits=(-250, 250), maxage=5, pollinterval=3, precision=0.01)) |
# -*- coding: utf-8 -*-
# coding: utf8
@auth.requires_membership('admin')
def index():
return locals()
@auth.requires_membership('admin')
def products():
products_grid = SQLFORM.grid(db.product, csv=False)
return locals()
@auth.requires_membership('admin')
def product_categories():
categories_grid = SQLFORM.grid(db.category, csv=False)
return locals()
@auth.requires_membership('admin')
def orders():
return locals()
@auth.requires_membership('admin')
def store_users():
users_grid = SQLFORM.grid(db.auth_user, csv=False)
return locals()
@auth.requires_membership('admin')
def user_groups():
groups_grid = SQLFORM.grid(db.auth_membership, csv=False)
return locals()
@auth.requires_membership('admin')
def suppliers():
suppliers_grid = SQLFORM.grid(db.supplier, csv=False)
return locals()
@auth.requires_membership('admin')
def carriers():
carriers_grid = SQLFORM.grid(db.carrier, csv=False)
return locals()
@auth.requires_membership('admin')
def carriers_tax():
carriers_tax_grid = SQLFORM.grid(db.carrier_tax, csv=False)
return locals()
@auth.requires_membership('admin')
def invoices():
return locals()
@auth.requires_membership('admin')
def merchandise_returns():
return locals()
@auth.requires_membership('admin')
def statuses():
return locals()
@auth.requires_membership('admin')
def order_messages():
return locals()
@auth.requires_membership('admin')
def costumers():
costumer_grid = db(db.auth_user)
return locals()
@auth.requires_membership('admin')
def costumer_groups():
return locals()
@auth.requires_membership('admin')
def shopping_carts():
return locals()
@cache.action()
def download():
"""
allows downloading of uploaded files
http://..../[app]/default/download/[filename]
"""
return response.download(request, db) | @auth.requires_membership('admin')
def index():
return locals()
@auth.requires_membership('admin')
def products():
products_grid = SQLFORM.grid(db.product, csv=False)
return locals()
@auth.requires_membership('admin')
def product_categories():
categories_grid = SQLFORM.grid(db.category, csv=False)
return locals()
@auth.requires_membership('admin')
def orders():
return locals()
@auth.requires_membership('admin')
def store_users():
users_grid = SQLFORM.grid(db.auth_user, csv=False)
return locals()
@auth.requires_membership('admin')
def user_groups():
groups_grid = SQLFORM.grid(db.auth_membership, csv=False)
return locals()
@auth.requires_membership('admin')
def suppliers():
suppliers_grid = SQLFORM.grid(db.supplier, csv=False)
return locals()
@auth.requires_membership('admin')
def carriers():
carriers_grid = SQLFORM.grid(db.carrier, csv=False)
return locals()
@auth.requires_membership('admin')
def carriers_tax():
carriers_tax_grid = SQLFORM.grid(db.carrier_tax, csv=False)
return locals()
@auth.requires_membership('admin')
def invoices():
return locals()
@auth.requires_membership('admin')
def merchandise_returns():
return locals()
@auth.requires_membership('admin')
def statuses():
return locals()
@auth.requires_membership('admin')
def order_messages():
return locals()
@auth.requires_membership('admin')
def costumers():
costumer_grid = db(db.auth_user)
return locals()
@auth.requires_membership('admin')
def costumer_groups():
return locals()
@auth.requires_membership('admin')
def shopping_carts():
return locals()
@cache.action()
def download():
"""
allows downloading of uploaded files
http://..../[app]/default/download/[filename]
"""
return response.download(request, db) |
num = int(input("Insert some numbers: "))
even = 0
odd = 0
while num > 0:
if num%2 == 0:
even += 1
else:
odd += 1
num = num//10
print("Even numbers = %d, Odd numbers = %d" % (even,odd))
| num = int(input('Insert some numbers: '))
even = 0
odd = 0
while num > 0:
if num % 2 == 0:
even += 1
else:
odd += 1
num = num // 10
print('Even numbers = %d, Odd numbers = %d' % (even, odd)) |
"""A board is a list of list of str. For example, the board
ANTT
XSOB
is represented as the list
[['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']]
A word list is a list of str. For example, the list of words
ANT
BOX
SOB
TO
is represented as the list
['ANT', 'BOX', 'SOB', 'TO']
"""
def is_valid_word(wordlist, word):
""" (list of str, str) -> bool
Return True if and only if word is an element of wordlist.
>>> is_valid_word(['ANT', 'BOX', 'SOB', 'TO'], 'TO')
True
>>>is_valid_word(['ANT', 'BOX', 'SOB', 'TO'], '')
False
"""
i = 0
while i < len(wordlist):
if word in wordlist:
i = i +1
return True
else:
return False
def make_str_from_row(board, row_index):
""" (list of list of str, int) -> str
Return the characters from the row of the board with index row_index
as a single string.
>>> make_str_from_row([['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']], 0)
'ANTT'
"""
word = ''
i= 0
while i < len(board[row_index]):
word = word + board[row_index][i]
i = i + 1
return word
def make_str_from_column(board, column_index):
""" (list of list of str, int) -> str
Return the characters from the column of the board with index column_index
as a single string.
>>> make_str_from_column([['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']], 1)
'NS'
"""
#first index change +1
#second index stays and its column_index
word = ''
for i in range(len(board)):
word = word + board[i][column_index]
return word
def board_contains_word_in_row(board, word):
""" (list of list of str, str) -> bool
Return True if and only if one or more of the rows of the board contains
word.
Precondition: board has at least one row and one column, and word is a
valid word.
>>> board_contains_word_in_row([['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']], 'SOB')
True
"""
for row_index in range(len(board)):
if word in make_str_from_row(board, row_index):
return True
return False
def board_contains_word_in_column(board, word):
""" (list of list of str, str) -> bool
Return True if and only if one or more of the columns of the board
contains word.
Precondition: board has at least one row and one column, and word is a
valid word.
>>> board_contains_word_in_column([['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']], 'NO')
False
"""
y = board[0]
for column_index in range(len(y)):
if word in make_str_from_column(board, column_index):
return True
return False
def board_contains_word(board, word):
""" (list of list of str, str) -> bool
Return True if and only if word appears in board.
Precondition: board has at least one row and one column.
>>> board_contains_word([['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']], 'ANT')
True
>>>board_contains_word([['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']], 'AX')
True
"""
a = board_contains_word_in_column(board, word)
b = board_contains_word_in_row(board, word)
if a or b:
return True
return False
def word_score(word):
""" (str) -> int
Return the point value the word earns.
Word length: < 3: 0 points
3-6: 1 point per character for all characters in word
7-9: 2 points per character for all characters in word
10+: 3 points per character for all characters in word
>>> word_score('DRUDGERY')
16
"""
if board_contains_word(board,word):
length = len(word)
if length < 3:
return 0
elif length >= 3 and length <=6:
score = 1 * len(word)
return score
elif length >=7 and length <= 9:
score = 2 * len(word)
return score
elif length >=10:
score = 3 * len(word)
return score
def update_score(player_info, word):
""" ([str, int] list, str) -> NoneType
player_info is a list with the player's name and score. Update player_info
by adding the point value word earns to the player's score.
>>> update_score(['Jonathan', 4], 'ANT')
"""
def num_words_on_board(board, words):
""" (list of list of str, list of str) -> int
Return how many words appear on board.
>>> num_words_on_board([['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']], ['ANT', 'BOX', 'SOB', 'TO'])
3
"""
def read_words(words_file):
""" (file open for reading) -> list of str
Return a list of all words (with newlines removed) from open file
words_file.
Precondition: Each line of the file contains a word in uppercase characters
from the standard English alphabet.
"""
def read_board(board_file):
""" (file open for reading) -> list of list of str
Return a board read from open file board_file. The board file will contain
one row of the board per line. Newlines are not included in the board.
"""
| """A board is a list of list of str. For example, the board
ANTT
XSOB
is represented as the list
[['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']]
A word list is a list of str. For example, the list of words
ANT
BOX
SOB
TO
is represented as the list
['ANT', 'BOX', 'SOB', 'TO']
"""
def is_valid_word(wordlist, word):
""" (list of str, str) -> bool
Return True if and only if word is an element of wordlist.
>>> is_valid_word(['ANT', 'BOX', 'SOB', 'TO'], 'TO')
True
>>>is_valid_word(['ANT', 'BOX', 'SOB', 'TO'], '')
False
"""
i = 0
while i < len(wordlist):
if word in wordlist:
i = i + 1
return True
else:
return False
def make_str_from_row(board, row_index):
""" (list of list of str, int) -> str
Return the characters from the row of the board with index row_index
as a single string.
>>> make_str_from_row([['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']], 0)
'ANTT'
"""
word = ''
i = 0
while i < len(board[row_index]):
word = word + board[row_index][i]
i = i + 1
return word
def make_str_from_column(board, column_index):
""" (list of list of str, int) -> str
Return the characters from the column of the board with index column_index
as a single string.
>>> make_str_from_column([['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']], 1)
'NS'
"""
word = ''
for i in range(len(board)):
word = word + board[i][column_index]
return word
def board_contains_word_in_row(board, word):
""" (list of list of str, str) -> bool
Return True if and only if one or more of the rows of the board contains
word.
Precondition: board has at least one row and one column, and word is a
valid word.
>>> board_contains_word_in_row([['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']], 'SOB')
True
"""
for row_index in range(len(board)):
if word in make_str_from_row(board, row_index):
return True
return False
def board_contains_word_in_column(board, word):
""" (list of list of str, str) -> bool
Return True if and only if one or more of the columns of the board
contains word.
Precondition: board has at least one row and one column, and word is a
valid word.
>>> board_contains_word_in_column([['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']], 'NO')
False
"""
y = board[0]
for column_index in range(len(y)):
if word in make_str_from_column(board, column_index):
return True
return False
def board_contains_word(board, word):
""" (list of list of str, str) -> bool
Return True if and only if word appears in board.
Precondition: board has at least one row and one column.
>>> board_contains_word([['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']], 'ANT')
True
>>>board_contains_word([['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']], 'AX')
True
"""
a = board_contains_word_in_column(board, word)
b = board_contains_word_in_row(board, word)
if a or b:
return True
return False
def word_score(word):
""" (str) -> int
Return the point value the word earns.
Word length: < 3: 0 points
3-6: 1 point per character for all characters in word
7-9: 2 points per character for all characters in word
10+: 3 points per character for all characters in word
>>> word_score('DRUDGERY')
16
"""
if board_contains_word(board, word):
length = len(word)
if length < 3:
return 0
elif length >= 3 and length <= 6:
score = 1 * len(word)
return score
elif length >= 7 and length <= 9:
score = 2 * len(word)
return score
elif length >= 10:
score = 3 * len(word)
return score
def update_score(player_info, word):
""" ([str, int] list, str) -> NoneType
player_info is a list with the player's name and score. Update player_info
by adding the point value word earns to the player's score.
>>> update_score(['Jonathan', 4], 'ANT')
"""
def num_words_on_board(board, words):
""" (list of list of str, list of str) -> int
Return how many words appear on board.
>>> num_words_on_board([['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']], ['ANT', 'BOX', 'SOB', 'TO'])
3
"""
def read_words(words_file):
""" (file open for reading) -> list of str
Return a list of all words (with newlines removed) from open file
words_file.
Precondition: Each line of the file contains a word in uppercase characters
from the standard English alphabet.
"""
def read_board(board_file):
""" (file open for reading) -> list of list of str
Return a board read from open file board_file. The board file will contain
one row of the board per line. Newlines are not included in the board.
""" |
def foo(x = []):
return x.append("x")
def bar(x = []):
return len(x)
foo()
bar()
class Owner(object):
@classmethod
def cm(cls, arg):
return cls
@classmethod
def cm2(cls, arg):
return arg
#Normal method
def m(self):
a = self.cm(0)
return a.cm2(1)
| def foo(x=[]):
return x.append('x')
def bar(x=[]):
return len(x)
foo()
bar()
class Owner(object):
@classmethod
def cm(cls, arg):
return cls
@classmethod
def cm2(cls, arg):
return arg
def m(self):
a = self.cm(0)
return a.cm2(1) |
#sequence cleaner removes sequences that are ambiguous (6-mer appending the poly sequence is indefinite ("N") and shifts all "N" characters
#in poly sequence right so that they can be combined
def sequenceCleaner(string):
if len(string) < 13:
return "", 0
if string[5] == "*":
return "", 0
if string[len(string)-6] == "*":
return "", 0
if not "*" in string[6:len(string)-6]:
return string[6:len(string)-6], len(string)-12
else:
return rightShiftN(string[6:len(string)-6])
def rightShiftN(string):
output = ""
indefinite = ""
total = 0.0
for i in string:
if i == "*":
indefinite = indefinite + i
total += 0.51
else:
output = output + i
total += 1.0
output = output + indefinite
return output, total | def sequence_cleaner(string):
if len(string) < 13:
return ('', 0)
if string[5] == '*':
return ('', 0)
if string[len(string) - 6] == '*':
return ('', 0)
if not '*' in string[6:len(string) - 6]:
return (string[6:len(string) - 6], len(string) - 12)
else:
return right_shift_n(string[6:len(string) - 6])
def right_shift_n(string):
output = ''
indefinite = ''
total = 0.0
for i in string:
if i == '*':
indefinite = indefinite + i
total += 0.51
else:
output = output + i
total += 1.0
output = output + indefinite
return (output, total) |
# Copyright 2015 The Bazel Authors. 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.
load(
"@io_bazel_rules_scala//scala:scala_maven_import_external.bzl",
_scala_maven_import_external = "scala_maven_import_external",
)
"""Helper functions for Scala cross-version support. Encapsulates the logic
of abstracting over Scala major version (2.11, 2.12, etc) for dependency
resolution."""
def default_scala_version():
"""return the scala version for use in maven coordinates"""
return "2.12.10" #TODO
def default_scala_version_jar_shas():
return {
"scala_compiler": "cedc3b9c39d215a9a3ffc0cc75a1d784b51e9edc7f13051a1b4ad5ae22cfbc0c",
"scala_library": "0a57044d10895f8d3dd66ad4286891f607169d948845ac51e17b4c1cf0ab569d",
"scala_reflect": "56b609e1bab9144fb51525bfa01ccd72028154fc40a58685a1e9adcbe7835730"
}
def extract_major_version(scala_version):
"""Return major Scala version given a full version, e.g. "2.11.11" -> "2.11" """
return scala_version[:scala_version.find(".", 2)]
def extract_major_version_underscore(scala_version):
"""Return major Scala version with underscore given a full version,
e.g. "2.11.11" -> "2_11" """
return extract_major_version(scala_version).replace(".", "_")
def default_scala_major_version():
return extract_major_version(default_scala_version())
def scala_mvn_artifact(
artifact,
major_scala_version = default_scala_major_version()):
"""Add scala version to maven artifact"""
gav = artifact.split(":")
groupid = gav[0]
artifactid = gav[1]
version = gav[2]
return "%s:%s_%s:%s" % (groupid, artifactid, major_scala_version, version)
def new_scala_default_repository(
scala_version,
scala_version_jar_shas,
maven_servers):
_scala_maven_import_external(
name = "io_bazel_rules_scala_scala_library",
artifact = "org.scala-lang:scala-library:{}".format(scala_version),
artifact_sha256 = scala_version_jar_shas["scala_library"],
licenses = ["notice"],
server_urls = maven_servers,
)
_scala_maven_import_external(
name = "io_bazel_rules_scala_scala_compiler",
artifact = "org.scala-lang:scala-compiler:{}".format(scala_version),
artifact_sha256 = scala_version_jar_shas["scala_compiler"],
licenses = ["notice"],
server_urls = maven_servers,
)
_scala_maven_import_external(
name = "io_bazel_rules_scala_scala_reflect",
artifact = "org.scala-lang:scala-reflect:{}".format(scala_version),
artifact_sha256 = scala_version_jar_shas["scala_reflect"],
licenses = ["notice"],
server_urls = maven_servers,
)
| load('@io_bazel_rules_scala//scala:scala_maven_import_external.bzl', _scala_maven_import_external='scala_maven_import_external')
'Helper functions for Scala cross-version support. Encapsulates the logic\nof abstracting over Scala major version (2.11, 2.12, etc) for dependency\nresolution.'
def default_scala_version():
"""return the scala version for use in maven coordinates"""
return '2.12.10'
def default_scala_version_jar_shas():
return {'scala_compiler': 'cedc3b9c39d215a9a3ffc0cc75a1d784b51e9edc7f13051a1b4ad5ae22cfbc0c', 'scala_library': '0a57044d10895f8d3dd66ad4286891f607169d948845ac51e17b4c1cf0ab569d', 'scala_reflect': '56b609e1bab9144fb51525bfa01ccd72028154fc40a58685a1e9adcbe7835730'}
def extract_major_version(scala_version):
"""Return major Scala version given a full version, e.g. "2.11.11" -> "2.11" """
return scala_version[:scala_version.find('.', 2)]
def extract_major_version_underscore(scala_version):
"""Return major Scala version with underscore given a full version,
e.g. "2.11.11" -> "2_11" """
return extract_major_version(scala_version).replace('.', '_')
def default_scala_major_version():
return extract_major_version(default_scala_version())
def scala_mvn_artifact(artifact, major_scala_version=default_scala_major_version()):
"""Add scala version to maven artifact"""
gav = artifact.split(':')
groupid = gav[0]
artifactid = gav[1]
version = gav[2]
return '%s:%s_%s:%s' % (groupid, artifactid, major_scala_version, version)
def new_scala_default_repository(scala_version, scala_version_jar_shas, maven_servers):
_scala_maven_import_external(name='io_bazel_rules_scala_scala_library', artifact='org.scala-lang:scala-library:{}'.format(scala_version), artifact_sha256=scala_version_jar_shas['scala_library'], licenses=['notice'], server_urls=maven_servers)
_scala_maven_import_external(name='io_bazel_rules_scala_scala_compiler', artifact='org.scala-lang:scala-compiler:{}'.format(scala_version), artifact_sha256=scala_version_jar_shas['scala_compiler'], licenses=['notice'], server_urls=maven_servers)
_scala_maven_import_external(name='io_bazel_rules_scala_scala_reflect', artifact='org.scala-lang:scala-reflect:{}'.format(scala_version), artifact_sha256=scala_version_jar_shas['scala_reflect'], licenses=['notice'], server_urls=maven_servers) |
def fibonaci(n):
if n <= 1:
return n
else:
return fibonaci(n-1)+fibonaci(n-2)
fibonaci(0) | def fibonaci(n):
if n <= 1:
return n
else:
return fibonaci(n - 1) + fibonaci(n - 2)
fibonaci(0) |
class Position:
def __init__(self, idx, ln, col, fn, ftxt) -> None:
self.idx = idx
self.ln = ln
self.col = col
self.fn = fn
self.ftxt = ftxt
def advance(self, current_char=None):
self.idx += 1
self.col += 1
if current_char == "\n":
self.ln += 1
self.col = 0
return self
def copy(self):
return Position(self.idx, self.ln, self.col, self.fn, self.ftxt)
| class Position:
def __init__(self, idx, ln, col, fn, ftxt) -> None:
self.idx = idx
self.ln = ln
self.col = col
self.fn = fn
self.ftxt = ftxt
def advance(self, current_char=None):
self.idx += 1
self.col += 1
if current_char == '\n':
self.ln += 1
self.col = 0
return self
def copy(self):
return position(self.idx, self.ln, self.col, self.fn, self.ftxt) |
def on_config():
# Here you can do all you want.
print("Called.")
def on_config_with_config(config):
print("Called with config.")
print(config["docs_dir"])
# You can change config, for example:
# config['docs_dir'] = 'other_directory'
# Optionally, you can return altered config to customize MkDocs.
# return config
def on_config_with_mkapi(config, mkapi):
print("Called with config and mkapi.")
print(config["docs_dir"])
print(mkapi)
| def on_config():
print('Called.')
def on_config_with_config(config):
print('Called with config.')
print(config['docs_dir'])
def on_config_with_mkapi(config, mkapi):
print('Called with config and mkapi.')
print(config['docs_dir'])
print(mkapi) |
##########################################################################
# Copyright (c) 2018-2019 NVIDIA Corporation. 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.
#
# File: DL4AGX/tools/nvcc/private/constants.bzl
# Description: Constants for use in creating cuda rules
##########################################################################
CUDA_ACCEPTABLE_SRC_EXTENSIONS = [".cu", ".c", ".cc", ".cxx", ".cpp"]
CUDA_ACCEPTABLE_HDR_EXTENSIONS = [".h", ".cuh", ".hpp", ".inl"]
CUDA_ACCEPTABLE_BIN_EXTENSIONS = [".ptx", ".cubin", ".fatbin",
".o", ".obj", ".a", ".lib",
".res", ".so"]
CUDA_ACCEPTABLE_EXTENSIONS = CUDA_ACCEPTABLE_SRC_EXTENSIONS + CUDA_ACCEPTABLE_BIN_EXTENSIONS + CUDA_ACCEPTABLE_HDR_EXTENSIONS | cuda_acceptable_src_extensions = ['.cu', '.c', '.cc', '.cxx', '.cpp']
cuda_acceptable_hdr_extensions = ['.h', '.cuh', '.hpp', '.inl']
cuda_acceptable_bin_extensions = ['.ptx', '.cubin', '.fatbin', '.o', '.obj', '.a', '.lib', '.res', '.so']
cuda_acceptable_extensions = CUDA_ACCEPTABLE_SRC_EXTENSIONS + CUDA_ACCEPTABLE_BIN_EXTENSIONS + CUDA_ACCEPTABLE_HDR_EXTENSIONS |
class Car(object):
condition = "new"
def __init__(self, model, color, mpg):
self.model = model
self.color = color
self.mpg = mpg
my_car = Car("Chevv", "GOLDEN", 1933)
print(my_car.model)
print(my_car.color)
print(my_car.mpg)
| class Car(object):
condition = 'new'
def __init__(self, model, color, mpg):
self.model = model
self.color = color
self.mpg = mpg
my_car = car('Chevv', 'GOLDEN', 1933)
print(my_car.model)
print(my_car.color)
print(my_car.mpg) |
def validate(name, bracket, bracket_side, bfr):
"""
Check if bracket is lowercase
"""
return bfr[bracket.begin:bracket.end].islower()
| def validate(name, bracket, bracket_side, bfr):
"""
Check if bracket is lowercase
"""
return bfr[bracket.begin:bracket.end].islower() |
def add(a, b) :
s = a + b
return s
#main app begins here
x = 2
y = 3
z = add(x, y)
print('Sum : ', z) | def add(a, b):
s = a + b
return s
x = 2
y = 3
z = add(x, y)
print('Sum : ', z) |
#service.process.factory.proc_provider_factories
class ProcProviderFactories(object):
def __init__(self, log):
self._log = log
self._factory = None
def get_factory(self, process):
#should instantiate the teradata factory
if self._factory is None:
tmp = __import__('service.process.factory.'+process.name.lower(), fromlist=[process.name+'Factory'])
self._factory = getattr(tmp, process.name+'Factory')(self._log)
return self._factory | class Procproviderfactories(object):
def __init__(self, log):
self._log = log
self._factory = None
def get_factory(self, process):
if self._factory is None:
tmp = __import__('service.process.factory.' + process.name.lower(), fromlist=[process.name + 'Factory'])
self._factory = getattr(tmp, process.name + 'Factory')(self._log)
return self._factory |
# Time: ls: O(l + klogk), l is the path length, k is the number of entries in the last level directory
# mkdir: O(l)
# addContentToFile: O(l + c), c is the content size
# readContentFromFile: O(l + c)
# Space: O(n + s), n is the number of dir/file nodes, s is the total content size.
# Design an in-memory file system to simulate the following functions:
#
# ls: Given a path in string format. If it is a file path,
# return a list that only contains this file's name.
# If it is a directory path, return the list of file and directory names in this directory.
# Your output (file and directory names together) should in lexicographic order.
#
# mkdir: Given a directory path that does not exist,
# you should make a new directory according to the path.
# If the middle directories in the path don't exist either,
# you should create them as well. This function has void return type.
#
# addContentToFile: Given a file path and file content in string format.
# If the file doesn't exist, you need to create that file containing given content.
# If the file already exists, you need to append given content to original content.
# This function has void return type.
#
# readContentFromFile: Given a file path, return its content in string format.
#
# Example:
# Input:
# ["FileSystem","ls","mkdir","addContentToFile","ls","readContentFromFile"]
# [[],["/"],["/a/b/c"],["/a/b/c/d","hello"],["/"],["/a/b/c/d"]]
# Output:
# [null,[],null,null,["a"],"hello"]
#
# Note:
# 1. You can assume all file or directory paths are absolute paths
# which begin with / and do not end with / except that the path is just "/".
# 2. You can assume that all operations will be passed valid parameters and
# users will not attempt to retrieve file content or list a directory or file that does not exist.
# 3. You can assume that all directory names and file names only contain lower-case letters,
# and same names won't exist in the same directory.
class TrieNode(object):
def __init__(self):
self.is_file = False
self.children = {}
self.content = ""
class FileSystem(object):
def __init__(self):
self.__root = TrieNode()
def ls(self, path):
"""
:type path: str
:rtype: List[str]
"""
curr = self.__getNode(path)
if curr.is_file:
return [self.__split(path, '/')[-1]]
return sorted(curr.children.keys())
def mkdir(self, path):
"""
:type path: str
:rtype: void
"""
curr = self.__putNode(path)
curr.is_file = False
def addContentToFile(self, filePath, content):
"""
:type filePath: str
:type content: str
:rtype: void
"""
curr = self.__putNode(filePath)
curr.is_file = True
curr.content += content
def readContentFromFile(self, filePath):
"""
:type filePath: str
:rtype: str
"""
return self.__getNode(filePath).content
def __getNode(self, path):
curr = self.__root
for s in self.__split(path, '/'):
curr = curr.children[s]
return curr
def __putNode(self, path):
curr = self.__root
for s in self.__split(path, '/'):
if s not in curr.children:
curr.children[s] = TrieNode()
curr = curr.children[s]
return curr
def __split(self, path, delim):
if path == '/':
return []
return path.split('/')[1:]
# Your FileSystem object will be instantiated and called as such:
# obj = FileSystem()
# param_1 = obj.ls(path)
# obj.mkdir(path)
# obj.addContentToFile(filePath,content)
# param_4 = obj.readContentFromFile(filePath)
| class Trienode(object):
def __init__(self):
self.is_file = False
self.children = {}
self.content = ''
class Filesystem(object):
def __init__(self):
self.__root = trie_node()
def ls(self, path):
"""
:type path: str
:rtype: List[str]
"""
curr = self.__getNode(path)
if curr.is_file:
return [self.__split(path, '/')[-1]]
return sorted(curr.children.keys())
def mkdir(self, path):
"""
:type path: str
:rtype: void
"""
curr = self.__putNode(path)
curr.is_file = False
def add_content_to_file(self, filePath, content):
"""
:type filePath: str
:type content: str
:rtype: void
"""
curr = self.__putNode(filePath)
curr.is_file = True
curr.content += content
def read_content_from_file(self, filePath):
"""
:type filePath: str
:rtype: str
"""
return self.__getNode(filePath).content
def __get_node(self, path):
curr = self.__root
for s in self.__split(path, '/'):
curr = curr.children[s]
return curr
def __put_node(self, path):
curr = self.__root
for s in self.__split(path, '/'):
if s not in curr.children:
curr.children[s] = trie_node()
curr = curr.children[s]
return curr
def __split(self, path, delim):
if path == '/':
return []
return path.split('/')[1:] |
def get_input():
file = open('inputs/bubble_sort.txt')
input = file.read()
file.close()
return input
def bubble_sort(a, n):
swap_count = 0
is_sorted = False
while not is_sorted:
is_sorted = True
for i in range(n-1):
if a[i] > a[i + 1]:
temp = a[i]
a[i] = a[i + 1]
a[i + 1] = temp
is_sorted = False
return a, swap_count
n, a = get_input().split('\n')
n = int(n)
a = list(map(int, a.split(' ')))
a, swap_count = bubble_sort(a, n)
print('Array is sorted in {} swaps.'.format(swap_count))
print('First Element: {}'.format(a[0]))
print('Last Element: {}'.format(a[n-1])) | def get_input():
file = open('inputs/bubble_sort.txt')
input = file.read()
file.close()
return input
def bubble_sort(a, n):
swap_count = 0
is_sorted = False
while not is_sorted:
is_sorted = True
for i in range(n - 1):
if a[i] > a[i + 1]:
temp = a[i]
a[i] = a[i + 1]
a[i + 1] = temp
is_sorted = False
return (a, swap_count)
(n, a) = get_input().split('\n')
n = int(n)
a = list(map(int, a.split(' ')))
(a, swap_count) = bubble_sort(a, n)
print('Array is sorted in {} swaps.'.format(swap_count))
print('First Element: {}'.format(a[0]))
print('Last Element: {}'.format(a[n - 1])) |
PROJECT_ID_LIST_URL = "https://cloudresourcemanager.googleapis.com/v1/projects"
HTTP_GET_METHOD = "GET"
class UtilBase(object):
def __init__(self, config):
self.config = config
self.__projectList = None
def getProjectList(self):
if self.__projectList != None:
return self.__projectList
projectData = None
if self.config.getIdType() == "PROJECT":
googleClient = self.config.getHttpClient()
singleprojectData = googleClient.make_request( HTTP_GET_METHOD, PROJECT_ID_LIST_URL + "/" + self.config.getId(), None, None)
if singleprojectData['isError']:
projectData = singleprojectData
else:
projectData= {
'isError': singleprojectData.get("isError"),
'defaultErrorObject':singleprojectData.get("defaultErrorObject"),
"data": {
'projects': [singleprojectData.get("data")]
}
}
if singleprojectData["data"].get('lifecycleState') != "ACTIVE":
raise Exception("Project Lifecycle state is: " + str(projectData['lifecycleState']))
else:
projectData = {
'isError': False,
'defaultErrorObject': {},
"data": {
'projects': self.__get_Project_List(None, True)
}
}
if projectData['isError']:
raise Exception("Error fetching projects")
projectList = projectData['data']['projects']
projectList = [project for project in projectList if project['lifecycleState'] == "ACTIVE"]
self.__projectList = projectList
return self.__projectList
def __get_Project_List(self, pageToken, isBegin):
if pageToken is None and not isBegin:
return []
googleClient = self.config.getHttpClient()
url = PROJECT_ID_LIST_URL
if pageToken is not None:
url = url + "?pageToken=" + pageToken + "&pageSize=100"
else:
url = url + "?pageSize=100"
projectData = googleClient.make_request(HTTP_GET_METHOD, url, None, None)
if projectData['isError']:
raise Exception("Error fetching Project Information \n" + str(projectData['defaultErrorObject']))
if 'projects' not in projectData['data'] or len(projectData['data']['projects']) == 0:
raise Exception("No Projects Found")
projectList = projectData['data']['projects']
if 'nextPageToken' in projectData['data']:
nextPageToken = str(projectData['data']['nextPageToken'])
projectList = projectList + (self.__get_Project_List(nextPageToken, False))
return projectList
def validateProjectId(self, projectId):
projectList = self.getProjectList()
for project in projectList:
if project['projectId'] == projectId:
return True
return False
| project_id_list_url = 'https://cloudresourcemanager.googleapis.com/v1/projects'
http_get_method = 'GET'
class Utilbase(object):
def __init__(self, config):
self.config = config
self.__projectList = None
def get_project_list(self):
if self.__projectList != None:
return self.__projectList
project_data = None
if self.config.getIdType() == 'PROJECT':
google_client = self.config.getHttpClient()
singleproject_data = googleClient.make_request(HTTP_GET_METHOD, PROJECT_ID_LIST_URL + '/' + self.config.getId(), None, None)
if singleprojectData['isError']:
project_data = singleprojectData
else:
project_data = {'isError': singleprojectData.get('isError'), 'defaultErrorObject': singleprojectData.get('defaultErrorObject'), 'data': {'projects': [singleprojectData.get('data')]}}
if singleprojectData['data'].get('lifecycleState') != 'ACTIVE':
raise exception('Project Lifecycle state is: ' + str(projectData['lifecycleState']))
else:
project_data = {'isError': False, 'defaultErrorObject': {}, 'data': {'projects': self.__get_Project_List(None, True)}}
if projectData['isError']:
raise exception('Error fetching projects')
project_list = projectData['data']['projects']
project_list = [project for project in projectList if project['lifecycleState'] == 'ACTIVE']
self.__projectList = projectList
return self.__projectList
def __get__project__list(self, pageToken, isBegin):
if pageToken is None and (not isBegin):
return []
google_client = self.config.getHttpClient()
url = PROJECT_ID_LIST_URL
if pageToken is not None:
url = url + '?pageToken=' + pageToken + '&pageSize=100'
else:
url = url + '?pageSize=100'
project_data = googleClient.make_request(HTTP_GET_METHOD, url, None, None)
if projectData['isError']:
raise exception('Error fetching Project Information \n' + str(projectData['defaultErrorObject']))
if 'projects' not in projectData['data'] or len(projectData['data']['projects']) == 0:
raise exception('No Projects Found')
project_list = projectData['data']['projects']
if 'nextPageToken' in projectData['data']:
next_page_token = str(projectData['data']['nextPageToken'])
project_list = projectList + self.__get_Project_List(nextPageToken, False)
return projectList
def validate_project_id(self, projectId):
project_list = self.getProjectList()
for project in projectList:
if project['projectId'] == projectId:
return True
return False |
NAME='logzmq'
CFLAGS = []
LDFLAGS = []
LIBS = ['-lzmq']
GCC_LIST = ['plugin']
| name = 'logzmq'
cflags = []
ldflags = []
libs = ['-lzmq']
gcc_list = ['plugin'] |
test = {
'name': 'Problem EC',
'points': 2,
'suites': [
{
'cases': [
{
'code': r"""
>>> # Testing status parameters
>>> slow = SlowThrower()
>>> scary = ScaryThrower()
>>> SlowThrower.food_cost
4
>>> ScaryThrower.food_cost
6
>>> slow.armor
1
>>> scary.armor
1
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> # Testing Slow
>>> slow = SlowThrower()
>>> bee = Bee(3)
>>> gamestate.places["tunnel_0_0"].add_insect(slow)
>>> gamestate.places["tunnel_0_4"].add_insect(bee)
>>> slow.action(gamestate)
>>> gamestate.time = 1
>>> bee.action(gamestate)
>>> bee.place.name # SlowThrower should cause slowness on odd turns
'tunnel_0_4'
>>> gamestate.time += 1
>>> bee.action(gamestate)
>>> bee.place.name # SlowThrower should cause slowness on odd turns
'tunnel_0_3'
>>> for _ in range(3):
... gamestate.time += 1
... bee.action(gamestate)
>>> bee.place.name
'tunnel_0_1'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> # Testing Scare
>>> scary = ScaryThrower()
>>> bee = Bee(3)
>>> gamestate.places["tunnel_0_0"].add_insect(scary)
>>> gamestate.places["tunnel_0_4"].add_insect(bee)
>>> scary.action(gamestate)
>>> bee.action(gamestate)
>>> bee.place.name # ScaryThrower should scare for two turns
'tunnel_0_5'
>>> bee.action(gamestate)
>>> bee.place.name # ScaryThrower should scare for two turns
'tunnel_0_6'
>>> bee.action(gamestate)
>>> bee.place.name
'tunnel_0_5'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> # Scary stings an ant
>>> scary = ScaryThrower()
>>> harvester = HarvesterAnt()
>>> bee = Bee(3)
>>> gamestate.places["tunnel_0_0"].add_insect(scary)
>>> gamestate.places["tunnel_0_4"].add_insect(bee)
>>> gamestate.places["tunnel_0_5"].add_insect(harvester)
>>> scary.action(gamestate)
>>> bee.action(gamestate)
>>> bee.place.name # ScaryThrower should scare for two turns
'tunnel_0_5'
>>> harvester.armor
1
>>> bee.action(gamestate)
>>> harvester.armor
0
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> # Testing if statuses stack
>>> slow = SlowThrower()
>>> bee = Bee(3)
>>> slow_place = gamestate.places["tunnel_0_0"]
>>> bee_place = gamestate.places["tunnel_0_8"]
>>> slow_place.add_insect(slow)
>>> bee_place.add_insect(bee)
>>> slow.action(gamestate) # slow bee two times
>>> slow.action(gamestate)
>>> gamestate.time = 1
>>> bee.action(gamestate) # do nothing. The outer slow has 2 turns to go, the inner one still has 3 turns
>>> bee.place.name
'tunnel_0_8'
>>> gamestate.time = 2
>>> bee.action(gamestate) # moves forward. The outer slow has 1 turn to go, the inner one has 2 turns
>>> bee.place.name
'tunnel_0_7'
>>> gamestate.time = 3
>>> bee.action(gamestate) # do nothing. The outer slow has no turns left, the inner one has 2 turns
>>> bee.place.name
'tunnel_0_7'
>>> gamestate.time = 4
>>> bee.action(gamestate) # moves forward. The inner slow has 1 turn
>>> bee.place.name
'tunnel_0_6'
>>> gamestate.time = 5
>>> bee.action(gamestate) # does nothing. The inner slow has no turns
>>> bee.place.name
'tunnel_0_6'
>>> gamestate.time = 6 # slow status have worn off
>>> bee.action(gamestate)
>>> bee.place.name
'tunnel_0_5'
>>> gamestate.time = 7 # slow status have worn off
>>> bee.action(gamestate)
>>> bee.place.name
'tunnel_0_4'
>>> gamestate.time = 8 # slow status have worn off
>>> bee.action(gamestate)
>>> bee.place.name
'tunnel_0_3'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> # Testing multiple scared bees
>>> scare1 = ScaryThrower()
>>> scare2 = ScaryThrower()
>>> bee1 = Bee(3)
>>> bee2 = Bee(3)
>>> gamestate.places["tunnel_0_0"].add_insect(scare1)
>>> gamestate.places["tunnel_0_1"].add_insect(bee1)
>>> gamestate.places["tunnel_0_4"].add_insect(scare2)
>>> gamestate.places["tunnel_0_5"].add_insect(bee2)
>>> scare1.action(gamestate)
>>> scare2.action(gamestate)
>>> bee1.action(gamestate)
>>> bee2.action(gamestate)
>>> bee1.place.name
'tunnel_0_2'
>>> bee2.place.name
'tunnel_0_6'
>>> bee1.action(gamestate)
>>> bee2.action(gamestate)
>>> bee1.place.name
'tunnel_0_3'
>>> bee2.place.name
'tunnel_0_7'
>>> bee1.action(gamestate)
>>> bee2.action(gamestate)
>>> bee1.place.name
'tunnel_0_2'
>>> bee2.place.name
'tunnel_0_6'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> scare = ScaryThrower()
>>> bee = Bee(3)
>>> gamestate.places["tunnel_0_0"].add_insect(scare)
>>> gamestate.places["tunnel_0_1"].add_insect(bee)
>>> scare.action(gamestate)
>>> bee.action(gamestate)
>>> bee.place.name
'tunnel_0_2'
>>> bee.action(gamestate)
>>> bee.place.name
'tunnel_0_3'
>>> #
>>> # Same bee should not be scared more than once
>>> scare.action(gamestate)
>>> bee.action(gamestate)
>>> bee.place.name
'tunnel_0_2'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> # Testing long status stack
>>> scary = ScaryThrower()
>>> slow = SlowThrower()
>>> bee = Bee(3)
>>> gamestate.places["tunnel_0_0"].add_insect(scary)
>>> gamestate.places["tunnel_0_1"].add_insect(slow)
>>> gamestate.places["tunnel_0_3"].add_insect(bee)
>>> scary.action(gamestate) # scare bee once
>>> gamestate.time = 0
>>> bee.action(gamestate) # scared
>>> bee.place.name
'tunnel_0_4'
>>> for _ in range(3): # slow bee three times
... slow.action(gamestate)
>>> gamestate.time = 1
>>> bee.action(gamestate) # scared, but also slowed thrice
>>> bee.place.name
'tunnel_0_4'
>>> gamestate.time = 2
>>> bee.action(gamestate) # scared and slowed thrice
>>> bee.place.name
'tunnel_0_5'
>>> gamestate.time = 3
>>> bee.action(gamestate) # slowed thrice
>>> bee.place.name
'tunnel_0_5'
>>> gamestate.time = 4
>>> bee.action(gamestate) # slowed twice
>>> bee.place.name
'tunnel_0_4'
>>> gamestate.time = 5
>>> bee.action(gamestate) # slowed twice
>>> bee.place.name
'tunnel_0_4'
>>> gamestate.time = 6
>>> bee.action(gamestate) # slowed once
>>> bee.place.name
'tunnel_0_3'
>>> gamestate.time = 7
>>> bee.action(gamestate) # statuses have worn off
>>> bee.place.name
'tunnel_0_2'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> scary = ScaryThrower()
>>> slow = SlowThrower()
>>> bee = Bee(3)
>>> gamestate.places["tunnel_0_0"].add_insect(scary)
>>> gamestate.places["tunnel_0_1"].add_insect(slow)
>>> gamestate.places["tunnel_0_3"].add_insect(bee)
>>> slow.action(gamestate) # slow bee
>>> scary.action(gamestate) # scare bee
>>> bee.place.name
'tunnel_0_3'
>>> gamestate.time = 0
>>> bee.action(gamestate) # scared and slowed
>>> bee.place.name
'tunnel_0_4'
>>> gamestate.time = 1
>>> bee.action(gamestate) # scared and slowed
>>> bee.place.name
'tunnel_0_4'
>>> gamestate.time = 2
>>> bee.action(gamestate) # slowed
>>> bee.place.name
'tunnel_0_3'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> from ants import *
>>> ScaryThrower.implemented
True
>>> SlowThrower.implemented
True
""",
'hidden': False,
'locked': False
}
],
'scored': True,
'setup': r"""
>>> from ants import *
>>> beehive, layout = Hive(AssaultPlan()), dry_layout
>>> dimensions = (1, 9)
>>> gamestate = GameState(None, beehive, ant_types(), layout, dimensions)
""",
'teardown': '',
'type': 'doctest'
}
]
}
| test = {'name': 'Problem EC', 'points': 2, 'suites': [{'cases': [{'code': '\n >>> # Testing status parameters\n >>> slow = SlowThrower()\n >>> scary = ScaryThrower()\n >>> SlowThrower.food_cost\n 4\n >>> ScaryThrower.food_cost\n 6\n >>> slow.armor\n 1\n >>> scary.armor\n 1\n ', 'hidden': False, 'locked': False}, {'code': '\n >>> # Testing Slow\n >>> slow = SlowThrower()\n >>> bee = Bee(3)\n >>> gamestate.places["tunnel_0_0"].add_insect(slow)\n >>> gamestate.places["tunnel_0_4"].add_insect(bee)\n >>> slow.action(gamestate)\n >>> gamestate.time = 1\n >>> bee.action(gamestate)\n >>> bee.place.name # SlowThrower should cause slowness on odd turns\n \'tunnel_0_4\'\n >>> gamestate.time += 1\n >>> bee.action(gamestate)\n >>> bee.place.name # SlowThrower should cause slowness on odd turns\n \'tunnel_0_3\'\n >>> for _ in range(3):\n ... gamestate.time += 1\n ... bee.action(gamestate)\n >>> bee.place.name\n \'tunnel_0_1\'\n ', 'hidden': False, 'locked': False}, {'code': '\n >>> # Testing Scare\n >>> scary = ScaryThrower()\n >>> bee = Bee(3)\n >>> gamestate.places["tunnel_0_0"].add_insect(scary)\n >>> gamestate.places["tunnel_0_4"].add_insect(bee)\n >>> scary.action(gamestate)\n >>> bee.action(gamestate)\n >>> bee.place.name # ScaryThrower should scare for two turns\n \'tunnel_0_5\'\n >>> bee.action(gamestate)\n >>> bee.place.name # ScaryThrower should scare for two turns\n \'tunnel_0_6\'\n >>> bee.action(gamestate)\n >>> bee.place.name\n \'tunnel_0_5\'\n ', 'hidden': False, 'locked': False}, {'code': '\n >>> # Scary stings an ant\n >>> scary = ScaryThrower()\n >>> harvester = HarvesterAnt()\n >>> bee = Bee(3)\n >>> gamestate.places["tunnel_0_0"].add_insect(scary)\n >>> gamestate.places["tunnel_0_4"].add_insect(bee)\n >>> gamestate.places["tunnel_0_5"].add_insect(harvester)\n >>> scary.action(gamestate)\n >>> bee.action(gamestate)\n >>> bee.place.name # ScaryThrower should scare for two turns\n \'tunnel_0_5\'\n >>> harvester.armor\n 1\n >>> bee.action(gamestate)\n >>> harvester.armor\n 0\n ', 'hidden': False, 'locked': False}, {'code': '\n >>> # Testing if statuses stack\n >>> slow = SlowThrower()\n >>> bee = Bee(3)\n >>> slow_place = gamestate.places["tunnel_0_0"]\n >>> bee_place = gamestate.places["tunnel_0_8"]\n >>> slow_place.add_insect(slow)\n >>> bee_place.add_insect(bee)\n >>> slow.action(gamestate) # slow bee two times\n >>> slow.action(gamestate)\n >>> gamestate.time = 1\n >>> bee.action(gamestate) # do nothing. The outer slow has 2 turns to go, the inner one still has 3 turns\n >>> bee.place.name\n \'tunnel_0_8\'\n >>> gamestate.time = 2\n >>> bee.action(gamestate) # moves forward. The outer slow has 1 turn to go, the inner one has 2 turns\n >>> bee.place.name\n \'tunnel_0_7\'\n >>> gamestate.time = 3\n >>> bee.action(gamestate) # do nothing. The outer slow has no turns left, the inner one has 2 turns\n >>> bee.place.name\n \'tunnel_0_7\'\n >>> gamestate.time = 4\n >>> bee.action(gamestate) # moves forward. The inner slow has 1 turn\n >>> bee.place.name\n \'tunnel_0_6\'\n >>> gamestate.time = 5\n >>> bee.action(gamestate) # does nothing. The inner slow has no turns\n >>> bee.place.name\n \'tunnel_0_6\'\n >>> gamestate.time = 6 # slow status have worn off\n >>> bee.action(gamestate)\n >>> bee.place.name\n \'tunnel_0_5\'\n >>> gamestate.time = 7 # slow status have worn off\n >>> bee.action(gamestate)\n >>> bee.place.name\n \'tunnel_0_4\'\n >>> gamestate.time = 8 # slow status have worn off\n >>> bee.action(gamestate)\n >>> bee.place.name\n \'tunnel_0_3\'\n ', 'hidden': False, 'locked': False}, {'code': '\n >>> # Testing multiple scared bees\n >>> scare1 = ScaryThrower()\n >>> scare2 = ScaryThrower()\n >>> bee1 = Bee(3)\n >>> bee2 = Bee(3)\n \n >>> gamestate.places["tunnel_0_0"].add_insect(scare1)\n >>> gamestate.places["tunnel_0_1"].add_insect(bee1)\n >>> gamestate.places["tunnel_0_4"].add_insect(scare2)\n >>> gamestate.places["tunnel_0_5"].add_insect(bee2)\n \n >>> scare1.action(gamestate)\n >>> scare2.action(gamestate)\n >>> bee1.action(gamestate)\n >>> bee2.action(gamestate)\n \n >>> bee1.place.name\n \'tunnel_0_2\'\n >>> bee2.place.name\n \'tunnel_0_6\'\n \n >>> bee1.action(gamestate)\n >>> bee2.action(gamestate)\n \n >>> bee1.place.name\n \'tunnel_0_3\'\n >>> bee2.place.name\n \'tunnel_0_7\'\n \n >>> bee1.action(gamestate)\n >>> bee2.action(gamestate)\n \n >>> bee1.place.name\n \'tunnel_0_2\'\n >>> bee2.place.name\n \'tunnel_0_6\'\n ', 'hidden': False, 'locked': False}, {'code': '\n >>> scare = ScaryThrower()\n >>> bee = Bee(3)\n >>> gamestate.places["tunnel_0_0"].add_insect(scare)\n >>> gamestate.places["tunnel_0_1"].add_insect(bee)\n \n >>> scare.action(gamestate)\n >>> bee.action(gamestate)\n \n >>> bee.place.name\n \'tunnel_0_2\'\n \n >>> bee.action(gamestate)\n \n >>> bee.place.name\n \'tunnel_0_3\'\n \n >>> #\n >>> # Same bee should not be scared more than once\n >>> scare.action(gamestate)\n >>> bee.action(gamestate)\n \n >>> bee.place.name\n \'tunnel_0_2\'\n ', 'hidden': False, 'locked': False}, {'code': '\n >>> # Testing long status stack\n >>> scary = ScaryThrower()\n >>> slow = SlowThrower()\n >>> bee = Bee(3)\n >>> gamestate.places["tunnel_0_0"].add_insect(scary)\n >>> gamestate.places["tunnel_0_1"].add_insect(slow)\n >>> gamestate.places["tunnel_0_3"].add_insect(bee)\n \n >>> scary.action(gamestate) # scare bee once\n \n >>> gamestate.time = 0\n >>> bee.action(gamestate) # scared\n >>> bee.place.name\n \'tunnel_0_4\'\n \n >>> for _ in range(3): # slow bee three times\n ... slow.action(gamestate)\n \n >>> gamestate.time = 1\n >>> bee.action(gamestate) # scared, but also slowed thrice\n >>> bee.place.name\n \'tunnel_0_4\'\n \n >>> gamestate.time = 2\n >>> bee.action(gamestate) # scared and slowed thrice\n >>> bee.place.name\n \'tunnel_0_5\'\n \n >>> gamestate.time = 3\n >>> bee.action(gamestate) # slowed thrice\n >>> bee.place.name\n \'tunnel_0_5\'\n \n >>> gamestate.time = 4\n >>> bee.action(gamestate) # slowed twice\n >>> bee.place.name\n \'tunnel_0_4\'\n \n >>> gamestate.time = 5\n >>> bee.action(gamestate) # slowed twice\n >>> bee.place.name\n \'tunnel_0_4\'\n \n >>> gamestate.time = 6\n >>> bee.action(gamestate) # slowed once\n >>> bee.place.name\n \'tunnel_0_3\'\n \n >>> gamestate.time = 7\n >>> bee.action(gamestate) # statuses have worn off\n >>> bee.place.name\n \'tunnel_0_2\'\n ', 'hidden': False, 'locked': False}, {'code': '\n >>> scary = ScaryThrower()\n >>> slow = SlowThrower()\n >>> bee = Bee(3)\n >>> gamestate.places["tunnel_0_0"].add_insect(scary)\n >>> gamestate.places["tunnel_0_1"].add_insect(slow)\n >>> gamestate.places["tunnel_0_3"].add_insect(bee)\n \n >>> slow.action(gamestate) # slow bee\n >>> scary.action(gamestate) # scare bee\n \n >>> bee.place.name\n \'tunnel_0_3\'\n \n >>> gamestate.time = 0\n >>> bee.action(gamestate) # scared and slowed\n >>> bee.place.name\n \'tunnel_0_4\'\n \n >>> gamestate.time = 1\n >>> bee.action(gamestate) # scared and slowed\n >>> bee.place.name\n \'tunnel_0_4\'\n \n >>> gamestate.time = 2\n >>> bee.action(gamestate) # slowed\n >>> bee.place.name\n \'tunnel_0_3\'\n ', 'hidden': False, 'locked': False}, {'code': '\n >>> from ants import *\n >>> ScaryThrower.implemented\n True\n >>> SlowThrower.implemented\n True\n ', 'hidden': False, 'locked': False}], 'scored': True, 'setup': '\n >>> from ants import *\n >>> beehive, layout = Hive(AssaultPlan()), dry_layout\n >>> dimensions = (1, 9)\n >>> gamestate = GameState(None, beehive, ant_types(), layout, dimensions)\n ', 'teardown': '', 'type': 'doctest'}]} |
# Copyright 2017 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
DEPS = [
'chromium',
'chromium_android',
'depot_tools/bot_update',
'depot_tools/gclient',
]
def RunSteps(api):
api.gclient.set_config('chromium')
api.chromium.set_config('chromium')
update_step = api.bot_update.ensure_checkout()
api.chromium_android.upload_apks_for_bisect(
update_properties=update_step.json.output['properties'],
bucket='test-bucket',
path='test/%s/path')
def GenTests(api):
yield api.test('basic')
| deps = ['chromium', 'chromium_android', 'depot_tools/bot_update', 'depot_tools/gclient']
def run_steps(api):
api.gclient.set_config('chromium')
api.chromium.set_config('chromium')
update_step = api.bot_update.ensure_checkout()
api.chromium_android.upload_apks_for_bisect(update_properties=update_step.json.output['properties'], bucket='test-bucket', path='test/%s/path')
def gen_tests(api):
yield api.test('basic') |
# class Tree:
# def __init__(self, val, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def solve(self, root):
if root:
root.left, root.right = self.solve(root.right), self.solve(root.left)
return root
| class Solution:
def solve(self, root):
if root:
(root.left, root.right) = (self.solve(root.right), self.solve(root.left))
return root |
products = ['bread','meat','egg','cheese']
file1 = open('products.txt','w')
for product in products:
file1.write(product+'\n')
file1.close()
file2= open('products.txt')
var = file2.readlines()
print(var)
| products = ['bread', 'meat', 'egg', 'cheese']
file1 = open('products.txt', 'w')
for product in products:
file1.write(product + '\n')
file1.close()
file2 = open('products.txt')
var = file2.readlines()
print(var) |
class Layer(object):
def __init__(self):
self.prevlayer = None
self.nextlayer = None
def forepropagation(self):
pass
def backpropagation(self):
pass
def initialization(self):
pass
| class Layer(object):
def __init__(self):
self.prevlayer = None
self.nextlayer = None
def forepropagation(self):
pass
def backpropagation(self):
pass
def initialization(self):
pass |
def collapse_sequences(message, collapse_char, collapsing = False):
if message == '':
return ''
# Approach 1:
prepend = message[0]
if prepend == collapse_char:
if collapsing:
prepend = ''
collapsing = True
else:
collapsing = False
return prepend + collapse_sequences(message[1:], collapse_char, collapsing)
# Approach 2:
# c = message[0]
# if c == collapse_char:
# if collapsing:
# return collapse_sequences(message[1:], collapse_char, True)
# else:
# return c + collapse_sequences(message[1:], collapse_char, True)
# return c + collapse_sequences(message[1:], collapse_char, False)
def main():
print(collapse_sequences("aabaaccaaaaaada", 'a'))
if __name__ == '__main__':
main() | def collapse_sequences(message, collapse_char, collapsing=False):
if message == '':
return ''
prepend = message[0]
if prepend == collapse_char:
if collapsing:
prepend = ''
collapsing = True
else:
collapsing = False
return prepend + collapse_sequences(message[1:], collapse_char, collapsing)
def main():
print(collapse_sequences('aabaaccaaaaaada', 'a'))
if __name__ == '__main__':
main() |
class Solution:
def threeSumClosest(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
minval=100000
nums.sort()
for i in range(len(nums)):
#if i>0 and num[i]==num[i-1]:
# continue
left=i+1
right=len(nums)-1
while left<right:
val=nums[i]+nums[left]+nums[right]
if abs(val-target)<minval:
minval=abs(val-target)
result=val
if val==target:
return target
if val<=target:
left+=1
else:
right-=1
return result
| class Solution:
def three_sum_closest(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
minval = 100000
nums.sort()
for i in range(len(nums)):
left = i + 1
right = len(nums) - 1
while left < right:
val = nums[i] + nums[left] + nums[right]
if abs(val - target) < minval:
minval = abs(val - target)
result = val
if val == target:
return target
if val <= target:
left += 1
else:
right -= 1
return result |
# Zombie Damage Skin
success = sm.addDamageSkin(2434661)
if success:
sm.chat("The Zombie Damage Skin has been added to your account's damage skin collection.")
| success = sm.addDamageSkin(2434661)
if success:
sm.chat("The Zombie Damage Skin has been added to your account's damage skin collection.") |
#
# Copyright (C) 2013 Google Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
{
'includes': [
'../build/features.gypi',
'../build/scripts/scripts.gypi',
'../build/win/precompile.gypi',
'blink_platform.gypi',
'heap/blink_heap.gypi',
],
'targets': [{
'target_name': 'blink_common',
'type': '<(component)',
'variables': { 'enable_wexit_time_destructors': 1 },
'dependencies': [
'../config.gyp:config',
'../wtf/wtf.gyp:wtf',
# FIXME: Can we remove the dependency on Skia?
'<(DEPTH)/skia/skia.gyp:skia',
],
'all_dependent_settings': {
'include_dirs': [
'..',
],
},
'export_dependent_settings': [
'<(DEPTH)/skia/skia.gyp:skia',
],
'defines': [
'BLINK_COMMON_IMPLEMENTATION=1',
'INSIDE_BLINK',
],
'include_dirs': [
'<(SHARED_INTERMEDIATE_DIR)/blink',
],
'sources': [
'exported/WebCString.cpp',
'exported/WebString.cpp',
'exported/WebCommon.cpp',
],
},
{
'target_name': 'blink_heap_asm_stubs',
'type': 'static_library',
# VS2010 does not correctly incrementally link obj files generated
# from asm files. This flag disables UseLibraryDependencyInputs to
# avoid this problem.
'msvs_2010_disable_uldi_when_referenced': 1,
'includes': [
'../../../yasm/yasm_compile.gypi',
],
'sources': [
'<@(platform_heap_asm_files)',
],
'variables': {
'more_yasm_flags': [],
'conditions': [
['OS == "mac"', {
'more_yasm_flags': [
# Necessary to ensure symbols end up with a _ prefix; added by
# yasm_compile.gypi for Windows, but not Mac.
'-DPREFIX',
],
}],
['OS == "win" and target_arch == "x64"', {
'more_yasm_flags': [
'-DX64WIN=1',
],
}],
['OS != "win" and target_arch == "x64"', {
'more_yasm_flags': [
'-DX64POSIX=1',
],
}],
['target_arch == "ia32"', {
'more_yasm_flags': [
'-DIA32=1',
],
}],
['target_arch == "arm"', {
'more_yasm_flags': [
'-DARM=1',
],
}],
],
'yasm_flags': [
'>@(more_yasm_flags)',
],
'yasm_output_path': '<(SHARED_INTERMEDIATE_DIR)/webcore/heap'
},
},
{
'target_name': 'blink_prerequisites',
'type': 'none',
'conditions': [
['OS=="mac"', {
'direct_dependent_settings': {
'defines': [
# Chromium's version of WebCore includes the following Objective-C
# classes. The system-provided WebCore framework may also provide
# these classes. Because of the nature of Objective-C binding
# (dynamically at runtime), it's possible for the
# Chromium-provided versions to interfere with the system-provided
# versions. This may happen when a system framework attempts to
# use core.framework, such as when converting an HTML-flavored
# string to an NSAttributedString. The solution is to force
# Objective-C class names that would conflict to use alternate
# names.
#
# This list will hopefully shrink but may also grow. Its
# performance is monitored by the "Check Objective-C Rename"
# postbuild step, and any suspicious-looking symbols not handled
# here or whitelisted in that step will cause a build failure.
#
# If this is unhandled, the console will receive log messages
# such as:
# com.google.Chrome[] objc[]: Class ScrollbarPrefsObserver is implemented in both .../Google Chrome.app/Contents/Versions/.../Google Chrome Helper.app/Contents/MacOS/../../../Google Chrome Framework.framework/Google Chrome Framework and /System/Library/Frameworks/WebKit.framework/Versions/A/Frameworks/WebCore.framework/Versions/A/WebCore. One of the two will be used. Which one is undefined.
'WebCascadeList=ChromiumWebCoreObjCWebCascadeList',
'WebScrollAnimationHelperDelegate=ChromiumWebCoreObjCWebScrollAnimationHelperDelegate',
'WebScrollbarPainterControllerDelegate=ChromiumWebCoreObjCWebScrollbarPainterControllerDelegate',
'WebScrollbarPainterDelegate=ChromiumWebCoreObjCWebScrollbarPainterDelegate',
'WebScrollbarPartAnimation=ChromiumWebCoreObjCWebScrollbarPartAnimation',
'WebCoreFlippedView=ChromiumWebCoreObjCWebCoreFlippedView',
'WebCoreTextFieldCell=ChromiumWebCoreObjCWebCoreTextFieldCell',
],
'postbuilds': [
{
# This step ensures that any Objective-C names that aren't
# redefined to be "safe" above will cause a build failure.
'postbuild_name': 'Check Objective-C Rename',
'variables': {
'class_whitelist_regex':
'ChromiumWebCoreObjC|TCMVisibleView|RTCMFlippedView|ScrollerStyleObserver|LayoutThemeNotificationObserver',
'category_whitelist_regex':
'WebCoreFocusRingDrawing|WebCoreTheme',
},
'action': [
'../build/scripts/check_objc_rename.sh',
'<(class_whitelist_regex)',
'<(category_whitelist_regex)',
],
},
],
},
}],
],
},
{
'target_name': 'blink_platform',
'type': '<(component)',
'dependencies': [
'../config.gyp:config',
'../wtf/wtf.gyp:wtf',
'blink_common',
'blink_heap_asm_stubs',
'blink_prerequisites',
'<(DEPTH)/gpu/gpu.gyp:gles2_c_lib',
'<(DEPTH)/skia/skia.gyp:skia',
'<(DEPTH)/third_party/icu/icu.gyp:icui18n',
'<(DEPTH)/third_party/icu/icu.gyp:icuuc',
'<(DEPTH)/third_party/libpng/libpng.gyp:libpng',
'<(DEPTH)/third_party/libwebp/libwebp.gyp:libwebp',
'<(DEPTH)/third_party/ots/ots.gyp:ots',
'<(DEPTH)/third_party/qcms/qcms.gyp:qcms',
'<(DEPTH)/url/url.gyp:url_lib',
'<(DEPTH)/v8/tools/gyp/v8.gyp:v8',
'platform_generated.gyp:make_platform_generated',
'<(DEPTH)/third_party/iccjpeg/iccjpeg.gyp:iccjpeg',
'<(libjpeg_gyp_path):libjpeg',
],
'export_dependent_settings': [
'<(DEPTH)/gpu/gpu.gyp:gles2_c_lib',
'<(DEPTH)/skia/skia.gyp:skia',
'<(DEPTH)/third_party/libpng/libpng.gyp:libpng',
'<(DEPTH)/third_party/libwebp/libwebp.gyp:libwebp',
'<(DEPTH)/third_party/ots/ots.gyp:ots',
'<(DEPTH)/third_party/qcms/qcms.gyp:qcms',
'<(DEPTH)/v8/tools/gyp/v8.gyp:v8',
'<(DEPTH)/url/url.gyp:url_lib',
'<(DEPTH)/third_party/iccjpeg/iccjpeg.gyp:iccjpeg',
'<(libjpeg_gyp_path):libjpeg',
],
'defines': [
'BLINK_PLATFORM_IMPLEMENTATION=1',
'INSIDE_BLINK',
],
'include_dirs': [
'<(angle_path)/include',
'<(SHARED_INTERMEDIATE_DIR)/blink',
],
'xcode_settings': {
# Some Mac-specific parts of WebKit won't compile without having this
# prefix header injected.
'GCC_PREFIX_HEADER': '<(DEPTH)/third_party/WebKit/Source/build/mac/Prefix.h',
},
'sources': [
'<@(platform_files)',
'<@(platform_heap_files)',
# Additional .cpp files from platform_generated.gyp:make_platform_generated actions.
'<(blink_platform_output_dir)/FontFamilyNames.cpp',
'<(blink_platform_output_dir)/RuntimeEnabledFeatures.cpp',
'<(blink_platform_output_dir)/RuntimeEnabledFeatures.h',
'<(blink_platform_output_dir)/ColorData.cpp',
],
'sources/': [
# Exclude all platform specific things, reinclude them below on a per-platform basis
# FIXME: Figure out how to store these patterns in a variable.
['exclude', '(cf|cg|mac|opentype|win)/'],
['exclude', '(?<!Chromium)(CF|CG|Mac|Win)\\.(cpp|mm?)$'],
# *NEON.cpp files need special compile options.
# They are moved to the webcore_0_neon target.
['exclude', 'graphics/cpu/arm/.*NEON\\.(cpp|h)'],
['exclude', 'graphics/cpu/arm/filters/.*NEON\\.(cpp|h)'],
],
# Disable c4267 warnings until we fix size_t to int truncations.
# Disable c4724 warnings which is generated in VS2012 due to improper
# compiler optimizations, see crbug.com/237063
'msvs_disabled_warnings': [ 4267, 4334, 4724 ],
'conditions': [
['OS=="linux" or OS=="android" or OS=="win"', {
'sources/': [
# Cherry-pick files excluded by the broader regular expressions above.
['include', 'fonts/opentype/OpenTypeTypes\\.h$'],
['include', 'fonts/opentype/OpenTypeVerticalData\\.(cpp|h)$'],
],
'dependencies': [
'<(DEPTH)/third_party/harfbuzz-ng/harfbuzz.gyp:harfbuzz-ng',
],
},
],
['OS=="linux" or OS=="android"', {
'sources/': [
['include', 'fonts/linux/FontPlatformDataLinux\\.cpp$'],
]
}, { # OS!="linux" and OS!="android"
'sources/': [
['exclude', 'fonts/linux/FontPlatformDataLinux\\.cpp$'],
]
}],
['OS=="mac"', {
'dependencies': [
'<(DEPTH)/third_party/harfbuzz-ng/harfbuzz.gyp:harfbuzz-ng',
],
'link_settings': {
'libraries': [
'$(SDKROOT)/System/Library/Frameworks/Accelerate.framework',
'$(SDKROOT)/System/Library/Frameworks/Carbon.framework',
'$(SDKROOT)/System/Library/Frameworks/Foundation.framework',
]
},
'sources/': [
# We use LocaleMac.mm instead of LocaleICU.cpp
['exclude', 'text/LocaleICU\\.(cpp|h)$'],
['include', 'text/LocaleMac\\.mm$'],
# The Mac uses mac/KillRingMac.mm instead of the dummy
# implementation.
['exclude', 'KillRingNone\\.cpp$'],
# The Mac build is USE(CF).
['include', 'CF\\.cpp$'],
# Use native Mac font code from core.
['include', '(fonts/)?mac/[^/]*Font[^/]*\\.(cpp|mm?)$'],
# TODO(dro): Merge the opentype vertical data files inclusion across all platforms.
['include', 'fonts/opentype/OpenTypeTypes\\.h$'],
['include', 'fonts/opentype/OpenTypeVerticalData\\.(cpp|h)$'],
# Cherry-pick some files that can't be included by broader regexps.
# Some of these are used instead of Chromium platform files, see
# the specific exclusions in the "exclude" list below.
['include', 'audio/mac/FFTFrameMac\\.cpp$'],
['include', 'fonts/mac/GlyphPageTreeNodeMac\\.cpp$'],
['include', 'mac/ColorMac\\.mm$'],
['include', 'mac/BlockExceptions\\.mm$'],
['include', 'mac/KillRingMac\\.mm$'],
['include', 'mac/LocalCurrentGraphicsContext\\.mm$'],
['include', 'mac/NSScrollerImpDetails\\.mm$'],
['include', 'mac/ScrollAnimatorMac\\.mm$'],
['include', 'mac/ThemeMac\\.h$'],
['include', 'mac/ThemeMac\\.mm$'],
['include', 'mac/WebCoreNSCellExtras\\.h$'],
['include', 'mac/WebCoreNSCellExtras\\.mm$'],
# Mac uses only ScrollAnimatorMac.
['exclude', 'scroll/ScrollbarThemeNonMacCommon\\.(cpp|h)$'],
['exclude', 'scroll/ScrollAnimatorNone\\.cpp$'],
['exclude', 'scroll/ScrollAnimatorNone\\.h$'],
['exclude', 'fonts/skia/FontCacheSkia\\.cpp$'],
['include', 'geometry/mac/FloatPointMac\\.mm$'],
['include', 'geometry/mac/FloatRectMac\\.mm$'],
['include', 'geometry/mac/FloatSizeMac\\.mm$'],
['include', 'geometry/mac/IntPointMac\\.mm$'],
['include', 'geometry/mac/IntRectMac\\.mm$'],
['include', 'geometry/cg/FloatPointCG\\.cpp$'],
['include', 'geometry/cg/FloatRectCG\\.cpp$'],
['include', 'geometry/cg/FloatSizeCG\\.cpp$'],
['include', 'geometry/cg/IntPointCG\\.cpp$'],
['include', 'geometry/cg/IntRectCG\\.cpp$'],
['include', 'geometry/cg/IntSizeCG\\.cpp$'],
],
}, { # OS!="mac"
'sources/': [
['exclude', 'mac/'],
['exclude', 'geometry/mac/'],
['exclude', 'geometry/cg/'],
['exclude', 'scroll/ScrollbarThemeMac'],
],
}],
['OS != "linux" and OS != "mac" and OS != "win"', {
'sources/': [
['exclude', 'VDMX[^/]+\\.(cpp|h)$'],
],
}],
['OS=="win"', {
'sources/': [
# We use LocaleWin.cpp instead of LocaleICU.cpp
['exclude', 'text/LocaleICU\\.(cpp|h)$'],
['include', 'text/LocaleWin\\.(cpp|h)$'],
['include', 'clipboard/ClipboardUtilitiesWin\\.(cpp|h)$'],
['include', 'fonts/opentype/'],
['include', 'fonts/win/FontCacheSkiaWin\\.cpp$'],
['include', 'fonts/win/FontFallbackWin\\.(cpp|h)$'],
['include', 'fonts/win/FontPlatformDataWin\\.cpp$'],
# SystemInfo.cpp is useful and we don't want to copy it.
['include', 'win/SystemInfo\\.cpp$'],
],
}, { # OS!="win"
'sources/': [
['exclude', 'win/'],
['exclude', 'Win\\.cpp$'],
['exclude', '/(Windows)[^/]*\\.cpp$'],
['include', 'fonts/opentype/OpenTypeSanitizer\\.cpp$'],
],
}],
['OS=="win" and chromium_win_pch==1', {
'sources/': [
['include', '<(DEPTH)/third_party/WebKit/Source/build/win/Precompile.cpp'],
],
}],
['OS=="android"', {
'sources/': [
['include', '^fonts/VDMXParser\\.cpp$'],
],
}, { # OS!="android"
'sources/': [
['exclude', 'Android\\.cpp$'],
],
}],
['OS=="linux"', {
'dependencies': [
'<(DEPTH)/build/linux/system.gyp:fontconfig',
],
'export_dependent_settings': [
'<(DEPTH)/build/linux/system.gyp:fontconfig',
],
}],
['use_default_render_theme==0', {
'sources/': [
['exclude', 'scroll/ScrollbarThemeAura\\.(cpp|h)'],
],
}],
['"WTF_USE_WEBAUDIO_FFMPEG=1" in feature_defines', {
'include_dirs': [
'<(DEPTH)/third_party/ffmpeg',
],
'dependencies': [
'<(DEPTH)/third_party/ffmpeg/ffmpeg.gyp:ffmpeg',
],
}],
['"WTF_USE_WEBAUDIO_OPENMAX_DL_FFT=1" in feature_defines', {
'include_dirs': [
'<(DEPTH)/third_party/openmax_dl',
],
'dependencies': [
'<(DEPTH)/third_party/openmax_dl/dl/dl.gyp:openmax_dl',
],
}],
['target_arch=="arm"', {
'dependencies': [
'blink_arm_neon',
],
}],
],
'target_conditions': [
['OS=="android"', {
'sources/': [
['include', 'exported/linux/WebFontRenderStyle\\.cpp$'],
['include', 'fonts/linux/FontPlatformDataLinux\\.cpp$'],
],
}],
],
},
# The *NEON.cpp files fail to compile when -mthumb is passed. Force
# them to build in ARM mode.
# See https://bugs.webkit.org/show_bug.cgi?id=62916.
{
'target_name': 'blink_arm_neon',
'conditions': [
['target_arch=="arm"', {
'type': 'static_library',
'dependencies': [
'blink_common',
],
'hard_dependency': 1,
'sources': [
'<@(platform_files)',
],
'sources/': [
['exclude', '.*'],
['include', 'graphics/cpu/arm/filters/.*NEON\\.(cpp|h)'],
],
'cflags': ['-marm'],
'conditions': [
['OS=="android"', {
'cflags!': ['-mthumb'],
}],
],
},{ # target_arch!="arm"
'type': 'none',
}],
],
}],
}
| {'includes': ['../build/features.gypi', '../build/scripts/scripts.gypi', '../build/win/precompile.gypi', 'blink_platform.gypi', 'heap/blink_heap.gypi'], 'targets': [{'target_name': 'blink_common', 'type': '<(component)', 'variables': {'enable_wexit_time_destructors': 1}, 'dependencies': ['../config.gyp:config', '../wtf/wtf.gyp:wtf', '<(DEPTH)/skia/skia.gyp:skia'], 'all_dependent_settings': {'include_dirs': ['..']}, 'export_dependent_settings': ['<(DEPTH)/skia/skia.gyp:skia'], 'defines': ['BLINK_COMMON_IMPLEMENTATION=1', 'INSIDE_BLINK'], 'include_dirs': ['<(SHARED_INTERMEDIATE_DIR)/blink'], 'sources': ['exported/WebCString.cpp', 'exported/WebString.cpp', 'exported/WebCommon.cpp']}, {'target_name': 'blink_heap_asm_stubs', 'type': 'static_library', 'msvs_2010_disable_uldi_when_referenced': 1, 'includes': ['../../../yasm/yasm_compile.gypi'], 'sources': ['<@(platform_heap_asm_files)'], 'variables': {'more_yasm_flags': [], 'conditions': [['OS == "mac"', {'more_yasm_flags': ['-DPREFIX']}], ['OS == "win" and target_arch == "x64"', {'more_yasm_flags': ['-DX64WIN=1']}], ['OS != "win" and target_arch == "x64"', {'more_yasm_flags': ['-DX64POSIX=1']}], ['target_arch == "ia32"', {'more_yasm_flags': ['-DIA32=1']}], ['target_arch == "arm"', {'more_yasm_flags': ['-DARM=1']}]], 'yasm_flags': ['>@(more_yasm_flags)'], 'yasm_output_path': '<(SHARED_INTERMEDIATE_DIR)/webcore/heap'}}, {'target_name': 'blink_prerequisites', 'type': 'none', 'conditions': [['OS=="mac"', {'direct_dependent_settings': {'defines': ['WebCascadeList=ChromiumWebCoreObjCWebCascadeList', 'WebScrollAnimationHelperDelegate=ChromiumWebCoreObjCWebScrollAnimationHelperDelegate', 'WebScrollbarPainterControllerDelegate=ChromiumWebCoreObjCWebScrollbarPainterControllerDelegate', 'WebScrollbarPainterDelegate=ChromiumWebCoreObjCWebScrollbarPainterDelegate', 'WebScrollbarPartAnimation=ChromiumWebCoreObjCWebScrollbarPartAnimation', 'WebCoreFlippedView=ChromiumWebCoreObjCWebCoreFlippedView', 'WebCoreTextFieldCell=ChromiumWebCoreObjCWebCoreTextFieldCell'], 'postbuilds': [{'postbuild_name': 'Check Objective-C Rename', 'variables': {'class_whitelist_regex': 'ChromiumWebCoreObjC|TCMVisibleView|RTCMFlippedView|ScrollerStyleObserver|LayoutThemeNotificationObserver', 'category_whitelist_regex': 'WebCoreFocusRingDrawing|WebCoreTheme'}, 'action': ['../build/scripts/check_objc_rename.sh', '<(class_whitelist_regex)', '<(category_whitelist_regex)']}]}}]]}, {'target_name': 'blink_platform', 'type': '<(component)', 'dependencies': ['../config.gyp:config', '../wtf/wtf.gyp:wtf', 'blink_common', 'blink_heap_asm_stubs', 'blink_prerequisites', '<(DEPTH)/gpu/gpu.gyp:gles2_c_lib', '<(DEPTH)/skia/skia.gyp:skia', '<(DEPTH)/third_party/icu/icu.gyp:icui18n', '<(DEPTH)/third_party/icu/icu.gyp:icuuc', '<(DEPTH)/third_party/libpng/libpng.gyp:libpng', '<(DEPTH)/third_party/libwebp/libwebp.gyp:libwebp', '<(DEPTH)/third_party/ots/ots.gyp:ots', '<(DEPTH)/third_party/qcms/qcms.gyp:qcms', '<(DEPTH)/url/url.gyp:url_lib', '<(DEPTH)/v8/tools/gyp/v8.gyp:v8', 'platform_generated.gyp:make_platform_generated', '<(DEPTH)/third_party/iccjpeg/iccjpeg.gyp:iccjpeg', '<(libjpeg_gyp_path):libjpeg'], 'export_dependent_settings': ['<(DEPTH)/gpu/gpu.gyp:gles2_c_lib', '<(DEPTH)/skia/skia.gyp:skia', '<(DEPTH)/third_party/libpng/libpng.gyp:libpng', '<(DEPTH)/third_party/libwebp/libwebp.gyp:libwebp', '<(DEPTH)/third_party/ots/ots.gyp:ots', '<(DEPTH)/third_party/qcms/qcms.gyp:qcms', '<(DEPTH)/v8/tools/gyp/v8.gyp:v8', '<(DEPTH)/url/url.gyp:url_lib', '<(DEPTH)/third_party/iccjpeg/iccjpeg.gyp:iccjpeg', '<(libjpeg_gyp_path):libjpeg'], 'defines': ['BLINK_PLATFORM_IMPLEMENTATION=1', 'INSIDE_BLINK'], 'include_dirs': ['<(angle_path)/include', '<(SHARED_INTERMEDIATE_DIR)/blink'], 'xcode_settings': {'GCC_PREFIX_HEADER': '<(DEPTH)/third_party/WebKit/Source/build/mac/Prefix.h'}, 'sources': ['<@(platform_files)', '<@(platform_heap_files)', '<(blink_platform_output_dir)/FontFamilyNames.cpp', '<(blink_platform_output_dir)/RuntimeEnabledFeatures.cpp', '<(blink_platform_output_dir)/RuntimeEnabledFeatures.h', '<(blink_platform_output_dir)/ColorData.cpp'], 'sources/': [['exclude', '(cf|cg|mac|opentype|win)/'], ['exclude', '(?<!Chromium)(CF|CG|Mac|Win)\\.(cpp|mm?)$'], ['exclude', 'graphics/cpu/arm/.*NEON\\.(cpp|h)'], ['exclude', 'graphics/cpu/arm/filters/.*NEON\\.(cpp|h)']], 'msvs_disabled_warnings': [4267, 4334, 4724], 'conditions': [['OS=="linux" or OS=="android" or OS=="win"', {'sources/': [['include', 'fonts/opentype/OpenTypeTypes\\.h$'], ['include', 'fonts/opentype/OpenTypeVerticalData\\.(cpp|h)$']], 'dependencies': ['<(DEPTH)/third_party/harfbuzz-ng/harfbuzz.gyp:harfbuzz-ng']}], ['OS=="linux" or OS=="android"', {'sources/': [['include', 'fonts/linux/FontPlatformDataLinux\\.cpp$']]}, {'sources/': [['exclude', 'fonts/linux/FontPlatformDataLinux\\.cpp$']]}], ['OS=="mac"', {'dependencies': ['<(DEPTH)/third_party/harfbuzz-ng/harfbuzz.gyp:harfbuzz-ng'], 'link_settings': {'libraries': ['$(SDKROOT)/System/Library/Frameworks/Accelerate.framework', '$(SDKROOT)/System/Library/Frameworks/Carbon.framework', '$(SDKROOT)/System/Library/Frameworks/Foundation.framework']}, 'sources/': [['exclude', 'text/LocaleICU\\.(cpp|h)$'], ['include', 'text/LocaleMac\\.mm$'], ['exclude', 'KillRingNone\\.cpp$'], ['include', 'CF\\.cpp$'], ['include', '(fonts/)?mac/[^/]*Font[^/]*\\.(cpp|mm?)$'], ['include', 'fonts/opentype/OpenTypeTypes\\.h$'], ['include', 'fonts/opentype/OpenTypeVerticalData\\.(cpp|h)$'], ['include', 'audio/mac/FFTFrameMac\\.cpp$'], ['include', 'fonts/mac/GlyphPageTreeNodeMac\\.cpp$'], ['include', 'mac/ColorMac\\.mm$'], ['include', 'mac/BlockExceptions\\.mm$'], ['include', 'mac/KillRingMac\\.mm$'], ['include', 'mac/LocalCurrentGraphicsContext\\.mm$'], ['include', 'mac/NSScrollerImpDetails\\.mm$'], ['include', 'mac/ScrollAnimatorMac\\.mm$'], ['include', 'mac/ThemeMac\\.h$'], ['include', 'mac/ThemeMac\\.mm$'], ['include', 'mac/WebCoreNSCellExtras\\.h$'], ['include', 'mac/WebCoreNSCellExtras\\.mm$'], ['exclude', 'scroll/ScrollbarThemeNonMacCommon\\.(cpp|h)$'], ['exclude', 'scroll/ScrollAnimatorNone\\.cpp$'], ['exclude', 'scroll/ScrollAnimatorNone\\.h$'], ['exclude', 'fonts/skia/FontCacheSkia\\.cpp$'], ['include', 'geometry/mac/FloatPointMac\\.mm$'], ['include', 'geometry/mac/FloatRectMac\\.mm$'], ['include', 'geometry/mac/FloatSizeMac\\.mm$'], ['include', 'geometry/mac/IntPointMac\\.mm$'], ['include', 'geometry/mac/IntRectMac\\.mm$'], ['include', 'geometry/cg/FloatPointCG\\.cpp$'], ['include', 'geometry/cg/FloatRectCG\\.cpp$'], ['include', 'geometry/cg/FloatSizeCG\\.cpp$'], ['include', 'geometry/cg/IntPointCG\\.cpp$'], ['include', 'geometry/cg/IntRectCG\\.cpp$'], ['include', 'geometry/cg/IntSizeCG\\.cpp$']]}, {'sources/': [['exclude', 'mac/'], ['exclude', 'geometry/mac/'], ['exclude', 'geometry/cg/'], ['exclude', 'scroll/ScrollbarThemeMac']]}], ['OS != "linux" and OS != "mac" and OS != "win"', {'sources/': [['exclude', 'VDMX[^/]+\\.(cpp|h)$']]}], ['OS=="win"', {'sources/': [['exclude', 'text/LocaleICU\\.(cpp|h)$'], ['include', 'text/LocaleWin\\.(cpp|h)$'], ['include', 'clipboard/ClipboardUtilitiesWin\\.(cpp|h)$'], ['include', 'fonts/opentype/'], ['include', 'fonts/win/FontCacheSkiaWin\\.cpp$'], ['include', 'fonts/win/FontFallbackWin\\.(cpp|h)$'], ['include', 'fonts/win/FontPlatformDataWin\\.cpp$'], ['include', 'win/SystemInfo\\.cpp$']]}, {'sources/': [['exclude', 'win/'], ['exclude', 'Win\\.cpp$'], ['exclude', '/(Windows)[^/]*\\.cpp$'], ['include', 'fonts/opentype/OpenTypeSanitizer\\.cpp$']]}], ['OS=="win" and chromium_win_pch==1', {'sources/': [['include', '<(DEPTH)/third_party/WebKit/Source/build/win/Precompile.cpp']]}], ['OS=="android"', {'sources/': [['include', '^fonts/VDMXParser\\.cpp$']]}, {'sources/': [['exclude', 'Android\\.cpp$']]}], ['OS=="linux"', {'dependencies': ['<(DEPTH)/build/linux/system.gyp:fontconfig'], 'export_dependent_settings': ['<(DEPTH)/build/linux/system.gyp:fontconfig']}], ['use_default_render_theme==0', {'sources/': [['exclude', 'scroll/ScrollbarThemeAura\\.(cpp|h)']]}], ['"WTF_USE_WEBAUDIO_FFMPEG=1" in feature_defines', {'include_dirs': ['<(DEPTH)/third_party/ffmpeg'], 'dependencies': ['<(DEPTH)/third_party/ffmpeg/ffmpeg.gyp:ffmpeg']}], ['"WTF_USE_WEBAUDIO_OPENMAX_DL_FFT=1" in feature_defines', {'include_dirs': ['<(DEPTH)/third_party/openmax_dl'], 'dependencies': ['<(DEPTH)/third_party/openmax_dl/dl/dl.gyp:openmax_dl']}], ['target_arch=="arm"', {'dependencies': ['blink_arm_neon']}]], 'target_conditions': [['OS=="android"', {'sources/': [['include', 'exported/linux/WebFontRenderStyle\\.cpp$'], ['include', 'fonts/linux/FontPlatformDataLinux\\.cpp$']]}]]}, {'target_name': 'blink_arm_neon', 'conditions': [['target_arch=="arm"', {'type': 'static_library', 'dependencies': ['blink_common'], 'hard_dependency': 1, 'sources': ['<@(platform_files)'], 'sources/': [['exclude', '.*'], ['include', 'graphics/cpu/arm/filters/.*NEON\\.(cpp|h)']], 'cflags': ['-marm'], 'conditions': [['OS=="android"', {'cflags!': ['-mthumb']}]]}, {'type': 'none'}]]}]} |
def poscode2word(pos):
tag_des = {
'CC': 'Coordinating conjunction',
'CD': 'Cardinal number',
'DT': 'Determiner',
'EX': 'Existential',
'FW': 'Foreign word',
'IN': 'Preposition',
'JJ': 'Adjective',
'JJR': 'Adjective, comparative',
'JJS': 'Adjective, superlative',
'LS': 'List item maker',
'MD': 'Modal',
'NN': 'Noun, sigular',
'NNS': 'Noun, plural',
'NNP': 'Proper noun, singular',
'NNPS': 'Proper noun, plural',
'PDT': 'Predeterminer',
'POS': 'Possessive ending',
'PRP': 'Personal pronoun',
'PRP$': 'Possessive pronoun',
'RB': 'Adverb',
'RBR': 'Adverb, comparative',
'RBS': 'Adverb, superlative',
'RP': 'Particle',
'SYM': 'Symbol',
'TO': 'to',
'UH': 'Interjection',
'VB': 'Verb, base form',
'VBD': 'Verb, past tense',
'VBG': 'Verb, gerund or present participle',
'VBP': 'Verb, non-3rd person singular present',
'VBZ': 'Verb, 3rd person singular present',
'WDT': 'Wh-determiner',
'WP': 'Wh-pronoun',
'WP$': 'Possessive wh-pronoun',
'WRB': 'Wh-adverb'
}
if pos in tag_des:
return tag_des[pos]
return pos
if __name__ == "__main__":
print(poscode2word('NN'))
| def poscode2word(pos):
tag_des = {'CC': 'Coordinating conjunction', 'CD': 'Cardinal number', 'DT': 'Determiner', 'EX': 'Existential', 'FW': 'Foreign word', 'IN': 'Preposition', 'JJ': 'Adjective', 'JJR': 'Adjective, comparative', 'JJS': 'Adjective, superlative', 'LS': 'List item maker', 'MD': 'Modal', 'NN': 'Noun, sigular', 'NNS': 'Noun, plural', 'NNP': 'Proper noun, singular', 'NNPS': 'Proper noun, plural', 'PDT': 'Predeterminer', 'POS': 'Possessive ending', 'PRP': 'Personal pronoun', 'PRP$': 'Possessive pronoun', 'RB': 'Adverb', 'RBR': 'Adverb, comparative', 'RBS': 'Adverb, superlative', 'RP': 'Particle', 'SYM': 'Symbol', 'TO': 'to', 'UH': 'Interjection', 'VB': 'Verb, base form', 'VBD': 'Verb, past tense', 'VBG': 'Verb, gerund or present participle', 'VBP': 'Verb, non-3rd person singular present', 'VBZ': 'Verb, 3rd person singular present', 'WDT': 'Wh-determiner', 'WP': 'Wh-pronoun', 'WP$': 'Possessive wh-pronoun', 'WRB': 'Wh-adverb'}
if pos in tag_des:
return tag_des[pos]
return pos
if __name__ == '__main__':
print(poscode2word('NN')) |
"""
Faster R-CNN with DIOU Assigner
Average Precision (AP) @[ IoU=0.50:0.95 | area= all | maxDets=1500 ] = 0.054
Average Precision (AP) @[ IoU=0.25 | area= all | maxDets=1500 ] = -1.000
Average Precision (AP) @[ IoU=0.50 | area= all | maxDets=1500 ] = 0.113
Average Precision (AP) @[ IoU=0.75 | area= all | maxDets=1500 ] = 0.040
Average Precision (AP) @[ IoU=0.50:0.95 | area=verytiny | maxDets=1500 ] = 0.000
Average Precision (AP) @[ IoU=0.50:0.95 | area= tiny | maxDets=1500 ] = 0.039
Average Precision (AP) @[ IoU=0.50:0.95 | area= small | maxDets=1500 ] = 0.122
Average Precision (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=1500 ] = 0.222
Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.139
Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets=300 ] = 0.148
Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets=1500 ] = 0.149
Average Recall (AR) @[ IoU=0.50:0.95 | area=verytiny | maxDets=1500 ] = 0.000
Average Recall (AR) @[ IoU=0.50:0.95 | area= tiny | maxDets=1500 ] = 0.076
Average Recall (AR) @[ IoU=0.50:0.95 | area= small | maxDets=1500 ] = 0.345
Average Recall (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=1500 ] = 0.436
Optimal LRP @[ IoU=0.50 | area= all | maxDets=1500 ] = 0.944
Optimal LRP Loc @[ IoU=0.50 | area= all | maxDets=1500 ] = 0.289
Optimal LRP FP @[ IoU=0.50 | area= all | maxDets=1500 ] = 0.743
Optimal LRP FN @[ IoU=0.50 | area= all | maxDets=1500 ] = 0.843
# Class-specific LRP-Optimal Thresholds #
[0.777 0.871 0.9 0.918 0.947 0.538 0.46 0.303]
+----------+-------+---------------+-------+--------------+-------+
| category | AP | category | AP | category | AP |
+----------+-------+---------------+-------+--------------+-------+
| airplane | 0.150 | bridge | 0.004 | storage-tank | 0.090 |
| ship | 0.092 | swimming-pool | 0.021 | vehicle | 0.049 |
| person | 0.023 | wind-mill | 0.000 | None | None |
+----------+-------+---------------+-------+--------------+-------+
+----------+-------+---------------+-------+--------------+-------+
| category | oLRP | category | oLRP | category | oLRP |
+----------+-------+---------------+-------+--------------+-------+
| airplane | 0.856 | bridge | 0.997 | storage-tank | 0.910 |
| ship | 0.915 | swimming-pool | 0.957 | vehicle | 0.950 |
| person | 0.971 | wind-mill | 0.999 | None | None |
+----------+-------+---------------+-------+--------------+-------+
"""
_base_ = [
'../_base_/models/faster_rcnn_r50_fpn_aitod.py',
'../_base_/datasets/aitod_detection.py',
'../_base_/schedules/schedule_1x.py',
'../_base_/default_runtime.py'
]
model = dict(
train_cfg=dict(
rpn=dict(
assigner=dict(
iou_calculator=dict(type='BboxDistanceMetric'),
assign_metric='diou')),
rcnn=dict(
assigner=dict(
iou_calculator=dict(type='BboxDistanceMetric'),
assign_metric='diou'))))
# optimizer
optimizer = dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0001)
# learning policy
checkpoint_config = dict(interval=4)
| """
Faster R-CNN with DIOU Assigner
Average Precision (AP) @[ IoU=0.50:0.95 | area= all | maxDets=1500 ] = 0.054
Average Precision (AP) @[ IoU=0.25 | area= all | maxDets=1500 ] = -1.000
Average Precision (AP) @[ IoU=0.50 | area= all | maxDets=1500 ] = 0.113
Average Precision (AP) @[ IoU=0.75 | area= all | maxDets=1500 ] = 0.040
Average Precision (AP) @[ IoU=0.50:0.95 | area=verytiny | maxDets=1500 ] = 0.000
Average Precision (AP) @[ IoU=0.50:0.95 | area= tiny | maxDets=1500 ] = 0.039
Average Precision (AP) @[ IoU=0.50:0.95 | area= small | maxDets=1500 ] = 0.122
Average Precision (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=1500 ] = 0.222
Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.139
Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets=300 ] = 0.148
Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets=1500 ] = 0.149
Average Recall (AR) @[ IoU=0.50:0.95 | area=verytiny | maxDets=1500 ] = 0.000
Average Recall (AR) @[ IoU=0.50:0.95 | area= tiny | maxDets=1500 ] = 0.076
Average Recall (AR) @[ IoU=0.50:0.95 | area= small | maxDets=1500 ] = 0.345
Average Recall (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=1500 ] = 0.436
Optimal LRP @[ IoU=0.50 | area= all | maxDets=1500 ] = 0.944
Optimal LRP Loc @[ IoU=0.50 | area= all | maxDets=1500 ] = 0.289
Optimal LRP FP @[ IoU=0.50 | area= all | maxDets=1500 ] = 0.743
Optimal LRP FN @[ IoU=0.50 | area= all | maxDets=1500 ] = 0.843
# Class-specific LRP-Optimal Thresholds #
[0.777 0.871 0.9 0.918 0.947 0.538 0.46 0.303]
+----------+-------+---------------+-------+--------------+-------+
| category | AP | category | AP | category | AP |
+----------+-------+---------------+-------+--------------+-------+
| airplane | 0.150 | bridge | 0.004 | storage-tank | 0.090 |
| ship | 0.092 | swimming-pool | 0.021 | vehicle | 0.049 |
| person | 0.023 | wind-mill | 0.000 | None | None |
+----------+-------+---------------+-------+--------------+-------+
+----------+-------+---------------+-------+--------------+-------+
| category | oLRP | category | oLRP | category | oLRP |
+----------+-------+---------------+-------+--------------+-------+
| airplane | 0.856 | bridge | 0.997 | storage-tank | 0.910 |
| ship | 0.915 | swimming-pool | 0.957 | vehicle | 0.950 |
| person | 0.971 | wind-mill | 0.999 | None | None |
+----------+-------+---------------+-------+--------------+-------+
"""
_base_ = ['../_base_/models/faster_rcnn_r50_fpn_aitod.py', '../_base_/datasets/aitod_detection.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py']
model = dict(train_cfg=dict(rpn=dict(assigner=dict(iou_calculator=dict(type='BboxDistanceMetric'), assign_metric='diou')), rcnn=dict(assigner=dict(iou_calculator=dict(type='BboxDistanceMetric'), assign_metric='diou'))))
optimizer = dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0001)
checkpoint_config = dict(interval=4) |
def part1(arr):
s = 0
for v in arr:
s += v // 3 - 2
return s
def part2(arr):
s = 0
for v in arr:
fuel = v // 3 - 2
s += fuel
while fuel > 0:
fuel = fuel // 3 - 2
if fuel > 0:
s += fuel
return s
def day1():
arr = [
80891, 109412, 149508, 114894, 97527, 59858, 113548, 110516, 97454, 84612, 84578, 87923, 102675, 114312, 144158,
147190, 53051, 115477, 50870, 122198, 91019, 114350, 88592, 119617, 61012, 67012, 85425, 62185, 124628, 98505,
53320, 123834, 105862, 113715, 149328, 72125, 107301, 110684, 86037, 102012, 133227, 66950, 64761, 141015,
132134, 87171, 84142, 80355, 124967, 87973, 98062, 79312, 120108, 97537, 89584, 55206, 68135, 83286, 66726,
101805, 72996, 113109, 116248, 132007, 128378, 52506, 113628, 62277, 73720, 101756, 141675, 107011, 81118,
60598, 122703, 129905, 67786, 50982, 96193, 70006, 137087, 136121, 146902, 74781, 50569, 102645, 99426, 97857,
122801, 55022, 81433, 60509, 66906, 142099, 126652, 103240, 141014, 55579, 143169, 125521
]
print(part1(arr))
print(part2(arr))
if __name__ == '__main__':
day1()
| def part1(arr):
s = 0
for v in arr:
s += v // 3 - 2
return s
def part2(arr):
s = 0
for v in arr:
fuel = v // 3 - 2
s += fuel
while fuel > 0:
fuel = fuel // 3 - 2
if fuel > 0:
s += fuel
return s
def day1():
arr = [80891, 109412, 149508, 114894, 97527, 59858, 113548, 110516, 97454, 84612, 84578, 87923, 102675, 114312, 144158, 147190, 53051, 115477, 50870, 122198, 91019, 114350, 88592, 119617, 61012, 67012, 85425, 62185, 124628, 98505, 53320, 123834, 105862, 113715, 149328, 72125, 107301, 110684, 86037, 102012, 133227, 66950, 64761, 141015, 132134, 87171, 84142, 80355, 124967, 87973, 98062, 79312, 120108, 97537, 89584, 55206, 68135, 83286, 66726, 101805, 72996, 113109, 116248, 132007, 128378, 52506, 113628, 62277, 73720, 101756, 141675, 107011, 81118, 60598, 122703, 129905, 67786, 50982, 96193, 70006, 137087, 136121, 146902, 74781, 50569, 102645, 99426, 97857, 122801, 55022, 81433, 60509, 66906, 142099, 126652, 103240, 141014, 55579, 143169, 125521]
print(part1(arr))
print(part2(arr))
if __name__ == '__main__':
day1() |
BASE_JSON_PATH = '/home/mdd36/tools350/tools350/assembler/base_jsn'
BASE_JSON_LOCAL = '/Users/matthew/Documents/SchoolWork/TA/ECE350/2019s/350_tools_mk2/tools350/assembler/base_jsn'
class InstructionType:
def __init__(self, types: dict):
self._instruction_types: dict = types
def get_by_type(self, type_: str) -> dict:
return self._instruction_types["types"][type_]
def is_branch(self, instr: str) -> bool:
return instr in self._instruction_types["branches"]
NOP = {"opcode": 5, "rd": 5, "rs": 5, "rt": 5, "shamt": 5, "aluop": 5, "zeroes": 2}
ERROR = {"err": 32}
| base_json_path = '/home/mdd36/tools350/tools350/assembler/base_jsn'
base_json_local = '/Users/matthew/Documents/SchoolWork/TA/ECE350/2019s/350_tools_mk2/tools350/assembler/base_jsn'
class Instructiontype:
def __init__(self, types: dict):
self._instruction_types: dict = types
def get_by_type(self, type_: str) -> dict:
return self._instruction_types['types'][type_]
def is_branch(self, instr: str) -> bool:
return instr in self._instruction_types['branches']
nop = {'opcode': 5, 'rd': 5, 'rs': 5, 'rt': 5, 'shamt': 5, 'aluop': 5, 'zeroes': 2}
error = {'err': 32} |
class Node:
def __init__(self, data):
self.left = None
self.right = None
self.data = data
def inorder(root):
if root is None:
return ""
res = ""
res += inorder(root.left)
res += "{} ".format(root.data)
res += inorder(root.right)
return res
def all_subtree(root):
if root is None:
return None
res = [root.data]
l = all_subtree(root.left)
if l is not None:
res += l
res.append(l)
r = all_subtree(root.right)
if r is not None:
res += r
res.append(r)
return res
def main():
root = Node(8)
root.left = Node(3)
root.right = Node(10)
print(inorder(root))
print(all_subtree(root))
if __name__ == "__main__":
main()
| class Node:
def __init__(self, data):
self.left = None
self.right = None
self.data = data
def inorder(root):
if root is None:
return ''
res = ''
res += inorder(root.left)
res += '{} '.format(root.data)
res += inorder(root.right)
return res
def all_subtree(root):
if root is None:
return None
res = [root.data]
l = all_subtree(root.left)
if l is not None:
res += l
res.append(l)
r = all_subtree(root.right)
if r is not None:
res += r
res.append(r)
return res
def main():
root = node(8)
root.left = node(3)
root.right = node(10)
print(inorder(root))
print(all_subtree(root))
if __name__ == '__main__':
main() |
test = {
'name': 'Problem 6',
'points': 1,
'suites': [
{
'cases': [
{
'answer': 'fd4dd892ccea3adcf9446dc4a9738d47',
'choices': [
r"""
Pair('quote', Pair(A, nil)), where:
A is the quoted expression
""",
r"""
[A], where:
A is the quoted expression
""",
r"""
Pair(A, nil), where:
A is the quoted expression
""",
r"""
A, where:
A is the quoted expression
"""
],
'hidden': False,
'locked': True,
'question': 'What is the structure of the expressions argument to do_quote_form?'
}
],
'scored': False,
'type': 'concept'
},
{
'cases': [
{
'code': r"""
>>> do_quote_form(Pair(3, nil), global_frame)
3c7e8a3a2176a696c3a66418f78dff6b
# locked
>>> do_quote_form(Pair('hi', nil), global_frame)
95448591e64e04a7a7885d5fb9b45583
# locked
>>> expr = Pair(Pair('+', Pair('x', Pair(2, nil))), nil)
>>> do_quote_form(expr, global_frame)
2301ee746b57783004f00f39498fdaed
# locked
""",
'hidden': False,
'locked': True
}
],
'scored': True,
'setup': r"""
>>> from scheme import *
>>> global_frame = create_global_frame()
""",
'teardown': '',
'type': 'doctest'
},
{
'cases': [
{
'code': r"""
scm> ''hello
f675ad62f5f67e5229145843fd6bbcaa
# locked
# choice: (quote hello)
# choice: hello
# choice: (hello)
# choice: (quote (quote (hello)))
scm> (quote (1 2))
484e4b42665b2864d685ef07fe666107
# locked
scm> (car '(1 2 3))
eb892a26497f936d1f6cae54aacc5f51
# locked
scm> (cdr '(1 2))
750540b47bda75ff036b4a9aa741b087
# locked
scm> (eval (cons 'car '('(4 2))))
46beb7deeeb5e9af1c8d785b12558317
# locked
""",
'hidden': False,
'locked': True
}
],
'scored': True,
'setup': '',
'teardown': '',
'type': 'scheme'
},
{
'cases': [
{
'code': r"""
>>> read_line(" 'x ")
d88f877a51ba10d1c3a834a690bb43e0
# locked
# choice: Pair('x', nil)
# choice: 'x'
# choice: Pair('quote', 'x')
# choice: Pair('quote', Pair('x', nil))
>>> read_line(" '(a b) ")
e16dd0e729d41b52ddd5d4d38cbfc7e6
# locked
# choice: Pair('a', Pair('b', nil))
# choice: Pair('quote', Pair(Pair('a', Pair('b', nil)), nil))
# choice: Pair('quote', Pair('a', 'b'))
# choice: Pair('quote', Pair('a', Pair('b', nil)))
""",
'hidden': False,
'locked': True
},
{
'code': r"""
>>> read_line("(a (b 'c))")
Pair('a', Pair(Pair('b', Pair(Pair('quote', Pair('c', nil)), nil)), nil))
>>> read_line("(a (b '(c d)))")
Pair('a', Pair(Pair('b', Pair(Pair('quote', Pair(Pair('c', Pair('d', nil)), nil)), nil)), nil))
>>> read_line("')")
SyntaxError
>>> read_line("'()")
Pair('quote', Pair(nil, nil))
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> read_line("'('a)")
Pair('quote', Pair(Pair(Pair('quote', Pair('a', nil)), nil), nil))
>>> read_line("''a")
Pair('quote', Pair(Pair('quote', Pair('a', nil)), nil))
>>> read_line("'('('a 'b 'c))")
Pair('quote', Pair(Pair(Pair('quote', Pair(Pair(Pair('quote', Pair('a', nil)), Pair(Pair('quote', Pair('b', nil)), Pair(Pair('quote', Pair('c', nil)), nil))), nil)), nil), nil))
>>> read_line("(+ '(1 2) 3)")
Pair('+', Pair(Pair('quote', Pair(Pair(1, Pair(2, nil)), nil)), Pair(3, nil)))
>>> read_line("'('+ '(1 2) '3)")
Pair('quote', Pair(Pair(Pair('quote', Pair('+', nil)), Pair(Pair('quote', Pair(Pair(1, Pair(2, nil)), nil)), Pair(Pair('quote', Pair(3, nil)), nil))), nil))
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> scheme_read(Buffer(tokenize_lines(["'hello"])))
Pair('quote', Pair('hello', nil))
>>> read_line("(car '(1 2))")
Pair('car', Pair(Pair('quote', Pair(Pair(1, Pair(2, nil)), nil)), nil))
>>> print(read_line("(car '(1 2))"))
(car (quote (1 2)))
>>> read_line("'('a)")
Pair('quote', Pair(Pair(Pair('quote', Pair('a', nil)), nil), nil))
>>> read_line("''a")
Pair('quote', Pair(Pair('quote', Pair('a', nil)), nil))
>>> read_line("'('('a 'b 'c))")
Pair('quote', Pair(Pair(Pair('quote', Pair(Pair(Pair('quote', Pair('a', nil)), Pair(Pair('quote', Pair('b', nil)), Pair(Pair('quote', Pair('c', nil)), nil))), nil)), nil), nil))
>>> read_line("(+ '(1 2) 3)")
Pair('+', Pair(Pair('quote', Pair(Pair(1, Pair(2, nil)), nil)), Pair(3, nil)))
>>> read_line("'('+ '(1 2) '3)")
Pair('quote', Pair(Pair(Pair('quote', Pair('+', nil)), Pair(Pair('quote', Pair(Pair(1, Pair(2, nil)), nil)), Pair(Pair('quote', Pair(3, nil)), nil))), nil))
""",
'hidden': False,
'locked': False
}
],
'scored': True,
'setup': r"""
>>> from scheme_reader import *
""",
'teardown': '',
'type': 'doctest'
},
{
'cases': [
{
'code': r"""
scm> (quote hello)
hello
scm> 'hello
hello
scm> ''hello
(quote hello)
scm> (quote (1 2))
(1 2)
scm> '(1 2)
(1 2)
scm> (car (car '((1))))
1
scm> (quote 3)
3
scm> '(a b c)
(a b c)
scm> '(1 '2)
(1 (quote 2))
""",
'hidden': False,
'locked': False
}
],
'scored': True,
'setup': '',
'teardown': '',
'type': 'scheme'
}
]
}
| test = {'name': 'Problem 6', 'points': 1, 'suites': [{'cases': [{'answer': 'fd4dd892ccea3adcf9446dc4a9738d47', 'choices': ["\n Pair('quote', Pair(A, nil)), where:\n A is the quoted expression\n ", '\n [A], where:\n A is the quoted expression\n ', '\n Pair(A, nil), where:\n A is the quoted expression\n ', '\n A, where:\n A is the quoted expression\n '], 'hidden': False, 'locked': True, 'question': 'What is the structure of the expressions argument to do_quote_form?'}], 'scored': False, 'type': 'concept'}, {'cases': [{'code': "\n >>> do_quote_form(Pair(3, nil), global_frame)\n 3c7e8a3a2176a696c3a66418f78dff6b\n # locked\n >>> do_quote_form(Pair('hi', nil), global_frame)\n 95448591e64e04a7a7885d5fb9b45583\n # locked\n >>> expr = Pair(Pair('+', Pair('x', Pair(2, nil))), nil)\n >>> do_quote_form(expr, global_frame)\n 2301ee746b57783004f00f39498fdaed\n # locked\n ", 'hidden': False, 'locked': True}], 'scored': True, 'setup': '\n >>> from scheme import *\n >>> global_frame = create_global_frame()\n ', 'teardown': '', 'type': 'doctest'}, {'cases': [{'code': "\n scm> ''hello\n f675ad62f5f67e5229145843fd6bbcaa\n # locked\n # choice: (quote hello)\n # choice: hello\n # choice: (hello)\n # choice: (quote (quote (hello)))\n scm> (quote (1 2))\n 484e4b42665b2864d685ef07fe666107\n # locked\n scm> (car '(1 2 3))\n eb892a26497f936d1f6cae54aacc5f51\n # locked\n scm> (cdr '(1 2))\n 750540b47bda75ff036b4a9aa741b087\n # locked\n scm> (eval (cons 'car '('(4 2))))\n 46beb7deeeb5e9af1c8d785b12558317\n # locked\n ", 'hidden': False, 'locked': True}], 'scored': True, 'setup': '', 'teardown': '', 'type': 'scheme'}, {'cases': [{'code': '\n >>> read_line(" \'x ")\n d88f877a51ba10d1c3a834a690bb43e0\n # locked\n # choice: Pair(\'x\', nil)\n # choice: \'x\'\n # choice: Pair(\'quote\', \'x\')\n # choice: Pair(\'quote\', Pair(\'x\', nil))\n >>> read_line(" \'(a b) ")\n e16dd0e729d41b52ddd5d4d38cbfc7e6\n # locked\n # choice: Pair(\'a\', Pair(\'b\', nil))\n # choice: Pair(\'quote\', Pair(Pair(\'a\', Pair(\'b\', nil)), nil))\n # choice: Pair(\'quote\', Pair(\'a\', \'b\'))\n # choice: Pair(\'quote\', Pair(\'a\', Pair(\'b\', nil)))\n ', 'hidden': False, 'locked': True}, {'code': '\n >>> read_line("(a (b \'c))")\n Pair(\'a\', Pair(Pair(\'b\', Pair(Pair(\'quote\', Pair(\'c\', nil)), nil)), nil))\n >>> read_line("(a (b \'(c d)))")\n Pair(\'a\', Pair(Pair(\'b\', Pair(Pair(\'quote\', Pair(Pair(\'c\', Pair(\'d\', nil)), nil)), nil)), nil))\n >>> read_line("\')")\n SyntaxError\n >>> read_line("\'()")\n Pair(\'quote\', Pair(nil, nil))\n ', 'hidden': False, 'locked': False}, {'code': '\n >>> read_line("\'(\'a)")\n Pair(\'quote\', Pair(Pair(Pair(\'quote\', Pair(\'a\', nil)), nil), nil))\n >>> read_line("\'\'a")\n Pair(\'quote\', Pair(Pair(\'quote\', Pair(\'a\', nil)), nil))\n >>> read_line("\'(\'(\'a \'b \'c))")\n Pair(\'quote\', Pair(Pair(Pair(\'quote\', Pair(Pair(Pair(\'quote\', Pair(\'a\', nil)), Pair(Pair(\'quote\', Pair(\'b\', nil)), Pair(Pair(\'quote\', Pair(\'c\', nil)), nil))), nil)), nil), nil))\n >>> read_line("(+ \'(1 2) 3)")\n Pair(\'+\', Pair(Pair(\'quote\', Pair(Pair(1, Pair(2, nil)), nil)), Pair(3, nil)))\n >>> read_line("\'(\'+ \'(1 2) \'3)")\n Pair(\'quote\', Pair(Pair(Pair(\'quote\', Pair(\'+\', nil)), Pair(Pair(\'quote\', Pair(Pair(1, Pair(2, nil)), nil)), Pair(Pair(\'quote\', Pair(3, nil)), nil))), nil))\n ', 'hidden': False, 'locked': False}, {'code': '\n >>> scheme_read(Buffer(tokenize_lines(["\'hello"])))\n Pair(\'quote\', Pair(\'hello\', nil))\n >>> read_line("(car \'(1 2))")\n Pair(\'car\', Pair(Pair(\'quote\', Pair(Pair(1, Pair(2, nil)), nil)), nil))\n >>> print(read_line("(car \'(1 2))"))\n (car (quote (1 2)))\n >>> read_line("\'(\'a)")\n Pair(\'quote\', Pair(Pair(Pair(\'quote\', Pair(\'a\', nil)), nil), nil))\n >>> read_line("\'\'a")\n Pair(\'quote\', Pair(Pair(\'quote\', Pair(\'a\', nil)), nil))\n >>> read_line("\'(\'(\'a \'b \'c))")\n Pair(\'quote\', Pair(Pair(Pair(\'quote\', Pair(Pair(Pair(\'quote\', Pair(\'a\', nil)), Pair(Pair(\'quote\', Pair(\'b\', nil)), Pair(Pair(\'quote\', Pair(\'c\', nil)), nil))), nil)), nil), nil))\n >>> read_line("(+ \'(1 2) 3)")\n Pair(\'+\', Pair(Pair(\'quote\', Pair(Pair(1, Pair(2, nil)), nil)), Pair(3, nil)))\n >>> read_line("\'(\'+ \'(1 2) \'3)")\n Pair(\'quote\', Pair(Pair(Pair(\'quote\', Pair(\'+\', nil)), Pair(Pair(\'quote\', Pair(Pair(1, Pair(2, nil)), nil)), Pair(Pair(\'quote\', Pair(3, nil)), nil))), nil))\n ', 'hidden': False, 'locked': False}], 'scored': True, 'setup': '\n >>> from scheme_reader import *\n ', 'teardown': '', 'type': 'doctest'}, {'cases': [{'code': "\n scm> (quote hello)\n hello\n scm> 'hello\n hello\n scm> ''hello\n (quote hello)\n scm> (quote (1 2))\n (1 2)\n scm> '(1 2)\n (1 2)\n scm> (car (car '((1))))\n 1\n scm> (quote 3)\n 3\n scm> '(a b c)\n (a b c)\n scm> '(1 '2)\n (1 (quote 2))\n ", 'hidden': False, 'locked': False}], 'scored': True, 'setup': '', 'teardown': '', 'type': 'scheme'}]} |
for i in range(int(input())):
sum = 0
y, x = map(int, input().split())
n = max(x,y)
sum += (n-1) * (n-1)
if n%2!=0:
sum += x + (n-y)
else:
sum += y + (n-x)
print(sum)
| for i in range(int(input())):
sum = 0
(y, x) = map(int, input().split())
n = max(x, y)
sum += (n - 1) * (n - 1)
if n % 2 != 0:
sum += x + (n - y)
else:
sum += y + (n - x)
print(sum) |
entries = [1, 2, 3, 4, 5]
print("all: {}".format(all(entries)))
print("any: {}".format(any(entries)))
print("Iterable with a 'False' value")
entries_with_zero = [1, 2, 0, 4, 5]
print("all: {}".format(all(entries_with_zero)))
print("any: {}".format(any(entries_with_zero)))
print()
print("Values interpreted as False in Python")
print("""False: {0}
None: {1}
0: {2}
0.0: {3}
empty list []: {4}
empty tuple (): {5}
empty string '': {6}
empty string "": {7}
empty mapping {{}}: {8}
""".format(False, bool(None), bool(0), bool(0.0), bool([]), bool(()), bool(''), bool(""), bool({})))
print("=" * 80)
name = "Tim"
if name:
print("Hello {}".format(name))
else:
print("Welcome, person with no name")
| entries = [1, 2, 3, 4, 5]
print('all: {}'.format(all(entries)))
print('any: {}'.format(any(entries)))
print("Iterable with a 'False' value")
entries_with_zero = [1, 2, 0, 4, 5]
print('all: {}'.format(all(entries_with_zero)))
print('any: {}'.format(any(entries_with_zero)))
print()
print('Values interpreted as False in Python')
print('False: {0}\nNone: {1}\n0: {2}\n0.0: {3}\nempty list []: {4}\nempty tuple (): {5}\nempty string \'\': {6}\nempty string "": {7}\nempty mapping {{}}: {8}\n'.format(False, bool(None), bool(0), bool(0.0), bool([]), bool(()), bool(''), bool(''), bool({})))
print('=' * 80)
name = 'Tim'
if name:
print('Hello {}'.format(name))
else:
print('Welcome, person with no name') |
# -*- coding: utf-8 -*-
#
# PySceneDetect: Python-Based Video Scene Detector
# ---------------------------------------------------------------
# [ Site: http://www.bcastell.com/projects/PySceneDetect/ ]
# [ Github: https://github.com/Breakthrough/PySceneDetect/ ]
# [ Documentation: http://pyscenedetect.readthedocs.org/ ]
#
# Copyright (C) 2014-2019 Brandon Castellano <http://www.bcastell.com>.
#
# PySceneDetect is licensed under the BSD 3-Clause License; see the included
# LICENSE file, or visit one of the following pages for details:
# - https://github.com/Breakthrough/PySceneDetect/
# - http://www.bcastell.com/projects/PySceneDetect/
#
# This software uses Numpy, OpenCV, click, tqdm, simpletable, and pytest.
# See the included LICENSE files or one of the above URLs for more information.
#
# 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 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.
#
""" Module: ``scenedetect.thirdparty``
This module includes all third-party libraries/dependencies that are distributed
with PySceneDetect. The source directory also includes the license files for all
packages that PySceneDetect depends on, to simplify distribution of binary builds.
"""
| """ Module: ``scenedetect.thirdparty``
This module includes all third-party libraries/dependencies that are distributed
with PySceneDetect. The source directory also includes the license files for all
packages that PySceneDetect depends on, to simplify distribution of binary builds.
""" |
class Solution(object):
def buddyStrings(self, A, B):
"""
:type A: str
:type B: str
:rtype: bool
"""
if len(A) != len(B):
return False
a, b, sa = [], [], set()
for i in range(0, len(A)):
if A[i] != B[i]:
a.append(A[i])
b.append(B[i])
sa.add(A[i])
if len(a) == 0:
if len(A) == len(sa):
return False
return True
if len(a) == 1 or len(a) > 2:
return False
return a[0] == b[1] and a[1] == b[0]
def test_buddy_strings():
s = Solution()
assert s.buddyStrings("ab", "ba")
assert s.buddyStrings("ab", "ab") is False
assert s.buddyStrings("aa", "aa")
assert s.buddyStrings("aaaaaaabc", "aaaaaaacb")
assert s.buddyStrings("", "aa") is False
| class Solution(object):
def buddy_strings(self, A, B):
"""
:type A: str
:type B: str
:rtype: bool
"""
if len(A) != len(B):
return False
(a, b, sa) = ([], [], set())
for i in range(0, len(A)):
if A[i] != B[i]:
a.append(A[i])
b.append(B[i])
sa.add(A[i])
if len(a) == 0:
if len(A) == len(sa):
return False
return True
if len(a) == 1 or len(a) > 2:
return False
return a[0] == b[1] and a[1] == b[0]
def test_buddy_strings():
s = solution()
assert s.buddyStrings('ab', 'ba')
assert s.buddyStrings('ab', 'ab') is False
assert s.buddyStrings('aa', 'aa')
assert s.buddyStrings('aaaaaaabc', 'aaaaaaacb')
assert s.buddyStrings('', 'aa') is False |
class Solution(object):
def numJewelsInStones(self, J, S):
"""
:type J: str
:type S: str
:rtype: int
"""
if len(J)==0 or len(S)==0:
return 0
answer=0
J_set = set(J)
for char in S:
if char in J_set:
answer+=1
return answer | class Solution(object):
def num_jewels_in_stones(self, J, S):
"""
:type J: str
:type S: str
:rtype: int
"""
if len(J) == 0 or len(S) == 0:
return 0
answer = 0
j_set = set(J)
for char in S:
if char in J_set:
answer += 1
return answer |
class GetCashgramStatus:
end_point = "/payout/v1/getCashgramStatus"
req_type = "GET"
def __init__(self, *args, **kwargs):
self.cashgramId = kwargs["cashgramId"] | class Getcashgramstatus:
end_point = '/payout/v1/getCashgramStatus'
req_type = 'GET'
def __init__(self, *args, **kwargs):
self.cashgramId = kwargs['cashgramId'] |
# ------------------------------
# 25. Reverse Nodes in k-Group
#
# Description:
# Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
# k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
#
# You may not alter the values in the nodes, only nodes itself may be changed.
# Only constant memory is allowed.
# For example,
# Given this linked list: 1->2->3->4->5
# For k = 2, you should return: 2->1->4->3->5
# For k = 3, you should return: 3->2->1->4->5
#
# Version: 1.0
# 09/21/17 by Jianfa
# ------------------------------
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reverseKGroup(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
pointer = {}
if not head:
return None
else:
i = 0
temp = head
while temp and i < k:
pointer[i] = temp
temp = temp.next
i += 1
if i < k:
return head
else:
while i > 1:
pointer[i-1].next = pointer[i-2]
i -= 1
pointer[0].next = self.reverseKGroup(temp, k)
return pointer[k-1]
# Used for test
# if __name__ == "__main__":
# test = Solution()
# d = ListNode(2)
# d.next = None
# c = ListNode(1)
# c.next = d
# b = ListNode(4)
# b.next = c
# a = ListNode(3)
# a.next = b
# head = test.reverseKGroup(a, 3)
# while head != None:
# print(head.val)
# head = head.next
# ------------------------------
# Summary:
# Still using recursion solution
# Some ideas from other solutions are processing every k nodes every time, until there are
# no k nodes in the list. | class Solution(object):
def reverse_k_group(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
pointer = {}
if not head:
return None
else:
i = 0
temp = head
while temp and i < k:
pointer[i] = temp
temp = temp.next
i += 1
if i < k:
return head
else:
while i > 1:
pointer[i - 1].next = pointer[i - 2]
i -= 1
pointer[0].next = self.reverseKGroup(temp, k)
return pointer[k - 1] |
description = 'Small Beam Limiter in Experimental Chamber 1'
group = 'optional'
devices = dict(
nbl_l = device('nicos.devices.generic.VirtualReferenceMotor',
description = 'Beam Limiter Left Blade',
lowlevel = True,
abslimits = (-250, 260),
unit = 'mm',
speed = 10,
refswitch = 'high',
),
nbl_r = device('nicos.devices.generic.VirtualReferenceMotor',
description = 'Beam Limiter Right Blade',
lowlevel = True,
abslimits = (-250, 260),
unit = 'mm',
speed = 10,
refswitch = 'high',
),
nbl_t = device('nicos.devices.generic.VirtualReferenceMotor',
description = 'Beam Limiter Top Blade',
lowlevel = True,
abslimits = (-250, 260),
unit = 'mm',
speed = 10,
refswitch = 'high',
),
nbl_b = device('nicos.devices.generic.VirtualReferenceMotor',
description = 'Beam Limiter Bottom Blade',
lowlevel = True,
abslimits = (-250, 260),
unit = 'mm',
speed = 10,
refswitch = 'high',
),
nbl = device('nicos_mlz.nectar.devices.BeamLimiter',
description = 'NECTAR Beam Limiter',
left = 'nbl_l',
right = 'nbl_r',
top = 'nbl_t',
bottom = 'nbl_b',
opmode = 'centered',
coordinates = 'opposite',
pollinterval = 5,
maxage = 10,
parallel_ref = True,
),
)
| description = 'Small Beam Limiter in Experimental Chamber 1'
group = 'optional'
devices = dict(nbl_l=device('nicos.devices.generic.VirtualReferenceMotor', description='Beam Limiter Left Blade', lowlevel=True, abslimits=(-250, 260), unit='mm', speed=10, refswitch='high'), nbl_r=device('nicos.devices.generic.VirtualReferenceMotor', description='Beam Limiter Right Blade', lowlevel=True, abslimits=(-250, 260), unit='mm', speed=10, refswitch='high'), nbl_t=device('nicos.devices.generic.VirtualReferenceMotor', description='Beam Limiter Top Blade', lowlevel=True, abslimits=(-250, 260), unit='mm', speed=10, refswitch='high'), nbl_b=device('nicos.devices.generic.VirtualReferenceMotor', description='Beam Limiter Bottom Blade', lowlevel=True, abslimits=(-250, 260), unit='mm', speed=10, refswitch='high'), nbl=device('nicos_mlz.nectar.devices.BeamLimiter', description='NECTAR Beam Limiter', left='nbl_l', right='nbl_r', top='nbl_t', bottom='nbl_b', opmode='centered', coordinates='opposite', pollinterval=5, maxage=10, parallel_ref=True)) |
async def test_admin_auth(client, admin, user):
res = await client.get('/admin', follow_redirect=False)
assert res.status_code == 307
# Login as an simple user
res = await client.post('/login', data={'email': user.email, 'password': 'pass'})
assert res.status_code == 200
res = await client.get('/admin', follow_redirect=False)
assert res.status_code == 307
# Login as an admin
res = await client.post('/login', data={'email': admin.email, 'password': 'pass'})
assert res.status_code == 200
res = await client.get('/admin', follow_redirect=False)
assert res.status_code == 200
assert 'initAdmin' in await res.text()
| async def test_admin_auth(client, admin, user):
res = await client.get('/admin', follow_redirect=False)
assert res.status_code == 307
res = await client.post('/login', data={'email': user.email, 'password': 'pass'})
assert res.status_code == 200
res = await client.get('/admin', follow_redirect=False)
assert res.status_code == 307
res = await client.post('/login', data={'email': admin.email, 'password': 'pass'})
assert res.status_code == 200
res = await client.get('/admin', follow_redirect=False)
assert res.status_code == 200
assert 'initAdmin' in await res.text() |
# https://edabit.com/challenge/Yj2Rew5XQYpu7Nosq
# Create a function that returns the number of frames shown in a given number of minutes for a certain FPS.
def frames(minutes: int, fps: int) -> int:
try:
total_frames = (minutes * 60) * fps
return total_frames
except TypeError as err:
print(f"Error: {err}")
print(frames(1, 1))
print(frames(10, 1))
print(frames(10, 25))
print(frames("a", "b"))
| def frames(minutes: int, fps: int) -> int:
try:
total_frames = minutes * 60 * fps
return total_frames
except TypeError as err:
print(f'Error: {err}')
print(frames(1, 1))
print(frames(10, 1))
print(frames(10, 25))
print(frames('a', 'b')) |
"""
HTTP/1.0 301 Moved Permanently
Location: http://www.google.ca/
Content-Type: text/html; charset=UTF-8
Date: Wed, 03 Oct 2018 19:51:01 GMT
Expires: Fri, 02 Nov 2018 19:51:01 GMT
Cache-Control: public, max-age=2592000
Server: gws
Content-Length: 218
X-XSS-Protection: 1; mode=block
X-Frame-Options: SAMEORIGIN
<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>301 Moved</TITLE></HEAD><BODY>
<H1>301 Moved</H1>
The document has moved
<A HREF="http://www.google.ca/">here</A>.
</BODY></HTML>
"""
"""
HTTP/1.1 200 OK
Connection: close
Server: gunicorn/19.9.0
Date: Wed, 03 Oct 2018 20:08:34 GMT
Content-Type: application/json
Content-Length: 245
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
Via: 1.1 vegur
{
"args": {
"assignment": "1",
"course": "networking"
},
"headers": {
"Connection": "close",
"Host": "httpbin.org"
},
"origin": "206.180.247.122",
"url": "http://httpbin.org/get?course=networking&assignment=1"
}
"""
class HttpRequest:
def __init__(self, host, path, query, headers):
self.path = path
self.host = host
self.query = query
self.headers = headers
def getGet(self):
headers = ( "GET "+ self.path + "?" + self.query + " HTTP/1.0\r\n"
"{headers}\r\n"
"Host:" + self.host + "\r\n\r\n")
header_bytes = headers.format(
headers=self.headers
).encode('utf-8')
return header_bytes
def getPost(self):
headers = ( "POST {path} HTTP/1.0\r\n"
"{headers}\r\n"
"Content-Length: {content_length}\r\n"
"Host: {host}\r\n"
"User-Agent: Concordia-HTTP/1.0\r\n"
"Connection: close\r\n\r\n")
body_bytes = self.query.encode('utf-8')
header_bytes = headers.format(
path=self.path,
headers=self.headers,
content_length=len(self.query),
host=self.host
).encode('utf-8')
return header_bytes + body_bytes
class HttpResponse:
def __init__(self, response):
self.text = response.decode('utf-8')
self.parseText()
def parseText(self):
texts = self.text.split("\r\n\r\n")
self.header = texts[0]
self.body = texts[1]
lines = self.header.split("\r\n")
infos = lines[0].split(" ")
self.code = infos[1]
self.status = infos[2]
if(self.code == HttpCode.redirect):
self.location = lines[1].split(" ")[1].split("//")[1][:-1]
print("Redirect to " + self.location)
class HttpCode:
redirect = "301"
ok = "200"
| """
HTTP/1.0 301 Moved Permanently
Location: http://www.google.ca/
Content-Type: text/html; charset=UTF-8
Date: Wed, 03 Oct 2018 19:51:01 GMT
Expires: Fri, 02 Nov 2018 19:51:01 GMT
Cache-Control: public, max-age=2592000
Server: gws
Content-Length: 218
X-XSS-Protection: 1; mode=block
X-Frame-Options: SAMEORIGIN
<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>301 Moved</TITLE></HEAD><BODY>
<H1>301 Moved</H1>
The document has moved
<A HREF="http://www.google.ca/">here</A>.
</BODY></HTML>
"""
'\nHTTP/1.1 200 OK\nConnection: close\nServer: gunicorn/19.9.0\nDate: Wed, 03 Oct 2018 20:08:34 GMT\nContent-Type: application/json\nContent-Length: 245\nAccess-Control-Allow-Origin: *\nAccess-Control-Allow-Credentials: true\nVia: 1.1 vegur\n\n{\n "args": {\n "assignment": "1", \n "course": "networking"\n }, \n "headers": {\n "Connection": "close", \n "Host": "httpbin.org"\n }, \n "origin": "206.180.247.122", \n "url": "http://httpbin.org/get?course=networking&assignment=1"\n}\n'
class Httprequest:
def __init__(self, host, path, query, headers):
self.path = path
self.host = host
self.query = query
self.headers = headers
def get_get(self):
headers = 'GET ' + self.path + '?' + self.query + ' HTTP/1.0\r\n{headers}\r\nHost:' + self.host + '\r\n\r\n'
header_bytes = headers.format(headers=self.headers).encode('utf-8')
return header_bytes
def get_post(self):
headers = 'POST {path} HTTP/1.0\r\n{headers}\r\nContent-Length: {content_length}\r\nHost: {host}\r\nUser-Agent: Concordia-HTTP/1.0\r\nConnection: close\r\n\r\n'
body_bytes = self.query.encode('utf-8')
header_bytes = headers.format(path=self.path, headers=self.headers, content_length=len(self.query), host=self.host).encode('utf-8')
return header_bytes + body_bytes
class Httpresponse:
def __init__(self, response):
self.text = response.decode('utf-8')
self.parseText()
def parse_text(self):
texts = self.text.split('\r\n\r\n')
self.header = texts[0]
self.body = texts[1]
lines = self.header.split('\r\n')
infos = lines[0].split(' ')
self.code = infos[1]
self.status = infos[2]
if self.code == HttpCode.redirect:
self.location = lines[1].split(' ')[1].split('//')[1][:-1]
print('Redirect to ' + self.location)
class Httpcode:
redirect = '301'
ok = '200' |
class Node():
def __init__(self, value):
self.value = value
self.next = None
class LinkedList():
def __init__(self):
self.head = None
def __str__(self):
current = self.head
output = ''
while current:
output += f"{ {str(current.value)} } ->"
current = current.next
return output
def append(self, value):
'''
this method to append value in the last node
input ==> value
'''
if value is None:
raise TypeError("insert() missing 1 required positional argument: 'value' ")
else:
new_node = Node(value)
if not self.head:
self.head = new_node
else:
new_node = Node(value)
current = self.head
while current.next:
current = current.next
current.next = new_node
def zipLists(list1,list2):
"""
Takes two linked lists as arguments. Zip the two linked lists together into one so that
the nodes alternate between the two lists and return a reference to the head of the zipped list.
"""
if not list1 :
return list1
if not list2 :
return list1
output =LinkedList()
current1 =list1.head
current2 =list2.head
while current1 :
output.append(current1.value)
if current2 :
output.append(current2.value)
current2 = current2.next
current1= current1.next
while current2 :
output.append(current2.value)
current2 =current2.next
return output.__str__()
if __name__ == "__main__":
majd = LinkedList()
majd.append(1)
majd.append(2)
ahmad = LinkedList()
ahmad.append(5)
ahmad.append(10) | class Node:
def __init__(self, value):
self.value = value
self.next = None
class Linkedlist:
def __init__(self):
self.head = None
def __str__(self):
current = self.head
output = ''
while current:
output += f'{ {str(current.value)}} ->'
current = current.next
return output
def append(self, value):
"""
this method to append value in the last node
input ==> value
"""
if value is None:
raise type_error("insert() missing 1 required positional argument: 'value' ")
else:
new_node = node(value)
if not self.head:
self.head = new_node
else:
new_node = node(value)
current = self.head
while current.next:
current = current.next
current.next = new_node
def zip_lists(list1, list2):
"""
Takes two linked lists as arguments. Zip the two linked lists together into one so that
the nodes alternate between the two lists and return a reference to the head of the zipped list.
"""
if not list1:
return list1
if not list2:
return list1
output = linked_list()
current1 = list1.head
current2 = list2.head
while current1:
output.append(current1.value)
if current2:
output.append(current2.value)
current2 = current2.next
current1 = current1.next
while current2:
output.append(current2.value)
current2 = current2.next
return output.__str__()
if __name__ == '__main__':
majd = linked_list()
majd.append(1)
majd.append(2)
ahmad = linked_list()
ahmad.append(5)
ahmad.append(10) |
list_one = [1, 2, 3]
list_two = [4, 5, 6,7]
lst = [0, *list_one, *list_two]
print(lst)
country_lst_one = ['Finland', 'Sweden', 'Norway']
country_lst_two = ['Denmark', 'Iceland']
nordic_countries = [*country_lst_one, *country_lst_two]
print(nordic_countries)
| list_one = [1, 2, 3]
list_two = [4, 5, 6, 7]
lst = [0, *list_one, *list_two]
print(lst)
country_lst_one = ['Finland', 'Sweden', 'Norway']
country_lst_two = ['Denmark', 'Iceland']
nordic_countries = [*country_lst_one, *country_lst_two]
print(nordic_countries) |
input = """
a(1) | a(3).
a(2).
c(1,1).
c(1,3).
d(1,5).
b(X) :- a(X), c(Y,X).
ok :- #max{V :b(V)} < X, d(Y,X).
"""
output = """
a(1) | a(3).
a(2).
c(1,1).
c(1,3).
d(1,5).
b(X) :- a(X), c(Y,X).
ok :- #max{V :b(V)} < X, d(Y,X).
"""
| input = '\na(1) | a(3).\na(2).\nc(1,1).\nc(1,3).\nd(1,5).\n\nb(X) :- a(X), c(Y,X).\n\nok :- #max{V :b(V)} < X, d(Y,X).\n'
output = '\na(1) | a(3).\na(2).\nc(1,1).\nc(1,3).\nd(1,5).\n\nb(X) :- a(X), c(Y,X).\n\nok :- #max{V :b(V)} < X, d(Y,X).\n' |
offices=[]
expected_offices = ("Federal", "Legislative", "State", "Local Government")
class PoliticalOffice():
@staticmethod
def exists(name):
"""
Checks if an office with the same name exists
Returns a boolean
"""
for office in offices:
if office["name"] == name:
return True
return False
@staticmethod
def check_office_type(office_type):
if office_type not in expected_offices:
return False
return True
@classmethod
def create_political_office(cls, name, office_type):
office= {
"office_id": len(offices)+1,
"name": name,
"type": office_type
}
offices.append(office)
return office
def get_political_office(self):
if len(offices) == 0: print('List is empty')
return offices
def get_specific_political_office(self, office_id):
for office in offices:
if office["office_id"] == office_id:
return office
| offices = []
expected_offices = ('Federal', 'Legislative', 'State', 'Local Government')
class Politicaloffice:
@staticmethod
def exists(name):
"""
Checks if an office with the same name exists
Returns a boolean
"""
for office in offices:
if office['name'] == name:
return True
return False
@staticmethod
def check_office_type(office_type):
if office_type not in expected_offices:
return False
return True
@classmethod
def create_political_office(cls, name, office_type):
office = {'office_id': len(offices) + 1, 'name': name, 'type': office_type}
offices.append(office)
return office
def get_political_office(self):
if len(offices) == 0:
print('List is empty')
return offices
def get_specific_political_office(self, office_id):
for office in offices:
if office['office_id'] == office_id:
return office |
"""
Queue.py
Description: This file contains the implementation of the queue data structure
"""
# The queue class is used to implement functionality of a queue using a list
class Queue:
# Default constructor
def __init__(self):
self.items = []
# Function used to tell us if the queue is empty
def isEmpty(self):
return self.items == []
# Function used to add an item to the queue
def enqueue(self, item):
self.items.insert(0, item)
# Function used to remove an item from the queue
def dequeue(self):
return self.items.pop()
# Function used to return the size of the queue
def size(self):
return len(self.items)
# Function used to check whether a value exists or not
def find(self, item):
return self.items.index(item)
# Function used to return the value at the particular position
def get(self, pos):
return self.items[pos]
# Function used to remove an item from the queue
def remove(self, item):
self.items.remove(item)
| """
Queue.py
Description: This file contains the implementation of the queue data structure
"""
class Queue:
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def enqueue(self, item):
self.items.insert(0, item)
def dequeue(self):
return self.items.pop()
def size(self):
return len(self.items)
def find(self, item):
return self.items.index(item)
def get(self, pos):
return self.items[pos]
def remove(self, item):
self.items.remove(item) |
# https://www.codechef.com/problems/DEVARRAY
n,Q=map(int,input().split())
max1,min1,a=-99999999999,99999999999,list(map(int,input().split()))
for z in range(n): min1,max1 = min(min1,a[z]),max(max1,a[z])
for z in range(Q): print("Yes") if(int(input()) in range(min1,max1+1)) else print("No") | (n, q) = map(int, input().split())
(max1, min1, a) = (-99999999999, 99999999999, list(map(int, input().split())))
for z in range(n):
(min1, max1) = (min(min1, a[z]), max(max1, a[z]))
for z in range(Q):
print('Yes') if int(input()) in range(min1, max1 + 1) else print('No') |
"""Task:"""
# Imports --------------------------------------------------------------
# Classes --------------------------------------------------------------
# Functions ------------------------------------------------------------
# Methods --------------------------------------------------------------
# Define Variables -----------------------------------------------------
# Execute Code ---------------------------------------------------------
| """Task:""" |
# Hash Table
# A website domain like "discuss.leetcode.com" consists of various subdomains. At the top level, we have "com", at the next level, we have "leetcode.com", and at the lowest level, "discuss.leetcode.com". When we visit a domain like "discuss.leetcode.com", we will also visit the parent domains "leetcode.com" and "com" implicitly.
#
# Now, call a "count-paired domain" to be a count (representing the number of visits this domain received), followed by a space, followed by the address. An example of a count-paired domain might be "9001 discuss.leetcode.com".
#
# We are given a list cpdomains of count-paired domains. We would like a list of count-paired domains, (in the same format as the input, and in any order), that explicitly counts the number of visits to each subdomain.
#
# Example 1:
# Input:
# ["9001 discuss.leetcode.com"]
# Output:
# ["9001 discuss.leetcode.com", "9001 leetcode.com", "9001 com"]
# Explanation:
# We only have one website domain: "discuss.leetcode.com". As discussed above, the subdomain "leetcode.com" and "com" will also be visited. So they will all be visited 9001 times.
#
# Example 2:
# Input:
# ["900 google.mail.com", "50 yahoo.com", "1 intel.mail.com", "5 wiki.org"]
# Output:
# ["901 mail.com","50 yahoo.com","900 google.mail.com","5 wiki.org","5 org","1 intel.mail.com","951 com"]
# Explanation:
# We will visit "google.mail.com" 900 times, "yahoo.com" 50 times, "intel.mail.com" once and "wiki.org" 5 times. For the subdomains, we will visit "mail.com" 900 + 1 = 901 times, "com" 900 + 50 + 1 = 951 times, and "org" 5 times.
#
# Notes:
#
# The length of cpdomains will not exceed 100.
# The length of each domain name will not exceed 100.
# Each address will have either 1 or 2 "." characters.
# The input count in any count-paired domain will not exceed 10000.
# The answer output can be returned in any order.
class Solution:
def subdomainVisits(self, cpdomains):
"""
:type cpdomains: List[str]
:rtype: List[str]
"""
pair = collections.defaultdict(int)
for item in cpdomains:
linkValue, link = item.split()
linkValue = int(linkValue)
pair[link] += linkValue
while "." in link:
link = link[link.find('.')+1:]
pair[link] += linkValue
output = []
for item in pair:
output.append(str(pair[item]) + " " + str(item))
return(output)
| class Solution:
def subdomain_visits(self, cpdomains):
"""
:type cpdomains: List[str]
:rtype: List[str]
"""
pair = collections.defaultdict(int)
for item in cpdomains:
(link_value, link) = item.split()
link_value = int(linkValue)
pair[link] += linkValue
while '.' in link:
link = link[link.find('.') + 1:]
pair[link] += linkValue
output = []
for item in pair:
output.append(str(pair[item]) + ' ' + str(item))
return output |
class Solution(object):
def singleNonDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) == 1:
return nums[0]
st = 0
ed = len(nums) - 1
if nums[st] != nums[st + 1]:
return nums[st]
if nums[ed] != nums[ed - 1]:
return nums[ed]
while st < ed:
md = int((st + ed) / 2)
if md % 2 == 0:
if nums[md] == nums[md + 1]:
st = md
continue
elif nums[md] == nums[md - 1]:
ed = md
continue
else:
return nums[md]
else:
if nums[md] == nums[md + 1]:
ed = md
continue
elif nums[md] == nums[md - 1]:
st = md
continue
else:
return nums[md]
return nums[st] | class Solution(object):
def single_non_duplicate(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) == 1:
return nums[0]
st = 0
ed = len(nums) - 1
if nums[st] != nums[st + 1]:
return nums[st]
if nums[ed] != nums[ed - 1]:
return nums[ed]
while st < ed:
md = int((st + ed) / 2)
if md % 2 == 0:
if nums[md] == nums[md + 1]:
st = md
continue
elif nums[md] == nums[md - 1]:
ed = md
continue
else:
return nums[md]
elif nums[md] == nums[md + 1]:
ed = md
continue
elif nums[md] == nums[md - 1]:
st = md
continue
else:
return nums[md]
return nums[st] |
_base_ = [
'../_base_/default_runtime.py', '../_base_/datasets/coco_detection.py'
]
# model settings
model = dict(
type='CenterNet',
pretrained='torchvision://resnet18',
backbone=dict(
type='ResNet',
depth=18,
num_stages=4,
out_indices=(0, 1, 2, 3),
frozen_stages=-1,
norm_cfg=dict(type='BN', requires_grad=True),
norm_eval=False,
zero_init_residual=False,
style='pytorch'),
neck=dict(
type='CenterFPN',
in_channels=(512, 256, 128, 64),
out_channels=64,
level_index=0,
reverse_levels=True,
with_last_norm=True,
with_last_relu=True,
upsample_cfg=dict(
type='deconv',
kernel_size=4,
stride=2,
padding=1,
output_padding=0,
bias=False)),
bbox_head=dict(
type='CenterHead',
num_classes=1,
in_channels=64,
feat_channels=64,
loss_heatmap=dict(
type='GaussianFocalLoss', alpha=2.0, gamma=4.0, loss_weight=1),
loss_offset=dict(type='L1Loss', loss_weight=1.0),
loss_bbox=dict(type='L1Loss', loss_weight=0.1)))
# training and testing settings
train_cfg = dict(
vis_every_n_iters=100,
min_overlap=0.7,
debug=False)
test_cfg = dict(
score_thr=0.01,
max_per_img=100)
# dataset settings, SEE: Normalize RGB https://aishack.in/tutorials/normalized-rgb/
img_norm_cfg = dict(
# NOTE: add `norm_rgb=True` if eval offical pretrained weights
# mean=[0.408, 0.447, 0.470], std=[0.289, 0.274, 0.278], to_rgb=False, norm_rgb=True)
# mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225], to_rgb=False, norm_rgb=True)
mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True)
train_pipeline = [
dict(type='LoadImageFromFile', to_float32=True),
dict(type='LoadAnnotations', with_bbox=True),
dict(type='PhotoMetricDistortion',
brightness_delta=32,
contrast_range=(0.5, 1.5),
saturation_range=(0.5, 1.5),
hue_delta=18),
dict(type='RandomLighting', scale=0.1),
dict(type='RandomCenterCropPad',
crop_size=(512, 512),
ratios=(0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3),
test_mode=False,
test_pad_mode=None,
**img_norm_cfg),
dict(type='Resize', img_scale=(512, 512), keep_ratio=False),
dict(type='RandomFlip', flip_ratio=0.5),
dict(type='Pad', size_divisor=32),
dict(type='Normalize', **img_norm_cfg),
dict(type='DefaultFormatBundle'),
dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']),
]
test_pipeline = [
dict(type='LoadImageFromFile', to_float32=True),
dict(
type='MultiScaleFlipAug',
scale_factor=1.0,
flip=False,
transforms=[
dict(type='Resize'),
dict(type='RandomFlip'),
dict(type='Pad', size_divisor=32),
dict(type='Normalize', **img_norm_cfg),
dict(type='ImageToTensor', keys=['img']),
dict(
type='Collect',
keys=['img'],
meta_keys=('filename', 'ori_shape', 'img_shape', 'pad_shape',
'scale_factor', 'flip', 'img_norm_cfg')),
])
]
classes = ('person', )
data = dict(
samples_per_gpu=32,
workers_per_gpu=2,
train=dict(classes=classes, pipeline=train_pipeline),
val=dict(classes=classes, pipeline=test_pipeline),
test=dict(classes=classes, pipeline=test_pipeline))
# optimizer
optimizer = dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0004,
paramwise_cfg=dict(bias_lr_mult=2., bias_decay_mult=0.))
optimizer_config = dict(grad_clip=dict(max_norm=35, norm_type=2))
# learning policy
lr_config = dict(
policy='step',
warmup='linear',
warmup_iters=1000,
warmup_ratio=1.0 / 5,
step=[90, 120])
checkpoint_config = dict(interval=5)
evaluation = dict(interval=1, metric=['bbox'], multitask=True)
# runtime settings
total_epochs = 140
cudnn_benchmark = True
find_unused_parameters = True | _base_ = ['../_base_/default_runtime.py', '../_base_/datasets/coco_detection.py']
model = dict(type='CenterNet', pretrained='torchvision://resnet18', backbone=dict(type='ResNet', depth=18, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=-1, norm_cfg=dict(type='BN', requires_grad=True), norm_eval=False, zero_init_residual=False, style='pytorch'), neck=dict(type='CenterFPN', in_channels=(512, 256, 128, 64), out_channels=64, level_index=0, reverse_levels=True, with_last_norm=True, with_last_relu=True, upsample_cfg=dict(type='deconv', kernel_size=4, stride=2, padding=1, output_padding=0, bias=False)), bbox_head=dict(type='CenterHead', num_classes=1, in_channels=64, feat_channels=64, loss_heatmap=dict(type='GaussianFocalLoss', alpha=2.0, gamma=4.0, loss_weight=1), loss_offset=dict(type='L1Loss', loss_weight=1.0), loss_bbox=dict(type='L1Loss', loss_weight=0.1)))
train_cfg = dict(vis_every_n_iters=100, min_overlap=0.7, debug=False)
test_cfg = dict(score_thr=0.01, max_per_img=100)
img_norm_cfg = dict(mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True)
train_pipeline = [dict(type='LoadImageFromFile', to_float32=True), dict(type='LoadAnnotations', with_bbox=True), dict(type='PhotoMetricDistortion', brightness_delta=32, contrast_range=(0.5, 1.5), saturation_range=(0.5, 1.5), hue_delta=18), dict(type='RandomLighting', scale=0.1), dict(type='RandomCenterCropPad', crop_size=(512, 512), ratios=(0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3), test_mode=False, test_pad_mode=None, **img_norm_cfg), dict(type='Resize', img_scale=(512, 512), keep_ratio=False), dict(type='RandomFlip', flip_ratio=0.5), dict(type='Pad', size_divisor=32), dict(type='Normalize', **img_norm_cfg), dict(type='DefaultFormatBundle'), dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels'])]
test_pipeline = [dict(type='LoadImageFromFile', to_float32=True), dict(type='MultiScaleFlipAug', scale_factor=1.0, flip=False, transforms=[dict(type='Resize'), dict(type='RandomFlip'), dict(type='Pad', size_divisor=32), dict(type='Normalize', **img_norm_cfg), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img'], meta_keys=('filename', 'ori_shape', 'img_shape', 'pad_shape', 'scale_factor', 'flip', 'img_norm_cfg'))])]
classes = ('person',)
data = dict(samples_per_gpu=32, workers_per_gpu=2, train=dict(classes=classes, pipeline=train_pipeline), val=dict(classes=classes, pipeline=test_pipeline), test=dict(classes=classes, pipeline=test_pipeline))
optimizer = dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0004, paramwise_cfg=dict(bias_lr_mult=2.0, bias_decay_mult=0.0))
optimizer_config = dict(grad_clip=dict(max_norm=35, norm_type=2))
lr_config = dict(policy='step', warmup='linear', warmup_iters=1000, warmup_ratio=1.0 / 5, step=[90, 120])
checkpoint_config = dict(interval=5)
evaluation = dict(interval=1, metric=['bbox'], multitask=True)
total_epochs = 140
cudnn_benchmark = True
find_unused_parameters = True |
class CTX:
"""
Global Class holding the configuration of the backward pass
"""
active_exts = tuple()
debug = False
@staticmethod
def set_active_exts(active_exts):
CTX.active_exts = tuple()
for act_ext in active_exts:
CTX.active_exts += (act_ext,)
@staticmethod
def get_active_exts():
return CTX.active_exts
@staticmethod
def add_hook_handle(hook_handle):
if getattr(CTX, "hook_handles", None) is None:
CTX.hook_handles = []
CTX.hook_handles.append(hook_handle)
@staticmethod
def remove_hooks():
for handle in CTX.hook_handles:
handle.remove()
CTX.hook_handles = []
@staticmethod
def is_extension_active(*extension_classes):
for backpack_ext in CTX.get_active_exts():
if isinstance(backpack_ext, extension_classes):
return True
return False
@staticmethod
def get_debug():
return CTX.debug
@staticmethod
def set_debug(debug):
CTX.debug = debug
| class Ctx:
"""
Global Class holding the configuration of the backward pass
"""
active_exts = tuple()
debug = False
@staticmethod
def set_active_exts(active_exts):
CTX.active_exts = tuple()
for act_ext in active_exts:
CTX.active_exts += (act_ext,)
@staticmethod
def get_active_exts():
return CTX.active_exts
@staticmethod
def add_hook_handle(hook_handle):
if getattr(CTX, 'hook_handles', None) is None:
CTX.hook_handles = []
CTX.hook_handles.append(hook_handle)
@staticmethod
def remove_hooks():
for handle in CTX.hook_handles:
handle.remove()
CTX.hook_handles = []
@staticmethod
def is_extension_active(*extension_classes):
for backpack_ext in CTX.get_active_exts():
if isinstance(backpack_ext, extension_classes):
return True
return False
@staticmethod
def get_debug():
return CTX.debug
@staticmethod
def set_debug(debug):
CTX.debug = debug |
# Copyright (c) 2012 OpenStack, LLC.
#
# Licensed under the Apache License, Version 2.0 (the 'License');
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an 'AS IS' BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
EXTENDED_ATTRIBUTES_2_0 = {
'networks': {
'v2attrs:something': {'allow_post': False,
'allow_put': False,
'is_visible': True},
'v2attrs:something_else': {'allow_post': True,
'allow_put': False,
'is_visible': False},
}
}
class V2attributes(object):
def get_name(self):
return "V2 Extended Attributes Example"
def get_alias(self):
return "v2attrs"
def get_description(self):
return "Demonstrates extended attributes on V2 core resources"
def get_namespace(self):
return "http://docs.openstack.org/ext/examples/v2attributes/api/v1.0"
def get_updated(self):
return "2012-07-18T10:00:00-00:00"
def get_extended_resources(self, version):
if version == "2.0":
return EXTENDED_ATTRIBUTES_2_0
else:
return {}
| extended_attributes_2_0 = {'networks': {'v2attrs:something': {'allow_post': False, 'allow_put': False, 'is_visible': True}, 'v2attrs:something_else': {'allow_post': True, 'allow_put': False, 'is_visible': False}}}
class V2Attributes(object):
def get_name(self):
return 'V2 Extended Attributes Example'
def get_alias(self):
return 'v2attrs'
def get_description(self):
return 'Demonstrates extended attributes on V2 core resources'
def get_namespace(self):
return 'http://docs.openstack.org/ext/examples/v2attributes/api/v1.0'
def get_updated(self):
return '2012-07-18T10:00:00-00:00'
def get_extended_resources(self, version):
if version == '2.0':
return EXTENDED_ATTRIBUTES_2_0
else:
return {} |
class HostVisual(ContainerVisual,IResource):
"""
Represents a System.Windows.Media.Visual object that can be connected anywhere to a parent visual tree.
HostVisual()
"""
def AddVisualChild(self,*args):
"""
AddVisualChild(self: Visual,child: Visual)
Defines the parent-child relationship between two visuals.
child: The child visual object to add to parent visual.
AddVisualChild(self: Window_16$17,child: Window_16$17)AddVisualChild(self: Label_17$18,child: Label_17$18)AddVisualChild(self: TextBox_18$19,child: TextBox_18$19)AddVisualChild(self: Button_19$20,child: Button_19$20)AddVisualChild(self: CheckBox_20$21,child: CheckBox_20$21)AddVisualChild(self: ComboBox_21$22,child: ComboBox_21$22)AddVisualChild(self: Separator_22$23,child: Separator_22$23)
"""
pass
def GetVisualChild(self,*args):
"""
GetVisualChild(self: ContainerVisual,index: int) -> Visual
Returns a specified child System.Windows.Media.Visual for the parent
System.Windows.Media.ContainerVisual.
index: A 32-bit signed integer that represents the index value of the child
System.Windows.Media.Visual. The value of index must be between 0 and
System.Windows.Media.ContainerVisual.VisualChildrenCount - 1.
Returns: The child System.Windows.Media.Visual.
"""
pass
def HitTestCore(self,*args):
"""
HitTestCore(self: HostVisual,hitTestParameters: GeometryHitTestParameters) -> GeometryHitTestResult
Implements
System.Windows.Media.HostVisual.HitTestCore(System.Windows.Media.GeometryHitTest
Parameters) to supply base hit testing behavior (returning
System.Windows.Media.GeometryHitTestParameters).
hitTestParameters: A value of type System.Windows.Media.GeometryHitTestParameters.
Returns: Returns a value of type System.Windows.Media.GeometryHitTestResult. The
System.Windows.Media.GeometryHitTestResult.VisualHit property contains the
visual that was hit.
HitTestCore(self: HostVisual,hitTestParameters: PointHitTestParameters) -> HitTestResult
Implements
System.Windows.Media.HostVisual.HitTestCore(System.Windows.Media.PointHitTestPar
ameters) to supply base hit testing behavior (returning
System.Windows.Media.PointHitTestParameters).
hitTestParameters: A value of type System.Windows.Media.PointHitTestParameters.
Returns: Returns a value of type System.Windows.Media.HitTestResult. The
System.Windows.Media.HitTestResult.VisualHit property contains the visual
object that was hit.
"""
pass
def OnDpiChanged(self,*args):
""" OnDpiChanged(self: Visual,oldDpi: DpiScale,newDpi: DpiScale)OnDpiChanged(self: Window_16$17,oldDpi: DpiScale,newDpi: DpiScale)OnDpiChanged(self: Label_17$18,oldDpi: DpiScale,newDpi: DpiScale)OnDpiChanged(self: TextBox_18$19,oldDpi: DpiScale,newDpi: DpiScale)OnDpiChanged(self: Button_19$20,oldDpi: DpiScale,newDpi: DpiScale)OnDpiChanged(self: CheckBox_20$21,oldDpi: DpiScale,newDpi: DpiScale)OnDpiChanged(self: ComboBox_21$22,oldDpi: DpiScale,newDpi: DpiScale)OnDpiChanged(self: Separator_22$23,oldDpi: DpiScale,newDpi: DpiScale) """
pass
def OnPropertyChanged(self,*args):
"""
OnPropertyChanged(self: DependencyObject,e: DependencyPropertyChangedEventArgs)
Invoked whenever the effective value of any dependency property on this
System.Windows.DependencyObject has been updated. The specific dependency
property that changed is reported in the event data.
e: Event data that will contain the dependency property identifier of interest,
the property metadata for the type,and old and new values.
OnPropertyChanged(self: Window_16$17,e: DependencyPropertyChangedEventArgs)OnPropertyChanged(self: Label_17$18,e: DependencyPropertyChangedEventArgs)OnPropertyChanged(self: TextBox_18$19,e: DependencyPropertyChangedEventArgs)OnPropertyChanged(self: Button_19$20,e: DependencyPropertyChangedEventArgs)OnPropertyChanged(self: CheckBox_20$21,e: DependencyPropertyChangedEventArgs)OnPropertyChanged(self: ComboBox_21$22,e: DependencyPropertyChangedEventArgs)OnPropertyChanged(self: Separator_22$23,e: DependencyPropertyChangedEventArgs)
"""
pass
def OnVisualChildrenChanged(self,*args):
"""
OnVisualChildrenChanged(self: Visual,visualAdded: DependencyObject,visualRemoved: DependencyObject)
Called when the System.Windows.Media.VisualCollection of the visual object is
modified.
visualAdded: The System.Windows.Media.Visual that was added to the collection
visualRemoved: The System.Windows.Media.Visual that was removed from the collection
OnVisualChildrenChanged(self: Window_16$17,visualAdded: DependencyObject,visualRemoved: DependencyObject)OnVisualChildrenChanged(self: Label_17$18,visualAdded: DependencyObject,visualRemoved: DependencyObject)OnVisualChildrenChanged(self: TextBox_18$19,visualAdded: DependencyObject,visualRemoved: DependencyObject)OnVisualChildrenChanged(self: Button_19$20,visualAdded: DependencyObject,visualRemoved: DependencyObject)OnVisualChildrenChanged(self: CheckBox_20$21,visualAdded: DependencyObject,visualRemoved: DependencyObject)OnVisualChildrenChanged(self: ComboBox_21$22,visualAdded: DependencyObject,visualRemoved: DependencyObject)OnVisualChildrenChanged(self: Separator_22$23,visualAdded: DependencyObject,visualRemoved: DependencyObject)
"""
pass
def OnVisualParentChanged(self,*args):
"""
OnVisualParentChanged(self: Visual,oldParent: DependencyObject)
Called when the parent of the visual object is changed.
oldParent: A value of type System.Windows.DependencyObject that represents the previous
parent of the System.Windows.Media.Visual object. If the
System.Windows.Media.Visual object did not have a previous parent,the value of
the parameter is null.
OnVisualParentChanged(self: Window_16$17,oldParent: DependencyObject)OnVisualParentChanged(self: Label_17$18,oldParent: DependencyObject)OnVisualParentChanged(self: TextBox_18$19,oldParent: DependencyObject)OnVisualParentChanged(self: Button_19$20,oldParent: DependencyObject)OnVisualParentChanged(self: CheckBox_20$21,oldParent: DependencyObject)OnVisualParentChanged(self: ComboBox_21$22,oldParent: DependencyObject)OnVisualParentChanged(self: Separator_22$23,oldParent: DependencyObject)
"""
pass
def RemoveVisualChild(self,*args):
"""
RemoveVisualChild(self: Visual,child: Visual)
Removes the parent-child relationship between two visuals.
child: The child visual object to remove from the parent visual.
RemoveVisualChild(self: Window_16$17,child: Window_16$17)RemoveVisualChild(self: Label_17$18,child: Label_17$18)RemoveVisualChild(self: TextBox_18$19,child: TextBox_18$19)RemoveVisualChild(self: Button_19$20,child: Button_19$20)RemoveVisualChild(self: CheckBox_20$21,child: CheckBox_20$21)RemoveVisualChild(self: ComboBox_21$22,child: ComboBox_21$22)RemoveVisualChild(self: Separator_22$23,child: Separator_22$23)
"""
pass
def ShouldSerializeProperty(self,*args):
"""
ShouldSerializeProperty(self: DependencyObject,dp: DependencyProperty) -> bool
Returns a value that indicates whether serialization processes should serialize
the value for the provided dependency property.
dp: The identifier for the dependency property that should be serialized.
Returns: true if the dependency property that is supplied should be value-serialized;
otherwise,false.
ShouldSerializeProperty(self: Window_16$17,dp: DependencyProperty) -> bool
ShouldSerializeProperty(self: Label_17$18,dp: DependencyProperty) -> bool
ShouldSerializeProperty(self: TextBox_18$19,dp: DependencyProperty) -> bool
ShouldSerializeProperty(self: Button_19$20,dp: DependencyProperty) -> bool
ShouldSerializeProperty(self: CheckBox_20$21,dp: DependencyProperty) -> bool
ShouldSerializeProperty(self: ComboBox_21$22,dp: DependencyProperty) -> bool
ShouldSerializeProperty(self: Separator_22$23,dp: DependencyProperty) -> bool
"""
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
VisualBitmapEffect=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the System.Windows.Media.Effects.BitmapEffect value for the System.Windows.Media.Visual.
"""
VisualBitmapEffectInput=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the System.Windows.Media.Effects.BitmapEffectInput value for the System.Windows.Media.Visual.
"""
VisualBitmapScalingMode=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the System.Windows.Media.BitmapScalingMode for the System.Windows.Media.Visual.
"""
VisualCacheMode=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets a cached representation of the System.Windows.Media.Visual.
"""
VisualChildrenCount=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the number of children for the System.Windows.Media.ContainerVisual.
"""
VisualClearTypeHint=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the System.Windows.Media.ClearTypeHint that determines how ClearType is rendered in the System.Windows.Media.Visual.
"""
VisualClip=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the clip region of the System.Windows.Media.Visual as a System.Windows.Media.Geometry value.
"""
VisualEdgeMode=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the edge mode of the System.Windows.Media.Visual as an System.Windows.Media.EdgeMode value.
"""
VisualEffect=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the bitmap effect to apply to the System.Windows.Media.Visual.
"""
VisualOffset=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the offset value of the visual object.
"""
VisualOpacity=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the opacity of the System.Windows.Media.Visual.
"""
VisualOpacityMask=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the System.Windows.Media.Brush value that represents the opacity mask of the System.Windows.Media.Visual.
"""
VisualParent=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the visual tree parent of the visual object.
"""
VisualScrollableAreaClip=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets a clipped scrollable area for the System.Windows.Media.Visual.
"""
VisualTextHintingMode=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the System.Windows.Media.TextHintingMode of the System.Windows.Media.Visual.
"""
VisualTextRenderingMode=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the System.Windows.Media.TextRenderingMode of the System.Windows.Media.Visual.
"""
VisualTransform=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the System.Windows.Media.Transform value for the System.Windows.Media.Visual.
"""
VisualXSnappingGuidelines=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the x-coordinate (vertical) guideline collection.
"""
VisualYSnappingGuidelines=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the y-coordinate (horizontal) guideline collection.
"""
| class Hostvisual(ContainerVisual, IResource):
"""
Represents a System.Windows.Media.Visual object that can be connected anywhere to a parent visual tree.
HostVisual()
"""
def add_visual_child(self, *args):
"""
AddVisualChild(self: Visual,child: Visual)
Defines the parent-child relationship between two visuals.
child: The child visual object to add to parent visual.
AddVisualChild(self: Window_16$17,child: Window_16$17)AddVisualChild(self: Label_17$18,child: Label_17$18)AddVisualChild(self: TextBox_18$19,child: TextBox_18$19)AddVisualChild(self: Button_19$20,child: Button_19$20)AddVisualChild(self: CheckBox_20$21,child: CheckBox_20$21)AddVisualChild(self: ComboBox_21$22,child: ComboBox_21$22)AddVisualChild(self: Separator_22$23,child: Separator_22$23)
"""
pass
def get_visual_child(self, *args):
"""
GetVisualChild(self: ContainerVisual,index: int) -> Visual
Returns a specified child System.Windows.Media.Visual for the parent
System.Windows.Media.ContainerVisual.
index: A 32-bit signed integer that represents the index value of the child
System.Windows.Media.Visual. The value of index must be between 0 and
System.Windows.Media.ContainerVisual.VisualChildrenCount - 1.
Returns: The child System.Windows.Media.Visual.
"""
pass
def hit_test_core(self, *args):
"""
HitTestCore(self: HostVisual,hitTestParameters: GeometryHitTestParameters) -> GeometryHitTestResult
Implements
System.Windows.Media.HostVisual.HitTestCore(System.Windows.Media.GeometryHitTest
Parameters) to supply base hit testing behavior (returning
System.Windows.Media.GeometryHitTestParameters).
hitTestParameters: A value of type System.Windows.Media.GeometryHitTestParameters.
Returns: Returns a value of type System.Windows.Media.GeometryHitTestResult. The
System.Windows.Media.GeometryHitTestResult.VisualHit property contains the
visual that was hit.
HitTestCore(self: HostVisual,hitTestParameters: PointHitTestParameters) -> HitTestResult
Implements
System.Windows.Media.HostVisual.HitTestCore(System.Windows.Media.PointHitTestPar
ameters) to supply base hit testing behavior (returning
System.Windows.Media.PointHitTestParameters).
hitTestParameters: A value of type System.Windows.Media.PointHitTestParameters.
Returns: Returns a value of type System.Windows.Media.HitTestResult. The
System.Windows.Media.HitTestResult.VisualHit property contains the visual
object that was hit.
"""
pass
def on_dpi_changed(self, *args):
""" OnDpiChanged(self: Visual,oldDpi: DpiScale,newDpi: DpiScale)OnDpiChanged(self: Window_16$17,oldDpi: DpiScale,newDpi: DpiScale)OnDpiChanged(self: Label_17$18,oldDpi: DpiScale,newDpi: DpiScale)OnDpiChanged(self: TextBox_18$19,oldDpi: DpiScale,newDpi: DpiScale)OnDpiChanged(self: Button_19$20,oldDpi: DpiScale,newDpi: DpiScale)OnDpiChanged(self: CheckBox_20$21,oldDpi: DpiScale,newDpi: DpiScale)OnDpiChanged(self: ComboBox_21$22,oldDpi: DpiScale,newDpi: DpiScale)OnDpiChanged(self: Separator_22$23,oldDpi: DpiScale,newDpi: DpiScale) """
pass
def on_property_changed(self, *args):
"""
OnPropertyChanged(self: DependencyObject,e: DependencyPropertyChangedEventArgs)
Invoked whenever the effective value of any dependency property on this
System.Windows.DependencyObject has been updated. The specific dependency
property that changed is reported in the event data.
e: Event data that will contain the dependency property identifier of interest,
the property metadata for the type,and old and new values.
OnPropertyChanged(self: Window_16$17,e: DependencyPropertyChangedEventArgs)OnPropertyChanged(self: Label_17$18,e: DependencyPropertyChangedEventArgs)OnPropertyChanged(self: TextBox_18$19,e: DependencyPropertyChangedEventArgs)OnPropertyChanged(self: Button_19$20,e: DependencyPropertyChangedEventArgs)OnPropertyChanged(self: CheckBox_20$21,e: DependencyPropertyChangedEventArgs)OnPropertyChanged(self: ComboBox_21$22,e: DependencyPropertyChangedEventArgs)OnPropertyChanged(self: Separator_22$23,e: DependencyPropertyChangedEventArgs)
"""
pass
def on_visual_children_changed(self, *args):
"""
OnVisualChildrenChanged(self: Visual,visualAdded: DependencyObject,visualRemoved: DependencyObject)
Called when the System.Windows.Media.VisualCollection of the visual object is
modified.
visualAdded: The System.Windows.Media.Visual that was added to the collection
visualRemoved: The System.Windows.Media.Visual that was removed from the collection
OnVisualChildrenChanged(self: Window_16$17,visualAdded: DependencyObject,visualRemoved: DependencyObject)OnVisualChildrenChanged(self: Label_17$18,visualAdded: DependencyObject,visualRemoved: DependencyObject)OnVisualChildrenChanged(self: TextBox_18$19,visualAdded: DependencyObject,visualRemoved: DependencyObject)OnVisualChildrenChanged(self: Button_19$20,visualAdded: DependencyObject,visualRemoved: DependencyObject)OnVisualChildrenChanged(self: CheckBox_20$21,visualAdded: DependencyObject,visualRemoved: DependencyObject)OnVisualChildrenChanged(self: ComboBox_21$22,visualAdded: DependencyObject,visualRemoved: DependencyObject)OnVisualChildrenChanged(self: Separator_22$23,visualAdded: DependencyObject,visualRemoved: DependencyObject)
"""
pass
def on_visual_parent_changed(self, *args):
"""
OnVisualParentChanged(self: Visual,oldParent: DependencyObject)
Called when the parent of the visual object is changed.
oldParent: A value of type System.Windows.DependencyObject that represents the previous
parent of the System.Windows.Media.Visual object. If the
System.Windows.Media.Visual object did not have a previous parent,the value of
the parameter is null.
OnVisualParentChanged(self: Window_16$17,oldParent: DependencyObject)OnVisualParentChanged(self: Label_17$18,oldParent: DependencyObject)OnVisualParentChanged(self: TextBox_18$19,oldParent: DependencyObject)OnVisualParentChanged(self: Button_19$20,oldParent: DependencyObject)OnVisualParentChanged(self: CheckBox_20$21,oldParent: DependencyObject)OnVisualParentChanged(self: ComboBox_21$22,oldParent: DependencyObject)OnVisualParentChanged(self: Separator_22$23,oldParent: DependencyObject)
"""
pass
def remove_visual_child(self, *args):
"""
RemoveVisualChild(self: Visual,child: Visual)
Removes the parent-child relationship between two visuals.
child: The child visual object to remove from the parent visual.
RemoveVisualChild(self: Window_16$17,child: Window_16$17)RemoveVisualChild(self: Label_17$18,child: Label_17$18)RemoveVisualChild(self: TextBox_18$19,child: TextBox_18$19)RemoveVisualChild(self: Button_19$20,child: Button_19$20)RemoveVisualChild(self: CheckBox_20$21,child: CheckBox_20$21)RemoveVisualChild(self: ComboBox_21$22,child: ComboBox_21$22)RemoveVisualChild(self: Separator_22$23,child: Separator_22$23)
"""
pass
def should_serialize_property(self, *args):
"""
ShouldSerializeProperty(self: DependencyObject,dp: DependencyProperty) -> bool
Returns a value that indicates whether serialization processes should serialize
the value for the provided dependency property.
dp: The identifier for the dependency property that should be serialized.
Returns: true if the dependency property that is supplied should be value-serialized;
otherwise,false.
ShouldSerializeProperty(self: Window_16$17,dp: DependencyProperty) -> bool
ShouldSerializeProperty(self: Label_17$18,dp: DependencyProperty) -> bool
ShouldSerializeProperty(self: TextBox_18$19,dp: DependencyProperty) -> bool
ShouldSerializeProperty(self: Button_19$20,dp: DependencyProperty) -> bool
ShouldSerializeProperty(self: CheckBox_20$21,dp: DependencyProperty) -> bool
ShouldSerializeProperty(self: ComboBox_21$22,dp: DependencyProperty) -> bool
ShouldSerializeProperty(self: Separator_22$23,dp: DependencyProperty) -> bool
"""
pass
def __init__(self, *args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
visual_bitmap_effect = property(lambda self: object(), lambda self, v: None, lambda self: None)
'Gets or sets the System.Windows.Media.Effects.BitmapEffect value for the System.Windows.Media.Visual.\n\n\n\n'
visual_bitmap_effect_input = property(lambda self: object(), lambda self, v: None, lambda self: None)
'Gets or sets the System.Windows.Media.Effects.BitmapEffectInput value for the System.Windows.Media.Visual.\n\n\n\n'
visual_bitmap_scaling_mode = property(lambda self: object(), lambda self, v: None, lambda self: None)
'Gets or sets the System.Windows.Media.BitmapScalingMode for the System.Windows.Media.Visual.\n\n\n\n'
visual_cache_mode = property(lambda self: object(), lambda self, v: None, lambda self: None)
'Gets or sets a cached representation of the System.Windows.Media.Visual.\n\n\n\n'
visual_children_count = property(lambda self: object(), lambda self, v: None, lambda self: None)
'Gets the number of children for the System.Windows.Media.ContainerVisual.\n\n\n\n'
visual_clear_type_hint = property(lambda self: object(), lambda self, v: None, lambda self: None)
'Gets or sets the System.Windows.Media.ClearTypeHint that determines how ClearType is rendered in the System.Windows.Media.Visual.\n\n\n\n'
visual_clip = property(lambda self: object(), lambda self, v: None, lambda self: None)
'Gets or sets the clip region of the System.Windows.Media.Visual as a System.Windows.Media.Geometry value.\n\n\n\n'
visual_edge_mode = property(lambda self: object(), lambda self, v: None, lambda self: None)
'Gets or sets the edge mode of the System.Windows.Media.Visual as an System.Windows.Media.EdgeMode value.\n\n\n\n'
visual_effect = property(lambda self: object(), lambda self, v: None, lambda self: None)
'Gets or sets the bitmap effect to apply to the System.Windows.Media.Visual.\n\n\n\n'
visual_offset = property(lambda self: object(), lambda self, v: None, lambda self: None)
'Gets or sets the offset value of the visual object.\n\n\n\n'
visual_opacity = property(lambda self: object(), lambda self, v: None, lambda self: None)
'Gets or sets the opacity of the System.Windows.Media.Visual.\n\n\n\n'
visual_opacity_mask = property(lambda self: object(), lambda self, v: None, lambda self: None)
'Gets or sets the System.Windows.Media.Brush value that represents the opacity mask of the System.Windows.Media.Visual.\n\n\n\n'
visual_parent = property(lambda self: object(), lambda self, v: None, lambda self: None)
'Gets the visual tree parent of the visual object.\n\n\n\n'
visual_scrollable_area_clip = property(lambda self: object(), lambda self, v: None, lambda self: None)
'Gets or sets a clipped scrollable area for the System.Windows.Media.Visual.\n\n\n\n'
visual_text_hinting_mode = property(lambda self: object(), lambda self, v: None, lambda self: None)
'Gets or sets the System.Windows.Media.TextHintingMode of the System.Windows.Media.Visual.\n\n\n\n'
visual_text_rendering_mode = property(lambda self: object(), lambda self, v: None, lambda self: None)
'Gets or sets the System.Windows.Media.TextRenderingMode of the System.Windows.Media.Visual.\n\n\n\n'
visual_transform = property(lambda self: object(), lambda self, v: None, lambda self: None)
'Gets or sets the System.Windows.Media.Transform value for the System.Windows.Media.Visual.\n\n\n\n'
visual_x_snapping_guidelines = property(lambda self: object(), lambda self, v: None, lambda self: None)
'Gets or sets the x-coordinate (vertical) guideline collection.\n\n\n\n'
visual_y_snapping_guidelines = property(lambda self: object(), lambda self, v: None, lambda self: None)
'Gets or sets the y-coordinate (horizontal) guideline collection.\n\n\n\n' |
# Python Program to subtract two numbers
# Store input numbers
num1 = input("Enter first number: ")
num2 = input("Enter second number: ")
# Sub two numbers
sub = float(num1) - float(num2)
# Display the sub
print("The sub of {0} and {1} is {2}".format(num1, num2, sub))
| num1 = input('Enter first number: ')
num2 = input('Enter second number: ')
sub = float(num1) - float(num2)
print('The sub of {0} and {1} is {2}'.format(num1, num2, sub)) |
BACKTEST_FLOW_OK = {
"nodeList": {
"1": {
"blockType": "DATA_BLOCK",
"blockId": 1,
"equity_name": {"options": ["AAPL"], "value": ""},
"data_type": {"options": ["intraday", "daily_adjusted"], "value": ""},
"interval": {"options": ["1min"], "value": ""},
"outputsize": {"options": ["compact", "full"], "value": ""},
"start_date": {"value": ""},
"end_date": {"value": ""},
},
},
"edgeList": [],
}
SCREENER_FLOW_OK = {
"nodeList": {
"1": {
"blockType": "BULK_DATA_BLOCK",
"blockId": 1,
"equity_name": {"options": ["AAPL"], "value": ""},
"data_type": {"options": ["intraday", "daily_adjusted"], "value": ""},
"interval": {"options": ["1min"], "value": ""},
"outputsize": {"options": ["compact", "full"], "value": ""},
"start_date": {"value": ""},
"end_date": {"value": ""},
},
},
"edgeList": [],
}
| backtest_flow_ok = {'nodeList': {'1': {'blockType': 'DATA_BLOCK', 'blockId': 1, 'equity_name': {'options': ['AAPL'], 'value': ''}, 'data_type': {'options': ['intraday', 'daily_adjusted'], 'value': ''}, 'interval': {'options': ['1min'], 'value': ''}, 'outputsize': {'options': ['compact', 'full'], 'value': ''}, 'start_date': {'value': ''}, 'end_date': {'value': ''}}}, 'edgeList': []}
screener_flow_ok = {'nodeList': {'1': {'blockType': 'BULK_DATA_BLOCK', 'blockId': 1, 'equity_name': {'options': ['AAPL'], 'value': ''}, 'data_type': {'options': ['intraday', 'daily_adjusted'], 'value': ''}, 'interval': {'options': ['1min'], 'value': ''}, 'outputsize': {'options': ['compact', 'full'], 'value': ''}, 'start_date': {'value': ''}, 'end_date': {'value': ''}}}, 'edgeList': []} |
numbers = [14, 2,3,4,5,6,7,6,5,7,8,8,9,10,11,12,13,14,14]
numbers2 =[]
for number in numbers:
if number not in numbers2:
numbers2.append(number)
print(numbers2) | numbers = [14, 2, 3, 4, 5, 6, 7, 6, 5, 7, 8, 8, 9, 10, 11, 12, 13, 14, 14]
numbers2 = []
for number in numbers:
if number not in numbers2:
numbers2.append(number)
print(numbers2) |
def solution(n: int) -> int:
b = to_bin(n)
if len(b) < 3:
return 0
gaps = []
gap_count = 0
for i in range(len(b)):
if b[i] == "1":
# gap stop. save gap and start counting again
gaps.append(gap_count)
# reset gap count
gap_count = 0
else:
# gap found
gap_count += 1
print(gaps)
return max(gaps)
def solution2(n: int) -> int:
b = to_bin(n)
len_b = len(b)
if len_b < 3:
return 0
max_gap = 0
gap_counter = 0
for i in range(len_b):
if b[i] == "1":
max_gap = gap_counter if gap_counter > max_gap else max_gap
# reset counter
gap_counter = 0
else:
gap_counter += 1
return max_gap
def to_bin(n: int) -> str:
"""convert number to binary """
b = bin(n)
return b[2:]
if __name__ == "__main__":
print(solution(1041))
print(solution2(1041))
print(solution(32))
print(solution2(32))
| def solution(n: int) -> int:
b = to_bin(n)
if len(b) < 3:
return 0
gaps = []
gap_count = 0
for i in range(len(b)):
if b[i] == '1':
gaps.append(gap_count)
gap_count = 0
else:
gap_count += 1
print(gaps)
return max(gaps)
def solution2(n: int) -> int:
b = to_bin(n)
len_b = len(b)
if len_b < 3:
return 0
max_gap = 0
gap_counter = 0
for i in range(len_b):
if b[i] == '1':
max_gap = gap_counter if gap_counter > max_gap else max_gap
gap_counter = 0
else:
gap_counter += 1
return max_gap
def to_bin(n: int) -> str:
"""convert number to binary """
b = bin(n)
return b[2:]
if __name__ == '__main__':
print(solution(1041))
print(solution2(1041))
print(solution(32))
print(solution2(32)) |
class MyClass:
print('MyClass created')
# instansiate a class
my_var = MyClass()
print(type(my_var))
print(dir(my_var)) | class Myclass:
print('MyClass created')
my_var = my_class()
print(type(my_var))
print(dir(my_var)) |
"""Provides a redirection point for platform specific implementations of starlark utilities."""
load(
"//tensorflow/core/platform:default/build_config.bzl",
_pyx_library = "pyx_library",
_tf_additional_all_protos = "tf_additional_all_protos",
_tf_additional_binary_deps = "tf_additional_binary_deps",
_tf_additional_core_deps = "tf_additional_core_deps",
_tf_additional_cupti_test_flags = "tf_additional_cupti_test_flags",
_tf_additional_cupti_utils_cuda_deps = "tf_additional_cupti_utils_cuda_deps",
_tf_additional_device_tracer_srcs = "tf_additional_device_tracer_srcs",
_tf_additional_env_hdrs = "tf_additional_env_hdrs",
_tf_additional_lib_deps = "tf_additional_lib_deps",
_tf_additional_lib_hdrs = "tf_additional_lib_hdrs",
_tf_additional_monitoring_hdrs = "tf_additional_monitoring_hdrs",
_tf_additional_proto_hdrs = "tf_additional_proto_hdrs",
_tf_additional_rpc_deps = "tf_additional_rpc_deps",
_tf_additional_tensor_coding_deps = "tf_additional_tensor_coding_deps",
_tf_additional_test_deps = "tf_additional_test_deps",
_tf_additional_test_srcs = "tf_additional_test_srcs",
_tf_fingerprint_deps = "tf_fingerprint_deps",
_tf_jspb_proto_library = "tf_jspb_proto_library",
_tf_kernel_tests_linkstatic = "tf_kernel_tests_linkstatic",
_tf_lib_proto_parsing_deps = "tf_lib_proto_parsing_deps",
_tf_proto_library = "tf_proto_library",
_tf_proto_library_cc = "tf_proto_library_cc",
_tf_proto_library_py = "tf_proto_library_py",
_tf_protobuf_compiler_deps = "tf_protobuf_compiler_deps",
_tf_protobuf_deps = "tf_protobuf_deps",
_tf_protos_all = "tf_protos_all",
_tf_protos_all_impl = "tf_protos_all_impl",
_tf_protos_grappler = "tf_protos_grappler",
_tf_protos_grappler_impl = "tf_protos_grappler_impl",
_tf_protos_profiler_impl = "tf_protos_profiler_impl",
_tf_py_clif_cc = "tf_py_clif_cc",
_tf_pyclif_proto_library = "tf_pyclif_proto_library",
)
pyx_library = _pyx_library
tf_additional_all_protos = _tf_additional_all_protos
tf_additional_binary_deps = _tf_additional_binary_deps
tf_additional_core_deps = _tf_additional_core_deps
tf_additional_cupti_test_flags = _tf_additional_cupti_test_flags
tf_additional_cupti_utils_cuda_deps = _tf_additional_cupti_utils_cuda_deps
tf_additional_device_tracer_srcs = _tf_additional_device_tracer_srcs
tf_additional_env_hdrs = _tf_additional_env_hdrs
tf_additional_lib_deps = _tf_additional_lib_deps
tf_additional_lib_hdrs = _tf_additional_lib_hdrs
tf_additional_monitoring_hdrs = _tf_additional_monitoring_hdrs
tf_additional_proto_hdrs = _tf_additional_proto_hdrs
tf_additional_rpc_deps = _tf_additional_rpc_deps
tf_additional_tensor_coding_deps = _tf_additional_tensor_coding_deps
tf_additional_test_deps = _tf_additional_test_deps
tf_additional_test_srcs = _tf_additional_test_srcs
tf_fingerprint_deps = _tf_fingerprint_deps
tf_jspb_proto_library = _tf_jspb_proto_library
tf_kernel_tests_linkstatic = _tf_kernel_tests_linkstatic
tf_lib_proto_parsing_deps = _tf_lib_proto_parsing_deps
tf_proto_library = _tf_proto_library
tf_proto_library_cc = _tf_proto_library_cc
tf_proto_library_py = _tf_proto_library_py
tf_protobuf_compiler_deps = _tf_protobuf_compiler_deps
tf_protobuf_deps = _tf_protobuf_deps
tf_protos_all = _tf_protos_all
tf_protos_all_impl = _tf_protos_all_impl
tf_protos_grappler = _tf_protos_grappler
tf_protos_grappler_impl = _tf_protos_grappler_impl
tf_protos_profiler_impl = _tf_protos_profiler_impl
tf_py_clif_cc = _tf_py_clif_cc
tf_pyclif_proto_library = _tf_pyclif_proto_library
| """Provides a redirection point for platform specific implementations of starlark utilities."""
load('//tensorflow/core/platform:default/build_config.bzl', _pyx_library='pyx_library', _tf_additional_all_protos='tf_additional_all_protos', _tf_additional_binary_deps='tf_additional_binary_deps', _tf_additional_core_deps='tf_additional_core_deps', _tf_additional_cupti_test_flags='tf_additional_cupti_test_flags', _tf_additional_cupti_utils_cuda_deps='tf_additional_cupti_utils_cuda_deps', _tf_additional_device_tracer_srcs='tf_additional_device_tracer_srcs', _tf_additional_env_hdrs='tf_additional_env_hdrs', _tf_additional_lib_deps='tf_additional_lib_deps', _tf_additional_lib_hdrs='tf_additional_lib_hdrs', _tf_additional_monitoring_hdrs='tf_additional_monitoring_hdrs', _tf_additional_proto_hdrs='tf_additional_proto_hdrs', _tf_additional_rpc_deps='tf_additional_rpc_deps', _tf_additional_tensor_coding_deps='tf_additional_tensor_coding_deps', _tf_additional_test_deps='tf_additional_test_deps', _tf_additional_test_srcs='tf_additional_test_srcs', _tf_fingerprint_deps='tf_fingerprint_deps', _tf_jspb_proto_library='tf_jspb_proto_library', _tf_kernel_tests_linkstatic='tf_kernel_tests_linkstatic', _tf_lib_proto_parsing_deps='tf_lib_proto_parsing_deps', _tf_proto_library='tf_proto_library', _tf_proto_library_cc='tf_proto_library_cc', _tf_proto_library_py='tf_proto_library_py', _tf_protobuf_compiler_deps='tf_protobuf_compiler_deps', _tf_protobuf_deps='tf_protobuf_deps', _tf_protos_all='tf_protos_all', _tf_protos_all_impl='tf_protos_all_impl', _tf_protos_grappler='tf_protos_grappler', _tf_protos_grappler_impl='tf_protos_grappler_impl', _tf_protos_profiler_impl='tf_protos_profiler_impl', _tf_py_clif_cc='tf_py_clif_cc', _tf_pyclif_proto_library='tf_pyclif_proto_library')
pyx_library = _pyx_library
tf_additional_all_protos = _tf_additional_all_protos
tf_additional_binary_deps = _tf_additional_binary_deps
tf_additional_core_deps = _tf_additional_core_deps
tf_additional_cupti_test_flags = _tf_additional_cupti_test_flags
tf_additional_cupti_utils_cuda_deps = _tf_additional_cupti_utils_cuda_deps
tf_additional_device_tracer_srcs = _tf_additional_device_tracer_srcs
tf_additional_env_hdrs = _tf_additional_env_hdrs
tf_additional_lib_deps = _tf_additional_lib_deps
tf_additional_lib_hdrs = _tf_additional_lib_hdrs
tf_additional_monitoring_hdrs = _tf_additional_monitoring_hdrs
tf_additional_proto_hdrs = _tf_additional_proto_hdrs
tf_additional_rpc_deps = _tf_additional_rpc_deps
tf_additional_tensor_coding_deps = _tf_additional_tensor_coding_deps
tf_additional_test_deps = _tf_additional_test_deps
tf_additional_test_srcs = _tf_additional_test_srcs
tf_fingerprint_deps = _tf_fingerprint_deps
tf_jspb_proto_library = _tf_jspb_proto_library
tf_kernel_tests_linkstatic = _tf_kernel_tests_linkstatic
tf_lib_proto_parsing_deps = _tf_lib_proto_parsing_deps
tf_proto_library = _tf_proto_library
tf_proto_library_cc = _tf_proto_library_cc
tf_proto_library_py = _tf_proto_library_py
tf_protobuf_compiler_deps = _tf_protobuf_compiler_deps
tf_protobuf_deps = _tf_protobuf_deps
tf_protos_all = _tf_protos_all
tf_protos_all_impl = _tf_protos_all_impl
tf_protos_grappler = _tf_protos_grappler
tf_protos_grappler_impl = _tf_protos_grappler_impl
tf_protos_profiler_impl = _tf_protos_profiler_impl
tf_py_clif_cc = _tf_py_clif_cc
tf_pyclif_proto_library = _tf_pyclif_proto_library |
"""Should raise SyntaxError: name 'cc' is assigned to prior to global declaration
"""
aa, bb, cc, dd = 1, 2, 3, 4
def fn():
cc = 1
global aa, bb, cc, dd
| """Should raise SyntaxError: name 'cc' is assigned to prior to global declaration
"""
(aa, bb, cc, dd) = (1, 2, 3, 4)
def fn():
cc = 1
global aa, bb, cc, dd |
class BTNode:
__slots__ = "value", "left", "right"
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def test_BTNode():
parent = BTNode(10)
left = BTNode(20)
right = BTNode(30)
parent.left = left
parent.right = right
print (parent.value)
print (parent.left.value)
print (parent.right.value)
if __name__ == '__main__':
test_BTNode()
| class Btnode:
__slots__ = ('value', 'left', 'right')
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def test_bt_node():
parent = bt_node(10)
left = bt_node(20)
right = bt_node(30)
parent.left = left
parent.right = right
print(parent.value)
print(parent.left.value)
print(parent.right.value)
if __name__ == '__main__':
test_bt_node() |
"""
Convenience classes for returning multiple values from functions
Examples:
Success w/ data: return ok_resp(some_obj)
Success w/ data and a message: return ok_resp(some_obj, 'It worked')
Error w/ message: return err_resp('some error message')
Error w/ message and data: return err_resp('some error message', dict(failed_lines=[45, 72])
"""
class BasicResponse:
def __init__(self, success, message=None, data=None):
"""
Initialize
"""
assert success in (True, False), "Success must be a Python boolean"
self.success = success
self.message = message
self.data = data
def as_dict(self):
"""
Return as a Python dict
- Can be sent back as a Django JSONResponse
"""
info = dict(success=self.success)
if self.message:
info['message'] = self.message
if self.data:
info['data'] = self.data
return info
def is_success(self):
"""
Can also use .success
"""
return self.success
def ok_resp(data, message=None):
"""Return a SuccessResponse with success=True and data"""
return BasicResponse(True, message=message, data=data)
def err_resp(err_msg, data=None):
"""Return a ErrorResponse with success=False and err_msg"""
return BasicResponse(False, message=err_msg, data=data)
if __name__ == '__main__':
br = ok_resp(dict(median=34))
print(br.as_dict())
br = ok_resp(dict(median=34), 'it worked!')
print(br.as_dict())
br = err_resp('did not go so well')
print(br.as_dict())
br = err_resp('did not go so well', dict(failed_term=45))
print(br.as_dict())
| """
Convenience classes for returning multiple values from functions
Examples:
Success w/ data: return ok_resp(some_obj)
Success w/ data and a message: return ok_resp(some_obj, 'It worked')
Error w/ message: return err_resp('some error message')
Error w/ message and data: return err_resp('some error message', dict(failed_lines=[45, 72])
"""
class Basicresponse:
def __init__(self, success, message=None, data=None):
"""
Initialize
"""
assert success in (True, False), 'Success must be a Python boolean'
self.success = success
self.message = message
self.data = data
def as_dict(self):
"""
Return as a Python dict
- Can be sent back as a Django JSONResponse
"""
info = dict(success=self.success)
if self.message:
info['message'] = self.message
if self.data:
info['data'] = self.data
return info
def is_success(self):
"""
Can also use .success
"""
return self.success
def ok_resp(data, message=None):
"""Return a SuccessResponse with success=True and data"""
return basic_response(True, message=message, data=data)
def err_resp(err_msg, data=None):
"""Return a ErrorResponse with success=False and err_msg"""
return basic_response(False, message=err_msg, data=data)
if __name__ == '__main__':
br = ok_resp(dict(median=34))
print(br.as_dict())
br = ok_resp(dict(median=34), 'it worked!')
print(br.as_dict())
br = err_resp('did not go so well')
print(br.as_dict())
br = err_resp('did not go so well', dict(failed_term=45))
print(br.as_dict()) |
#!/usr/bin/python
# -*- coding: utf-8 -*-
DEBUG = True
USE_TZ = True
SECRET_KEY = "KEY"
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": ":memory:",
}
}
ROOT_URLCONF = "tests.urls"
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.messages",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.sites",
"beerfest",
"rest_framework",
]
MIDDLEWARE = (
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
)
SITE_ID = 1
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": ["tests/templates"],
"OPTIONS": {
"context_processors": [
"django.contrib.auth.context_processors.auth",
"django.contrib.messages.context_processors.messages",
],
},
},
]
| debug = True
use_tz = True
secret_key = 'KEY'
databases = {'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:'}}
root_urlconf = 'tests.urls'
installed_apps = ['django.contrib.admin', 'django.contrib.messages', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'beerfest', 'rest_framework']
middleware = ('django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware')
site_id = 1
templates = [{'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['tests/templates'], 'OPTIONS': {'context_processors': ['django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages']}}] |
#!/home/rob/.pyenv/shims/python3
def example(param):
"""param must be greater than 0"""
assert param > 0
#if __debug__:
# if not param > 0:
# raise AssertionError
# do stuff here...
if __name__ == '__main__':
example(0) | def example(param):
"""param must be greater than 0"""
assert param > 0
if __name__ == '__main__':
example(0) |
"""
VIS_DATA
"""
#def get_img_figure(n_subplots=1):
def plot_img(ax, img, **kwargs):
title = kwargs.pop('title', 'Image')
ax.imshow(img)
ax.set_title(title)
| """
VIS_DATA
"""
def plot_img(ax, img, **kwargs):
title = kwargs.pop('title', 'Image')
ax.imshow(img)
ax.set_title(title) |
# -*- coding: utf-8 -*-
"""
/***************************************************************************
Configuration file
The PlanHeat tool was implemented as part of the PLANHEAT project.
This file contains several global variables used inside the different sub-modules.
-------------------
begin : 2019-04-25
git sha : $Format:%H$
copyright : (C) 2019 by PlanHeat consortium
email : stefano.barberis@rina.org
***************************************************************************/
"""
### Files and directories
WORKING_DIRECTORY_NAME = "planheat_data"
TEMP_WORKING_DIRECTORY_NAME = "temp"
MAPPING_DIRECTORY_NAME = "mapping"
PLANNING_DIRECTORY_NAME = "planning"
PROJECT_INFO_JSON_NAME = "info.json"
# Mapping files
MAPPING_CMM_SMM_DB_FILE_NAME = "planheat.db"
DMM_FOLDER = "DMM"
DMM_PREFIX = "DMM_result"
DMM_FUTURE_SUFFIX = "_future"
DMM_HOURLY_SUFFIX = "_hourly"
DMM_FUTURE_HOURLY_SUFFIX = "_future_hourly"
SMM_FOLDER = "SMM"
CMM_BASELINE_FOLDER = "CMMB"
CMM_FUTURE_FOLDER = "CMMF"
INPUT_FOLDER = "input_files"
# Planning District files
DISTRICT_FOLDER = "District"
BASELINE_FOLDER = "Baseline"
FUTURE_FOLDER = "Future"
TOOLS_FOLDER = "Tools"
KPIS_FOLDER = "KPIs"
STREETS_FOLDER = "Streets"
BUILDING_SHAPE = "Building_shape"
# Planning City files
CITY_FOLDER = "City"
CMM_WIZARD_FOLDER = "Wizard"
# Clean files for master plugins
PROJECTS_CLEAN_DATA_DIR = "project_init_data"
ANTWERP_TEST_CASE_FILE_NAME = "antwerp_scenario_clean.zip"
# Objects constants names
PROJECT_NAME_KEY = "Name"
PROJECT_DESCRIPTION_KEY = "Description"
PROJECT_CREATION_DATE_KEY = "Creation date"
PROJECT_ID_KEY = "Id"
KEYS_TO_SHOW = [PROJECT_NAME_KEY, PROJECT_CREATION_DATE_KEY, PROJECT_DESCRIPTION_KEY]
DATE_FMT = "%Y-%m-%d %H:%M"
PROJECT_NAME_DEFAULT = "Unamed project" | """
/***************************************************************************
Configuration file
The PlanHeat tool was implemented as part of the PLANHEAT project.
This file contains several global variables used inside the different sub-modules.
-------------------
begin : 2019-04-25
git sha : $Format:%H$
copyright : (C) 2019 by PlanHeat consortium
email : stefano.barberis@rina.org
***************************************************************************/
"""
working_directory_name = 'planheat_data'
temp_working_directory_name = 'temp'
mapping_directory_name = 'mapping'
planning_directory_name = 'planning'
project_info_json_name = 'info.json'
mapping_cmm_smm_db_file_name = 'planheat.db'
dmm_folder = 'DMM'
dmm_prefix = 'DMM_result'
dmm_future_suffix = '_future'
dmm_hourly_suffix = '_hourly'
dmm_future_hourly_suffix = '_future_hourly'
smm_folder = 'SMM'
cmm_baseline_folder = 'CMMB'
cmm_future_folder = 'CMMF'
input_folder = 'input_files'
district_folder = 'District'
baseline_folder = 'Baseline'
future_folder = 'Future'
tools_folder = 'Tools'
kpis_folder = 'KPIs'
streets_folder = 'Streets'
building_shape = 'Building_shape'
city_folder = 'City'
cmm_wizard_folder = 'Wizard'
projects_clean_data_dir = 'project_init_data'
antwerp_test_case_file_name = 'antwerp_scenario_clean.zip'
project_name_key = 'Name'
project_description_key = 'Description'
project_creation_date_key = 'Creation date'
project_id_key = 'Id'
keys_to_show = [PROJECT_NAME_KEY, PROJECT_CREATION_DATE_KEY, PROJECT_DESCRIPTION_KEY]
date_fmt = '%Y-%m-%d %H:%M'
project_name_default = 'Unamed project' |
class Solution:
# @param prices, a list of integer
# @return an integer
def maxProfit(self, prices):
n = len(prices)
if n < 2:
return 0
min_price = prices[0]
res = 0
for i in xrange(1, n):
res = max(res, prices[i]-min_price)
min_price = min(min_price, prices[i])
return res
| class Solution:
def max_profit(self, prices):
n = len(prices)
if n < 2:
return 0
min_price = prices[0]
res = 0
for i in xrange(1, n):
res = max(res, prices[i] - min_price)
min_price = min(min_price, prices[i])
return res |
# Python 3: Simple output (with Unicode)
print("Hello, I'm Python!")
# Input, assignment
name = input('What is your name?\n')
print('Hi, %s.' % name)
| print("Hello, I'm Python!")
name = input('What is your name?\n')
print('Hi, %s.' % name) |
# Time complexity: O(n) where n is number of nodes in Tree
# Approach: Checking binary search tree conditions on each node recursively.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isValidBST(self, root: Optional[TreeNode], l=-2**31-1, r=2**31) -> bool:
if not root:
return True
elif l<root.val and root.val<r:
return self.isValidBST(root.left, l, root.val) and self.isValidBST(root.right, root.val, r)
return False | class Solution:
def is_valid_bst(self, root: Optional[TreeNode], l=-2 ** 31 - 1, r=2 ** 31) -> bool:
if not root:
return True
elif l < root.val and root.val < r:
return self.isValidBST(root.left, l, root.val) and self.isValidBST(root.right, root.val, r)
return False |
"""
1. Clarification
2. Possible solutions
- simulation
- math
3. Coding
4. Tests
"""
# T=O(n), S=O(n)
class Solution:
def totalMoney(self, n: int) -> int:
return sum(i%7 + 1 + i//7 for i in range(n))
# # T=O(1), S=O(1)
# class Solution:
# def totalMoney(self, n: int) -> int:
# extra, weeks = n % 7, n // 7
# return 28*weeks + 7*weeks*(weeks-1)//2 + weeks*extra + extra*(extra+1)//2
| """
1. Clarification
2. Possible solutions
- simulation
- math
3. Coding
4. Tests
"""
class Solution:
def total_money(self, n: int) -> int:
return sum((i % 7 + 1 + i // 7 for i in range(n))) |
class Node():
def __init__(self):
self.children = {}
self.endofword = False
self.string = ""
class Trie():
def __init__(self):
self.root = Node()
def insert(self, word):
pointer = self.root
for char in word:
if char not in pointer.children:
pointer.children[char] = Node()
pointer = pointer.children[char]
pointer.endofword = True
pointer.string = word
def search(self, word):
pointer = self.root
for char in word:
if char not in pointer.children:
# print("here")
return ""
pointer = pointer.children[char]
if pointer.endofword is True:
return pointer.string
return ""
class Solution:
def replaceWords(self, dict: List[str], sentence: str) -> str:
prefixtree = Trie()
ans = ""
for word in dict:
prefixtree.insert(word)
for word in sentence.split():
root = prefixtree.search(word)
if root == "":
ans += word
else:
ans += root
ans += " "
return ans[:-1]
| class Node:
def __init__(self):
self.children = {}
self.endofword = False
self.string = ''
class Trie:
def __init__(self):
self.root = node()
def insert(self, word):
pointer = self.root
for char in word:
if char not in pointer.children:
pointer.children[char] = node()
pointer = pointer.children[char]
pointer.endofword = True
pointer.string = word
def search(self, word):
pointer = self.root
for char in word:
if char not in pointer.children:
return ''
pointer = pointer.children[char]
if pointer.endofword is True:
return pointer.string
return ''
class Solution:
def replace_words(self, dict: List[str], sentence: str) -> str:
prefixtree = trie()
ans = ''
for word in dict:
prefixtree.insert(word)
for word in sentence.split():
root = prefixtree.search(word)
if root == '':
ans += word
else:
ans += root
ans += ' '
return ans[:-1] |
#-----------------------------------------------------------------------
# helper modules for argparse:
# - check if values are in a certain range, are positive, etc.
# - https://github.com/Sorbus/artichoke
#-----------------------------------------------------------------------
def check_range(value):
ivalue = int(value)
if ivalue < 1 or ivalue > 3200:
raise argparse.ArgumentTypeError("%s is not a valid positive int value" % value)
return ivalue
def check_positive(value):
ivalue = int(value)
if ivalue < 0:
raise argparse.ArgumentTypeError("%s is not a valid positive int value" % value)
return ivalue | def check_range(value):
ivalue = int(value)
if ivalue < 1 or ivalue > 3200:
raise argparse.ArgumentTypeError('%s is not a valid positive int value' % value)
return ivalue
def check_positive(value):
ivalue = int(value)
if ivalue < 0:
raise argparse.ArgumentTypeError('%s is not a valid positive int value' % value)
return ivalue |
#logaritmica
#No. de digitos de un numero
def digitos(i):
cont=0
if i == 0:
return '0'
while i > 0:
cont=cont+1
i = i//10
return cont
numeros=list(range(1,1000))
print(numeros)
ite=[]
for a in numeros:
ite.append(digitos(a))
print(digitos(a))
| def digitos(i):
cont = 0
if i == 0:
return '0'
while i > 0:
cont = cont + 1
i = i // 10
return cont
numeros = list(range(1, 1000))
print(numeros)
ite = []
for a in numeros:
ite.append(digitos(a))
print(digitos(a)) |
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 21 00:23:43 2019
@author: yanxi
"""
def addDummyNP(fname):
res=[]
with open(fname) as f:
for line in f:
l = line.split(',')
l.insert(2,'0')
res.append(','.join(l))
if len(res) != 0:
with open(fname, 'w') as f:
for line in res:
f.write(line)
| """
Created on Mon Oct 21 00:23:43 2019
@author: yanxi
"""
def add_dummy_np(fname):
res = []
with open(fname) as f:
for line in f:
l = line.split(',')
l.insert(2, '0')
res.append(','.join(l))
if len(res) != 0:
with open(fname, 'w') as f:
for line in res:
f.write(line) |
# Guess Number Higher or Lower II
class Solution(object):
def getMoneyAmount(self, n):
"""
the strategy is to choose the option that if the worst consequence of that option occurs,
it's the least worst case among all options
specifically, if picking any number in a range, find the highest amount of money to pay,
then choose the minimal highest amount (minmax)
dp[i][j]: smallest amount of money to pay to win in guessing from i to j
dp[i][i] = 0 no cost for one number
dp[i][i+1] = i pick the first in two numbers so that worst case is i
dp[i][j] = min(k + max(dp[i][k-1], dp[k+1][j])) i < k < j
(if k is picked, check highest amount to pay if the answer is on the left or right)
"""
dp = [[0] * (n + 1) for _ in range(n + 1)]
for i in range(1, n):
dp[i][i + 1] = i
for width in range(3, n + 1):
for i in range(1, n - width + 2):
j = i + width - 1
range_min = float('inf')
for k in range(i + 1, j):
curr_max = k + max(dp[i][k - 1], dp[k + 1][j])
range_min = min(range_min, curr_max)
dp[i][j] = range_min
return dp[1][n]
| class Solution(object):
def get_money_amount(self, n):
"""
the strategy is to choose the option that if the worst consequence of that option occurs,
it's the least worst case among all options
specifically, if picking any number in a range, find the highest amount of money to pay,
then choose the minimal highest amount (minmax)
dp[i][j]: smallest amount of money to pay to win in guessing from i to j
dp[i][i] = 0 no cost for one number
dp[i][i+1] = i pick the first in two numbers so that worst case is i
dp[i][j] = min(k + max(dp[i][k-1], dp[k+1][j])) i < k < j
(if k is picked, check highest amount to pay if the answer is on the left or right)
"""
dp = [[0] * (n + 1) for _ in range(n + 1)]
for i in range(1, n):
dp[i][i + 1] = i
for width in range(3, n + 1):
for i in range(1, n - width + 2):
j = i + width - 1
range_min = float('inf')
for k in range(i + 1, j):
curr_max = k + max(dp[i][k - 1], dp[k + 1][j])
range_min = min(range_min, curr_max)
dp[i][j] = range_min
return dp[1][n] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.