content
stringlengths 7
1.05M
| fixed_cases
stringlengths 1
1.28M
|
---|---|
class Solution(object):
def connect(self, root):
"""
:type root: TreeLinkNode
:rtype: nothing
"""
if root == None:
return
p = root.next
while p:
if p.left != None:
p = p.left
break
elif p.right != None:
p = p.right
break
p = p.next
if (root.right != None):
root.right.next = p
if(root.left != None):
if root.right != None:
root.left.next = root.right
else:
root.left.next = p
self.connect(root.right)
self.connect(root.left)
| class Solution(object):
def connect(self, root):
"""
:type root: TreeLinkNode
:rtype: nothing
"""
if root == None:
return
p = root.next
while p:
if p.left != None:
p = p.left
break
elif p.right != None:
p = p.right
break
p = p.next
if root.right != None:
root.right.next = p
if root.left != None:
if root.right != None:
root.left.next = root.right
else:
root.left.next = p
self.connect(root.right)
self.connect(root.left) |
# Tuples
coordinates = (4, 5) # Cant be changed or modified
print(coordinates[1])
# coordinates[1] = 10
# print(coordinates[1])
| coordinates = (4, 5)
print(coordinates[1]) |
# 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.
"""Compiles trivial C++ program using Goma.
Intended to be used as a very simple litmus test of Goma health on LUCI staging
environment. Linux and OSX only.
"""
DEPS = [
'build/goma',
'recipe_engine/context',
'recipe_engine/file',
'recipe_engine/path',
'recipe_engine/platform',
'recipe_engine/properties',
'recipe_engine/step',
'recipe_engine/time',
]
HELLO_WORLD_CPP = """
#include <iostream>
int get_number();
int main() {
std::cout << "Hello, world!" << std::endl;
std::cout << "Non-static part " << get_number() << std::endl;
return 0;
}
"""
MODULE_CPP = """
int get_number() {
return %(time)d;
}
"""
def RunSteps(api):
root_dir = api.path['tmp_base']
# TODO(vadimsh): We need to somehow pull clang binaries and use them instead
# of system-provided g++. Otherwise Goma may fall back to local execution,
# since system-provided g++ may not be whitelisted in Goma.
# One static object file and one "dynamic", to test cache hit and cache miss.
source_code = {
'hello_world.cpp': HELLO_WORLD_CPP,
'module.cpp': MODULE_CPP % {'time': int(api.time.time())},
}
for name, data in sorted(source_code.items()):
api.file.write_text('write %s' % name, root_dir.join(name), data)
api.goma.ensure_goma(client_type='candidate')
api.goma.start()
gomacc = api.goma.goma_dir.join('gomacc')
out = root_dir.join('compiled_binary')
build_exit_status = None
try:
# We want goma proxy to actually hit the backends, so disable fallback to
# the local compiler.
gomacc_env = {
'GOMA_USE_LOCAL': 'false',
'GOMA_FALLBACK': 'false',
}
with api.context(env=gomacc_env):
objs = []
for name in sorted(source_code):
obj = root_dir.join(name.replace('.cpp', '.o'))
api.step(
'compile %s' % name,
[gomacc, 'g++', '-c', root_dir.join(name), '-o', obj])
objs.append(obj)
api.step('link', [gomacc, 'g++', '-o', out] + objs)
build_exit_status = 0
except api.step.StepFailure as e:
build_exit_status = e.retcode
raise e
finally:
api.goma.stop(build_exit_status=build_exit_status)
api.step('run', [out])
def GenTests(api):
yield (
api.test('linux') +
api.platform.name('linux') +
api.properties.generic(
buildername='test_builder',
mastername='test_master'))
yield (
api.test('linux_fail') +
api.platform.name('linux') +
api.properties.generic(
buildername='test_builder',
mastername='test_master') +
api.step_data('link', retcode=1))
| """Compiles trivial C++ program using Goma.
Intended to be used as a very simple litmus test of Goma health on LUCI staging
environment. Linux and OSX only.
"""
deps = ['build/goma', 'recipe_engine/context', 'recipe_engine/file', 'recipe_engine/path', 'recipe_engine/platform', 'recipe_engine/properties', 'recipe_engine/step', 'recipe_engine/time']
hello_world_cpp = '\n#include <iostream>\n\nint get_number();\n\nint main() {\n std::cout << "Hello, world!" << std::endl;\n std::cout << "Non-static part " << get_number() << std::endl;\n return 0;\n}\n'
module_cpp = '\nint get_number() {\n return %(time)d;\n}\n'
def run_steps(api):
root_dir = api.path['tmp_base']
source_code = {'hello_world.cpp': HELLO_WORLD_CPP, 'module.cpp': MODULE_CPP % {'time': int(api.time.time())}}
for (name, data) in sorted(source_code.items()):
api.file.write_text('write %s' % name, root_dir.join(name), data)
api.goma.ensure_goma(client_type='candidate')
api.goma.start()
gomacc = api.goma.goma_dir.join('gomacc')
out = root_dir.join('compiled_binary')
build_exit_status = None
try:
gomacc_env = {'GOMA_USE_LOCAL': 'false', 'GOMA_FALLBACK': 'false'}
with api.context(env=gomacc_env):
objs = []
for name in sorted(source_code):
obj = root_dir.join(name.replace('.cpp', '.o'))
api.step('compile %s' % name, [gomacc, 'g++', '-c', root_dir.join(name), '-o', obj])
objs.append(obj)
api.step('link', [gomacc, 'g++', '-o', out] + objs)
build_exit_status = 0
except api.step.StepFailure as e:
build_exit_status = e.retcode
raise e
finally:
api.goma.stop(build_exit_status=build_exit_status)
api.step('run', [out])
def gen_tests(api):
yield (api.test('linux') + api.platform.name('linux') + api.properties.generic(buildername='test_builder', mastername='test_master'))
yield (api.test('linux_fail') + api.platform.name('linux') + api.properties.generic(buildername='test_builder', mastername='test_master') + api.step_data('link', retcode=1)) |
# ###########################################################
# ## generate menu
# ###########################################################
_a = request.application
_c = request.controller
_f = request.function
response.title = '%s %s' % (_f, '/'.join(request.args))
response.subtitle = 'admin'
response.menu = [(T('site'), _f == 'site', URL(_a,'default','site'))]
if request.args:
_t = request.args[0]
response.menu.append((T('edit'), _c == 'default' and _f == 'design',
URL(_a,'default','design',args=_t)))
response.menu.append((T('about'), _c == 'default' and _f == 'about',
URL(_a,'default','about',args=_t)))
response.menu.append((T('errors'), _c == 'default' and _f == 'errors',
URL(_a,'default','errors',args=_t)))
response.menu.append((T('versioning'),
_c == 'mercurial' and _f == 'commit',
URL(_a,'mercurial','commit',args=_t)))
if not session.authorized:
response.menu = [(T('login'), True, '')]
else:
response.menu.append((T('logout'), False,
URL(_a,'default',f='logout')))
response.menu.append((T('help'), False, URL('examples','default','index')))
| _a = request.application
_c = request.controller
_f = request.function
response.title = '%s %s' % (_f, '/'.join(request.args))
response.subtitle = 'admin'
response.menu = [(t('site'), _f == 'site', url(_a, 'default', 'site'))]
if request.args:
_t = request.args[0]
response.menu.append((t('edit'), _c == 'default' and _f == 'design', url(_a, 'default', 'design', args=_t)))
response.menu.append((t('about'), _c == 'default' and _f == 'about', url(_a, 'default', 'about', args=_t)))
response.menu.append((t('errors'), _c == 'default' and _f == 'errors', url(_a, 'default', 'errors', args=_t)))
response.menu.append((t('versioning'), _c == 'mercurial' and _f == 'commit', url(_a, 'mercurial', 'commit', args=_t)))
if not session.authorized:
response.menu = [(t('login'), True, '')]
else:
response.menu.append((t('logout'), False, url(_a, 'default', f='logout')))
response.menu.append((t('help'), False, url('examples', 'default', 'index'))) |
__author__ = 'sibirrer'
# this file contains a class to make a Moffat profile
__all__ = ['Moffat']
class Moffat(object):
"""
this class contains functions to evaluate a Moffat surface brightness profile
.. math::
I(r) = I_0 * (1 + (r/\\alpha)^2)^{-\\beta}
with :math:`I_0 = amp`.
"""
def __init__(self):
self.param_names = ['amp', 'alpha', 'beta', 'center_x', 'center_y']
self.lower_limit_default = {'amp': 0, 'alpha': 0, 'beta': 0, 'center_x': -100, 'center_y': -100}
self.upper_limit_default = {'amp': 100, 'alpha': 10, 'beta': 10, 'center_x': 100, 'center_y': 100}
def function(self, x, y, amp, alpha, beta, center_x=0, center_y=0):
"""
2D Moffat profile
:param x: x-position (angle)
:param y: y-position (angle)
:param amp: normalization
:param alpha: scale
:param beta: exponent
:param center_x: x-center
:param center_y: y-center
:return: surface brightness
"""
x_shift = x - center_x
y_shift = y - center_y
return amp * (1. + (x_shift**2+y_shift**2)/alpha**2)**(-beta)
| __author__ = 'sibirrer'
__all__ = ['Moffat']
class Moffat(object):
"""
this class contains functions to evaluate a Moffat surface brightness profile
.. math::
I(r) = I_0 * (1 + (r/\\alpha)^2)^{-\\beta}
with :math:`I_0 = amp`.
"""
def __init__(self):
self.param_names = ['amp', 'alpha', 'beta', 'center_x', 'center_y']
self.lower_limit_default = {'amp': 0, 'alpha': 0, 'beta': 0, 'center_x': -100, 'center_y': -100}
self.upper_limit_default = {'amp': 100, 'alpha': 10, 'beta': 10, 'center_x': 100, 'center_y': 100}
def function(self, x, y, amp, alpha, beta, center_x=0, center_y=0):
"""
2D Moffat profile
:param x: x-position (angle)
:param y: y-position (angle)
:param amp: normalization
:param alpha: scale
:param beta: exponent
:param center_x: x-center
:param center_y: y-center
:return: surface brightness
"""
x_shift = x - center_x
y_shift = y - center_y
return amp * (1.0 + (x_shift ** 2 + y_shift ** 2) / alpha ** 2) ** (-beta) |
tempratures = [10,-20, -289, 100]
def c_to_f(c):
if c<-273.15:
return ""
return c* 9/5 +32
def writeToFile(input):
with open("output.txt","a") as file:
file.write(input)
for temp in tempratures:
writeToFile(str(c_to_f(temp)))
| tempratures = [10, -20, -289, 100]
def c_to_f(c):
if c < -273.15:
return ''
return c * 9 / 5 + 32
def write_to_file(input):
with open('output.txt', 'a') as file:
file.write(input)
for temp in tempratures:
write_to_file(str(c_to_f(temp))) |
class VoiceClient(object):
def __init__(self, base_obj):
self.base_obj = base_obj
self.api_resource = "/voice/v1/{}"
def create(self,
direction,
to,
caller_id,
execution_logic,
reference_logic='',
country_iso2='us',
technology='pstn',
status_callback_uri=''):
api_resource = self.api_resource.format(direction)
return self.base_obj.post(api_resource=api_resource, direction=direction, to=to,
caller_id=caller_id, execution_logic=execution_logic, reference_logic=reference_logic,
country_iso2=country_iso2, technology=technology, status_callback_uri=status_callback_uri)
def update(self, reference_id, execution_logic):
api_resource = self.api_resource.format(reference_id)
return self.base_obj.put(api_resource=api_resource,
execution_logic=execution_logic)
def delete(self, reference_id):
api_resource = self.api_resource.format(reference_id)
return self.base_obj.delete(api_resource=api_resource)
def get_status(self, reference_id):
api_resource = self.api_resource.format(reference_id)
return self.base_obj.get(api_resource=api_resource)
| class Voiceclient(object):
def __init__(self, base_obj):
self.base_obj = base_obj
self.api_resource = '/voice/v1/{}'
def create(self, direction, to, caller_id, execution_logic, reference_logic='', country_iso2='us', technology='pstn', status_callback_uri=''):
api_resource = self.api_resource.format(direction)
return self.base_obj.post(api_resource=api_resource, direction=direction, to=to, caller_id=caller_id, execution_logic=execution_logic, reference_logic=reference_logic, country_iso2=country_iso2, technology=technology, status_callback_uri=status_callback_uri)
def update(self, reference_id, execution_logic):
api_resource = self.api_resource.format(reference_id)
return self.base_obj.put(api_resource=api_resource, execution_logic=execution_logic)
def delete(self, reference_id):
api_resource = self.api_resource.format(reference_id)
return self.base_obj.delete(api_resource=api_resource)
def get_status(self, reference_id):
api_resource = self.api_resource.format(reference_id)
return self.base_obj.get(api_resource=api_resource) |
class Solution(object):
def _dfs(self,num,res,n):
if num>n:
return
res.append(num)
num=num*10
if num<=n:
for i in xrange(10):
self._dfs(num+i,res,n)
def sovleOn(self,n):
res=[]
cur=1
for i in xrange(1,n+1):
res.append(cur)
if cur*10<=n:
cur=cur*10
# if the num not end with 9,plus 1
# since if 19 the next should 2 not 20
elif cur%10!=9 and cur+1<=n:
cur+=1
else:
# get the 199--2 499--5
while (cur/10)%10==9:
cur/=10
cur=cur/10+1
return res
def lexicalOrder(self, n):
"""
:type n: int
:rtype: List[int]
"""
return self.sovleOn(n)
res=[]
for i in xrange(1,10):
self._dfs(i,res,n)
return res | class Solution(object):
def _dfs(self, num, res, n):
if num > n:
return
res.append(num)
num = num * 10
if num <= n:
for i in xrange(10):
self._dfs(num + i, res, n)
def sovle_on(self, n):
res = []
cur = 1
for i in xrange(1, n + 1):
res.append(cur)
if cur * 10 <= n:
cur = cur * 10
elif cur % 10 != 9 and cur + 1 <= n:
cur += 1
else:
while cur / 10 % 10 == 9:
cur /= 10
cur = cur / 10 + 1
return res
def lexical_order(self, n):
"""
:type n: int
:rtype: List[int]
"""
return self.sovleOn(n)
res = []
for i in xrange(1, 10):
self._dfs(i, res, n)
return res |
expected_output = {
"ospf-statistics-information": {
"ospf-statistics": {
"dbds-retransmit": "203656",
"dbds-retransmit-5seconds": "0",
"flood-queue-depth": "0",
"lsas-acknowledged": "225554974",
"lsas-acknowledged-5seconds": "0",
"lsas-flooded": "66582263",
"lsas-flooded-5seconds": "0",
"lsas-high-prio-flooded": "375568998",
"lsas-high-prio-flooded-5seconds": "0",
"lsas-nbr-transmit": "3423982",
"lsas-nbr-transmit-5seconds": "0",
"lsas-requested": "3517",
"lsas-requested-5seconds": "0",
"lsas-retransmit": "8064643",
"lsas-retransmit-5seconds": "0",
"ospf-errors": {
"subnet-mismatch-error": "12"
},
"packet-statistics": [
{
"ospf-packet-type": "Hello",
"packets-received": "5703920",
"packets-received-5seconds": "3",
"packets-sent": "6202169",
"packets-sent-5seconds": "0"
},
{
"ospf-packet-type": "DbD",
"packets-received": "185459",
"packets-received-5seconds": "0",
"packets-sent": "212983",
"packets-sent-5seconds": "0"
},
{
"ospf-packet-type": "LSReq",
"packets-received": "208",
"packets-received-5seconds": "0",
"packets-sent": "214",
"packets-sent-5seconds": "0"
},
{
"ospf-packet-type": "LSUpdate",
"packets-received": "16742100",
"packets-received-5seconds": "0",
"packets-sent": "15671465",
"packets-sent-5seconds": "0"
},
{
"ospf-packet-type": "LSAck",
"packets-received": "2964236",
"packets-received-5seconds": "0",
"packets-sent": "5229203",
"packets-sent-5seconds": "0"
}
],
"total-database-summaries": "0",
"total-linkstate-request": "0",
"total-retransmits": "0"
}
}
}
| expected_output = {'ospf-statistics-information': {'ospf-statistics': {'dbds-retransmit': '203656', 'dbds-retransmit-5seconds': '0', 'flood-queue-depth': '0', 'lsas-acknowledged': '225554974', 'lsas-acknowledged-5seconds': '0', 'lsas-flooded': '66582263', 'lsas-flooded-5seconds': '0', 'lsas-high-prio-flooded': '375568998', 'lsas-high-prio-flooded-5seconds': '0', 'lsas-nbr-transmit': '3423982', 'lsas-nbr-transmit-5seconds': '0', 'lsas-requested': '3517', 'lsas-requested-5seconds': '0', 'lsas-retransmit': '8064643', 'lsas-retransmit-5seconds': '0', 'ospf-errors': {'subnet-mismatch-error': '12'}, 'packet-statistics': [{'ospf-packet-type': 'Hello', 'packets-received': '5703920', 'packets-received-5seconds': '3', 'packets-sent': '6202169', 'packets-sent-5seconds': '0'}, {'ospf-packet-type': 'DbD', 'packets-received': '185459', 'packets-received-5seconds': '0', 'packets-sent': '212983', 'packets-sent-5seconds': '0'}, {'ospf-packet-type': 'LSReq', 'packets-received': '208', 'packets-received-5seconds': '0', 'packets-sent': '214', 'packets-sent-5seconds': '0'}, {'ospf-packet-type': 'LSUpdate', 'packets-received': '16742100', 'packets-received-5seconds': '0', 'packets-sent': '15671465', 'packets-sent-5seconds': '0'}, {'ospf-packet-type': 'LSAck', 'packets-received': '2964236', 'packets-received-5seconds': '0', 'packets-sent': '5229203', 'packets-sent-5seconds': '0'}], 'total-database-summaries': '0', 'total-linkstate-request': '0', 'total-retransmits': '0'}}} |
# coding: gbk
"""
@author: sdy
@email: sdy@epri.sgcc.com.cn
Abstract distribution and generation class
"""
class ADG(object):
def __init__(self, work_path, fmt):
self.work_path = work_path
self.fmt = fmt
self.features = None
self.mode = 'all'
def distribution_assess(self):
raise NotImplementedError
def generate_all(self):
raise NotImplementedError
def choose_samples(self, size):
raise NotImplementedError
def generate_one(self, power, idx, out_path):
raise NotImplementedError
def remove_samples(self):
raise NotImplementedError
def done(self):
raise NotImplementedError
| """
@author: sdy
@email: sdy@epri.sgcc.com.cn
Abstract distribution and generation class
"""
class Adg(object):
def __init__(self, work_path, fmt):
self.work_path = work_path
self.fmt = fmt
self.features = None
self.mode = 'all'
def distribution_assess(self):
raise NotImplementedError
def generate_all(self):
raise NotImplementedError
def choose_samples(self, size):
raise NotImplementedError
def generate_one(self, power, idx, out_path):
raise NotImplementedError
def remove_samples(self):
raise NotImplementedError
def done(self):
raise NotImplementedError |
"""
This file must be kept up-to-date with Stripe, especially the slugs:
https://manage.stripe.com/plans
"""
PLANS = {}
class Plan(object):
def __init__(self, value, slug, display):
self.value = value
self.slug = slug
self.display = display
PLANS[slug] = self
FREE = Plan(1, 'free', "Free plan")
| """
This file must be kept up-to-date with Stripe, especially the slugs:
https://manage.stripe.com/plans
"""
plans = {}
class Plan(object):
def __init__(self, value, slug, display):
self.value = value
self.slug = slug
self.display = display
PLANS[slug] = self
free = plan(1, 'free', 'Free plan') |
N = int(input())
S = input()
if N % 2 == 1:
print('No')
exit()
if S[:N // 2] == S[N // 2:]:
print('Yes')
else:
print('No')
| n = int(input())
s = input()
if N % 2 == 1:
print('No')
exit()
if S[:N // 2] == S[N // 2:]:
print('Yes')
else:
print('No') |
#!/usr/bin/env python
#
# Cloudlet Infrastructure for Mobile Computing
# - Task Assistance
#
# Author: Zhuo Chen <zhuoc@cs.cmu.edu>
#
# Copyright (C) 2011-2013 Carnegie Mellon University
# 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.
#
# If True, configurations are set to process video stream in real-time (use
# with lego_server.py)
# If False, configurations are set to process one independent image (use with
# img.py)
IS_STREAMING = True
RECOGNIZE_ONLY = False
# Port for communication between proxy and task server
TASK_SERVER_PORT = 6090
BEST_ENGINE = "LEGO_FAST"
CHECK_ALGORITHM = "table"
CHECK_LAST_TH = 1
# Port for communication between master and workder proxies
MASTER_SERVER_PORT = 6091
# Whether or not to save the displayed image in a temporary directory
SAVE_IMAGE = False
# Convert all incoming frames to a fixed size to ease processing
IMAGE_HEIGHT = 360
IMAGE_WIDTH = 640
BLUR_KERNEL_SIZE = int(IMAGE_WIDTH // 16 + 1)
# Display
DISPLAY_MAX_PIXEL = 640
DISPLAY_SCALE = 5
DISPLAY_LIST_ALL = ['test', 'input', 'DoB', 'mask_black', 'mask_black_dots',
'board', 'board_border_line', 'board_edge', 'board_grey',
'board_mask_black', 'board_mask_black_dots', 'board_DoB',
'edge_inv',
'edge',
'board_n0', 'board_n1', 'board_n2', 'board_n3', 'board_n4',
'board_n5', 'board_n6',
'lego_u_edge_S', 'lego_u_edge_norm_L', 'lego_u_dots_L',
'lego_full', 'lego', 'lego_only_color',
'lego_correct', 'lego_rect', 'lego_cropped', 'lego_color',
'plot_line', 'lego_syn',
'guidance']
DISPLAY_LIST_TEST = ['input', 'board', 'lego_u_edge_S', 'lego_u_edge_norm_L',
'lego_u_dots_L', 'lego_syn']
DISPLAY_LIST_STREAM = ['input', 'lego_syn']
# DISPLAY_LIST_TASK = ['input', 'board', 'lego_syn', 'guidance']
DISPLAY_LIST_TASK = []
if not IS_STREAMING:
DISPLAY_LIST = DISPLAY_LIST_TEST
else:
if RECOGNIZE_ONLY:
DISPLAY_LIST = DISPLAY_LIST_STREAM
else:
DISPLAY_LIST = DISPLAY_LIST_TASK
DISPLAY_WAIT_TIME = 1 if IS_STREAMING else 500
## Black dots
BD_COUNT_N_ROW = 9
BD_COUNT_N_COL = 16
BD_BLOCK_HEIGHT = IMAGE_HEIGHT // BD_COUNT_N_ROW
BD_BLOCK_WIDTH = IMAGE_WIDTH // BD_COUNT_N_COL
BD_BLOCK_SPAN = max(BD_BLOCK_HEIGHT, BD_BLOCK_WIDTH)
BD_BLOCK_AREA = BD_BLOCK_HEIGHT * BD_BLOCK_WIDTH
BD_COUNT_THRESH = 25
BD_MAX_PERI = (IMAGE_HEIGHT + IMAGE_HEIGHT) // 40
BD_MAX_SPAN = int(BD_MAX_PERI / 4.0 + 0.5)
# Two ways to check black dot size:
# 'simple': check contour length and area
# 'complete": check x & y max span also
CHECK_BD_SIZE = 'simple'
## Color detection
# H: hue, S: saturation, V: value (which means brightness)
# L: lower_bound, U: upper_bound, TH: threshold
# TODO:
BLUE = {'H': 110, 'S_L': 100, 'B_TH': 110} # H: 108
YELLOW = {'H': 30, 'S_L': 100, 'B_TH': 170} # H: 25 B_TH: 180
GREEN = {'H': 70, 'S_L': 100, 'B_TH': 60} # H: 80 B_TH: 75
RED = {'H': 0, 'S_L': 100, 'B_TH': 130}
BLACK = {'S_U': 70, 'V_U': 60}
# WHITE = {'S_U' : 60, 'B_L' : 101, 'B_TH' : 160} # this includes side white,
# too
WHITE = {'S_U': 60, 'V_L': 150}
BD_DOB_MIN_V = 30
# If using a labels to represent color, this is the right color: 0 means
# nothing (background) and 7 means unsure
COLOR_ORDER = ['nothing', 'white', 'green', 'yellow', 'red', 'blue', 'black',
'unsure']
## Board
BOARD_MIN_AREA = BD_BLOCK_AREA * 7
BOARD_MIN_LINE_LENGTH = BD_BLOCK_SPAN
BOARD_MIN_VOTE = BD_BLOCK_SPAN // 2
# Once board is detected, convert it to a perspective-corrected standard size
# for further processing
BOARD_RECONSTRUCT_HEIGHT = 155 * 1
BOARD_RECONSTRUCT_WIDTH = 270 * 1
BOARD_BD_MAX_PERI = (BOARD_RECONSTRUCT_HEIGHT + BOARD_RECONSTRUCT_WIDTH) // 30
BOARD_BD_MAX_SPAN = int(BOARD_BD_MAX_PERI / 4.0 + 1.5)
BOARD_RECONSTRUCT_AREA = BOARD_RECONSTRUCT_HEIGHT * BOARD_RECONSTRUCT_WIDTH
BOARD_RECONSTRUCT_PERI = (
BOARD_RECONSTRUCT_HEIGHT +
BOARD_RECONSTRUCT_WIDTH) * 2
BOARD_RECONSTRUCT_CENTER = (
BOARD_RECONSTRUCT_HEIGHT // 2, BOARD_RECONSTRUCT_WIDTH // 2)
## Bricks
BRICK_HEIGHT = BOARD_RECONSTRUCT_HEIGHT / 12.25 # magic number
BRICK_WIDTH = BOARD_RECONSTRUCT_WIDTH / 26.2 # magic number
BRICK_HEIGHT_THICKNESS_RATIO = 15 / 12.25 # magic number
BLOCK_DETECTION_OFFSET = 2
BRICK_MIN_BM_RATIO = .85
## Optimizations
# If True, performs a second step fine-grained board detection algorithm.
# Depending on the other algorithms, this is usually not needed.
OPT_FINE_BOARD = False
# Treat background pixels differently
OPT_NOTHING = False
BM_WINDOW_MIN_TIME = 0.1
BM_WINDOW_MIN_COUNT = 1
# The percentage of right pixels in each block must be higher than this
# threshold
WORST_RATIO_BLOCK_THRESH = 0.6
# If True, do perspective correction first, then color normalization
# If False, do perspective correction after color has been normalized
# Not used anymore...
PERS_NORM = True
## Consts
ACTION_ADD = 0
ACTION_REMOVE = 1
ACTION_TARGET = 2
ACTION_MOVE = 3
DIRECTION_NONE = 0
DIRECTION_UP = 1
DIRECTION_DOWN = 2
GOOD_WORDS = ["Excellent. ", "Great. ", "Good job. ", "Wonderful. "]
def setup(is_streaming):
global IS_STREAMING, DISPLAY_LIST, DISPLAY_WAIT_TIME, SAVE_IMAGE
IS_STREAMING = is_streaming
if not IS_STREAMING:
DISPLAY_LIST = DISPLAY_LIST_TEST
else:
if RECOGNIZE_ONLY:
DISPLAY_LIST = DISPLAY_LIST_STREAM
else:
DISPLAY_LIST = DISPLAY_LIST_TASK
DISPLAY_WAIT_TIME = 1 if IS_STREAMING else 500
SAVE_IMAGE = not IS_STREAMING
| is_streaming = True
recognize_only = False
task_server_port = 6090
best_engine = 'LEGO_FAST'
check_algorithm = 'table'
check_last_th = 1
master_server_port = 6091
save_image = False
image_height = 360
image_width = 640
blur_kernel_size = int(IMAGE_WIDTH // 16 + 1)
display_max_pixel = 640
display_scale = 5
display_list_all = ['test', 'input', 'DoB', 'mask_black', 'mask_black_dots', 'board', 'board_border_line', 'board_edge', 'board_grey', 'board_mask_black', 'board_mask_black_dots', 'board_DoB', 'edge_inv', 'edge', 'board_n0', 'board_n1', 'board_n2', 'board_n3', 'board_n4', 'board_n5', 'board_n6', 'lego_u_edge_S', 'lego_u_edge_norm_L', 'lego_u_dots_L', 'lego_full', 'lego', 'lego_only_color', 'lego_correct', 'lego_rect', 'lego_cropped', 'lego_color', 'plot_line', 'lego_syn', 'guidance']
display_list_test = ['input', 'board', 'lego_u_edge_S', 'lego_u_edge_norm_L', 'lego_u_dots_L', 'lego_syn']
display_list_stream = ['input', 'lego_syn']
display_list_task = []
if not IS_STREAMING:
display_list = DISPLAY_LIST_TEST
elif RECOGNIZE_ONLY:
display_list = DISPLAY_LIST_STREAM
else:
display_list = DISPLAY_LIST_TASK
display_wait_time = 1 if IS_STREAMING else 500
bd_count_n_row = 9
bd_count_n_col = 16
bd_block_height = IMAGE_HEIGHT // BD_COUNT_N_ROW
bd_block_width = IMAGE_WIDTH // BD_COUNT_N_COL
bd_block_span = max(BD_BLOCK_HEIGHT, BD_BLOCK_WIDTH)
bd_block_area = BD_BLOCK_HEIGHT * BD_BLOCK_WIDTH
bd_count_thresh = 25
bd_max_peri = (IMAGE_HEIGHT + IMAGE_HEIGHT) // 40
bd_max_span = int(BD_MAX_PERI / 4.0 + 0.5)
check_bd_size = 'simple'
blue = {'H': 110, 'S_L': 100, 'B_TH': 110}
yellow = {'H': 30, 'S_L': 100, 'B_TH': 170}
green = {'H': 70, 'S_L': 100, 'B_TH': 60}
red = {'H': 0, 'S_L': 100, 'B_TH': 130}
black = {'S_U': 70, 'V_U': 60}
white = {'S_U': 60, 'V_L': 150}
bd_dob_min_v = 30
color_order = ['nothing', 'white', 'green', 'yellow', 'red', 'blue', 'black', 'unsure']
board_min_area = BD_BLOCK_AREA * 7
board_min_line_length = BD_BLOCK_SPAN
board_min_vote = BD_BLOCK_SPAN // 2
board_reconstruct_height = 155 * 1
board_reconstruct_width = 270 * 1
board_bd_max_peri = (BOARD_RECONSTRUCT_HEIGHT + BOARD_RECONSTRUCT_WIDTH) // 30
board_bd_max_span = int(BOARD_BD_MAX_PERI / 4.0 + 1.5)
board_reconstruct_area = BOARD_RECONSTRUCT_HEIGHT * BOARD_RECONSTRUCT_WIDTH
board_reconstruct_peri = (BOARD_RECONSTRUCT_HEIGHT + BOARD_RECONSTRUCT_WIDTH) * 2
board_reconstruct_center = (BOARD_RECONSTRUCT_HEIGHT // 2, BOARD_RECONSTRUCT_WIDTH // 2)
brick_height = BOARD_RECONSTRUCT_HEIGHT / 12.25
brick_width = BOARD_RECONSTRUCT_WIDTH / 26.2
brick_height_thickness_ratio = 15 / 12.25
block_detection_offset = 2
brick_min_bm_ratio = 0.85
opt_fine_board = False
opt_nothing = False
bm_window_min_time = 0.1
bm_window_min_count = 1
worst_ratio_block_thresh = 0.6
pers_norm = True
action_add = 0
action_remove = 1
action_target = 2
action_move = 3
direction_none = 0
direction_up = 1
direction_down = 2
good_words = ['Excellent. ', 'Great. ', 'Good job. ', 'Wonderful. ']
def setup(is_streaming):
global IS_STREAMING, DISPLAY_LIST, DISPLAY_WAIT_TIME, SAVE_IMAGE
is_streaming = is_streaming
if not IS_STREAMING:
display_list = DISPLAY_LIST_TEST
elif RECOGNIZE_ONLY:
display_list = DISPLAY_LIST_STREAM
else:
display_list = DISPLAY_LIST_TASK
display_wait_time = 1 if IS_STREAMING else 500
save_image = not IS_STREAMING |
class Node():
def __init__(self, value=None):
self.children = []
self.parent = None
self.value = value
def add_child(self, node):
if type(node).__name__ == 'Node':
node.parent = self
self.children.append(node)
else:
raise ValueError
def get_parent(self):
return self.parent.value if self.parent else 'root' | class Node:
def __init__(self, value=None):
self.children = []
self.parent = None
self.value = value
def add_child(self, node):
if type(node).__name__ == 'Node':
node.parent = self
self.children.append(node)
else:
raise ValueError
def get_parent(self):
return self.parent.value if self.parent else 'root' |
"""Hamming Distance from Exercism"""
def distance(strand_a, strand_b):
"""Determine the hamming distance between two RNA strings
param: str strand_a
param: str strand_b
return: int calculation of the hamming distance between strand_a and strand_b
"""
if len(strand_a) != len(strand_b):
raise ValueError("Strands must be of equal length.")
distance = 0
for i, _ in enumerate(strand_a):
if strand_a[i] != strand_b[i]:
distance += 1
return distance
| """Hamming Distance from Exercism"""
def distance(strand_a, strand_b):
"""Determine the hamming distance between two RNA strings
param: str strand_a
param: str strand_b
return: int calculation of the hamming distance between strand_a and strand_b
"""
if len(strand_a) != len(strand_b):
raise value_error('Strands must be of equal length.')
distance = 0
for (i, _) in enumerate(strand_a):
if strand_a[i] != strand_b[i]:
distance += 1
return distance |
#def spam():
# eggs = 31337
#spam()
#print(eggs)
"""
def spam():
eggs = 98
bacon()
print(eggs)
def bacon():
ham = 101
eggs = 0
spam()
"""
"""
# Global variables can be read from local scope.
def spam():
print(eggs)
eggs = 42
spam()
print(eggs)
"""
"""
# Local and global variables with the same name.
def spam():
eggs = 'spam local'
print(eggs) # prints 'spam local'
def bacon():
eggs = 'bacon local'
print(eggs) # prints 'bacon local'
spam()
print(eggs) # prints 'bacon local'
eggs = 'global'
bacon()
print(eggs) # prints 'global'
"""
"""
# the global statement
def spam():
global eggs
eggs = 'spam'
eggs = 'it don\'t matter'
spam()
print(eggs)
"""
"""
def spam():
global eggs
eggs = 'spam' # this is the global
def bacon():
eggs = 'bacon' # this is a local
def ham():
print(eggs) # this is the global
eggs = 42 # this is global
spam()
print(eggs)
"""
# Python will not fall back to using the global eggs variable
def spam():
eggs = 'wha??'
print(eggs) # ERROR!
eggs = 'spam local'
eggs = 'global'
spam()
# This error happens because Python sees that there is an assignment statement for eggs in the spam() function and therefore considers eggs to be local. Because print(eggs) is executed before eggs is assigned anything, the local variable eggs doesn't exist.
| """
def spam():
eggs = 98
bacon()
print(eggs)
def bacon():
ham = 101
eggs = 0
spam()
"""
'\n# Global variables can be read from local scope.\ndef spam():\n print(eggs)\neggs = 42\nspam()\nprint(eggs)\n'
"\n# Local and global variables with the same name.\n\ndef spam():\n eggs = 'spam local'\n print(eggs) # prints 'spam local'\ndef bacon():\n eggs = 'bacon local'\n print(eggs) # prints 'bacon local'\n spam()\n print(eggs) # prints 'bacon local'\n\neggs = 'global'\nbacon()\nprint(eggs) # prints 'global'\n"
"\n# the global statement\n\ndef spam():\n global eggs\n eggs = 'spam'\n\neggs = 'it don't matter'\nspam()\nprint(eggs)\n"
"\ndef spam():\n global eggs\n eggs = 'spam' # this is the global\n\ndef bacon():\n eggs = 'bacon' # this is a local\n\ndef ham():\n print(eggs) # this is the global\n\neggs = 42 # this is global\nspam()\nprint(eggs)\n"
def spam():
eggs = 'wha??'
print(eggs)
eggs = 'spam local'
eggs = 'global'
spam() |
# https://leetcode.com/problems/minimum-moves-to-equal-array-elements/
# Explanation: https://leetcode.com/problems/minimum-moves-to-equal-array-elements/discuss/93817/It-is-a-math-question
# Source: https://leetcode.com/problems/minimum-moves-to-equal-array-elements/discuss/272994/Python-Greedy-Sum-Min*Len
class Solution:
def minMoves(self, nums: List[int]) -> int:
return sum(nums) - min(nums)*len(nums) | class Solution:
def min_moves(self, nums: List[int]) -> int:
return sum(nums) - min(nums) * len(nums) |
# Given two binary strings, return their sum (also a binary string).
#
# For example,
# a = "11"
# b = "1"
# Return "100".
class Solution:
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
la = len(a)
lb = len(b)
if la >= lb:
length = la
else:
length = lb
digits = []
addition = 0
for x in range(1, length + 1):
if x > la:
an = 0
else:
an = int(a[-x])
if x > lb:
bn = 0
else:
bn = int(b[-x])
res = an + bn + addition
if res == 3:
digits.append("1")
addition = 1
elif res == 2:
digits.append("0")
addition = 1
elif res == 1:
digits.append("1")
addition = 0
elif res == 0:
digits.append("0")
addition = 0
if addition != 0:
digits.append(str(addition))
digits.reverse()
return "".join(digits)
s = Solution()
print(s.addBinary("0", "0"))
# print(s.addBinary("11", "1"))
| class Solution:
def add_binary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
la = len(a)
lb = len(b)
if la >= lb:
length = la
else:
length = lb
digits = []
addition = 0
for x in range(1, length + 1):
if x > la:
an = 0
else:
an = int(a[-x])
if x > lb:
bn = 0
else:
bn = int(b[-x])
res = an + bn + addition
if res == 3:
digits.append('1')
addition = 1
elif res == 2:
digits.append('0')
addition = 1
elif res == 1:
digits.append('1')
addition = 0
elif res == 0:
digits.append('0')
addition = 0
if addition != 0:
digits.append(str(addition))
digits.reverse()
return ''.join(digits)
s = solution()
print(s.addBinary('0', '0')) |
# Event: LCCS Python Fundamental Skills Workshop
# Date: Dec 2018
# Author: Joe English, PDST
# eMail: computerscience@pdst.ie
# Purpose: To find (and fix) two syntax errors
# A program to display Green Eggs and Ham (v4)
def showChorus():
print()
print("I do not like green eggs and ham.")
print("I do not like them Sam-I-am.")
print()
def showVerse1():
print("I do not like them here or there.")
print("I do not like them anywhere.")
print("I do not like them in a house")
print("I do not like them with a mouse")
def displayVerse2():
print("I do not like them in a box")
print("I do not like them with a fox")
print("I will not eat them in the rain.")
print("I will not eat them on a train")
# Program execution starts here
showChorus()
displayVerse1() # SYNTAX ERROR 1 - function 'displayVerse1' does not exist
showChorus()
showVerse2() # SYNTAX ERROR 2 - function 'showVerse2' does not exist
showChorus()
| def show_chorus():
print()
print('I do not like green eggs and ham.')
print('I do not like them Sam-I-am.')
print()
def show_verse1():
print('I do not like them here or there.')
print('I do not like them anywhere.')
print('I do not like them in a house')
print('I do not like them with a mouse')
def display_verse2():
print('I do not like them in a box')
print('I do not like them with a fox')
print('I will not eat them in the rain.')
print('I will not eat them on a train')
show_chorus()
display_verse1()
show_chorus()
show_verse2()
show_chorus() |
_base_ = [
'../_base_/models/repdet_repvgg_pafpn.py',
'../_base_/datasets/coco_detection.py',
'../_base_/schedules/schedule_poly.py', '../_base_/default_runtime.py'
]
# model settings
model = dict(
type='RepDet',
pretrained='/data/kartikes/repvgg_models/repvgg_b1g2.pth',
backbone=dict(
type='RepVGG',
arch='B1g2',
out_stages=[1, 2, 3, 4],
activation='ReLU',
last_channel=1024,
deploy=False),
neck=dict(
type='NanoPAN',
in_channels=[128, 256, 512, 1024],
out_channels=256,
num_outs=5,
start_level=1,
add_extra_convs='on_input'),
bbox_head=dict(
type='NanoDetHead',
num_classes=80,
in_channels=256,
stacked_convs=2,
feat_channels=256,
share_cls_reg=True,
reg_max=10,
norm_cfg=dict(type='BN', requires_grad=True),
anchor_generator=dict(
type='AnchorGenerator',
ratios=[1.0],
octave_base_scale=8,
scales_per_octave=1,
strides=[8, 16, 32]),
loss_cls=dict(
type='QualityFocalLoss',
use_sigmoid=True,
beta=2.0,
loss_weight=1.0),
loss_dfl=dict(type='DistributionFocalLoss', loss_weight=0.25),
loss_bbox=dict(type='GIoULoss', loss_weight=2.0))
)
optimizer = dict(type='SGD', lr=0.025, momentum=0.9, weight_decay=0.0001)
data = dict(
samples_per_gpu=4,
workers_per_gpu=2)
find_unused_parameters=True
runner = dict(type='EpochBasedRunner', max_epochs=12)
| _base_ = ['../_base_/models/repdet_repvgg_pafpn.py', '../_base_/datasets/coco_detection.py', '../_base_/schedules/schedule_poly.py', '../_base_/default_runtime.py']
model = dict(type='RepDet', pretrained='/data/kartikes/repvgg_models/repvgg_b1g2.pth', backbone=dict(type='RepVGG', arch='B1g2', out_stages=[1, 2, 3, 4], activation='ReLU', last_channel=1024, deploy=False), neck=dict(type='NanoPAN', in_channels=[128, 256, 512, 1024], out_channels=256, num_outs=5, start_level=1, add_extra_convs='on_input'), bbox_head=dict(type='NanoDetHead', num_classes=80, in_channels=256, stacked_convs=2, feat_channels=256, share_cls_reg=True, reg_max=10, norm_cfg=dict(type='BN', requires_grad=True), anchor_generator=dict(type='AnchorGenerator', ratios=[1.0], octave_base_scale=8, scales_per_octave=1, strides=[8, 16, 32]), loss_cls=dict(type='QualityFocalLoss', use_sigmoid=True, beta=2.0, loss_weight=1.0), loss_dfl=dict(type='DistributionFocalLoss', loss_weight=0.25), loss_bbox=dict(type='GIoULoss', loss_weight=2.0)))
optimizer = dict(type='SGD', lr=0.025, momentum=0.9, weight_decay=0.0001)
data = dict(samples_per_gpu=4, workers_per_gpu=2)
find_unused_parameters = True
runner = dict(type='EpochBasedRunner', max_epochs=12) |
# Holy Stone - Holy Ground at the Snowfield (3rd job)
questIDs = [1431, 1432, 1433, 1435, 1436, 1437, 1439, 1440, 1442, 1443, 1445, 1446, 1447, 1448]
hasQuest = False
for qid in questIDs:
if sm.hasQuest(qid):
hasQuest = True
break
if hasQuest:
if sm.sendAskYesNo("#b(A mysterious energy surrounds this stone. Do you want to investigate?)"):
sm.warpInstanceIn(910540000, 0)
else:
sm.sendSayOkay("#b(A mysterious energy surrounds this stone)#k")
| quest_i_ds = [1431, 1432, 1433, 1435, 1436, 1437, 1439, 1440, 1442, 1443, 1445, 1446, 1447, 1448]
has_quest = False
for qid in questIDs:
if sm.hasQuest(qid):
has_quest = True
break
if hasQuest:
if sm.sendAskYesNo('#b(A mysterious energy surrounds this stone. Do you want to investigate?)'):
sm.warpInstanceIn(910540000, 0)
else:
sm.sendSayOkay('#b(A mysterious energy surrounds this stone)#k') |
class CustomException(Exception):
def __init__(self, *args, **kwargs):
return super().__init__(self, *args, **kwargs)
def __str__(self):
return str(self.args [1])
class DeprecatedException(CustomException):
def __init__(self, *args, **kwargs):
return super().__init__(*args, **kwargs)
class DailyLimitException(CustomException):
def __init__(self, *args, **kwargs):
return super().__init__(*args, **kwargs)
class InvalidArgumentException(CustomException):
def __init__(self, *args, **kwargs):
return super().__init__(*args, **kwargs)
class IdOrAuthEmptyException(CustomException):
def __init__(self, *args, **kwargs):
return super().__init__(*args, **kwargs)
class NotFoundException(CustomException):
def __init__(self, *args, **kwargs):
return super().__init__(*args, **kwargs)
class NotSupported(CustomException):
def __init__(self, *args, **kwargs):
return super().__init__(*args, **kwargs)
class SessionLimitException(CustomException):
def __init__(self, *args, **kwargs):
return super().__init__(*args, **kwargs)
class WrongCredentials(CustomException):
def __init__(self, *args, **kwargs):
return super().__init__(*args, **kwargs)
class PaladinsOnlyException(CustomException):
def __init__(self, *args, **kwargs):
return super().__init__(*args, **kwargs)
class SmiteOnlyException(CustomException):
def __init__(self, *args, **kwargs):
return super().__init__(*args, **kwargs)
class RealmRoyaleOnlyException(CustomException):
def __init__(self, *args, **kwargs):
return super().__init__(*args, **kwargs)
class PlayerNotFoundException(CustomException):
def __init__(self, *args, **kwargs):
return super().__init__(*args, **kwargs)
class GetMatchPlayerDetailsException(CustomException):
def __init__(self, *args, **kwargs):
return super().__init__(*args, **kwargs)
class UnexpectedException(CustomException):
def __init__(self, *args, **kwargs):
return super().__init__(*args, **kwargs)
class RequestErrorException(CustomException):
def __init__(self, *args, **kwargs):
return super().__init__(*args, **kwargs)
| class Customexception(Exception):
def __init__(self, *args, **kwargs):
return super().__init__(self, *args, **kwargs)
def __str__(self):
return str(self.args[1])
class Deprecatedexception(CustomException):
def __init__(self, *args, **kwargs):
return super().__init__(*args, **kwargs)
class Dailylimitexception(CustomException):
def __init__(self, *args, **kwargs):
return super().__init__(*args, **kwargs)
class Invalidargumentexception(CustomException):
def __init__(self, *args, **kwargs):
return super().__init__(*args, **kwargs)
class Idorauthemptyexception(CustomException):
def __init__(self, *args, **kwargs):
return super().__init__(*args, **kwargs)
class Notfoundexception(CustomException):
def __init__(self, *args, **kwargs):
return super().__init__(*args, **kwargs)
class Notsupported(CustomException):
def __init__(self, *args, **kwargs):
return super().__init__(*args, **kwargs)
class Sessionlimitexception(CustomException):
def __init__(self, *args, **kwargs):
return super().__init__(*args, **kwargs)
class Wrongcredentials(CustomException):
def __init__(self, *args, **kwargs):
return super().__init__(*args, **kwargs)
class Paladinsonlyexception(CustomException):
def __init__(self, *args, **kwargs):
return super().__init__(*args, **kwargs)
class Smiteonlyexception(CustomException):
def __init__(self, *args, **kwargs):
return super().__init__(*args, **kwargs)
class Realmroyaleonlyexception(CustomException):
def __init__(self, *args, **kwargs):
return super().__init__(*args, **kwargs)
class Playernotfoundexception(CustomException):
def __init__(self, *args, **kwargs):
return super().__init__(*args, **kwargs)
class Getmatchplayerdetailsexception(CustomException):
def __init__(self, *args, **kwargs):
return super().__init__(*args, **kwargs)
class Unexpectedexception(CustomException):
def __init__(self, *args, **kwargs):
return super().__init__(*args, **kwargs)
class Requesterrorexception(CustomException):
def __init__(self, *args, **kwargs):
return super().__init__(*args, **kwargs) |
class solutionLeetcode_3:
def lengthOfLongestSubstring(self, s: str) -> (int, str):
if not s:
return 0
left = 0
lookup = set()
n = len(s)
max_len = 0
cur_len = 0
for i in range(n):
cur_len += 1
while s[i] in lookup:
lookup.remove(s[left])
left += 1
cur_len -= 1
if cur_len > max_len:
max_len = cur_len
lookup.add(s[i])
longestSubstring = s[left:left+max_len+1]
return max_len, longestSubstring
class solutionLeetcode_4:
def findMedianSortedArrays(self, nums1, nums2):
nums1.extend(nums2)
nums1.sort()
if len(nums1) % 2 == 0:
return sum(nums1[[len(nums1)//2]-1:len(nums1)//2+1])/2 # // is int division.
else:
return nums1[(len(nums1)-1)//2]
class solutionLeetcode_5:
def longestPalindrome(self, s):
str_length = len(s)
max_length = 0
start = 0
for i in range(str_length):
if i - max_length >= 1 and s[i - max_length - 1:i + 2] == s[i - max_length - 1:i+2][::-1]:
start = i - max_length - 1
max_length += 2
continue
if i - max_length >= 0 and s[i - max_length:i + 2] == s[i - max_length:i + 2][::-1]:
start = i - max_length
max_length += 1
return s[start:start + max_length + 1]
class solutionLeetcode_6:
def convert(self, s:str, numRows:int) -> list:
if numRows < 2:
return s
res = ["" for _ in range(numRows)] # "" stands for string
i, flag = 0, -1
for c in s:
res[i] += c
if i == 0 or i == numRows - 1:
flag = -flag
i += flag
return "".join(res)
class solutionLeetcode_7:
def reverse(self, x) -> int:
s = str(x)[::-1].strip('-') # use extended slices to reverse a string.
if int(s) < 2**31:
if x >= 0:
return int(s)
else:
return 0 - int(s)
return 0
class solutionLeetcode_8:
def myAtoi(self, str: str) -> int:
validChar = ['-', '+', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
validNumber = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
if len(str) == 0:
return 0
startIndex = -1
endIndex = 0
initialChar = True
lastEntryValid = True
stringChar = ''
for i in range(len(str)):
if str[i] == ' ' and initialChar:
continue
if (str[i] not in validChar) and initialChar:
return 0
if (str[i] in validChar) and initialChar:
initialChar = False
startIndex = i
if i == len(str) - 1:
if str[i] in ['-', '+']:
return 0
else:
return int(str)
if (i < len(str) - 1) and (str[i + 1] not in validNumber):
if str[i] in ['-', '+']:
return 0
else:
return int(str[i])
continue
if (str[i] not in validNumber) and (not initialChar):
endIndex = i
lastEntryValid = False
break
if startIndex == -1:
return 0
if lastEntryValid:
endIndex = len(str)
numberStr = str[startIndex:endIndex]
resultNumber = int(numberStr)
if resultNumber >= 2 ** 31:
return 2 ** 31 - 1
elif resultNumber <= -2 ** 31:
return -2 ** 31
else:
return resultNumber
class solutionLeetcode_10:
def isMatch(self, text: str, pattern: str) -> bool:
if not pattern:
return not text
firstMatch = bool(text) and pattern[0] in {text[0], '.'}
if len(pattern) >= 2 and pattern[1] == '*':
return self.isMatch(text, pattern[2:]) or (firstMatch and self.isMatch(text[1:], pattern))
else:
return firstMatch and self.isMatch(text[1:], pattern[1:])
class solutionLeetcode_11:
def maxArea(self, height):
"""
:type height: List[int]
:rtype: int
"""
maxArea = 0
left = 0
right = len(height) - 1
while left < right:
area = (right - left) * min(height[left], height[right])
if maxArea < area:
maxArea = area
if height[left] < height[right]:
left += 1
else:
right -=1
return maxArea
| class Solutionleetcode_3:
def length_of_longest_substring(self, s: str) -> (int, str):
if not s:
return 0
left = 0
lookup = set()
n = len(s)
max_len = 0
cur_len = 0
for i in range(n):
cur_len += 1
while s[i] in lookup:
lookup.remove(s[left])
left += 1
cur_len -= 1
if cur_len > max_len:
max_len = cur_len
lookup.add(s[i])
longest_substring = s[left:left + max_len + 1]
return (max_len, longestSubstring)
class Solutionleetcode_4:
def find_median_sorted_arrays(self, nums1, nums2):
nums1.extend(nums2)
nums1.sort()
if len(nums1) % 2 == 0:
return sum(nums1[[len(nums1) // 2] - 1:len(nums1) // 2 + 1]) / 2
else:
return nums1[(len(nums1) - 1) // 2]
class Solutionleetcode_5:
def longest_palindrome(self, s):
str_length = len(s)
max_length = 0
start = 0
for i in range(str_length):
if i - max_length >= 1 and s[i - max_length - 1:i + 2] == s[i - max_length - 1:i + 2][::-1]:
start = i - max_length - 1
max_length += 2
continue
if i - max_length >= 0 and s[i - max_length:i + 2] == s[i - max_length:i + 2][::-1]:
start = i - max_length
max_length += 1
return s[start:start + max_length + 1]
class Solutionleetcode_6:
def convert(self, s: str, numRows: int) -> list:
if numRows < 2:
return s
res = ['' for _ in range(numRows)]
(i, flag) = (0, -1)
for c in s:
res[i] += c
if i == 0 or i == numRows - 1:
flag = -flag
i += flag
return ''.join(res)
class Solutionleetcode_7:
def reverse(self, x) -> int:
s = str(x)[::-1].strip('-')
if int(s) < 2 ** 31:
if x >= 0:
return int(s)
else:
return 0 - int(s)
return 0
class Solutionleetcode_8:
def my_atoi(self, str: str) -> int:
valid_char = ['-', '+', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
valid_number = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
if len(str) == 0:
return 0
start_index = -1
end_index = 0
initial_char = True
last_entry_valid = True
string_char = ''
for i in range(len(str)):
if str[i] == ' ' and initialChar:
continue
if str[i] not in validChar and initialChar:
return 0
if str[i] in validChar and initialChar:
initial_char = False
start_index = i
if i == len(str) - 1:
if str[i] in ['-', '+']:
return 0
else:
return int(str)
if i < len(str) - 1 and str[i + 1] not in validNumber:
if str[i] in ['-', '+']:
return 0
else:
return int(str[i])
continue
if str[i] not in validNumber and (not initialChar):
end_index = i
last_entry_valid = False
break
if startIndex == -1:
return 0
if lastEntryValid:
end_index = len(str)
number_str = str[startIndex:endIndex]
result_number = int(numberStr)
if resultNumber >= 2 ** 31:
return 2 ** 31 - 1
elif resultNumber <= -2 ** 31:
return -2 ** 31
else:
return resultNumber
class Solutionleetcode_10:
def is_match(self, text: str, pattern: str) -> bool:
if not pattern:
return not text
first_match = bool(text) and pattern[0] in {text[0], '.'}
if len(pattern) >= 2 and pattern[1] == '*':
return self.isMatch(text, pattern[2:]) or (firstMatch and self.isMatch(text[1:], pattern))
else:
return firstMatch and self.isMatch(text[1:], pattern[1:])
class Solutionleetcode_11:
def max_area(self, height):
"""
:type height: List[int]
:rtype: int
"""
max_area = 0
left = 0
right = len(height) - 1
while left < right:
area = (right - left) * min(height[left], height[right])
if maxArea < area:
max_area = area
if height[left] < height[right]:
left += 1
else:
right -= 1
return maxArea |
#==============================================================================
# Copyright 2011 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#==============================================================================
class BuildError(Exception):
"""
Base exception for errors raised while building
"""
pass
class NoSuchConfigSetError(BuildError):
"""
Exception signifying no config error with specified name exists
"""
def __init__(self, msg):
self.msg = msg
def __str__(self):
return self.msg
class NoSuchConfigurationError(BuildError):
"""
Exception signifying no config error with specified name exists
"""
def __init__(self, msg):
self.msg = msg
def __str__(self):
return self.msg
class CircularConfigSetDependencyError(BuildError):
"""
Exception signifying circular dependency in configSets
"""
def __init__(self, msg):
self.msg = msg
def __str__(self):
return self.msg
class ToolError(BuildError):
"""
Exception raised by Tools when they cannot successfully change reality
Attributes:
msg - a human-readable error message
code - an error code, if applicable
"""
def __init__(self, msg, code=None):
self.msg = msg
self.code = code
def __str__(self):
if (self.code):
return '%s (return code %s)' % (self.msg, self.code)
else:
return self.msg
| class Builderror(Exception):
"""
Base exception for errors raised while building
"""
pass
class Nosuchconfigseterror(BuildError):
"""
Exception signifying no config error with specified name exists
"""
def __init__(self, msg):
self.msg = msg
def __str__(self):
return self.msg
class Nosuchconfigurationerror(BuildError):
"""
Exception signifying no config error with specified name exists
"""
def __init__(self, msg):
self.msg = msg
def __str__(self):
return self.msg
class Circularconfigsetdependencyerror(BuildError):
"""
Exception signifying circular dependency in configSets
"""
def __init__(self, msg):
self.msg = msg
def __str__(self):
return self.msg
class Toolerror(BuildError):
"""
Exception raised by Tools when they cannot successfully change reality
Attributes:
msg - a human-readable error message
code - an error code, if applicable
"""
def __init__(self, msg, code=None):
self.msg = msg
self.code = code
def __str__(self):
if self.code:
return '%s (return code %s)' % (self.msg, self.code)
else:
return self.msg |
#!/usr/bin/env python
# encoding: utf-8
"""
@Author: yangwenhao
@Contact: 874681044@qq.com
@Software: PyCharm
@File: __init__.py.py
@Time: 2020/3/27 10:43 AM
@Overview:
"""
| """
@Author: yangwenhao
@Contact: 874681044@qq.com
@Software: PyCharm
@File: __init__.py.py
@Time: 2020/3/27 10:43 AM
@Overview:
""" |
def f(x):
if x <= -2:
f = 1 - (x + 2)**2
return f
if -2 < x <= 2:
f = -(x/2)
return f
if 2 < x:
f = (x - 2)**2 + 1
return f
x = int(input())
print(f(x))
| def f(x):
if x <= -2:
f = 1 - (x + 2) ** 2
return f
if -2 < x <= 2:
f = -(x / 2)
return f
if 2 < x:
f = (x - 2) ** 2 + 1
return f
x = int(input())
print(f(x)) |
dnas = [
['jVXfX<', 37, 64, 24.67, 14, 7, -4.53, {'ott_len': 42, 'ott_percent': 508, 'stop_loss': 263, 'risk_reward': 65, 'chop_rsi_len': 31, 'chop_bandwidth': 83}],
['o:JK9p', 50, 62, 32.74, 37, 8, -0.2, {'ott_len': 45, 'ott_percent': 259, 'stop_loss': 201, 'risk_reward': 41, 'chop_rsi_len': 12, 'chop_bandwidth': 274}],
['tGVME/', 35, 74, 20.06, 20, 10, -4.75, {'ott_len': 48, 'ott_percent': 375, 'stop_loss': 254, 'risk_reward': 43, 'chop_rsi_len': 20, 'chop_bandwidth': 36}],
['a<<sMo', 59, 27, 25.74, 33, 6, -1.06, {'ott_len': 36, 'ott_percent': 277, 'stop_loss': 139, 'risk_reward': 76, 'chop_rsi_len': 24, 'chop_bandwidth': 271}],
['`Ol@gL', 29, 65, 9.47, 25, 8, -2.95, {'ott_len': 36, 'ott_percent': 446, 'stop_loss': 351, 'risk_reward': 31, 'chop_rsi_len': 40, 'chop_bandwidth': 142}],
['SWJi?Y', 36, 73, 32.8, 37, 8, -0.92, {'ott_len': 28, 'ott_percent': 516, 'stop_loss': 201, 'risk_reward': 68, 'chop_rsi_len': 16, 'chop_bandwidth': 190}],
['v@WLkU', 46, 47, 45.51, 20, 10, -4.43, {'ott_len': 49, 'ott_percent': 313, 'stop_loss': 258, 'risk_reward': 42, 'chop_rsi_len': 43, 'chop_bandwidth': 175}],
['lR\\iHN', 38, 62, 35.84, 28, 7, -4.01, {'ott_len': 43, 'ott_percent': 472, 'stop_loss': 280, 'risk_reward': 68, 'chop_rsi_len': 21, 'chop_bandwidth': 149}],
['l7\\gc^', 60, 35, 42.7, 25, 8, -1.2, {'ott_len': 43, 'ott_percent': 233, 'stop_loss': 280, 'risk_reward': 66, 'chop_rsi_len': 38, 'chop_bandwidth': 208}],
['wLXY\\1', 36, 71, 20.85, 14, 7, -4.76, {'ott_len': 50, 'ott_percent': 419, 'stop_loss': 263, 'risk_reward': 53, 'chop_rsi_len': 34, 'chop_bandwidth': 43}],
['i7nMgb', 54, 24, 28.38, 0, 4, -2.04, {'ott_len': 41, 'ott_percent': 233, 'stop_loss': 360, 'risk_reward': 43, 'chop_rsi_len': 40, 'chop_bandwidth': 223}],
['F/0eI[', 40, 154, 33.68, 42, 21, 2.91, {'ott_len': 20, 'ott_percent': 162, 'stop_loss': 85, 'risk_reward': 64, 'chop_rsi_len': 22, 'chop_bandwidth': 197}],
['\\ERgMp', 53, 28, 16.3, 33, 6, -2.59, {'ott_len': 33, 'ott_percent': 357, 'stop_loss': 236, 'risk_reward': 66, 'chop_rsi_len': 24, 'chop_bandwidth': 274}],
['_7@QqN', 44, 87, 28.24, 46, 15, 3.21, {'ott_len': 35, 'ott_percent': 233, 'stop_loss': 156, 'risk_reward': 46, 'chop_rsi_len': 46, 'chop_bandwidth': 149}],
['OEJO,F', 41, 105, 33.62, 20, 10, -4.61, {'ott_len': 25, 'ott_percent': 357, 'stop_loss': 201, 'risk_reward': 45, 'chop_rsi_len': 4, 'chop_bandwidth': 120}],
['5swn)a', 30, 86, 13.25, 8, 12, -6.03, {'ott_len': 9, 'ott_percent': 765, 'stop_loss': 400, 'risk_reward': 72, 'chop_rsi_len': 3, 'chop_bandwidth': 219}],
['4juD3[', 36, 95, 32.91, 14, 7, -3.13, {'ott_len': 8, 'ott_percent': 685, 'stop_loss': 391, 'risk_reward': 35, 'chop_rsi_len': 9, 'chop_bandwidth': 197}],
['91u6iJ', 33, 163, 31.1, 25, 27, -3.59, {'ott_len': 12, 'ott_percent': 180, 'stop_loss': 391, 'risk_reward': 22, 'chop_rsi_len': 41, 'chop_bandwidth': 135}],
['c3rg61', 39, 91, 11.05, 27, 11, -1.18, {'ott_len': 38, 'ott_percent': 197, 'stop_loss': 378, 'risk_reward': 66, 'chop_rsi_len': 11, 'chop_bandwidth': 43}],
['\\BAZGb', 40, 71, 22.33, 36, 11, -3.44, {'ott_len': 33, 'ott_percent': 330, 'stop_loss': 161, 'risk_reward': 54, 'chop_rsi_len': 21, 'chop_bandwidth': 223}],
['H<XF,l', 40, 98, 31.16, 16, 12, -5.22, {'ott_len': 21, 'ott_percent': 277, 'stop_loss': 263, 'risk_reward': 37, 'chop_rsi_len': 4, 'chop_bandwidth': 260}],
['5Bl/TL', 32, 153, 26.35, 28, 21, 0.03, {'ott_len': 9, 'ott_percent': 330, 'stop_loss': 351, 'risk_reward': 16, 'chop_rsi_len': 29, 'chop_bandwidth': 142}],
['DFRlX-', 38, 112, 21.16, 27, 11, -1.95, {'ott_len': 18, 'ott_percent': 366, 'stop_loss': 236, 'risk_reward': 70, 'chop_rsi_len': 31, 'chop_bandwidth': 28}],
['1EkquE', 33, 156, 45.58, 27, 18, -1.61, {'ott_len': 7, 'ott_percent': 357, 'stop_loss': 347, 'risk_reward': 75, 'chop_rsi_len': 49, 'chop_bandwidth': 116}],
['D9YmB.', 35, 139, 12.09, 42, 14, -1.17, {'ott_len': 18, 'ott_percent': 251, 'stop_loss': 267, 'risk_reward': 71, 'chop_rsi_len': 18, 'chop_bandwidth': 32}],
['_(KrZG', 40, 145, 18.09, 28, 21, -4.73, {'ott_len': 35, 'ott_percent': 100, 'stop_loss': 205, 'risk_reward': 76, 'chop_rsi_len': 32, 'chop_bandwidth': 124}],
['1CndgF', 34, 156, 49.82, 41, 17, 2.8, {'ott_len': 7, 'ott_percent': 339, 'stop_loss': 360, 'risk_reward': 63, 'chop_rsi_len': 40, 'chop_bandwidth': 120}],
['tutp,b', 50, 40, 52.45, 0, 5, -5.75, {'ott_len': 48, 'ott_percent': 782, 'stop_loss': 387, 'risk_reward': 74, 'chop_rsi_len': 4, 'chop_bandwidth': 223}],
['07t1iJ', 30, 199, 23.05, 26, 30, -1.64, {'ott_len': 6, 'ott_percent': 233, 'stop_loss': 387, 'risk_reward': 18, 'chop_rsi_len': 41, 'chop_bandwidth': 135}],
['75\\adC', 37, 200, 68.9, 21, 32, -4.78, {'ott_len': 10, 'ott_percent': 215, 'stop_loss': 280, 'risk_reward': 61, 'chop_rsi_len': 38, 'chop_bandwidth': 109}],
]
| dnas = [['jVXfX<', 37, 64, 24.67, 14, 7, -4.53, {'ott_len': 42, 'ott_percent': 508, 'stop_loss': 263, 'risk_reward': 65, 'chop_rsi_len': 31, 'chop_bandwidth': 83}], ['o:JK9p', 50, 62, 32.74, 37, 8, -0.2, {'ott_len': 45, 'ott_percent': 259, 'stop_loss': 201, 'risk_reward': 41, 'chop_rsi_len': 12, 'chop_bandwidth': 274}], ['tGVME/', 35, 74, 20.06, 20, 10, -4.75, {'ott_len': 48, 'ott_percent': 375, 'stop_loss': 254, 'risk_reward': 43, 'chop_rsi_len': 20, 'chop_bandwidth': 36}], ['a<<sMo', 59, 27, 25.74, 33, 6, -1.06, {'ott_len': 36, 'ott_percent': 277, 'stop_loss': 139, 'risk_reward': 76, 'chop_rsi_len': 24, 'chop_bandwidth': 271}], ['`Ol@gL', 29, 65, 9.47, 25, 8, -2.95, {'ott_len': 36, 'ott_percent': 446, 'stop_loss': 351, 'risk_reward': 31, 'chop_rsi_len': 40, 'chop_bandwidth': 142}], ['SWJi?Y', 36, 73, 32.8, 37, 8, -0.92, {'ott_len': 28, 'ott_percent': 516, 'stop_loss': 201, 'risk_reward': 68, 'chop_rsi_len': 16, 'chop_bandwidth': 190}], ['v@WLkU', 46, 47, 45.51, 20, 10, -4.43, {'ott_len': 49, 'ott_percent': 313, 'stop_loss': 258, 'risk_reward': 42, 'chop_rsi_len': 43, 'chop_bandwidth': 175}], ['lR\\iHN', 38, 62, 35.84, 28, 7, -4.01, {'ott_len': 43, 'ott_percent': 472, 'stop_loss': 280, 'risk_reward': 68, 'chop_rsi_len': 21, 'chop_bandwidth': 149}], ['l7\\gc^', 60, 35, 42.7, 25, 8, -1.2, {'ott_len': 43, 'ott_percent': 233, 'stop_loss': 280, 'risk_reward': 66, 'chop_rsi_len': 38, 'chop_bandwidth': 208}], ['wLXY\\1', 36, 71, 20.85, 14, 7, -4.76, {'ott_len': 50, 'ott_percent': 419, 'stop_loss': 263, 'risk_reward': 53, 'chop_rsi_len': 34, 'chop_bandwidth': 43}], ['i7nMgb', 54, 24, 28.38, 0, 4, -2.04, {'ott_len': 41, 'ott_percent': 233, 'stop_loss': 360, 'risk_reward': 43, 'chop_rsi_len': 40, 'chop_bandwidth': 223}], ['F/0eI[', 40, 154, 33.68, 42, 21, 2.91, {'ott_len': 20, 'ott_percent': 162, 'stop_loss': 85, 'risk_reward': 64, 'chop_rsi_len': 22, 'chop_bandwidth': 197}], ['\\ERgMp', 53, 28, 16.3, 33, 6, -2.59, {'ott_len': 33, 'ott_percent': 357, 'stop_loss': 236, 'risk_reward': 66, 'chop_rsi_len': 24, 'chop_bandwidth': 274}], ['_7@QqN', 44, 87, 28.24, 46, 15, 3.21, {'ott_len': 35, 'ott_percent': 233, 'stop_loss': 156, 'risk_reward': 46, 'chop_rsi_len': 46, 'chop_bandwidth': 149}], ['OEJO,F', 41, 105, 33.62, 20, 10, -4.61, {'ott_len': 25, 'ott_percent': 357, 'stop_loss': 201, 'risk_reward': 45, 'chop_rsi_len': 4, 'chop_bandwidth': 120}], ['5swn)a', 30, 86, 13.25, 8, 12, -6.03, {'ott_len': 9, 'ott_percent': 765, 'stop_loss': 400, 'risk_reward': 72, 'chop_rsi_len': 3, 'chop_bandwidth': 219}], ['4juD3[', 36, 95, 32.91, 14, 7, -3.13, {'ott_len': 8, 'ott_percent': 685, 'stop_loss': 391, 'risk_reward': 35, 'chop_rsi_len': 9, 'chop_bandwidth': 197}], ['91u6iJ', 33, 163, 31.1, 25, 27, -3.59, {'ott_len': 12, 'ott_percent': 180, 'stop_loss': 391, 'risk_reward': 22, 'chop_rsi_len': 41, 'chop_bandwidth': 135}], ['c3rg61', 39, 91, 11.05, 27, 11, -1.18, {'ott_len': 38, 'ott_percent': 197, 'stop_loss': 378, 'risk_reward': 66, 'chop_rsi_len': 11, 'chop_bandwidth': 43}], ['\\BAZGb', 40, 71, 22.33, 36, 11, -3.44, {'ott_len': 33, 'ott_percent': 330, 'stop_loss': 161, 'risk_reward': 54, 'chop_rsi_len': 21, 'chop_bandwidth': 223}], ['H<XF,l', 40, 98, 31.16, 16, 12, -5.22, {'ott_len': 21, 'ott_percent': 277, 'stop_loss': 263, 'risk_reward': 37, 'chop_rsi_len': 4, 'chop_bandwidth': 260}], ['5Bl/TL', 32, 153, 26.35, 28, 21, 0.03, {'ott_len': 9, 'ott_percent': 330, 'stop_loss': 351, 'risk_reward': 16, 'chop_rsi_len': 29, 'chop_bandwidth': 142}], ['DFRlX-', 38, 112, 21.16, 27, 11, -1.95, {'ott_len': 18, 'ott_percent': 366, 'stop_loss': 236, 'risk_reward': 70, 'chop_rsi_len': 31, 'chop_bandwidth': 28}], ['1EkquE', 33, 156, 45.58, 27, 18, -1.61, {'ott_len': 7, 'ott_percent': 357, 'stop_loss': 347, 'risk_reward': 75, 'chop_rsi_len': 49, 'chop_bandwidth': 116}], ['D9YmB.', 35, 139, 12.09, 42, 14, -1.17, {'ott_len': 18, 'ott_percent': 251, 'stop_loss': 267, 'risk_reward': 71, 'chop_rsi_len': 18, 'chop_bandwidth': 32}], ['_(KrZG', 40, 145, 18.09, 28, 21, -4.73, {'ott_len': 35, 'ott_percent': 100, 'stop_loss': 205, 'risk_reward': 76, 'chop_rsi_len': 32, 'chop_bandwidth': 124}], ['1CndgF', 34, 156, 49.82, 41, 17, 2.8, {'ott_len': 7, 'ott_percent': 339, 'stop_loss': 360, 'risk_reward': 63, 'chop_rsi_len': 40, 'chop_bandwidth': 120}], ['tutp,b', 50, 40, 52.45, 0, 5, -5.75, {'ott_len': 48, 'ott_percent': 782, 'stop_loss': 387, 'risk_reward': 74, 'chop_rsi_len': 4, 'chop_bandwidth': 223}], ['07t1iJ', 30, 199, 23.05, 26, 30, -1.64, {'ott_len': 6, 'ott_percent': 233, 'stop_loss': 387, 'risk_reward': 18, 'chop_rsi_len': 41, 'chop_bandwidth': 135}], ['75\\adC', 37, 200, 68.9, 21, 32, -4.78, {'ott_len': 10, 'ott_percent': 215, 'stop_loss': 280, 'risk_reward': 61, 'chop_rsi_len': 38, 'chop_bandwidth': 109}]] |
def createArray(dims) :
if len(dims) == 1:
return [0 for _ in range(dims[0])]
return [createArray(dims[1:]) for _ in range(dims[0])]
def f(A, x, y):
m = len(A)
for i in range(m):
if A[i][x] > A[i][y]:
return 0
return 1
class Solution(object):
def minDeletionSize(self, A):
"""
:type A: List[str]
:rtype: int
"""
n = len(A[0])
g = createArray([n, n])
for i in range(n):
for j in range(i+1, n):
g[i][j] = f(A, i, j)
dp = createArray([n])
for i in range(0, n):
dp[i] = 1
for j in range(0, i):
if g[j][i] == 1:
if dp[i] < dp[j] + 1:
dp[i] = dp[j] + 1
return n - max(dp)
| def create_array(dims):
if len(dims) == 1:
return [0 for _ in range(dims[0])]
return [create_array(dims[1:]) for _ in range(dims[0])]
def f(A, x, y):
m = len(A)
for i in range(m):
if A[i][x] > A[i][y]:
return 0
return 1
class Solution(object):
def min_deletion_size(self, A):
"""
:type A: List[str]
:rtype: int
"""
n = len(A[0])
g = create_array([n, n])
for i in range(n):
for j in range(i + 1, n):
g[i][j] = f(A, i, j)
dp = create_array([n])
for i in range(0, n):
dp[i] = 1
for j in range(0, i):
if g[j][i] == 1:
if dp[i] < dp[j] + 1:
dp[i] = dp[j] + 1
return n - max(dp) |
lista = list(range(0,10001))
for cont in range(0,10001):
print(lista[cont])
for valor in lista:
print(valor) | lista = list(range(0, 10001))
for cont in range(0, 10001):
print(lista[cont])
for valor in lista:
print(valor) |
cont = 1
while True:
t = int(input('Quer saber a tabuada de que numero ? '))
if t < 0:
break
for c in range (1, 11):
print(f'{t} X {c} = {t * c}')
print('Obrigado!') | cont = 1
while True:
t = int(input('Quer saber a tabuada de que numero ? '))
if t < 0:
break
for c in range(1, 11):
print(f'{t} X {c} = {t * c}')
print('Obrigado!') |
#!/usr/bin/env python3
seq = 'ACGACGCAGGAGGAGAGTTTCAGAGATCACGAATACATCCATATTACCCAGAGAGAG'
w = 11
for i in range(len(seq) - w + 1):
count = 0
for j in range(i, i + w):
if seq[j] == 'G' or seq[j] == 'C':
count += 1
print(f'{i} {seq[i:i+w]} {(count / w) : .4f}')
| seq = 'ACGACGCAGGAGGAGAGTTTCAGAGATCACGAATACATCCATATTACCCAGAGAGAG'
w = 11
for i in range(len(seq) - w + 1):
count = 0
for j in range(i, i + w):
if seq[j] == 'G' or seq[j] == 'C':
count += 1
print(f'{i} {seq[i:i + w]} {count / w: .4f}') |
# Princess No Damage Skin (30-Days)
success = sm.addDamageSkin(2432803)
if success:
sm.chat("The Princess No Damage Skin (30-Days) has been added to your account's damage skin collection.")
| success = sm.addDamageSkin(2432803)
if success:
sm.chat("The Princess No Damage Skin (30-Days) has been added to your account's damage skin collection.") |
class HiddenPeople():
"""Class for holding information on people"""
def __init__(self):
self.people = {
'Paul': {'bald': False, 'beard': False, 'eyes': 'brown', 'gender': 'man', 'hair': 'white', 'hat': False,
'glasses': True, 'moustache': False},
'Richard': {'bald': True, 'beard': True, 'eyes': 'brown', 'gender': 'man', 'hair': 'brown',
'hat': False, 'glasses': False, 'moustache': True},
'George': {'bald': False, 'beard': False, 'eyes': 'brown', 'gender': 'boy', 'hair': 'white',
'hat': True, 'glasses': False, 'moustache': False},
'Frans': {'bald': False, 'beard': False, 'eyes': 'brown', 'gender': 'boy', 'hair': 'red', 'hat': False,
'glasses': False, 'moustache': False},
'Bernard': {'bald': False, 'beard': False, 'eyes': 'brown', 'gender': 'boy', 'hair': 'brown',
'hat': True, 'glasses': True, 'moustache': False},
'Anne': {'bald': False, 'beard': False, 'eyes': 'brown', 'gender': 'girl', 'hair': 'black',
'hat': False, 'glasses': False, 'moustache': False},
'Joe': {'bald': False, 'beard': False, 'eyes': 'brown', 'gender': 'boy', 'hair': 'blonde', 'hat': False,
'glasses': True, 'moustache': False},
'Peter': {'bald': False, 'beard': False, 'eyes': 'blue', 'gender': 'boy', 'hair': 'white', 'hat': False,
'glasses': False, 'moustache': False},
'Tom': {'bald': True, 'beard': False, 'eyes': 'blue', 'gender': 'boy', 'hair': 'black', 'hat': False,
'glasses': True, 'moustache': False},
'Susan': {'bald': False, 'beard': False, 'eyes': 'brown', 'gender': 'girl', 'hair': 'blonde',
'hat': False, 'glasses': False, 'moustache': False},
'Sam': {'bald': True, 'beard': False, 'eyes': 'brown', 'gender': 'boy', 'hair': 'white', 'hat': False,
'glasses': True, 'moustache': False},
'Maria': {'bald': False, 'beard': False, 'eyes': 'brown', 'gender': 'girl', 'hair': 'brown',
'hat': True, 'glasses': False, 'moustache': False},
'Robert': {'bald': False, 'beard': False, 'eyes': 'blue', 'gender': 'boy', 'hair': 'brown',
'hat': False, 'glasses': False, 'moustache': False},
'Alex': {'bald': False, 'beard': False, 'eyes': 'brown', 'gender': 'boy', 'hair': 'black', 'hat': False,
'glasses': False, 'moustache': True},
'Charles': {'bald': False, 'beard': False, 'eyes': 'brown', 'gender': 'boy', 'hair': 'blonde',
'hat': False, 'glasses': False, 'moustache': True},
'Philip': {'bald': False, 'beard': True, 'eyes': 'brown', 'gender': 'boy', 'hair': 'black',
'hat': False, 'glasses': False, 'moustache': False},
'David': {'bald': False, 'beard': True, 'eyes': 'brown', 'gender': 'boy', 'hair': 'blonde',
'hat': False, 'glasses': False, 'moustache': False},
'Eric': {'bald': False, 'beard': False, 'eyes': 'brown', 'gender': 'boy', 'hair': 'blonde',
'hat': True, 'glasses': False, 'moustache': False},
'Bill': {'bald': True, 'beard': True, 'eyes': 'brown', 'gender': 'boy', 'hair': 'red',
'hat': False, 'glasses': False, 'moustache': False},
'Alfred': {'bald': False, 'beard': False, 'eyes': 'blue', 'gender': 'boy', 'hair': 'red', 'hat': False,
'glasses': False, 'moustache': True},
'Anita': {'bald': False, 'beard': False, 'eyes': 'blue', 'gender': 'girl', 'hair': 'white',
'hat': False, 'glasses': False, 'moustache': False},
'Max': {'bald': False, 'beard': False, 'eyes': 'brown', 'gender': 'boy', 'hair': 'black', 'hat': False,
'glasses': False, 'moustache': True},
'Herman': {'bald': True, 'beard': False, 'eyes': 'brown', 'gender': 'boy', 'hair': 'red', 'hat': False,
'glasses': False, 'moustache': False},
'Claire': {'bald': False, 'beard': False, 'eyes': 'brown', 'gender': 'girl', 'hair': 'red', 'hat': True,
'glasses': True, 'moustache': False}}
def removeperson(self, attribute):
"""Remove a person from listing of people to choose"""
removelist = []
for person in self.people:
if self.people[person][attribute]:
removelist.append(person)
for person in removelist:
del self.people[person]
def printpeople(self):
for person in self.people:
print(person + ": " + str(self.people[person]))
| class Hiddenpeople:
"""Class for holding information on people"""
def __init__(self):
self.people = {'Paul': {'bald': False, 'beard': False, 'eyes': 'brown', 'gender': 'man', 'hair': 'white', 'hat': False, 'glasses': True, 'moustache': False}, 'Richard': {'bald': True, 'beard': True, 'eyes': 'brown', 'gender': 'man', 'hair': 'brown', 'hat': False, 'glasses': False, 'moustache': True}, 'George': {'bald': False, 'beard': False, 'eyes': 'brown', 'gender': 'boy', 'hair': 'white', 'hat': True, 'glasses': False, 'moustache': False}, 'Frans': {'bald': False, 'beard': False, 'eyes': 'brown', 'gender': 'boy', 'hair': 'red', 'hat': False, 'glasses': False, 'moustache': False}, 'Bernard': {'bald': False, 'beard': False, 'eyes': 'brown', 'gender': 'boy', 'hair': 'brown', 'hat': True, 'glasses': True, 'moustache': False}, 'Anne': {'bald': False, 'beard': False, 'eyes': 'brown', 'gender': 'girl', 'hair': 'black', 'hat': False, 'glasses': False, 'moustache': False}, 'Joe': {'bald': False, 'beard': False, 'eyes': 'brown', 'gender': 'boy', 'hair': 'blonde', 'hat': False, 'glasses': True, 'moustache': False}, 'Peter': {'bald': False, 'beard': False, 'eyes': 'blue', 'gender': 'boy', 'hair': 'white', 'hat': False, 'glasses': False, 'moustache': False}, 'Tom': {'bald': True, 'beard': False, 'eyes': 'blue', 'gender': 'boy', 'hair': 'black', 'hat': False, 'glasses': True, 'moustache': False}, 'Susan': {'bald': False, 'beard': False, 'eyes': 'brown', 'gender': 'girl', 'hair': 'blonde', 'hat': False, 'glasses': False, 'moustache': False}, 'Sam': {'bald': True, 'beard': False, 'eyes': 'brown', 'gender': 'boy', 'hair': 'white', 'hat': False, 'glasses': True, 'moustache': False}, 'Maria': {'bald': False, 'beard': False, 'eyes': 'brown', 'gender': 'girl', 'hair': 'brown', 'hat': True, 'glasses': False, 'moustache': False}, 'Robert': {'bald': False, 'beard': False, 'eyes': 'blue', 'gender': 'boy', 'hair': 'brown', 'hat': False, 'glasses': False, 'moustache': False}, 'Alex': {'bald': False, 'beard': False, 'eyes': 'brown', 'gender': 'boy', 'hair': 'black', 'hat': False, 'glasses': False, 'moustache': True}, 'Charles': {'bald': False, 'beard': False, 'eyes': 'brown', 'gender': 'boy', 'hair': 'blonde', 'hat': False, 'glasses': False, 'moustache': True}, 'Philip': {'bald': False, 'beard': True, 'eyes': 'brown', 'gender': 'boy', 'hair': 'black', 'hat': False, 'glasses': False, 'moustache': False}, 'David': {'bald': False, 'beard': True, 'eyes': 'brown', 'gender': 'boy', 'hair': 'blonde', 'hat': False, 'glasses': False, 'moustache': False}, 'Eric': {'bald': False, 'beard': False, 'eyes': 'brown', 'gender': 'boy', 'hair': 'blonde', 'hat': True, 'glasses': False, 'moustache': False}, 'Bill': {'bald': True, 'beard': True, 'eyes': 'brown', 'gender': 'boy', 'hair': 'red', 'hat': False, 'glasses': False, 'moustache': False}, 'Alfred': {'bald': False, 'beard': False, 'eyes': 'blue', 'gender': 'boy', 'hair': 'red', 'hat': False, 'glasses': False, 'moustache': True}, 'Anita': {'bald': False, 'beard': False, 'eyes': 'blue', 'gender': 'girl', 'hair': 'white', 'hat': False, 'glasses': False, 'moustache': False}, 'Max': {'bald': False, 'beard': False, 'eyes': 'brown', 'gender': 'boy', 'hair': 'black', 'hat': False, 'glasses': False, 'moustache': True}, 'Herman': {'bald': True, 'beard': False, 'eyes': 'brown', 'gender': 'boy', 'hair': 'red', 'hat': False, 'glasses': False, 'moustache': False}, 'Claire': {'bald': False, 'beard': False, 'eyes': 'brown', 'gender': 'girl', 'hair': 'red', 'hat': True, 'glasses': True, 'moustache': False}}
def removeperson(self, attribute):
"""Remove a person from listing of people to choose"""
removelist = []
for person in self.people:
if self.people[person][attribute]:
removelist.append(person)
for person in removelist:
del self.people[person]
def printpeople(self):
for person in self.people:
print(person + ': ' + str(self.people[person])) |
# 1) count = To count how many time a particular word & char. is appearing
x = "Keep grinding keep hustling"
print(x.count("t"))
# 2) index = To get index of letter(gives the lowest index)
x="Keep grinding keep hustling"
print(x.index("t")) # will give the lowest index value of (t)
# 3) find = To get index of letter(gives the lowest index) | Return -1 on failure.
x = "Keep grinding keep hustling"
print(x.find("t"))
'''
NOTE : print(x.index("t",34)) : Search starts from index value 34 including 34
'''
| x = 'Keep grinding keep hustling'
print(x.count('t'))
x = 'Keep grinding keep hustling'
print(x.index('t'))
x = 'Keep grinding keep hustling'
print(x.find('t'))
'\nNOTE : print(x.index("t",34)) : Search starts from index value 34 including 34\n' |
# example of redefinition __repr__ and __str__ of exception
class MyBad(Exception):
def __str__(self):
return 'My mistake!'
class MyBad2(Exception):
def __repr__(self):
return 'Not calable' # because buid-in method has __str__
try:
raise MyBad('spam')
except MyBad as X:
print(X) # My mistake!
print(X.args) # ('spam',)
try:
raise MyBad2('spam')
except MyBad2 as X:
print(X) # spam
print(X.args) # ('spam',)
raise MyBad('spam') # __main__.MyBad2: My mistake!
# raise MyBad2('spam') # __main__.MyBad2: spam | class Mybad(Exception):
def __str__(self):
return 'My mistake!'
class Mybad2(Exception):
def __repr__(self):
return 'Not calable'
try:
raise my_bad('spam')
except MyBad as X:
print(X)
print(X.args)
try:
raise my_bad2('spam')
except MyBad2 as X:
print(X)
print(X.args)
raise my_bad('spam') |
class Solution:
def findUnsortedSubarray(self, nums: List[int]) -> int:
'''
T: O(n log n) and S: O(1)
'''
n = len(nums)
sorted_nums = sorted(nums)
start, end = n + 1, -1
for i in range(n):
if nums[i] != sorted_nums[i]:
start = min(start, i)
end = max(end, i)
diff = end - start
return diff + 1 if diff > 0 else 0
| class Solution:
def find_unsorted_subarray(self, nums: List[int]) -> int:
"""
T: O(n log n) and S: O(1)
"""
n = len(nums)
sorted_nums = sorted(nums)
(start, end) = (n + 1, -1)
for i in range(n):
if nums[i] != sorted_nums[i]:
start = min(start, i)
end = max(end, i)
diff = end - start
return diff + 1 if diff > 0 else 0 |
# "javascript" section for javascript. see @app.route('/config.js') in app/views.py
# oauth constants
HOSTNAME = "http://hackathon.chinacloudapp.cn" # host name of the UI site
QQ_OAUTH_STATE = "openhackathon" # todo state should be constant. Actually it should be unguessable to prevent CSFA
HACkATHON_API_ENDPOINT = "http://hackathon.chinacloudapp.cn:15000"
Config = {
"environment": "local",
"login": {
"github": {
"access_token_url": 'https://github.com/login/oauth/access_token?client_id=a10e2290ed907918d5ab&client_secret=5b240a2a1bed6a6cf806fc2f34eb38a33ce03d75&redirect_uri=%s/github&code=' % HOSTNAME,
"user_info_url": 'https://api.github.com/user?access_token=',
"emails_info_url": 'https://api.github.com/user/emails?access_token='
},
"qq": {
"access_token_url": 'https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&client_id=101192358&client_secret=d94f8e7baee4f03371f52d21c4400cab&redirect_uri=%s/qq&code=' % HOSTNAME,
"openid_url": 'https://graph.qq.com/oauth2.0/me?access_token=',
"user_info_url": 'https://graph.qq.com/user/get_user_info?access_token=%s&oauth_consumer_key=%s&openid=%s'
},
"gitcafe": {
"access_token_url": 'https://api.gitcafe.com/oauth/token?client_id=25ba4f6f90603bd2f3d310d11c0665d937db8971c8a5db00f6c9b9852547d6b8&client_secret=e3d821e82d15096054abbc7fbf41727d3650cab6404a242373f5c446c0918634&redirect_uri=%s/gitcafe&grant_type=authorization_code&code=' % HOSTNAME
},
"provider_enabled": ["github", "qq", "gitcafe"],
"session_minutes": 60,
"token_expiration_minutes": 60 * 24
},
"hackathon-api": {
"endpoint": HACkATHON_API_ENDPOINT
},
"javascript": {
"renren": {
"clientID": "client_id=7e0932f4c5b34176b0ca1881f5e88562",
"redirect_url": "redirect_uri=%s/renren" % HOSTNAME,
"scope": "scope=read_user_message+read_user_feed+read_user_photo",
"response_type": "response_type=token",
},
"github": {
"clientID": "client_id=a10e2290ed907918d5ab",
"redirect_uri": "redirect_uri=%s/github" % HOSTNAME,
"scope": "scope=user",
},
"google": {
"clientID": "client_id=304944766846-7jt8jbm39f1sj4kf4gtsqspsvtogdmem.apps.googleusercontent.com",
"redirect_url": "redirect_uri=%s/google" % HOSTNAME,
"scope": "scope=https://www.googleapis.com/auth/userinfo.profile+https://www.googleapis.com/auth/userinfo.email",
"response_type": "response_type=token",
},
"qq": {
"clientID": "client_id=101192358",
"redirect_uri": "redirect_uri=%s/qq" % HOSTNAME,
"scope": "scope=get_user_info",
"state": "state=%s" % QQ_OAUTH_STATE,
"response_type": "response_type=code",
},
"gitcafe": {
"clientID": "client_id=25ba4f6f90603bd2f3d310d11c0665d937db8971c8a5db00f6c9b9852547d6b8",
"clientSecret": "client_secret=e3d821e82d15096054abbc7fbf41727d3650cab6404a242373f5c446c0918634",
"redirect_uri": "redirect_uri=http://hackathon.chinacloudapp.cn/gitcafe",
"response_type": "response_type=code",
"scope": "scope=public"
},
"hackathon": {
"name": "open-xml-sdk",
"endpoint": HACkATHON_API_ENDPOINT
}
}
}
| hostname = 'http://hackathon.chinacloudapp.cn'
qq_oauth_state = 'openhackathon'
ha_ck_athon_api_endpoint = 'http://hackathon.chinacloudapp.cn:15000'
config = {'environment': 'local', 'login': {'github': {'access_token_url': 'https://github.com/login/oauth/access_token?client_id=a10e2290ed907918d5ab&client_secret=5b240a2a1bed6a6cf806fc2f34eb38a33ce03d75&redirect_uri=%s/github&code=' % HOSTNAME, 'user_info_url': 'https://api.github.com/user?access_token=', 'emails_info_url': 'https://api.github.com/user/emails?access_token='}, 'qq': {'access_token_url': 'https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&client_id=101192358&client_secret=d94f8e7baee4f03371f52d21c4400cab&redirect_uri=%s/qq&code=' % HOSTNAME, 'openid_url': 'https://graph.qq.com/oauth2.0/me?access_token=', 'user_info_url': 'https://graph.qq.com/user/get_user_info?access_token=%s&oauth_consumer_key=%s&openid=%s'}, 'gitcafe': {'access_token_url': 'https://api.gitcafe.com/oauth/token?client_id=25ba4f6f90603bd2f3d310d11c0665d937db8971c8a5db00f6c9b9852547d6b8&client_secret=e3d821e82d15096054abbc7fbf41727d3650cab6404a242373f5c446c0918634&redirect_uri=%s/gitcafe&grant_type=authorization_code&code=' % HOSTNAME}, 'provider_enabled': ['github', 'qq', 'gitcafe'], 'session_minutes': 60, 'token_expiration_minutes': 60 * 24}, 'hackathon-api': {'endpoint': HACkATHON_API_ENDPOINT}, 'javascript': {'renren': {'clientID': 'client_id=7e0932f4c5b34176b0ca1881f5e88562', 'redirect_url': 'redirect_uri=%s/renren' % HOSTNAME, 'scope': 'scope=read_user_message+read_user_feed+read_user_photo', 'response_type': 'response_type=token'}, 'github': {'clientID': 'client_id=a10e2290ed907918d5ab', 'redirect_uri': 'redirect_uri=%s/github' % HOSTNAME, 'scope': 'scope=user'}, 'google': {'clientID': 'client_id=304944766846-7jt8jbm39f1sj4kf4gtsqspsvtogdmem.apps.googleusercontent.com', 'redirect_url': 'redirect_uri=%s/google' % HOSTNAME, 'scope': 'scope=https://www.googleapis.com/auth/userinfo.profile+https://www.googleapis.com/auth/userinfo.email', 'response_type': 'response_type=token'}, 'qq': {'clientID': 'client_id=101192358', 'redirect_uri': 'redirect_uri=%s/qq' % HOSTNAME, 'scope': 'scope=get_user_info', 'state': 'state=%s' % QQ_OAUTH_STATE, 'response_type': 'response_type=code'}, 'gitcafe': {'clientID': 'client_id=25ba4f6f90603bd2f3d310d11c0665d937db8971c8a5db00f6c9b9852547d6b8', 'clientSecret': 'client_secret=e3d821e82d15096054abbc7fbf41727d3650cab6404a242373f5c446c0918634', 'redirect_uri': 'redirect_uri=http://hackathon.chinacloudapp.cn/gitcafe', 'response_type': 'response_type=code', 'scope': 'scope=public'}, 'hackathon': {'name': 'open-xml-sdk', 'endpoint': HACkATHON_API_ENDPOINT}}} |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def getTargetCopy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode:
if not target or not original or not cloned: return None
if target.val == original.val == cloned.val: return cloned
node = self.getTargetCopy(original.left, cloned.left, target)
if node: return node
node = self.getTargetCopy(original.right, cloned.right, target)
if node: return node
return None
| class Solution:
def get_target_copy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode:
if not target or not original or (not cloned):
return None
if target.val == original.val == cloned.val:
return cloned
node = self.getTargetCopy(original.left, cloned.left, target)
if node:
return node
node = self.getTargetCopy(original.right, cloned.right, target)
if node:
return node
return None |
class City:
name = "city"
size = "default"
draw = -1
danger = -1
population = [] | class City:
name = 'city'
size = 'default'
draw = -1
danger = -1
population = [] |
# >>> s = set("Hacker")
# >>> print s.difference("Rank")
# set(['c', 'r', 'e', 'H'])
# >>> print s.difference(set(['R', 'a', 'n', 'k']))
# set(['c', 'r', 'e', 'H'])
# >>> print s.difference(['R', 'a', 'n', 'k'])
# set(['c', 'r', 'e', 'H'])
# >>> print s.difference(enumerate(['R', 'a', 'n', 'k']))
# set(['a', 'c', 'r', 'e', 'H', 'k'])
# >>> print s.difference({"Rank":1})
# set(['a', 'c', 'e', 'H', 'k', 'r'])
# >>> s - set("Rank")
# set(['H', 'c', 'r', 'e'])
if __name__ == "__main__":
eng = input()
eng_stu = set(map(int, input().split()))
fre = input()
fre_stu = set(map(int, input().split()))
eng_only = eng_stu - fre_stu
print(len(eng_only))
| if __name__ == '__main__':
eng = input()
eng_stu = set(map(int, input().split()))
fre = input()
fre_stu = set(map(int, input().split()))
eng_only = eng_stu - fre_stu
print(len(eng_only)) |
SECRET_KEY = None
DB_HOST = "localhost"
DB_NAME = "kido"
DB_USERNAME = "kido"
DB_PASSWORD = "kido"
COMPRESSOR_DEBUG = False
COMPRESSOR_OFFLINE_COMPRESS = True
| secret_key = None
db_host = 'localhost'
db_name = 'kido'
db_username = 'kido'
db_password = 'kido'
compressor_debug = False
compressor_offline_compress = True |
def consolidate(sets):
setlist = [s for s in sets if s]
for i, s1 in enumerate(setlist):
if s1:
for s2 in setlist[i+1:]:
intersection = s1.intersection(s2)
if intersection:
s2.update(s1)
s1.clear()
s1 = s2
return [s for s in setlist if s]
| def consolidate(sets):
setlist = [s for s in sets if s]
for (i, s1) in enumerate(setlist):
if s1:
for s2 in setlist[i + 1:]:
intersection = s1.intersection(s2)
if intersection:
s2.update(s1)
s1.clear()
s1 = s2
return [s for s in setlist if s] |
class InterpreterException(Exception):
def __init__(self, message):
self.message = message
def __str__(self):
return self.message
class SymbolNotFound(InterpreterException):
pass
class UnexpectedCharacter(InterpreterException):
pass
class ParserSyntaxError(InterpreterException):
pass
class DuplicateSymbol(InterpreterException):
pass
class InterpreterRuntimeError(InterpreterException):
pass
class InvalidParamCount(InterpreterRuntimeError):
pass | class Interpreterexception(Exception):
def __init__(self, message):
self.message = message
def __str__(self):
return self.message
class Symbolnotfound(InterpreterException):
pass
class Unexpectedcharacter(InterpreterException):
pass
class Parsersyntaxerror(InterpreterException):
pass
class Duplicatesymbol(InterpreterException):
pass
class Interpreterruntimeerror(InterpreterException):
pass
class Invalidparamcount(InterpreterRuntimeError):
pass |
#! /usr/bin/env python
#
# parameters/standard.py
#
# Nick Barnes, Ravenbrook Limited, 2010-02-15
# Avi Persin, Revision 2016-01-06
"""Parameters controlling the standard GISTEMP algorithm.
Various parameters controlling each phase of the algorithm are
collected and documented here. They appear here in approximately the
order in which they are used in the algorithm.
Parameters controlling cccgistemp extensions to the standard GISTEMP
algorithm, or obsolete features of GISTEMP, are in other parameter
files.
"""
station_drop_minimum_months = 20
"""A station record must have at least one month of the year with at
least this many valid data values, otherwise it is dropped immediately
prior to the peri-urban adjustment step."""
rural_designator = "global_light <= 10"
"""Describes the test used to determine whether a station is rural or
not, in terms of the station metadata fields. Relevant fields are:
'global_light' (global satellite nighttime radiance value); 'popcls'
(GHCN population class flag; the value 'R' stands for rural);
'us_light' (class derived from satellite nighttime radiance covering
the US and some neighbouring stations), 'berkeley' (a field of unknown
provenance which seems to be related to the Berkeley Earth Surface
Temperature project).
The value of this parameter may be a comma separated sequence. Each
member in that sequence can either be a metadata field name, or a
numeric comparison on a metadata field name (e.g. "global_light <= 10",
the default). If a field name appears on its own, the meaning is
field-dependent.
The fields are consulted in the order specified until one is found
that is not blank, and that obeys the condition (the only field which
is likely to be blank is 'us_light': this sequential feature is
required to emulate a previous version of GISTEMP).
Previous versions of GISTEMP can be "emulated" as follows:
"popcls" GISTEMP 1999 to 2001
"us_light, popcls" GISTEMP 2001 to 2010
"global_light <= 10" GISTEMP 2010 onwards
"global_light <= 0" GISTEMP 2011 passing 2 as second arg to do_comb_step2.sh
"berkeley <= 0" GISTEMP 2011 passing 3 as second arg to do_comb_step2.sh
"""
urban_adjustment_min_years = 20
"""When trying to calculate an urban station adjustment, at least this
many years have to have sufficient rural stations (if there are
not enough qualifying years, we may try again at a larger radius)."""
urban_adjustment_proportion_good = 2.0 / 3.0
"""When trying to calculate an urban station adjustment, at least this
proportion of the years to which the fit applies have to have
sufficient rural stations (if there are insufficient stations, we may
try again at a larger radius)."""
urban_adjustment_min_rural_stations = 3
"""When trying to calculate an urban station adjustment, a year
without at least this number of valid readings from rural stations is
not used to calculate the fit."""
urban_adjustment_min_leg = 5
"""When finding a two-part adjustment, only consider knee years which
have at least this many data points (note: not years) on each side."""
urban_adjustment_short_leg = 7
"""When a two-part adjustment has been identified, if either leg is
shorter than this number of years, a one-part adjustment is applied
instead."""
urban_adjustment_steep_leg = 0.1
"""When a two-part adjustment has been identified, if the gradient of
either leg is steeper than this (in absolute degrees Celsius per
year), or if the difference between the leg gradients is greater than
this, a one-part adjustment is applied instead."""
urban_adjustment_leg_difference = 0.05
"""When a two-part adjustment has been identified, if the difference
in gradient between the two legs is greater than this (in absolute
degrees Celsius per year), it is counted separately for statistical
purposes."""
urban_adjustment_reverse_gradient = 0.02
"""When a two-part adjustment has been identified, if the two
gradients have opposite sign, and both gradients are steeper than this
(in absolute degrees Celsius per year), a one-part adjustment is
applied instead."""
urban_adjustment_full_radius = 1000.0
"""Range in kilometres within which a rural station will be considered
for adjusting an urban station record. Half of this radius will be
attempted first."""
rural_station_min_overlap = 20
"""When combining rural station annual anomaly records to calculate
urban adjustment parameters, do not combine a candidate rural record
if it has fewer than this number years of overlap."""
gridding_min_overlap = 20
"""When combining station records to give a grid record, do not
combine a candidate station record if it has fewer than this number of
years of overlap with the combined grid record."""
gridding_radius = 1200.0
"""The radius in kilometres used to find and weight station records to
give a grid record."""
gridding_reference_period = (1951, 1980)
"""When gridding, temperature series are turned into anomaly series by
subtracting monthly means computed over a reference period. This is
the first and last years of that reference period."""
sea_surface_cutoff_temp = -1.77
"""When incorporating monthly sea-surface datasets, treat any
temperature colder than this as missing data."""
subbox_min_valid = 240
"""When combining the sub-boxes into boxes, do not use any sub-box
record, either land or ocean, which has fewer than this number of
valid data."""
subbox_land_range = 100
"""If a subbox has both land data and ocean data, but the distance
from the subbox centre to the nearest station used in its record is
less than this, the land data is used in preference to the ocean data
when calculating the box series. Note: the distance used is actually a
great-circle chord length."""
subbox_reference_period = (1961, 1990)
"""When combining subbox records into box records, temperature series
are turned into anomaly series by subtracting monthly means computed
over a reference period. This is the first and last years of that
reference period."""
box_min_overlap = 20
"""When combining subbox records to make box records, do not combine a
calendar month from a candidate subbox record if it has fewer than
this number of years of overlap with the same calendar month in the
combined box record. Also used when combining boxes into zones."""
box_reference_period = (1951, 1980)
"""When combining box records into zone records, temperature series
are turned into anomaly series by subtracting monthly means computed
over a reference period. This is the first and last years of that
reference period."""
zone_annual_min_months = 6
"""When computing zone annual means, require at least this many valid
month data."""
| """Parameters controlling the standard GISTEMP algorithm.
Various parameters controlling each phase of the algorithm are
collected and documented here. They appear here in approximately the
order in which they are used in the algorithm.
Parameters controlling cccgistemp extensions to the standard GISTEMP
algorithm, or obsolete features of GISTEMP, are in other parameter
files.
"""
station_drop_minimum_months = 20
'A station record must have at least one month of the year with at\nleast this many valid data values, otherwise it is dropped immediately\nprior to the peri-urban adjustment step.'
rural_designator = 'global_light <= 10'
'Describes the test used to determine whether a station is rural or\nnot, in terms of the station metadata fields. Relevant fields are:\n\'global_light\' (global satellite nighttime radiance value); \'popcls\'\n(GHCN population class flag; the value \'R\' stands for rural);\n\'us_light\' (class derived from satellite nighttime radiance covering\nthe US and some neighbouring stations), \'berkeley\' (a field of unknown\nprovenance which seems to be related to the Berkeley Earth Surface\nTemperature project).\n\nThe value of this parameter may be a comma separated sequence. Each\nmember in that sequence can either be a metadata field name, or a\nnumeric comparison on a metadata field name (e.g. "global_light <= 10",\nthe default). If a field name appears on its own, the meaning is\nfield-dependent.\n\nThe fields are consulted in the order specified until one is found\nthat is not blank, and that obeys the condition (the only field which\nis likely to be blank is \'us_light\': this sequential feature is\nrequired to emulate a previous version of GISTEMP).\n\nPrevious versions of GISTEMP can be "emulated" as follows:\n"popcls" GISTEMP 1999 to 2001\n"us_light, popcls" GISTEMP 2001 to 2010\n"global_light <= 10" GISTEMP 2010 onwards\n"global_light <= 0" GISTEMP 2011 passing 2 as second arg to do_comb_step2.sh \n"berkeley <= 0" GISTEMP 2011 passing 3 as second arg to do_comb_step2.sh \n'
urban_adjustment_min_years = 20
'When trying to calculate an urban station adjustment, at least this\nmany years have to have sufficient rural stations (if there are\nnot enough qualifying years, we may try again at a larger radius).'
urban_adjustment_proportion_good = 2.0 / 3.0
'When trying to calculate an urban station adjustment, at least this\nproportion of the years to which the fit applies have to have\nsufficient rural stations (if there are insufficient stations, we may\ntry again at a larger radius).'
urban_adjustment_min_rural_stations = 3
'When trying to calculate an urban station adjustment, a year\nwithout at least this number of valid readings from rural stations is\nnot used to calculate the fit.'
urban_adjustment_min_leg = 5
'When finding a two-part adjustment, only consider knee years which\nhave at least this many data points (note: not years) on each side.'
urban_adjustment_short_leg = 7
'When a two-part adjustment has been identified, if either leg is\nshorter than this number of years, a one-part adjustment is applied\ninstead.'
urban_adjustment_steep_leg = 0.1
'When a two-part adjustment has been identified, if the gradient of\neither leg is steeper than this (in absolute degrees Celsius per\nyear), or if the difference between the leg gradients is greater than\nthis, a one-part adjustment is applied instead.'
urban_adjustment_leg_difference = 0.05
'When a two-part adjustment has been identified, if the difference\nin gradient between the two legs is greater than this (in absolute\ndegrees Celsius per year), it is counted separately for statistical\npurposes.'
urban_adjustment_reverse_gradient = 0.02
'When a two-part adjustment has been identified, if the two\ngradients have opposite sign, and both gradients are steeper than this\n(in absolute degrees Celsius per year), a one-part adjustment is\napplied instead.'
urban_adjustment_full_radius = 1000.0
'Range in kilometres within which a rural station will be considered\nfor adjusting an urban station record. Half of this radius will be\nattempted first.'
rural_station_min_overlap = 20
'When combining rural station annual anomaly records to calculate\nurban adjustment parameters, do not combine a candidate rural record\nif it has fewer than this number years of overlap.'
gridding_min_overlap = 20
'When combining station records to give a grid record, do not\ncombine a candidate station record if it has fewer than this number of\nyears of overlap with the combined grid record.'
gridding_radius = 1200.0
'The radius in kilometres used to find and weight station records to\ngive a grid record.'
gridding_reference_period = (1951, 1980)
'When gridding, temperature series are turned into anomaly series by\nsubtracting monthly means computed over a reference period. This is\nthe first and last years of that reference period.'
sea_surface_cutoff_temp = -1.77
'When incorporating monthly sea-surface datasets, treat any\ntemperature colder than this as missing data.'
subbox_min_valid = 240
'When combining the sub-boxes into boxes, do not use any sub-box\nrecord, either land or ocean, which has fewer than this number of\nvalid data.'
subbox_land_range = 100
'If a subbox has both land data and ocean data, but the distance\nfrom the subbox centre to the nearest station used in its record is\nless than this, the land data is used in preference to the ocean data\nwhen calculating the box series. Note: the distance used is actually a\ngreat-circle chord length.'
subbox_reference_period = (1961, 1990)
'When combining subbox records into box records, temperature series\nare turned into anomaly series by subtracting monthly means computed\nover a reference period. This is the first and last years of that\nreference period.'
box_min_overlap = 20
'When combining subbox records to make box records, do not combine a\ncalendar month from a candidate subbox record if it has fewer than\nthis number of years of overlap with the same calendar month in the\ncombined box record. Also used when combining boxes into zones.'
box_reference_period = (1951, 1980)
'When combining box records into zone records, temperature series\nare turned into anomaly series by subtracting monthly means computed\nover a reference period. This is the first and last years of that\nreference period.'
zone_annual_min_months = 6
'When computing zone annual means, require at least this many valid\nmonth data.' |
#Copyright (c) 2009-11, Walter Bender, Tony Forster
# This procedure is invoked when the user-definable block on the
# "extras" palette is selected.
# Usage: Import this code into a Python (user-definable) block; when
# this code is run, the current mouse status will be pushed to the
# FILO heap. If a mouse button event occurs, a y, x, and 1 are pushed
# to the heap. If no button is pressed, 0 is pushed to the heap.
# To use these data, pop the heap in a compare block to determine if a
# button has been pushed. If a 1 was popped from the heap, pop the x
# and y coordinates.
def myblock(tw, x): # ignore second argument
''' Push mouse event to stack '''
if tw.mouse_flag == 1:
# push y first so x will be popped first
tw.lc.heap.append((tw.canvas.height / 2) - tw.mouse_y)
tw.lc.heap.append(tw.mouse_x - (tw.canvas.width / 2))
tw.lc.heap.append(1) # mouse event
tw.mouse_flag = 0
else:
tw.lc.heap.append(0) # no mouse event
| def myblock(tw, x):
""" Push mouse event to stack """
if tw.mouse_flag == 1:
tw.lc.heap.append(tw.canvas.height / 2 - tw.mouse_y)
tw.lc.heap.append(tw.mouse_x - tw.canvas.width / 2)
tw.lc.heap.append(1)
tw.mouse_flag = 0
else:
tw.lc.heap.append(0) |
can_juggle = True
# The code below has problems. See if
# you can fix them!
#if can_juggle print("I can juggle!")
#else
print("I can't juggle.")
| can_juggle = True
print("I can't juggle.") |
# decompiled-by-hand & optimized
# definitely not gonna refactor this one
# 0.18s on pypy3
ip_reg = 4
reg = [0, 0, 0, 0, 0, 0]
i = 0
seen = set()
lst = []
while True:
i += 1
break_true = False
while True:
if break_true:
if i == 1:
print("1)", reg[1])
if reg[1] in seen:
if len(lst) == 25000:
p2 = max(seen, key=lambda x: lst.index(x))
print("2)", p2)
exit()
seen.add(reg[1])
lst.append(reg[1])
break
reg[2] = reg[1] | 65536 # 6
reg[1] = 8725355 # 7
while True:
reg[5] = reg[2] & 255 # 8
reg[1] += reg[5] # 9
reg[1] &= 16777215 # 10
reg[1] *= 65899 # 11
reg[1] &= 16777215 # 12
reg[2] = reg[2] // 256
if reg[2] == 0:
break_true = True
break
break_true = False
| ip_reg = 4
reg = [0, 0, 0, 0, 0, 0]
i = 0
seen = set()
lst = []
while True:
i += 1
break_true = False
while True:
if break_true:
if i == 1:
print('1)', reg[1])
if reg[1] in seen:
if len(lst) == 25000:
p2 = max(seen, key=lambda x: lst.index(x))
print('2)', p2)
exit()
seen.add(reg[1])
lst.append(reg[1])
break
reg[2] = reg[1] | 65536
reg[1] = 8725355
while True:
reg[5] = reg[2] & 255
reg[1] += reg[5]
reg[1] &= 16777215
reg[1] *= 65899
reg[1] &= 16777215
reg[2] = reg[2] // 256
if reg[2] == 0:
break_true = True
break
break_true = False |
"""Write a program that allow user enter a file name (path) then content, allow user to save it"""
filename = input("Please input filename")
f= open(filename,"w+")
content = input("Please input content")
f.write(content) | """Write a program that allow user enter a file name (path) then content, allow user to save it"""
filename = input('Please input filename')
f = open(filename, 'w+')
content = input('Please input content')
f.write(content) |
class DxlNmapOptions:
"""
Constants that are used to execute Nmap tool
+-------------+---------+----------------------------------------------------------+
| Option | Command | Description |
+=============+=========+==========================================================+
| Aggressive | -A | Aggressive Scan |
| Scan | | |
+-------------+---------+----------------------------------------------------------+
| Operating | -O | Operating system in the current host |
| System | | |
+-------------+---------+----------------------------------------------------------+
| Aggressive | -O - A | Both options |
| Scan | | |
| + | | |
| Operating | | |
| System | | |
+-------------+---------+----------------------------------------------------------+
"""
AGGRESSIVE_SCAN = "-A"
OPERATING_SYSTEM = "-O"
AGGRESSIVE_SCAN_OP_SYSTEM = "-O -A"
| class Dxlnmapoptions:
"""
Constants that are used to execute Nmap tool
+-------------+---------+----------------------------------------------------------+
| Option | Command | Description |
+=============+=========+==========================================================+
| Aggressive | -A | Aggressive Scan |
| Scan | | |
+-------------+---------+----------------------------------------------------------+
| Operating | -O | Operating system in the current host |
| System | | |
+-------------+---------+----------------------------------------------------------+
| Aggressive | -O - A | Both options |
| Scan | | |
| + | | |
| Operating | | |
| System | | |
+-------------+---------+----------------------------------------------------------+
"""
aggressive_scan = '-A'
operating_system = '-O'
aggressive_scan_op_system = '-O -A' |
# See
# The configuration file should be a valid Python source file with a python extension (e.g. gunicorn.conf.py).
# https://docs.gunicorn.org/en/stable/configure.html
bind='127.0.0.1:8962'
timeout=75
daemon=True
user='user'
accesslog='/var/local/log/user/blockchain_backup.gunicorn.access.log'
errorlog='/var/local/log/user/blockchain_backup.gunicorn.error.log'
log_level='debug'
capture_output=True
max_requests=3
workers=1
| bind = '127.0.0.1:8962'
timeout = 75
daemon = True
user = 'user'
accesslog = '/var/local/log/user/blockchain_backup.gunicorn.access.log'
errorlog = '/var/local/log/user/blockchain_backup.gunicorn.error.log'
log_level = 'debug'
capture_output = True
max_requests = 3
workers = 1 |
size = 5
m = (2 * size)-2
for i in range(0, size):
for j in range(0, m):
print(end=" ")
m = m - 1
for j in range(0, i + 1):
if(m%2!=0):
print("*", end=" ")
print("") | size = 5
m = 2 * size - 2
for i in range(0, size):
for j in range(0, m):
print(end=' ')
m = m - 1
for j in range(0, i + 1):
if m % 2 != 0:
print('*', end=' ')
print('') |
__version__ = '2.0.0'
__description__ = 'Sample for calculations with data from the ctrlX Data Layer'
__author__ = 'Fantastic Python Developers'
__licence__ = 'MIT License'
__copyright__ = 'Copyright (c) 2021 Bosch Rexroth AG' | __version__ = '2.0.0'
__description__ = 'Sample for calculations with data from the ctrlX Data Layer'
__author__ = 'Fantastic Python Developers'
__licence__ = 'MIT License'
__copyright__ = 'Copyright (c) 2021 Bosch Rexroth AG' |
__all__ = (
'readonly_admin',
'singleton'
)
| __all__ = ('readonly_admin', 'singleton') |
integer = [
['lld', 'long long', 9223372036854775807, -9223372036854775808],
['ld', 'long', 9223372036854775807, -9223372036854775808],
['lu', 'unsigned long', 18446744073709551615, 0],
['d', 'signed', 2147483647, -2147483648],
['u', 'unsigned', 4294967295, 0],
['hd', 'short', 32767, -32768],
['hu', 'unsigned short', 65535, 0],
['c', 'char', 127, -128],
['c', 'unsigned char', 255, 0],
['d', '_Bool', 1, 0],
]
real = [
['f', 'float', 3.40282e+38, -3.40282e+38],
['f', 'double', 1.79769e+308, -1.79769e+308],
['Lf', 'long double', 1.79769e+308, -1.79769e+308]
]
# todo: fix path
path = ''
directory = 'env'
filename1 = f'{directory}/code1.c'
filename2 = f'{directory}/code2.c'
logfile1 = f'{directory}/log1.txt'
logfile2 = f'{directory}/log2.txt'
eo_out = f'{directory}/eo_out.txt'
c_out = f'{directory}/c_out.txt'
c_bin = f'{directory}/a.out'
launcher = '../../bin/launcher.py'
full_log = None
resultDir = '../../../result'
| integer = [['lld', 'long long', 9223372036854775807, -9223372036854775808], ['ld', 'long', 9223372036854775807, -9223372036854775808], ['lu', 'unsigned long', 18446744073709551615, 0], ['d', 'signed', 2147483647, -2147483648], ['u', 'unsigned', 4294967295, 0], ['hd', 'short', 32767, -32768], ['hu', 'unsigned short', 65535, 0], ['c', 'char', 127, -128], ['c', 'unsigned char', 255, 0], ['d', '_Bool', 1, 0]]
real = [['f', 'float', 3.40282e+38, -3.40282e+38], ['f', 'double', 1.79769e+308, -1.79769e+308], ['Lf', 'long double', 1.79769e+308, -1.79769e+308]]
path = ''
directory = 'env'
filename1 = f'{directory}/code1.c'
filename2 = f'{directory}/code2.c'
logfile1 = f'{directory}/log1.txt'
logfile2 = f'{directory}/log2.txt'
eo_out = f'{directory}/eo_out.txt'
c_out = f'{directory}/c_out.txt'
c_bin = f'{directory}/a.out'
launcher = '../../bin/launcher.py'
full_log = None
result_dir = '../../../result' |
#!/usr/bin/env python
#
# Create filter taps to use for interpolation filter in
# clock recovery algorithm. These taps are copied from
# GNU Radio at gnuradio/filter/interpolator_taps.h.
#
# This file includes them in natural order and I want
# them stored in reversed order such that they can be
# used directly.
#
filters = [
[ 0.00000e+00, 0.00000e+00, 0.00000e+00, 0.00000e+00, 1.00000e+00, 0.00000e+00, 0.00000e+00, 0.00000e+00 ],
[ -1.54700e-04, 8.53777e-04, -2.76968e-03, 7.89295e-03, 9.98534e-01, -5.41054e-03, 1.24642e-03, -1.98993e-04 ],
[ -3.09412e-04, 1.70888e-03, -5.55134e-03, 1.58840e-02, 9.96891e-01, -1.07209e-02, 2.47942e-03, -3.96391e-04 ],
[ -4.64053e-04, 2.56486e-03, -8.34364e-03, 2.39714e-02, 9.95074e-01, -1.59305e-02, 3.69852e-03, -5.92100e-04 ],
[ -6.18544e-04, 3.42130e-03, -1.11453e-02, 3.21531e-02, 9.93082e-01, -2.10389e-02, 4.90322e-03, -7.86031e-04 ],
[ -7.72802e-04, 4.27773e-03, -1.39548e-02, 4.04274e-02, 9.90917e-01, -2.60456e-02, 6.09305e-03, -9.78093e-04 ],
[ -9.26747e-04, 5.13372e-03, -1.67710e-02, 4.87921e-02, 9.88580e-01, -3.09503e-02, 7.26755e-03, -1.16820e-03 ],
[ -1.08030e-03, 5.98883e-03, -1.95925e-02, 5.72454e-02, 9.86071e-01, -3.57525e-02, 8.42626e-03, -1.35627e-03 ],
[ -1.23337e-03, 6.84261e-03, -2.24178e-02, 6.57852e-02, 9.83392e-01, -4.04519e-02, 9.56876e-03, -1.54221e-03 ],
[ -1.38589e-03, 7.69462e-03, -2.52457e-02, 7.44095e-02, 9.80543e-01, -4.50483e-02, 1.06946e-02, -1.72594e-03 ],
[ -1.53777e-03, 8.54441e-03, -2.80746e-02, 8.31162e-02, 9.77526e-01, -4.95412e-02, 1.18034e-02, -1.90738e-03 ],
[ -1.68894e-03, 9.39154e-03, -3.09033e-02, 9.19033e-02, 9.74342e-01, -5.39305e-02, 1.28947e-02, -2.08645e-03 ],
[ -1.83931e-03, 1.02356e-02, -3.37303e-02, 1.00769e-01, 9.70992e-01, -5.82159e-02, 1.39681e-02, -2.26307e-03 ],
[ -1.98880e-03, 1.10760e-02, -3.65541e-02, 1.09710e-01, 9.67477e-01, -6.23972e-02, 1.50233e-02, -2.43718e-03 ],
[ -2.13733e-03, 1.19125e-02, -3.93735e-02, 1.18725e-01, 9.63798e-01, -6.64743e-02, 1.60599e-02, -2.60868e-03 ],
[ -2.28483e-03, 1.27445e-02, -4.21869e-02, 1.27812e-01, 9.59958e-01, -7.04471e-02, 1.70776e-02, -2.77751e-03 ],
[ -2.43121e-03, 1.35716e-02, -4.49929e-02, 1.36968e-01, 9.55956e-01, -7.43154e-02, 1.80759e-02, -2.94361e-03 ],
[ -2.57640e-03, 1.43934e-02, -4.77900e-02, 1.46192e-01, 9.51795e-01, -7.80792e-02, 1.90545e-02, -3.10689e-03 ],
[ -2.72032e-03, 1.52095e-02, -5.05770e-02, 1.55480e-01, 9.47477e-01, -8.17385e-02, 2.00132e-02, -3.26730e-03 ],
[ -2.86289e-03, 1.60193e-02, -5.33522e-02, 1.64831e-01, 9.43001e-01, -8.52933e-02, 2.09516e-02, -3.42477e-03 ],
[ -3.00403e-03, 1.68225e-02, -5.61142e-02, 1.74242e-01, 9.38371e-01, -8.87435e-02, 2.18695e-02, -3.57923e-03 ],
[ -3.14367e-03, 1.76185e-02, -5.88617e-02, 1.83711e-01, 9.33586e-01, -9.20893e-02, 2.27664e-02, -3.73062e-03 ],
[ -3.28174e-03, 1.84071e-02, -6.15931e-02, 1.93236e-01, 9.28650e-01, -9.53307e-02, 2.36423e-02, -3.87888e-03 ],
[ -3.41815e-03, 1.91877e-02, -6.43069e-02, 2.02814e-01, 9.23564e-01, -9.84679e-02, 2.44967e-02, -4.02397e-03 ],
[ -3.55283e-03, 1.99599e-02, -6.70018e-02, 2.12443e-01, 9.18329e-01, -1.01501e-01, 2.53295e-02, -4.16581e-03 ],
[ -3.68570e-03, 2.07233e-02, -6.96762e-02, 2.22120e-01, 9.12947e-01, -1.04430e-01, 2.61404e-02, -4.30435e-03 ],
[ -3.81671e-03, 2.14774e-02, -7.23286e-02, 2.31843e-01, 9.07420e-01, -1.07256e-01, 2.69293e-02, -4.43955e-03 ],
[ -3.94576e-03, 2.22218e-02, -7.49577e-02, 2.41609e-01, 9.01749e-01, -1.09978e-01, 2.76957e-02, -4.57135e-03 ],
[ -4.07279e-03, 2.29562e-02, -7.75620e-02, 2.51417e-01, 8.95936e-01, -1.12597e-01, 2.84397e-02, -4.69970e-03 ],
[ -4.19774e-03, 2.36801e-02, -8.01399e-02, 2.61263e-01, 8.89984e-01, -1.15113e-01, 2.91609e-02, -4.82456e-03 ],
[ -4.32052e-03, 2.43930e-02, -8.26900e-02, 2.71144e-01, 8.83893e-01, -1.17526e-01, 2.98593e-02, -4.94589e-03 ],
[ -4.44107e-03, 2.50946e-02, -8.52109e-02, 2.81060e-01, 8.77666e-01, -1.19837e-01, 3.05345e-02, -5.06363e-03 ],
[ -4.55932e-03, 2.57844e-02, -8.77011e-02, 2.91006e-01, 8.71305e-01, -1.22047e-01, 3.11866e-02, -5.17776e-03 ],
[ -4.67520e-03, 2.64621e-02, -9.01591e-02, 3.00980e-01, 8.64812e-01, -1.24154e-01, 3.18153e-02, -5.28823e-03 ],
[ -4.78866e-03, 2.71272e-02, -9.25834e-02, 3.10980e-01, 8.58189e-01, -1.26161e-01, 3.24205e-02, -5.39500e-03 ],
[ -4.89961e-03, 2.77794e-02, -9.49727e-02, 3.21004e-01, 8.51437e-01, -1.28068e-01, 3.30021e-02, -5.49804e-03 ],
[ -5.00800e-03, 2.84182e-02, -9.73254e-02, 3.31048e-01, 8.44559e-01, -1.29874e-01, 3.35600e-02, -5.59731e-03 ],
[ -5.11376e-03, 2.90433e-02, -9.96402e-02, 3.41109e-01, 8.37557e-01, -1.31581e-01, 3.40940e-02, -5.69280e-03 ],
[ -5.21683e-03, 2.96543e-02, -1.01915e-01, 3.51186e-01, 8.30432e-01, -1.33189e-01, 3.46042e-02, -5.78446e-03 ],
[ -5.31716e-03, 3.02507e-02, -1.04150e-01, 3.61276e-01, 8.23188e-01, -1.34699e-01, 3.50903e-02, -5.87227e-03 ],
[ -5.41467e-03, 3.08323e-02, -1.06342e-01, 3.71376e-01, 8.15826e-01, -1.36111e-01, 3.55525e-02, -5.95620e-03 ],
[ -5.50931e-03, 3.13987e-02, -1.08490e-01, 3.81484e-01, 8.08348e-01, -1.37426e-01, 3.59905e-02, -6.03624e-03 ],
[ -5.60103e-03, 3.19495e-02, -1.10593e-01, 3.91596e-01, 8.00757e-01, -1.38644e-01, 3.64044e-02, -6.11236e-03 ],
[ -5.68976e-03, 3.24843e-02, -1.12650e-01, 4.01710e-01, 7.93055e-01, -1.39767e-01, 3.67941e-02, -6.18454e-03 ],
[ -5.77544e-03, 3.30027e-02, -1.14659e-01, 4.11823e-01, 7.85244e-01, -1.40794e-01, 3.71596e-02, -6.25277e-03 ],
[ -5.85804e-03, 3.35046e-02, -1.16618e-01, 4.21934e-01, 7.77327e-01, -1.41727e-01, 3.75010e-02, -6.31703e-03 ],
[ -5.93749e-03, 3.39894e-02, -1.18526e-01, 4.32038e-01, 7.69305e-01, -1.42566e-01, 3.78182e-02, -6.37730e-03 ],
[ -6.01374e-03, 3.44568e-02, -1.20382e-01, 4.42134e-01, 7.61181e-01, -1.43313e-01, 3.81111e-02, -6.43358e-03 ],
[ -6.08674e-03, 3.49066e-02, -1.22185e-01, 4.52218e-01, 7.52958e-01, -1.43968e-01, 3.83800e-02, -6.48585e-03 ],
[ -6.15644e-03, 3.53384e-02, -1.23933e-01, 4.62289e-01, 7.44637e-01, -1.44531e-01, 3.86247e-02, -6.53412e-03 ],
[ -6.22280e-03, 3.57519e-02, -1.25624e-01, 4.72342e-01, 7.36222e-01, -1.45004e-01, 3.88454e-02, -6.57836e-03 ],
[ -6.28577e-03, 3.61468e-02, -1.27258e-01, 4.82377e-01, 7.27714e-01, -1.45387e-01, 3.90420e-02, -6.61859e-03 ],
[ -6.34530e-03, 3.65227e-02, -1.28832e-01, 4.92389e-01, 7.19116e-01, -1.45682e-01, 3.92147e-02, -6.65479e-03 ],
[ -6.40135e-03, 3.68795e-02, -1.30347e-01, 5.02377e-01, 7.10431e-01, -1.45889e-01, 3.93636e-02, -6.68698e-03 ],
[ -6.45388e-03, 3.72167e-02, -1.31800e-01, 5.12337e-01, 7.01661e-01, -1.46009e-01, 3.94886e-02, -6.71514e-03 ],
[ -6.50285e-03, 3.75341e-02, -1.33190e-01, 5.22267e-01, 6.92808e-01, -1.46043e-01, 3.95900e-02, -6.73929e-03 ],
[ -6.54823e-03, 3.78315e-02, -1.34515e-01, 5.32164e-01, 6.83875e-01, -1.45993e-01, 3.96678e-02, -6.75943e-03 ],
[ -6.58996e-03, 3.81085e-02, -1.35775e-01, 5.42025e-01, 6.74865e-01, -1.45859e-01, 3.97222e-02, -6.77557e-03 ],
[ -6.62802e-03, 3.83650e-02, -1.36969e-01, 5.51849e-01, 6.65779e-01, -1.45641e-01, 3.97532e-02, -6.78771e-03 ],
[ -6.66238e-03, 3.86006e-02, -1.38094e-01, 5.61631e-01, 6.56621e-01, -1.45343e-01, 3.97610e-02, -6.79588e-03 ],
[ -6.69300e-03, 3.88151e-02, -1.39150e-01, 5.71370e-01, 6.47394e-01, -1.44963e-01, 3.97458e-02, -6.80007e-03 ],
[ -6.71985e-03, 3.90083e-02, -1.40136e-01, 5.81063e-01, 6.38099e-01, -1.44503e-01, 3.97077e-02, -6.80032e-03 ],
[ -6.74291e-03, 3.91800e-02, -1.41050e-01, 5.90706e-01, 6.28739e-01, -1.43965e-01, 3.96469e-02, -6.79662e-03 ],
[ -6.76214e-03, 3.93299e-02, -1.41891e-01, 6.00298e-01, 6.19318e-01, -1.43350e-01, 3.95635e-02, -6.78902e-03 ],
[ -6.77751e-03, 3.94578e-02, -1.42658e-01, 6.09836e-01, 6.09836e-01, -1.42658e-01, 3.94578e-02, -6.77751e-03 ],
[ -6.78902e-03, 3.95635e-02, -1.43350e-01, 6.19318e-01, 6.00298e-01, -1.41891e-01, 3.93299e-02, -6.76214e-03 ],
[ -6.79662e-03, 3.96469e-02, -1.43965e-01, 6.28739e-01, 5.90706e-01, -1.41050e-01, 3.91800e-02, -6.74291e-03 ],
[ -6.80032e-03, 3.97077e-02, -1.44503e-01, 6.38099e-01, 5.81063e-01, -1.40136e-01, 3.90083e-02, -6.71985e-03 ],
[ -6.80007e-03, 3.97458e-02, -1.44963e-01, 6.47394e-01, 5.71370e-01, -1.39150e-01, 3.88151e-02, -6.69300e-03 ],
[ -6.79588e-03, 3.97610e-02, -1.45343e-01, 6.56621e-01, 5.61631e-01, -1.38094e-01, 3.86006e-02, -6.66238e-03 ],
[ -6.78771e-03, 3.97532e-02, -1.45641e-01, 6.65779e-01, 5.51849e-01, -1.36969e-01, 3.83650e-02, -6.62802e-03 ],
[ -6.77557e-03, 3.97222e-02, -1.45859e-01, 6.74865e-01, 5.42025e-01, -1.35775e-01, 3.81085e-02, -6.58996e-03 ],
[ -6.75943e-03, 3.96678e-02, -1.45993e-01, 6.83875e-01, 5.32164e-01, -1.34515e-01, 3.78315e-02, -6.54823e-03 ],
[ -6.73929e-03, 3.95900e-02, -1.46043e-01, 6.92808e-01, 5.22267e-01, -1.33190e-01, 3.75341e-02, -6.50285e-03 ],
[ -6.71514e-03, 3.94886e-02, -1.46009e-01, 7.01661e-01, 5.12337e-01, -1.31800e-01, 3.72167e-02, -6.45388e-03 ],
[ -6.68698e-03, 3.93636e-02, -1.45889e-01, 7.10431e-01, 5.02377e-01, -1.30347e-01, 3.68795e-02, -6.40135e-03 ],
[ -6.65479e-03, 3.92147e-02, -1.45682e-01, 7.19116e-01, 4.92389e-01, -1.28832e-01, 3.65227e-02, -6.34530e-03 ],
[ -6.61859e-03, 3.90420e-02, -1.45387e-01, 7.27714e-01, 4.82377e-01, -1.27258e-01, 3.61468e-02, -6.28577e-03 ],
[ -6.57836e-03, 3.88454e-02, -1.45004e-01, 7.36222e-01, 4.72342e-01, -1.25624e-01, 3.57519e-02, -6.22280e-03 ],
[ -6.53412e-03, 3.86247e-02, -1.44531e-01, 7.44637e-01, 4.62289e-01, -1.23933e-01, 3.53384e-02, -6.15644e-03 ],
[ -6.48585e-03, 3.83800e-02, -1.43968e-01, 7.52958e-01, 4.52218e-01, -1.22185e-01, 3.49066e-02, -6.08674e-03 ],
[ -6.43358e-03, 3.81111e-02, -1.43313e-01, 7.61181e-01, 4.42134e-01, -1.20382e-01, 3.44568e-02, -6.01374e-03 ],
[ -6.37730e-03, 3.78182e-02, -1.42566e-01, 7.69305e-01, 4.32038e-01, -1.18526e-01, 3.39894e-02, -5.93749e-03 ],
[ -6.31703e-03, 3.75010e-02, -1.41727e-01, 7.77327e-01, 4.21934e-01, -1.16618e-01, 3.35046e-02, -5.85804e-03 ],
[ -6.25277e-03, 3.71596e-02, -1.40794e-01, 7.85244e-01, 4.11823e-01, -1.14659e-01, 3.30027e-02, -5.77544e-03 ],
[ -6.18454e-03, 3.67941e-02, -1.39767e-01, 7.93055e-01, 4.01710e-01, -1.12650e-01, 3.24843e-02, -5.68976e-03 ],
[ -6.11236e-03, 3.64044e-02, -1.38644e-01, 8.00757e-01, 3.91596e-01, -1.10593e-01, 3.19495e-02, -5.60103e-03 ],
[ -6.03624e-03, 3.59905e-02, -1.37426e-01, 8.08348e-01, 3.81484e-01, -1.08490e-01, 3.13987e-02, -5.50931e-03 ],
[ -5.95620e-03, 3.55525e-02, -1.36111e-01, 8.15826e-01, 3.71376e-01, -1.06342e-01, 3.08323e-02, -5.41467e-03 ],
[ -5.87227e-03, 3.50903e-02, -1.34699e-01, 8.23188e-01, 3.61276e-01, -1.04150e-01, 3.02507e-02, -5.31716e-03 ],
[ -5.78446e-03, 3.46042e-02, -1.33189e-01, 8.30432e-01, 3.51186e-01, -1.01915e-01, 2.96543e-02, -5.21683e-03 ],
[ -5.69280e-03, 3.40940e-02, -1.31581e-01, 8.37557e-01, 3.41109e-01, -9.96402e-02, 2.90433e-02, -5.11376e-03 ],
[ -5.59731e-03, 3.35600e-02, -1.29874e-01, 8.44559e-01, 3.31048e-01, -9.73254e-02, 2.84182e-02, -5.00800e-03 ],
[ -5.49804e-03, 3.30021e-02, -1.28068e-01, 8.51437e-01, 3.21004e-01, -9.49727e-02, 2.77794e-02, -4.89961e-03 ],
[ -5.39500e-03, 3.24205e-02, -1.26161e-01, 8.58189e-01, 3.10980e-01, -9.25834e-02, 2.71272e-02, -4.78866e-03 ],
[ -5.28823e-03, 3.18153e-02, -1.24154e-01, 8.64812e-01, 3.00980e-01, -9.01591e-02, 2.64621e-02, -4.67520e-03 ],
[ -5.17776e-03, 3.11866e-02, -1.22047e-01, 8.71305e-01, 2.91006e-01, -8.77011e-02, 2.57844e-02, -4.55932e-03 ],
[ -5.06363e-03, 3.05345e-02, -1.19837e-01, 8.77666e-01, 2.81060e-01, -8.52109e-02, 2.50946e-02, -4.44107e-03 ],
[ -4.94589e-03, 2.98593e-02, -1.17526e-01, 8.83893e-01, 2.71144e-01, -8.26900e-02, 2.43930e-02, -4.32052e-03 ],
[ -4.82456e-03, 2.91609e-02, -1.15113e-01, 8.89984e-01, 2.61263e-01, -8.01399e-02, 2.36801e-02, -4.19774e-03 ],
[ -4.69970e-03, 2.84397e-02, -1.12597e-01, 8.95936e-01, 2.51417e-01, -7.75620e-02, 2.29562e-02, -4.07279e-03 ],
[ -4.57135e-03, 2.76957e-02, -1.09978e-01, 9.01749e-01, 2.41609e-01, -7.49577e-02, 2.22218e-02, -3.94576e-03 ],
[ -4.43955e-03, 2.69293e-02, -1.07256e-01, 9.07420e-01, 2.31843e-01, -7.23286e-02, 2.14774e-02, -3.81671e-03 ],
[ -4.30435e-03, 2.61404e-02, -1.04430e-01, 9.12947e-01, 2.22120e-01, -6.96762e-02, 2.07233e-02, -3.68570e-03 ],
[ -4.16581e-03, 2.53295e-02, -1.01501e-01, 9.18329e-01, 2.12443e-01, -6.70018e-02, 1.99599e-02, -3.55283e-03 ],
[ -4.02397e-03, 2.44967e-02, -9.84679e-02, 9.23564e-01, 2.02814e-01, -6.43069e-02, 1.91877e-02, -3.41815e-03 ],
[ -3.87888e-03, 2.36423e-02, -9.53307e-02, 9.28650e-01, 1.93236e-01, -6.15931e-02, 1.84071e-02, -3.28174e-03 ],
[ -3.73062e-03, 2.27664e-02, -9.20893e-02, 9.33586e-01, 1.83711e-01, -5.88617e-02, 1.76185e-02, -3.14367e-03 ],
[ -3.57923e-03, 2.18695e-02, -8.87435e-02, 9.38371e-01, 1.74242e-01, -5.61142e-02, 1.68225e-02, -3.00403e-03 ],
[ -3.42477e-03, 2.09516e-02, -8.52933e-02, 9.43001e-01, 1.64831e-01, -5.33522e-02, 1.60193e-02, -2.86289e-03 ],
[ -3.26730e-03, 2.00132e-02, -8.17385e-02, 9.47477e-01, 1.55480e-01, -5.05770e-02, 1.52095e-02, -2.72032e-03 ],
[ -3.10689e-03, 1.90545e-02, -7.80792e-02, 9.51795e-01, 1.46192e-01, -4.77900e-02, 1.43934e-02, -2.57640e-03 ],
[ -2.94361e-03, 1.80759e-02, -7.43154e-02, 9.55956e-01, 1.36968e-01, -4.49929e-02, 1.35716e-02, -2.43121e-03 ],
[ -2.77751e-03, 1.70776e-02, -7.04471e-02, 9.59958e-01, 1.27812e-01, -4.21869e-02, 1.27445e-02, -2.28483e-03 ],
[ -2.60868e-03, 1.60599e-02, -6.64743e-02, 9.63798e-01, 1.18725e-01, -3.93735e-02, 1.19125e-02, -2.13733e-03 ],
[ -2.43718e-03, 1.50233e-02, -6.23972e-02, 9.67477e-01, 1.09710e-01, -3.65541e-02, 1.10760e-02, -1.98880e-03 ],
[ -2.26307e-03, 1.39681e-02, -5.82159e-02, 9.70992e-01, 1.00769e-01, -3.37303e-02, 1.02356e-02, -1.83931e-03 ],
[ -2.08645e-03, 1.28947e-02, -5.39305e-02, 9.74342e-01, 9.19033e-02, -3.09033e-02, 9.39154e-03, -1.68894e-03 ],
[ -1.90738e-03, 1.18034e-02, -4.95412e-02, 9.77526e-01, 8.31162e-02, -2.80746e-02, 8.54441e-03, -1.53777e-03 ],
[ -1.72594e-03, 1.06946e-02, -4.50483e-02, 9.80543e-01, 7.44095e-02, -2.52457e-02, 7.69462e-03, -1.38589e-03 ],
[ -1.54221e-03, 9.56876e-03, -4.04519e-02, 9.83392e-01, 6.57852e-02, -2.24178e-02, 6.84261e-03, -1.23337e-03 ],
[ -1.35627e-03, 8.42626e-03, -3.57525e-02, 9.86071e-01, 5.72454e-02, -1.95925e-02, 5.98883e-03, -1.08030e-03 ],
[ -1.16820e-03, 7.26755e-03, -3.09503e-02, 9.88580e-01, 4.87921e-02, -1.67710e-02, 5.13372e-03, -9.26747e-04 ],
[ -9.78093e-04, 6.09305e-03, -2.60456e-02, 9.90917e-01, 4.04274e-02, -1.39548e-02, 4.27773e-03, -7.72802e-04 ],
[ -7.86031e-04, 4.90322e-03, -2.10389e-02, 9.93082e-01, 3.21531e-02, -1.11453e-02, 3.42130e-03, -6.18544e-04 ],
[ -5.92100e-04, 3.69852e-03, -1.59305e-02, 9.95074e-01, 2.39714e-02, -8.34364e-03, 2.56486e-03, -4.64053e-04 ],
[ -3.96391e-04, 2.47942e-03, -1.07209e-02, 9.96891e-01, 1.58840e-02, -5.55134e-03, 1.70888e-03, -3.09412e-04 ],
[ -1.98993e-04, 1.24642e-03, -5.41054e-03, 9.98534e-01, 7.89295e-03, -2.76968e-03, 8.53777e-04, -1.54700e-04 ],
[ 0.00000e+00, 0.00000e+00, 0.00000e+00, 1.00000e+00, 0.00000e+00, 0.00000e+00, 0.00000e+00, 0.00000e+00 ]
]
print("static const int NUM_TAPS = 8;")
print("static const int NUM_STEPS = 128;")
print("static const mmseTaps[NUM_STEPS+1][NUM_TAPS] = {")
for taps in filters:
body = ", ".join("%.5e" % t for t in reversed(taps))
print("{ " + body + " },")
print("};")
| filters = [[0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0], [-0.0001547, 0.000853777, -0.00276968, 0.00789295, 0.998534, -0.00541054, 0.00124642, -0.000198993], [-0.000309412, 0.00170888, -0.00555134, 0.015884, 0.996891, -0.0107209, 0.00247942, -0.000396391], [-0.000464053, 0.00256486, -0.00834364, 0.0239714, 0.995074, -0.0159305, 0.00369852, -0.0005921], [-0.000618544, 0.0034213, -0.0111453, 0.0321531, 0.993082, -0.0210389, 0.00490322, -0.000786031], [-0.000772802, 0.00427773, -0.0139548, 0.0404274, 0.990917, -0.0260456, 0.00609305, -0.000978093], [-0.000926747, 0.00513372, -0.016771, 0.0487921, 0.98858, -0.0309503, 0.00726755, -0.0011682], [-0.0010803, 0.00598883, -0.0195925, 0.0572454, 0.986071, -0.0357525, 0.00842626, -0.00135627], [-0.00123337, 0.00684261, -0.0224178, 0.0657852, 0.983392, -0.0404519, 0.00956876, -0.00154221], [-0.00138589, 0.00769462, -0.0252457, 0.0744095, 0.980543, -0.0450483, 0.0106946, -0.00172594], [-0.00153777, 0.00854441, -0.0280746, 0.0831162, 0.977526, -0.0495412, 0.0118034, -0.00190738], [-0.00168894, 0.00939154, -0.0309033, 0.0919033, 0.974342, -0.0539305, 0.0128947, -0.00208645], [-0.00183931, 0.0102356, -0.0337303, 0.100769, 0.970992, -0.0582159, 0.0139681, -0.00226307], [-0.0019888, 0.011076, -0.0365541, 0.10971, 0.967477, -0.0623972, 0.0150233, -0.00243718], [-0.00213733, 0.0119125, -0.0393735, 0.118725, 0.963798, -0.0664743, 0.0160599, -0.00260868], [-0.00228483, 0.0127445, -0.0421869, 0.127812, 0.959958, -0.0704471, 0.0170776, -0.00277751], [-0.00243121, 0.0135716, -0.0449929, 0.136968, 0.955956, -0.0743154, 0.0180759, -0.00294361], [-0.0025764, 0.0143934, -0.04779, 0.146192, 0.951795, -0.0780792, 0.0190545, -0.00310689], [-0.00272032, 0.0152095, -0.050577, 0.15548, 0.947477, -0.0817385, 0.0200132, -0.0032673], [-0.00286289, 0.0160193, -0.0533522, 0.164831, 0.943001, -0.0852933, 0.0209516, -0.00342477], [-0.00300403, 0.0168225, -0.0561142, 0.174242, 0.938371, -0.0887435, 0.0218695, -0.00357923], [-0.00314367, 0.0176185, -0.0588617, 0.183711, 0.933586, -0.0920893, 0.0227664, -0.00373062], [-0.00328174, 0.0184071, -0.0615931, 0.193236, 0.92865, -0.0953307, 0.0236423, -0.00387888], [-0.00341815, 0.0191877, -0.0643069, 0.202814, 0.923564, -0.0984679, 0.0244967, -0.00402397], [-0.00355283, 0.0199599, -0.0670018, 0.212443, 0.918329, -0.101501, 0.0253295, -0.00416581], [-0.0036857, 0.0207233, -0.0696762, 0.22212, 0.912947, -0.10443, 0.0261404, -0.00430435], [-0.00381671, 0.0214774, -0.0723286, 0.231843, 0.90742, -0.107256, 0.0269293, -0.00443955], [-0.00394576, 0.0222218, -0.0749577, 0.241609, 0.901749, -0.109978, 0.0276957, -0.00457135], [-0.00407279, 0.0229562, -0.077562, 0.251417, 0.895936, -0.112597, 0.0284397, -0.0046997], [-0.00419774, 0.0236801, -0.0801399, 0.261263, 0.889984, -0.115113, 0.0291609, -0.00482456], [-0.00432052, 0.024393, -0.08269, 0.271144, 0.883893, -0.117526, 0.0298593, -0.00494589], [-0.00444107, 0.0250946, -0.0852109, 0.28106, 0.877666, -0.119837, 0.0305345, -0.00506363], [-0.00455932, 0.0257844, -0.0877011, 0.291006, 0.871305, -0.122047, 0.0311866, -0.00517776], [-0.0046752, 0.0264621, -0.0901591, 0.30098, 0.864812, -0.124154, 0.0318153, -0.00528823], [-0.00478866, 0.0271272, -0.0925834, 0.31098, 0.858189, -0.126161, 0.0324205, -0.005395], [-0.00489961, 0.0277794, -0.0949727, 0.321004, 0.851437, -0.128068, 0.0330021, -0.00549804], [-0.005008, 0.0284182, -0.0973254, 0.331048, 0.844559, -0.129874, 0.03356, -0.00559731], [-0.00511376, 0.0290433, -0.0996402, 0.341109, 0.837557, -0.131581, 0.034094, -0.0056928], [-0.00521683, 0.0296543, -0.101915, 0.351186, 0.830432, -0.133189, 0.0346042, -0.00578446], [-0.00531716, 0.0302507, -0.10415, 0.361276, 0.823188, -0.134699, 0.0350903, -0.00587227], [-0.00541467, 0.0308323, -0.106342, 0.371376, 0.815826, -0.136111, 0.0355525, -0.0059562], [-0.00550931, 0.0313987, -0.10849, 0.381484, 0.808348, -0.137426, 0.0359905, -0.00603624], [-0.00560103, 0.0319495, -0.110593, 0.391596, 0.800757, -0.138644, 0.0364044, -0.00611236], [-0.00568976, 0.0324843, -0.11265, 0.40171, 0.793055, -0.139767, 0.0367941, -0.00618454], [-0.00577544, 0.0330027, -0.114659, 0.411823, 0.785244, -0.140794, 0.0371596, -0.00625277], [-0.00585804, 0.0335046, -0.116618, 0.421934, 0.777327, -0.141727, 0.037501, -0.00631703], [-0.00593749, 0.0339894, -0.118526, 0.432038, 0.769305, -0.142566, 0.0378182, -0.0063773], [-0.00601374, 0.0344568, -0.120382, 0.442134, 0.761181, -0.143313, 0.0381111, -0.00643358], [-0.00608674, 0.0349066, -0.122185, 0.452218, 0.752958, -0.143968, 0.03838, -0.00648585], [-0.00615644, 0.0353384, -0.123933, 0.462289, 0.744637, -0.144531, 0.0386247, -0.00653412], [-0.0062228, 0.0357519, -0.125624, 0.472342, 0.736222, -0.145004, 0.0388454, -0.00657836], [-0.00628577, 0.0361468, -0.127258, 0.482377, 0.727714, -0.145387, 0.039042, -0.00661859], [-0.0063453, 0.0365227, -0.128832, 0.492389, 0.719116, -0.145682, 0.0392147, -0.00665479], [-0.00640135, 0.0368795, -0.130347, 0.502377, 0.710431, -0.145889, 0.0393636, -0.00668698], [-0.00645388, 0.0372167, -0.1318, 0.512337, 0.701661, -0.146009, 0.0394886, -0.00671514], [-0.00650285, 0.0375341, -0.13319, 0.522267, 0.692808, -0.146043, 0.03959, -0.00673929], [-0.00654823, 0.0378315, -0.134515, 0.532164, 0.683875, -0.145993, 0.0396678, -0.00675943], [-0.00658996, 0.0381085, -0.135775, 0.542025, 0.674865, -0.145859, 0.0397222, -0.00677557], [-0.00662802, 0.038365, -0.136969, 0.551849, 0.665779, -0.145641, 0.0397532, -0.00678771], [-0.00666238, 0.0386006, -0.138094, 0.561631, 0.656621, -0.145343, 0.039761, -0.00679588], [-0.006693, 0.0388151, -0.13915, 0.57137, 0.647394, -0.144963, 0.0397458, -0.00680007], [-0.00671985, 0.0390083, -0.140136, 0.581063, 0.638099, -0.144503, 0.0397077, -0.00680032], [-0.00674291, 0.03918, -0.14105, 0.590706, 0.628739, -0.143965, 0.0396469, -0.00679662], [-0.00676214, 0.0393299, -0.141891, 0.600298, 0.619318, -0.14335, 0.0395635, -0.00678902], [-0.00677751, 0.0394578, -0.142658, 0.609836, 0.609836, -0.142658, 0.0394578, -0.00677751], [-0.00678902, 0.0395635, -0.14335, 0.619318, 0.600298, -0.141891, 0.0393299, -0.00676214], [-0.00679662, 0.0396469, -0.143965, 0.628739, 0.590706, -0.14105, 0.03918, -0.00674291], [-0.00680032, 0.0397077, -0.144503, 0.638099, 0.581063, -0.140136, 0.0390083, -0.00671985], [-0.00680007, 0.0397458, -0.144963, 0.647394, 0.57137, -0.13915, 0.0388151, -0.006693], [-0.00679588, 0.039761, -0.145343, 0.656621, 0.561631, -0.138094, 0.0386006, -0.00666238], [-0.00678771, 0.0397532, -0.145641, 0.665779, 0.551849, -0.136969, 0.038365, -0.00662802], [-0.00677557, 0.0397222, -0.145859, 0.674865, 0.542025, -0.135775, 0.0381085, -0.00658996], [-0.00675943, 0.0396678, -0.145993, 0.683875, 0.532164, -0.134515, 0.0378315, -0.00654823], [-0.00673929, 0.03959, -0.146043, 0.692808, 0.522267, -0.13319, 0.0375341, -0.00650285], [-0.00671514, 0.0394886, -0.146009, 0.701661, 0.512337, -0.1318, 0.0372167, -0.00645388], [-0.00668698, 0.0393636, -0.145889, 0.710431, 0.502377, -0.130347, 0.0368795, -0.00640135], [-0.00665479, 0.0392147, -0.145682, 0.719116, 0.492389, -0.128832, 0.0365227, -0.0063453], [-0.00661859, 0.039042, -0.145387, 0.727714, 0.482377, -0.127258, 0.0361468, -0.00628577], [-0.00657836, 0.0388454, -0.145004, 0.736222, 0.472342, -0.125624, 0.0357519, -0.0062228], [-0.00653412, 0.0386247, -0.144531, 0.744637, 0.462289, -0.123933, 0.0353384, -0.00615644], [-0.00648585, 0.03838, -0.143968, 0.752958, 0.452218, -0.122185, 0.0349066, -0.00608674], [-0.00643358, 0.0381111, -0.143313, 0.761181, 0.442134, -0.120382, 0.0344568, -0.00601374], [-0.0063773, 0.0378182, -0.142566, 0.769305, 0.432038, -0.118526, 0.0339894, -0.00593749], [-0.00631703, 0.037501, -0.141727, 0.777327, 0.421934, -0.116618, 0.0335046, -0.00585804], [-0.00625277, 0.0371596, -0.140794, 0.785244, 0.411823, -0.114659, 0.0330027, -0.00577544], [-0.00618454, 0.0367941, -0.139767, 0.793055, 0.40171, -0.11265, 0.0324843, -0.00568976], [-0.00611236, 0.0364044, -0.138644, 0.800757, 0.391596, -0.110593, 0.0319495, -0.00560103], [-0.00603624, 0.0359905, -0.137426, 0.808348, 0.381484, -0.10849, 0.0313987, -0.00550931], [-0.0059562, 0.0355525, -0.136111, 0.815826, 0.371376, -0.106342, 0.0308323, -0.00541467], [-0.00587227, 0.0350903, -0.134699, 0.823188, 0.361276, -0.10415, 0.0302507, -0.00531716], [-0.00578446, 0.0346042, -0.133189, 0.830432, 0.351186, -0.101915, 0.0296543, -0.00521683], [-0.0056928, 0.034094, -0.131581, 0.837557, 0.341109, -0.0996402, 0.0290433, -0.00511376], [-0.00559731, 0.03356, -0.129874, 0.844559, 0.331048, -0.0973254, 0.0284182, -0.005008], [-0.00549804, 0.0330021, -0.128068, 0.851437, 0.321004, -0.0949727, 0.0277794, -0.00489961], [-0.005395, 0.0324205, -0.126161, 0.858189, 0.31098, -0.0925834, 0.0271272, -0.00478866], [-0.00528823, 0.0318153, -0.124154, 0.864812, 0.30098, -0.0901591, 0.0264621, -0.0046752], [-0.00517776, 0.0311866, -0.122047, 0.871305, 0.291006, -0.0877011, 0.0257844, -0.00455932], [-0.00506363, 0.0305345, -0.119837, 0.877666, 0.28106, -0.0852109, 0.0250946, -0.00444107], [-0.00494589, 0.0298593, -0.117526, 0.883893, 0.271144, -0.08269, 0.024393, -0.00432052], [-0.00482456, 0.0291609, -0.115113, 0.889984, 0.261263, -0.0801399, 0.0236801, -0.00419774], [-0.0046997, 0.0284397, -0.112597, 0.895936, 0.251417, -0.077562, 0.0229562, -0.00407279], [-0.00457135, 0.0276957, -0.109978, 0.901749, 0.241609, -0.0749577, 0.0222218, -0.00394576], [-0.00443955, 0.0269293, -0.107256, 0.90742, 0.231843, -0.0723286, 0.0214774, -0.00381671], [-0.00430435, 0.0261404, -0.10443, 0.912947, 0.22212, -0.0696762, 0.0207233, -0.0036857], [-0.00416581, 0.0253295, -0.101501, 0.918329, 0.212443, -0.0670018, 0.0199599, -0.00355283], [-0.00402397, 0.0244967, -0.0984679, 0.923564, 0.202814, -0.0643069, 0.0191877, -0.00341815], [-0.00387888, 0.0236423, -0.0953307, 0.92865, 0.193236, -0.0615931, 0.0184071, -0.00328174], [-0.00373062, 0.0227664, -0.0920893, 0.933586, 0.183711, -0.0588617, 0.0176185, -0.00314367], [-0.00357923, 0.0218695, -0.0887435, 0.938371, 0.174242, -0.0561142, 0.0168225, -0.00300403], [-0.00342477, 0.0209516, -0.0852933, 0.943001, 0.164831, -0.0533522, 0.0160193, -0.00286289], [-0.0032673, 0.0200132, -0.0817385, 0.947477, 0.15548, -0.050577, 0.0152095, -0.00272032], [-0.00310689, 0.0190545, -0.0780792, 0.951795, 0.146192, -0.04779, 0.0143934, -0.0025764], [-0.00294361, 0.0180759, -0.0743154, 0.955956, 0.136968, -0.0449929, 0.0135716, -0.00243121], [-0.00277751, 0.0170776, -0.0704471, 0.959958, 0.127812, -0.0421869, 0.0127445, -0.00228483], [-0.00260868, 0.0160599, -0.0664743, 0.963798, 0.118725, -0.0393735, 0.0119125, -0.00213733], [-0.00243718, 0.0150233, -0.0623972, 0.967477, 0.10971, -0.0365541, 0.011076, -0.0019888], [-0.00226307, 0.0139681, -0.0582159, 0.970992, 0.100769, -0.0337303, 0.0102356, -0.00183931], [-0.00208645, 0.0128947, -0.0539305, 0.974342, 0.0919033, -0.0309033, 0.00939154, -0.00168894], [-0.00190738, 0.0118034, -0.0495412, 0.977526, 0.0831162, -0.0280746, 0.00854441, -0.00153777], [-0.00172594, 0.0106946, -0.0450483, 0.980543, 0.0744095, -0.0252457, 0.00769462, -0.00138589], [-0.00154221, 0.00956876, -0.0404519, 0.983392, 0.0657852, -0.0224178, 0.00684261, -0.00123337], [-0.00135627, 0.00842626, -0.0357525, 0.986071, 0.0572454, -0.0195925, 0.00598883, -0.0010803], [-0.0011682, 0.00726755, -0.0309503, 0.98858, 0.0487921, -0.016771, 0.00513372, -0.000926747], [-0.000978093, 0.00609305, -0.0260456, 0.990917, 0.0404274, -0.0139548, 0.00427773, -0.000772802], [-0.000786031, 0.00490322, -0.0210389, 0.993082, 0.0321531, -0.0111453, 0.0034213, -0.000618544], [-0.0005921, 0.00369852, -0.0159305, 0.995074, 0.0239714, -0.00834364, 0.00256486, -0.000464053], [-0.000396391, 0.00247942, -0.0107209, 0.996891, 0.015884, -0.00555134, 0.00170888, -0.000309412], [-0.000198993, 0.00124642, -0.00541054, 0.998534, 0.00789295, -0.00276968, 0.000853777, -0.0001547], [0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0]]
print('static const int NUM_TAPS = 8;')
print('static const int NUM_STEPS = 128;')
print('static const mmseTaps[NUM_STEPS+1][NUM_TAPS] = {')
for taps in filters:
body = ', '.join(('%.5e' % t for t in reversed(taps)))
print('{ ' + body + ' },')
print('};') |
class Node:
def __init__(self, val: int):
self.val = val
self.prev = None
self.next = None
class DoublyLinkedList:
def takeinput(self) -> Node:
inputlist = [int(x) for x in input().split()]
head = None
temp = None
for curr in inputlist:
if curr == -1:
break
Newnode = Node(curr)
if head is None:
head = Newnode
temp = head
else:
temp.next = Newnode
Newnode.prev = temp
temp = temp.next
return head
def printLL(self, head: Node) -> None:
temp = head
while temp is not None:
print(temp.val, end='->')
temp = temp.next
print("None")
def getLength(self, head: Node) -> int:
count = 0
temp = head
while temp is not None:
count += 1
temp = temp.next
return temp
def getMiddle(self, head: Node) -> int:
slow = head
fast = head
while fast and fast.next is not None:
slow = slow.next
fast = fast.next.next
return slow.val
def reverseLL(self, head: Node) -> Node:
pass | class Node:
def __init__(self, val: int):
self.val = val
self.prev = None
self.next = None
class Doublylinkedlist:
def takeinput(self) -> Node:
inputlist = [int(x) for x in input().split()]
head = None
temp = None
for curr in inputlist:
if curr == -1:
break
newnode = node(curr)
if head is None:
head = Newnode
temp = head
else:
temp.next = Newnode
Newnode.prev = temp
temp = temp.next
return head
def print_ll(self, head: Node) -> None:
temp = head
while temp is not None:
print(temp.val, end='->')
temp = temp.next
print('None')
def get_length(self, head: Node) -> int:
count = 0
temp = head
while temp is not None:
count += 1
temp = temp.next
return temp
def get_middle(self, head: Node) -> int:
slow = head
fast = head
while fast and fast.next is not None:
slow = slow.next
fast = fast.next.next
return slow.val
def reverse_ll(self, head: Node) -> Node:
pass |
class Combo():
def combine(self,n, k):
A = list(range(1,n + 1))
res = self.comb(A, k)
return res
def comb(self, A, n):
if n == 0:
return [[]]
l = []
for i in range(0, len(A)):
m = A[i]
remLst = A[i + 1:]
for p in self.comb(remLst, n - 1):
l.append([m] + p)
return l
def combinations(n, list, combos=[]):
# initialize combos during the first pass through
if combos is None:
combos = []
if len(list) == n:
# when list has been dwindeled down to size n
# check to see if the combo has already been found
# if not, add it to our list
if combos.count(list) == 0:
combos.append(list)
combos.sort()
return combos
else:
# for each item in our list, make a recursive
# call to find all possible combos of it and
# the remaining items
for i in range(len(list)):
refined_list = list[:i] + list[i+1:]
combos = combinations(n, refined_list, combos)
return combos
a = Combo()
A = 4
B = 2
# print(a.combine(A,B))
print(a.comb([1,2,3,4], 2))
print(a.comb([1,2,3,4,5], 2))
| class Combo:
def combine(self, n, k):
a = list(range(1, n + 1))
res = self.comb(A, k)
return res
def comb(self, A, n):
if n == 0:
return [[]]
l = []
for i in range(0, len(A)):
m = A[i]
rem_lst = A[i + 1:]
for p in self.comb(remLst, n - 1):
l.append([m] + p)
return l
def combinations(n, list, combos=[]):
if combos is None:
combos = []
if len(list) == n:
if combos.count(list) == 0:
combos.append(list)
combos.sort()
return combos
else:
for i in range(len(list)):
refined_list = list[:i] + list[i + 1:]
combos = combinations(n, refined_list, combos)
return combos
a = combo()
a = 4
b = 2
print(a.comb([1, 2, 3, 4], 2))
print(a.comb([1, 2, 3, 4, 5], 2)) |
f = open('./day4.py')
for chunk in iter(lambda :f.read(10),''):
print(chunk)
| f = open('./day4.py')
for chunk in iter(lambda : f.read(10), ''):
print(chunk) |
class WebsiteBaseError(Exception):
pass
class TreeTraversal(WebsiteBaseError):
def __init__(self, tree, request, segment, req=None):
super().__init__()
self.tree, self.request, self.segment, self.req = tree, request, segment, req
def __str__(self) -> str:
return f"{self.tree} > {self.request}[{self.segment}] {'' if self.req is None else self.req}"
class BufferRead(WebsiteBaseError):
def __init__(self, buffer):
super().__init__()
self.buffer = buffer
def __str__(self) -> str:
return f"{self.buffer}"
| class Websitebaseerror(Exception):
pass
class Treetraversal(WebsiteBaseError):
def __init__(self, tree, request, segment, req=None):
super().__init__()
(self.tree, self.request, self.segment, self.req) = (tree, request, segment, req)
def __str__(self) -> str:
return f"{self.tree} > {self.request}[{self.segment}] {('' if self.req is None else self.req)}"
class Bufferread(WebsiteBaseError):
def __init__(self, buffer):
super().__init__()
self.buffer = buffer
def __str__(self) -> str:
return f'{self.buffer}' |
linelist = [line for line in open('Day 02.input').readlines()]
hor = 0
dep = 0
for line in linelist:
mov, amount = line.split(' ')
if mov == 'forward':
hor += int(amount)
else:
dep += int(amount) * (-1 if mov == 'up' else 1)
print(hor * dep)
| linelist = [line for line in open('Day 02.input').readlines()]
hor = 0
dep = 0
for line in linelist:
(mov, amount) = line.split(' ')
if mov == 'forward':
hor += int(amount)
else:
dep += int(amount) * (-1 if mov == 'up' else 1)
print(hor * dep) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Simple color picker program."""
BANNER = """ .::::::::::::::::::::::::::::::::::::::::::::::::.
.. .... ..
.. ...... ... ..
|S .F.Cards.. F.G ia
nt sS.F.Gi||BASE BAL LB
AS EBALLBASEBA||S .F. Gi
an tsS.F.Giants S. F.
Gi ||BASEBALLBA SE BA
LL BASEBA||N.Y.Yankees.F .Gia nt
sS .F.Gi||BASEBALLBASEBALLBASEB A|
|S .F.MetsS.F.GiantsS.F.Gi||BASE BA
LL BA SEBALLBASEBA||S.T.L.Cards.Reds S.
F. Gi||B ASEBALLBASEBALLBASEBA||S.F.GiantsS.F .G
ia nt sS.F.Gi||BASEBALLBASEBALLBASEBA||S.F .G
ia ntsT.B.Rayss.F.Gi||BASEBALL BA
S EBALLBASEBA|'`''''''''''' S
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
____ ____ ____ _ ____ ____ ____
| __ )| __ ) / ___| / \ | _ \| _ \/ ___|
| _ \| _ \ _____| | / _ \ | |_) | | | \___ \
| |_) | |_) |_____| |___ / ___ \| _ <| |_| |___) |
|____/|____/ \____/_/ \_|_| \_|____/|____/
"""
| """Simple color picker program."""
banner = " .::::::::::::::::::::::::::::::::::::::::::::::::.\n .. .... ..\n .. ...... ... ..\n |S .F.Cards.. F.G ia\n nt sS.F.Gi||BASE BAL LB\n AS EBALLBASEBA||S .F. Gi\n an tsS.F.Giants S. F.\n Gi ||BASEBALLBA SE BA\n LL BASEBA||N.Y.Yankees.F .Gia nt\n sS .F.Gi||BASEBALLBASEBALLBASEB A|\n |S .F.MetsS.F.GiantsS.F.Gi||BASE BA\n LL BA SEBALLBASEBA||S.T.L.Cards.Reds S.\n F. Gi||B ASEBALLBASEBALLBASEBA||S.F.GiantsS.F .G\n ia nt sS.F.Gi||BASEBALLBASEBALLBASEBA||S.F .G\n ia ntsT.B.Rayss.F.Gi||BASEBALL BA\n S EBALLBASEBA|'`''''''''''' S\n :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\n ____ ____ ____ _ ____ ____ ____\n | __ )| __ ) / ___| / \\ | _ \\| _ \\/ ___| \n | _ \\| _ \\ _____| | / _ \\ | |_) | | | \\___ \\ \n | |_) | |_) |_____| |___ / ___ \\| _ <| |_| |___) |\n |____/|____/ \\____/_/ \\_|_| \\_|____/|____/ \n " |
def convert_sample_to_shot_wow(sample, with_knowledge=True):
prefix = "Dialogue:\n"
assert len(sample["dialogue"]) == len(sample["meta"])
for turn, meta in zip(sample["dialogue"],sample["meta"]):
prefix += f"User: {turn[0]}" +"\n"
if with_knowledge:
if len(meta)>0:
prefix += f"KB: {meta[0]}" +"\n"
else:
prefix += f"KB: None" +"\n"
if turn[1] == "":
prefix += f"Assistant:"
return prefix
else:
prefix += f"Assistant: {turn[1]}" +"\n"
return prefix
def convert_sample_to_shot_wow_interact(sample, with_knowledge=True):
prefix = "Dialogue:\n"
assert len(sample["dialogue"]) == len(sample["KB_wiki"])
for turn, meta in zip(sample["dialogue"],sample["KB_wiki"]):
prefix += f"User: {turn[0]}" +"\n"
if with_knowledge:
if len(meta)>0:
prefix += f"KB: {meta[0]}" +"\n"
else:
prefix += f"KB: None" +"\n"
if turn[1] == "":
prefix += f"Assistant:"
return prefix
else:
prefix += f"Assistant: {turn[1]}" +"\n"
return prefix
| def convert_sample_to_shot_wow(sample, with_knowledge=True):
prefix = 'Dialogue:\n'
assert len(sample['dialogue']) == len(sample['meta'])
for (turn, meta) in zip(sample['dialogue'], sample['meta']):
prefix += f'User: {turn[0]}' + '\n'
if with_knowledge:
if len(meta) > 0:
prefix += f'KB: {meta[0]}' + '\n'
else:
prefix += f'KB: None' + '\n'
if turn[1] == '':
prefix += f'Assistant:'
return prefix
else:
prefix += f'Assistant: {turn[1]}' + '\n'
return prefix
def convert_sample_to_shot_wow_interact(sample, with_knowledge=True):
prefix = 'Dialogue:\n'
assert len(sample['dialogue']) == len(sample['KB_wiki'])
for (turn, meta) in zip(sample['dialogue'], sample['KB_wiki']):
prefix += f'User: {turn[0]}' + '\n'
if with_knowledge:
if len(meta) > 0:
prefix += f'KB: {meta[0]}' + '\n'
else:
prefix += f'KB: None' + '\n'
if turn[1] == '':
prefix += f'Assistant:'
return prefix
else:
prefix += f'Assistant: {turn[1]}' + '\n'
return prefix |
# Test cases that are expected to fail, e.g. unimplemented features or bug-fixes.
# Remove from list when fixed.
xfail = {
"namespace_keywords", # 70
"googletypes_struct", # 9
"googletypes_value", # 9
"import_capitalized_package",
"example", # This is the example in the readme. Not a test.
}
services = {
"googletypes_response",
"googletypes_response_embedded",
"service",
"service_separate_packages",
"import_service_input_message",
"googletypes_service_returns_empty",
"googletypes_service_returns_googletype",
"example_service",
"empty_service",
}
# Indicate json sample messages to skip when testing that json (de)serialization
# is symmetrical becuase some cases legitimately are not symmetrical.
# Each key references the name of the test scenario and the values in the tuple
# Are the names of the json files.
non_symmetrical_json = {"empty_repeated": ("empty_repeated",)}
| xfail = {'namespace_keywords', 'googletypes_struct', 'googletypes_value', 'import_capitalized_package', 'example'}
services = {'googletypes_response', 'googletypes_response_embedded', 'service', 'service_separate_packages', 'import_service_input_message', 'googletypes_service_returns_empty', 'googletypes_service_returns_googletype', 'example_service', 'empty_service'}
non_symmetrical_json = {'empty_repeated': ('empty_repeated',)} |
class Settings:
BOT_KEY = ""
HOST_NAME = "127.0.0.1"
USER_NAME = "root"
USER_PASS = "Andrey171200"
SQL_NAME = "moneysaver"
| class Settings:
bot_key = ''
host_name = '127.0.0.1'
user_name = 'root'
user_pass = 'Andrey171200'
sql_name = 'moneysaver' |
{
"targets": [
{
"target_name": "binding",
"sources": [
"native\\winhttpBindings.cpp"
],
"include_dirs": [
"<!@(node -p \"require('node-addon-api').include\")"
],
"libraries": [
"WinHTTP.lib",
"-DelayLoad:node.exe"
],
"msbuild_settings": {
"ClCompile": {
"RuntimeLibrary": "MultiThreaded"
}
}
}
]
}
| {'targets': [{'target_name': 'binding', 'sources': ['native\\winhttpBindings.cpp'], 'include_dirs': ['<!@(node -p "require(\'node-addon-api\').include")'], 'libraries': ['WinHTTP.lib', '-DelayLoad:node.exe'], 'msbuild_settings': {'ClCompile': {'RuntimeLibrary': 'MultiThreaded'}}}]} |
def open_file():
while True:
file_name = input("Enter input file: ")
try:
measles = open(file_name, "r")
break
except:
print("File unable to open. Invalid name or file doesn't exist!")
continue # name it re-prompts for a write name
return measles
def process_file(measles):
while True:
year = input("Enter year: ")
if len(year) == 4: # this ensures that the year has four characters
break
else:
print("Invalid year. Year MUST be four digits")
continue
while True: # this loop assigns the income level
print("Income levels;\n Input 1 for WB_LI\n Input 2 for WB_LMI\n Input 3 for WB_UMI\n Input 4 for WB_HI")
income = input("Enter income level(1,2,3,4): ")
if income == "1":
income = "WB_LI"
break
elif income == "2":
income = "WB_LMI"
break
elif income == "3":
income = "WB_UMI"
break
elif income == "4":
income = "WB_HI"
break
else:
print("Invalid income level!") # an invalid input re-prompts till the right one is made
continue
count = 0
percentages = []
countries = []
for line in measles:
if (line[88:92] == year) and (line[51:56] == income or line[51:57] == income): # Ensures the criteria is met
count += 1
percentages.append(int(line[59:61])) # adds percentages to the list percentages
country = line[0:51]
country = str(country)
country = country.strip()
countries.append(country) # adds percentages to the list of countries
continue
country_percentage = dict(zip(countries, percentages)) # Creates a dictionary with country as the key and percentage as values
if count > 0:
percent_sum = sum(percentages)
percent_avg = percent_sum / count # average of percentages
max_percentage = max(percentages)
min_percentage = min(percentages)
# gets countries for maximum percentages to this list
max_country = [country for country, percentage in country_percentage.items() if percentage == max_percentage]
# gets countries for minimum percentages to this list
min_country = [country for country, percentage in country_percentage.items() if percentage == min_percentage]
print(f"Nunber of countries in the record: {count}")
print(f"Average percentage for {year} with {income} is {percent_avg:.1f}%")
print(f"Country(ies) have maximum percentage in {year} with {income} of {max_percentage}%")
for i in max_country: # print contries with maximum percentages
print(" >", i)
print(f"Country(ies) have minimum percentage in {year} with {income} of {min_percentage}%")
for i in min_country: # print contries with minimum percentages
print(" >", i)
else: # if there is no item in the list, it prints this
print(f"The year {year} does not exist in the record...")
def main():
measles = open_file()
process_file(measles)
measles.close()
main()
| def open_file():
while True:
file_name = input('Enter input file: ')
try:
measles = open(file_name, 'r')
break
except:
print("File unable to open. Invalid name or file doesn't exist!")
continue
return measles
def process_file(measles):
while True:
year = input('Enter year: ')
if len(year) == 4:
break
else:
print('Invalid year. Year MUST be four digits')
continue
while True:
print('Income levels;\n Input 1 for WB_LI\n Input 2 for WB_LMI\n Input 3 for WB_UMI\n Input 4 for WB_HI')
income = input('Enter income level(1,2,3,4): ')
if income == '1':
income = 'WB_LI'
break
elif income == '2':
income = 'WB_LMI'
break
elif income == '3':
income = 'WB_UMI'
break
elif income == '4':
income = 'WB_HI'
break
else:
print('Invalid income level!')
continue
count = 0
percentages = []
countries = []
for line in measles:
if line[88:92] == year and (line[51:56] == income or line[51:57] == income):
count += 1
percentages.append(int(line[59:61]))
country = line[0:51]
country = str(country)
country = country.strip()
countries.append(country)
continue
country_percentage = dict(zip(countries, percentages))
if count > 0:
percent_sum = sum(percentages)
percent_avg = percent_sum / count
max_percentage = max(percentages)
min_percentage = min(percentages)
max_country = [country for (country, percentage) in country_percentage.items() if percentage == max_percentage]
min_country = [country for (country, percentage) in country_percentage.items() if percentage == min_percentage]
print(f'Nunber of countries in the record: {count}')
print(f'Average percentage for {year} with {income} is {percent_avg:.1f}%')
print(f'Country(ies) have maximum percentage in {year} with {income} of {max_percentage}%')
for i in max_country:
print(' >', i)
print(f'Country(ies) have minimum percentage in {year} with {income} of {min_percentage}%')
for i in min_country:
print(' >', i)
else:
print(f'The year {year} does not exist in the record...')
def main():
measles = open_file()
process_file(measles)
measles.close()
main() |
def get_obj1():
obj = \
{
"sha": "d25341478381063d1c76e81b3a52e0592a7c997f",
"commit": {
"author": {
"name": "Stephen Dolan",
"email": "mu@netsoc.tcd.ie",
"date": "2013-06-22T16:30:59Z"
},
"committer": {
"name": "Stephen Dolan",
"email": "mu@netsoc.tcd.ie",
"date": "2013-06-22T16:30:59Z"
},
"message": "Merge pull request #162 from stedolan/utf8-fixes\n\nUtf8 fixes. Closes #161",
"tree": {
"sha": "6ab697a8dfb5a96e124666bf6d6213822599fb40",
"url": "https://api.github.com/repos/stedolan/jq/git/trees/6ab697a8dfb5a96e124666bf6d6213822599fb40"
},
"url": "https://api.github.com/repos/stedolan/jq/git/commits/d25341478381063d1c76e81b3a52e0592a7c997f",
"comment_count": 0
},
"url": "https://api.github.com/repos/stedolan/jq/commits/d25341478381063d1c76e81b3a52e0592a7c997f",
"html_url": "https://github.com/stedolan/jq/commit/d25341478381063d1c76e81b3a52e0592a7c997f",
"comments_url": "https://api.github.com/repos/stedolan/jq/commits/d25341478381063d1c76e81b3a52e0592a7c997f/comments",
"author": {
"login": "stedolan",
"id": 79765,
"avatar_url": "https://avatars.githubusercontent.com/u/79765?v=3",
"gravatar_id": "",
"url": "https://api.github.com/users/stedolan",
"html_url": "https://github.com/stedolan",
"followers_url": "https://api.github.com/users/stedolan/followers",
"following_url": "https://api.github.com/users/stedolan/following{/other_user}",
"gists_url": "https://api.github.com/users/stedolan/gists{/gist_id}",
"starred_url": "https://api.github.com/users/stedolan/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/stedolan/subscriptions",
"organizations_url": "https://api.github.com/users/stedolan/orgs",
"repos_url": "https://api.github.com/users/stedolan/repos",
"events_url": "https://api.github.com/users/stedolan/events{/privacy}",
"received_events_url": "https://api.github.com/users/stedolan/received_events",
"type": "User",
"site_admin": False
},
"committer": {
"login": "stedolan",
"id": 79765,
"avatar_url": "https://avatars.githubusercontent.com/u/79765?v=3",
"gravatar_id": "",
"url": "https://api.github.com/users/stedolan",
"html_url": "https://github.com/stedolan",
"followers_url": "https://api.github.com/users/stedolan/followers",
"following_url": "https://api.github.com/users/stedolan/following{/other_user}",
"gists_url": "https://api.github.com/users/stedolan/gists{/gist_id}",
"starred_url": "https://api.github.com/users/stedolan/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/stedolan/subscriptions",
"organizations_url": "https://api.github.com/users/stedolan/orgs",
"repos_url": "https://api.github.com/users/stedolan/repos",
"events_url": "https://api.github.com/users/stedolan/events{/privacy}",
"received_events_url": "https://api.github.com/users/stedolan/received_events",
"type": "User",
"site_admin": False
},
"parents": [
{
"sha": "54b9c9bdb225af5d886466d72f47eafc51acb4f7",
"url": "https://api.github.com/repos/stedolan/jq/commits/54b9c9bdb225af5d886466d72f47eafc51acb4f7",
"html_url": "https://github.com/stedolan/jq/commit/54b9c9bdb225af5d886466d72f47eafc51acb4f7"
},
{
"sha": "8b1b503609c161fea4b003a7179b3fbb2dd4345a",
"url": "https://api.github.com/repos/stedolan/jq/commits/8b1b503609c161fea4b003a7179b3fbb2dd4345a",
"html_url": "https://github.com/stedolan/jq/commit/8b1b503609c161fea4b003a7179b3fbb2dd4345a"
}
]
}
return obj | def get_obj1():
obj = {'sha': 'd25341478381063d1c76e81b3a52e0592a7c997f', 'commit': {'author': {'name': 'Stephen Dolan', 'email': 'mu@netsoc.tcd.ie', 'date': '2013-06-22T16:30:59Z'}, 'committer': {'name': 'Stephen Dolan', 'email': 'mu@netsoc.tcd.ie', 'date': '2013-06-22T16:30:59Z'}, 'message': 'Merge pull request #162 from stedolan/utf8-fixes\n\nUtf8 fixes. Closes #161', 'tree': {'sha': '6ab697a8dfb5a96e124666bf6d6213822599fb40', 'url': 'https://api.github.com/repos/stedolan/jq/git/trees/6ab697a8dfb5a96e124666bf6d6213822599fb40'}, 'url': 'https://api.github.com/repos/stedolan/jq/git/commits/d25341478381063d1c76e81b3a52e0592a7c997f', 'comment_count': 0}, 'url': 'https://api.github.com/repos/stedolan/jq/commits/d25341478381063d1c76e81b3a52e0592a7c997f', 'html_url': 'https://github.com/stedolan/jq/commit/d25341478381063d1c76e81b3a52e0592a7c997f', 'comments_url': 'https://api.github.com/repos/stedolan/jq/commits/d25341478381063d1c76e81b3a52e0592a7c997f/comments', 'author': {'login': 'stedolan', 'id': 79765, 'avatar_url': 'https://avatars.githubusercontent.com/u/79765?v=3', 'gravatar_id': '', 'url': 'https://api.github.com/users/stedolan', 'html_url': 'https://github.com/stedolan', 'followers_url': 'https://api.github.com/users/stedolan/followers', 'following_url': 'https://api.github.com/users/stedolan/following{/other_user}', 'gists_url': 'https://api.github.com/users/stedolan/gists{/gist_id}', 'starred_url': 'https://api.github.com/users/stedolan/starred{/owner}{/repo}', 'subscriptions_url': 'https://api.github.com/users/stedolan/subscriptions', 'organizations_url': 'https://api.github.com/users/stedolan/orgs', 'repos_url': 'https://api.github.com/users/stedolan/repos', 'events_url': 'https://api.github.com/users/stedolan/events{/privacy}', 'received_events_url': 'https://api.github.com/users/stedolan/received_events', 'type': 'User', 'site_admin': False}, 'committer': {'login': 'stedolan', 'id': 79765, 'avatar_url': 'https://avatars.githubusercontent.com/u/79765?v=3', 'gravatar_id': '', 'url': 'https://api.github.com/users/stedolan', 'html_url': 'https://github.com/stedolan', 'followers_url': 'https://api.github.com/users/stedolan/followers', 'following_url': 'https://api.github.com/users/stedolan/following{/other_user}', 'gists_url': 'https://api.github.com/users/stedolan/gists{/gist_id}', 'starred_url': 'https://api.github.com/users/stedolan/starred{/owner}{/repo}', 'subscriptions_url': 'https://api.github.com/users/stedolan/subscriptions', 'organizations_url': 'https://api.github.com/users/stedolan/orgs', 'repos_url': 'https://api.github.com/users/stedolan/repos', 'events_url': 'https://api.github.com/users/stedolan/events{/privacy}', 'received_events_url': 'https://api.github.com/users/stedolan/received_events', 'type': 'User', 'site_admin': False}, 'parents': [{'sha': '54b9c9bdb225af5d886466d72f47eafc51acb4f7', 'url': 'https://api.github.com/repos/stedolan/jq/commits/54b9c9bdb225af5d886466d72f47eafc51acb4f7', 'html_url': 'https://github.com/stedolan/jq/commit/54b9c9bdb225af5d886466d72f47eafc51acb4f7'}, {'sha': '8b1b503609c161fea4b003a7179b3fbb2dd4345a', 'url': 'https://api.github.com/repos/stedolan/jq/commits/8b1b503609c161fea4b003a7179b3fbb2dd4345a', 'html_url': 'https://github.com/stedolan/jq/commit/8b1b503609c161fea4b003a7179b3fbb2dd4345a'}]}
return obj |
description = 'system setup'
group = 'lowlevel'
sysconfig = dict(
cache = 'localhost',
instrument = 'ErWIN',
experiment = 'Exp',
datasinks = ['conssink', 'dmnsink'],
notifiers = [],
)
modules = ['nicos.commands.standard']
devices = dict(
ErWIN = device('nicos.devices.instrument.Instrument',
description = 'ErWIN instrument',
instrument = 'ErWIN',
responsible = 'Michael Heere <michael.heere@kit.edu>',
website = 'https://mlz-garching.de/erwin',
operators = [
'Karlsruhe Institute of Technology (KIT)',
],
),
Sample = device('nicos.devices.sample.Sample',
description = 'sample object',
),
Exp = device('nicos_mlz.devices.experiment.Experiment',
description = 'experiment object',
dataroot = 'data',
sample = 'Sample',
reporttemplate = '',
sendmail = False,
serviceexp = 'p0',
mailsender = 'erwin@frm2.tum.de',
mailserver = 'mailhost.frm2.tum.de',
elog = True,
managerights = dict(
enableDirMode = 0o775,
enableFileMode = 0o644,
disableDirMode = 0o550,
disableFileMode = 0o440,
owner = 'erwin',
group = 'erwin'
),
),
filesink = device('nicos.devices.datasinks.AsciiScanfileSink'),
conssink = device('nicos.devices.datasinks.ConsoleScanSink'),
dmnsink = device('nicos.devices.datasinks.DaemonSink'),
Space = device('nicos.devices.generic.FreeSpace',
description = 'The amount of free space for storing data',
warnlimits = (5., None),
path = None,
minfree = 5,
),
LogSpace = device('nicos.devices.generic.FreeSpace',
description = 'Space on log drive',
path = 'log',
warnlimits = (.5, None),
minfree = 0.5,
lowlevel = True,
),
)
| description = 'system setup'
group = 'lowlevel'
sysconfig = dict(cache='localhost', instrument='ErWIN', experiment='Exp', datasinks=['conssink', 'dmnsink'], notifiers=[])
modules = ['nicos.commands.standard']
devices = dict(ErWIN=device('nicos.devices.instrument.Instrument', description='ErWIN instrument', instrument='ErWIN', responsible='Michael Heere <michael.heere@kit.edu>', website='https://mlz-garching.de/erwin', operators=['Karlsruhe Institute of Technology (KIT)']), Sample=device('nicos.devices.sample.Sample', description='sample object'), Exp=device('nicos_mlz.devices.experiment.Experiment', description='experiment object', dataroot='data', sample='Sample', reporttemplate='', sendmail=False, serviceexp='p0', mailsender='erwin@frm2.tum.de', mailserver='mailhost.frm2.tum.de', elog=True, managerights=dict(enableDirMode=509, enableFileMode=420, disableDirMode=360, disableFileMode=288, owner='erwin', group='erwin')), filesink=device('nicos.devices.datasinks.AsciiScanfileSink'), conssink=device('nicos.devices.datasinks.ConsoleScanSink'), dmnsink=device('nicos.devices.datasinks.DaemonSink'), Space=device('nicos.devices.generic.FreeSpace', description='The amount of free space for storing data', warnlimits=(5.0, None), path=None, minfree=5), LogSpace=device('nicos.devices.generic.FreeSpace', description='Space on log drive', path='log', warnlimits=(0.5, None), minfree=0.5, lowlevel=True)) |
# -*- coding: utf-8 -*-
"""
1265. Print Immutable Linked List in Reverse
You are given an immutable linked list, print out all values of each node in reverse with the help of the following
interface:
ImmutableListNode: An interface of immutable linked list, you are given the head of the list.
You need to use the following functions to access the linked list (you can't access the ImmutableListNode directly):
ImmutableListNode.printValue(): Print value of the current node.
ImmutableListNode.getNext(): Return the next node.
The input is only given to initialize the linked list internally.
You must solve this problem without modifying the linked list.
In other words, you must operate the linked list using only the mentioned APIs.
Constraints:
The length of the linked list is between [1, 1000].
The value of each node in the linked list is between [-1000, 1000].
Follow up:
Could you solve this problem in:
Constant space complexity?
Linear time complexity and less than linear space complexity?
"""
"""
This is the ImmutableListNode's API interface.
You should not implement it, or speculate about its implementation.
"""
class ImmutableListNode:
def printValue(self) -> None: # print the value of this node.
pass
def getNext(self) -> 'ImmutableListNode': # return the next node.
pass
class Solution:
def printLinkedListInReverse(self, head: 'ImmutableListNode') -> None:
if head is None:
return
self.printLinkedListInReverse(head.getNext())
head.printValue()
| """
1265. Print Immutable Linked List in Reverse
You are given an immutable linked list, print out all values of each node in reverse with the help of the following
interface:
ImmutableListNode: An interface of immutable linked list, you are given the head of the list.
You need to use the following functions to access the linked list (you can't access the ImmutableListNode directly):
ImmutableListNode.printValue(): Print value of the current node.
ImmutableListNode.getNext(): Return the next node.
The input is only given to initialize the linked list internally.
You must solve this problem without modifying the linked list.
In other words, you must operate the linked list using only the mentioned APIs.
Constraints:
The length of the linked list is between [1, 1000].
The value of each node in the linked list is between [-1000, 1000].
Follow up:
Could you solve this problem in:
Constant space complexity?
Linear time complexity and less than linear space complexity?
"""
"\nThis is the ImmutableListNode's API interface.\nYou should not implement it, or speculate about its implementation.\n"
class Immutablelistnode:
def print_value(self) -> None:
pass
def get_next(self) -> 'ImmutableListNode':
pass
class Solution:
def print_linked_list_in_reverse(self, head: 'ImmutableListNode') -> None:
if head is None:
return
self.printLinkedListInReverse(head.getNext())
head.printValue() |
num1 = input()
num2 = input()
num3 = input()
print(int(num1) + int(num2) + int(num3))
| num1 = input()
num2 = input()
num3 = input()
print(int(num1) + int(num2) + int(num3)) |
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def print_list(self):
temp = self.head
linked_list = ''
while temp:
linked_list += str(temp.data) + " -> "
temp = temp.next
print(linked_list)
# lists start at 0
def insert_node(self, val, pos):
target = Node(val)
# specific case for replacing head
if pos == 0:
target.next = self.head
self.head = target
return
def get_prev(position):
temp = self.head
count = 1
while count < position:
temp = temp.next
count += 1
return temp
# Getting previous node
prev = get_prev(pos)
if prev.next:
# Temp variable for upcoming node
next_node = prev.next
# Set previous next to our target node
prev.next = target
# Set next node of target node from temp variable
target.next = next_node
def delete_node(self, key):
temp = self.head
if temp is None:
return
if temp.data == key:
self.head = temp.next
temp = None
return
while temp.next.data != key:
temp = temp.next
# Getting target node
target_node = temp.next
# Set previous node's next to target's next
temp.next = target_node.next
# Remove target node's pointer
target_node.next = None
# Nodes: 4 -> 5 -> 7 -> 2
link = LinkedList()
link.head = Node(4)
first_node = Node(5)
second_node = Node(7)
third_node = Node(2)
link.head.next = first_node
first_node.next = second_node
second_node.next = third_node
link.print_list()
# Nodes: 4 -> 5 -> 7 -> 2
# Insert 3 at index 2
# Nodes: 4 -> 5 -> 3 -> 7 -> 2
link.insert_node(3, 2)
link.print_list()
# Nodes: 4 -> 5 -> 3 -> 7 -> 2
# Delete 3
# Nodes: 4 -> 5 -> 7 -> 2
link.delete_node(3)
link.print_list()
| class Node:
def __init__(self, data):
self.data = data
self.next = None
class Linkedlist:
def __init__(self):
self.head = None
def print_list(self):
temp = self.head
linked_list = ''
while temp:
linked_list += str(temp.data) + ' -> '
temp = temp.next
print(linked_list)
def insert_node(self, val, pos):
target = node(val)
if pos == 0:
target.next = self.head
self.head = target
return
def get_prev(position):
temp = self.head
count = 1
while count < position:
temp = temp.next
count += 1
return temp
prev = get_prev(pos)
if prev.next:
next_node = prev.next
prev.next = target
target.next = next_node
def delete_node(self, key):
temp = self.head
if temp is None:
return
if temp.data == key:
self.head = temp.next
temp = None
return
while temp.next.data != key:
temp = temp.next
target_node = temp.next
temp.next = target_node.next
target_node.next = None
link = linked_list()
link.head = node(4)
first_node = node(5)
second_node = node(7)
third_node = node(2)
link.head.next = first_node
first_node.next = second_node
second_node.next = third_node
link.print_list()
link.insert_node(3, 2)
link.print_list()
link.delete_node(3)
link.print_list() |
def bubblesort(L):
keepgoing = True
while keepgoing:
keepgoing = False
for i in range(len(L)-1):
if L[i]>L[i+1]:
L[i], L[i+1] = L[i+1], L[i]
keepgoing = True
| def bubblesort(L):
keepgoing = True
while keepgoing:
keepgoing = False
for i in range(len(L) - 1):
if L[i] > L[i + 1]:
(L[i], L[i + 1]) = (L[i + 1], L[i])
keepgoing = True |
# Hydro settings
TIME_ZONE = 'UTC'
LANGUAGE_CODE = 'en-us'
APPLICATION_NAME = 'HYDRO'
SECRET_KEY = '8lu*6g0lg)9w!ba+a$edk)xx)x%rxgb$i1&022shmi1jcgihb*'
# SESSION_TIMEOUT is used in validate_session_active decorator to see if the
# session is active.
SECOND = 1
MINUTE = SECOND * 60
SECONDS_IN_DAY = SECOND*86400
MYSQL_CACHE_DB = 'cache'
MYSQL_STATS_DB = 'stats'
MYSQL_CACHE_TABLE = 'hydro_cache_table'
CACHE_IN_MEMORY_KEY_EXPIRE = 600
CACHE_DB_KEY_EXPIRE = 86400
USE_STATS_DB = False
DATABASES = {
'stats': {
'ENGINE': 'django.db.backends.mysql',
'NAME': MYSQL_STATS_DB,
'USER': 'root',
'PASSWORD': 'xxxx',
'HOST': '127.0.0.1',
'OPTIONS': {
"init_command": "SET storage_engine=INNODB; SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;",
"compress": True
},
},
'cache': {
'ENGINE': 'django.db.backends.mysql',
'NAME': MYSQL_CACHE_DB,
'USER': 'root',
'PASSWORD': 'xxxx',
'HOST': '127.0.0.1',
'OPTIONS': {
"init_command": "SET storage_engine=INNODB; SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;",
"compress": True
},
},
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'cache',
'USER': 'root',
'PASSWORD': 'xxxx',
'HOST': '127.0.0.1',
'OPTIONS': {
"init_command": "SET storage_engine=INNODB; SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;",
"compress": True
}
},
}
| time_zone = 'UTC'
language_code = 'en-us'
application_name = 'HYDRO'
secret_key = '8lu*6g0lg)9w!ba+a$edk)xx)x%rxgb$i1&022shmi1jcgihb*'
second = 1
minute = SECOND * 60
seconds_in_day = SECOND * 86400
mysql_cache_db = 'cache'
mysql_stats_db = 'stats'
mysql_cache_table = 'hydro_cache_table'
cache_in_memory_key_expire = 600
cache_db_key_expire = 86400
use_stats_db = False
databases = {'stats': {'ENGINE': 'django.db.backends.mysql', 'NAME': MYSQL_STATS_DB, 'USER': 'root', 'PASSWORD': 'xxxx', 'HOST': '127.0.0.1', 'OPTIONS': {'init_command': 'SET storage_engine=INNODB; SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;', 'compress': True}}, 'cache': {'ENGINE': 'django.db.backends.mysql', 'NAME': MYSQL_CACHE_DB, 'USER': 'root', 'PASSWORD': 'xxxx', 'HOST': '127.0.0.1', 'OPTIONS': {'init_command': 'SET storage_engine=INNODB; SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;', 'compress': True}}, 'default': {'ENGINE': 'django.db.backends.mysql', 'NAME': 'cache', 'USER': 'root', 'PASSWORD': 'xxxx', 'HOST': '127.0.0.1', 'OPTIONS': {'init_command': 'SET storage_engine=INNODB; SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;', 'compress': True}}} |
def load_external_repo():
native.local_repository(
name = "ext_repo",
path = "test/external_repo/repo",
)
| def load_external_repo():
native.local_repository(name='ext_repo', path='test/external_repo/repo') |
'''
Created on May 26, 2012
@author: Charlie
'''
class MainModule01(object):
def __init__(self):
pass | """
Created on May 26, 2012
@author: Charlie
"""
class Mainmodule01(object):
def __init__(self):
pass |
#
# PySNMP MIB module GENERIC-3COM-VLAN-MIB-1-0-7 (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/GENERIC-3COM-VLAN-MIB-1-0-7
# Produced by pysmi-0.3.4 at Wed May 1 11:09:00 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols("ASN1", "OctetString", "ObjectIdentifier", "Integer")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsUnion, SingleValueConstraint, ValueRangeConstraint, ValueSizeConstraint, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "SingleValueConstraint", "ValueRangeConstraint", "ValueSizeConstraint", "ConstraintsIntersection")
ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup")
NotificationType, Counter32, Integer32, ObjectIdentity, Counter64, IpAddress, MibIdentifier, iso, ModuleIdentity, Unsigned32, Gauge32, TimeTicks, MibScalar, MibTable, MibTableRow, MibTableColumn, Bits, enterprises = mibBuilder.importSymbols("SNMPv2-SMI", "NotificationType", "Counter32", "Integer32", "ObjectIdentity", "Counter64", "IpAddress", "MibIdentifier", "iso", "ModuleIdentity", "Unsigned32", "Gauge32", "TimeTicks", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Bits", "enterprises")
TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString")
class RowStatus(Integer32):
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6))
namedValues = NamedValues(("active", 1), ("notInService", 2), ("notReady", 3), ("createAndGo", 4), ("createAndWait", 5), ("destroy", 6))
a3Com = MibIdentifier((1, 3, 6, 1, 4, 1, 43))
generic = MibIdentifier((1, 3, 6, 1, 4, 1, 43, 10))
genExperimental = MibIdentifier((1, 3, 6, 1, 4, 1, 43, 10, 1))
genVirtual = MibIdentifier((1, 3, 6, 1, 4, 1, 43, 10, 1, 14))
a3ComVlanGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 1))
a3ComVlanProtocolsGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 2))
a3ComVirtualGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 3))
a3ComEncapsulationGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 4))
class A3ComVlanType(Integer32):
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20))
namedValues = NamedValues(("vlanLayer2", 1), ("vlanUnspecifiedProtocols", 2), ("vlanIPProtocol", 3), ("vlanIPXProtocol", 4), ("vlanAppleTalkProtocol", 5), ("vlanXNSProtocol", 6), ("vlanISOProtocol", 7), ("vlanDECNetProtocol", 8), ("vlanNetBIOSProtocol", 9), ("vlanSNAProtocol", 10), ("vlanVINESProtocol", 11), ("vlanX25Protocol", 12), ("vlanIGMPProtocol", 13), ("vlanSessionLayer", 14), ("vlanNetBeui", 15), ("vlanLayeredProtocols", 16), ("vlanIPXIIProtocol", 17), ("vlanIPX8022Protocol", 18), ("vlanIPX8023Protocol", 19), ("vlanIPX8022SNAPProtocol", 20))
class A3ComVlanLayer3Type(Integer32):
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13))
namedValues = NamedValues(("vlanIPProtocol", 1), ("vlanIPXProtocol", 2), ("vlanAppleTalkProtocol", 3), ("vlanXNSProtocol", 4), ("vlanSNAProtocol", 5), ("vlanDECNetProtocol", 6), ("vlanNetBIOSProtocol", 7), ("vlanVINESProtocol", 8), ("vlanX25Protocol", 9), ("vlanIPXIIProtocol", 10), ("vlanIPX8022Protocol", 11), ("vlanIPX8023Protocol", 12), ("vlanIPX8022SNAPProtocol", 13))
class A3ComVlanModeType(Integer32):
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3))
namedValues = NamedValues(("vlanUseDefault", 1), ("vlanOpen", 2), ("vlanClosed", 3))
a3ComVlanGlobalMappingTable = MibTable((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 1, 1), )
if mibBuilder.loadTexts: a3ComVlanGlobalMappingTable.setStatus('mandatory')
if mibBuilder.loadTexts: a3ComVlanGlobalMappingTable.setDescription('This table lists VLAN interfaces that are globally identified. A single entry exists in this list for each VLAN interface in the system that is bound to a global identifier.')
a3ComVlanGlobalMappingEntry = MibTableRow((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 1, 1, 1), ).setIndexNames((0, "GENERIC-3COM-VLAN-MIB-1-0-7", "a3ComVlanGlobalMappingIdentifier"))
if mibBuilder.loadTexts: a3ComVlanGlobalMappingEntry.setStatus('mandatory')
if mibBuilder.loadTexts: a3ComVlanGlobalMappingEntry.setDescription('An individual VLAN interface global mapping entry. Entries in this table are created by setting the a3ComVlanIfGlobalIdentifier object in the a3ComVlanIfTable to a non-zero value.')
a3ComVlanGlobalMappingIdentifier = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 1, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535)))
if mibBuilder.loadTexts: a3ComVlanGlobalMappingIdentifier.setStatus('mandatory')
if mibBuilder.loadTexts: a3ComVlanGlobalMappingIdentifier.setDescription('An index into the a3ComVlanGlobalMappingTable and an administratively assigned global VLAN identifier. The value of this object globally identifies the VLAN interface. For VLAN interfaces, on different network devices, which are part of the same globally identified VLAN, the value of this object will be the same.')
a3ComVlanGlobalMappingIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 1, 1, 1, 2), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: a3ComVlanGlobalMappingIfIndex.setStatus('mandatory')
if mibBuilder.loadTexts: a3ComVlanGlobalMappingIfIndex.setDescription('The value of a3ComVlanIfIndex for the VLAN interface in the a3ComVlanIfTable, which is bound to the global identifier specified by this entry.')
a3ComVlanIfTable = MibTable((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 1, 2), )
if mibBuilder.loadTexts: a3ComVlanIfTable.setStatus('mandatory')
if mibBuilder.loadTexts: a3ComVlanIfTable.setDescription('This table lists VLAN interfaces that exist within a device. A single entry exists in this list for each VLAN interface in the system. A VLAN interface may be created, destroyed and/or mapped to a globally identified vlan.')
a3ComVlanIfEntry = MibTableRow((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 1, 2, 1), ).setIndexNames((0, "GENERIC-3COM-VLAN-MIB-1-0-7", "a3ComVlanIfIndex"))
if mibBuilder.loadTexts: a3ComVlanIfEntry.setStatus('mandatory')
if mibBuilder.loadTexts: a3ComVlanIfEntry.setDescription('An individual VLAN interface entry. When an NMS wishes to create a new entry in this table, it must obtain a non-zero index from the a3ComNextAvailableVirtIfIndex object. Row creation in this table will fail if the chosen index value does not match the current value returned from the a3ComNextAvailableVirtIfIndex object.')
a3ComVlanIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 1, 2, 1, 1), Integer32())
if mibBuilder.loadTexts: a3ComVlanIfIndex.setStatus('mandatory')
if mibBuilder.loadTexts: a3ComVlanIfIndex.setDescription("The index value of this row and the vlan's ifIndex in the ifTable. The NMS obtains the index value for this row by reading the a3ComNextAvailableVirtIfIndex object.")
a3ComVlanIfDescr = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 1, 2, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 80))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: a3ComVlanIfDescr.setStatus('mandatory')
if mibBuilder.loadTexts: a3ComVlanIfDescr.setDescription('This is a description of the VLAN interface.')
a3ComVlanIfType = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 1, 2, 1, 3), A3ComVlanType()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: a3ComVlanIfType.setStatus('mandatory')
if mibBuilder.loadTexts: a3ComVlanIfType.setDescription('The VLAN interface type.')
a3ComVlanIfGlobalIdentifier = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 1, 2, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: a3ComVlanIfGlobalIdentifier.setStatus('mandatory')
if mibBuilder.loadTexts: a3ComVlanIfGlobalIdentifier.setDescription('An administratively assigned global VLAN identifier. For VLAN interfaces, on different network devices, which are part of the same globally identified VLAN, the value of this object will be the same. The binding between a global identifier and a VLAN interface can be created or removed. To create a binding an NMS must write a non-zero value to this object. To delete a binding, the NMS must write a zero to this object.')
a3ComVlanIfInfo = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 1, 2, 1, 5), OctetString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: a3ComVlanIfInfo.setStatus('mandatory')
if mibBuilder.loadTexts: a3ComVlanIfInfo.setDescription('A TLV encoded information string for the VLAN interface. The information contained within this string corresponds to VLAN information not contained within this table, but contained elsewhere within this MIB module. The purpose of this string is to provide an NMS with a quick read mechanism of all related VLAN interface information. The encoding rules are defined according to: tag = 2 bytes length = 2 bytes value = n bytes The following tags are defined: TAG OBJECT DESCRIPTION 1 a3ComIpVlanIpNetAddress IP Network Address of IP VLAN 2 a3ComIpVlanIpNetMask IP Network Mask of IP VLAN')
a3ComVlanIfStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 1, 2, 1, 6), RowStatus()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: a3ComVlanIfStatus.setStatus('mandatory')
if mibBuilder.loadTexts: a3ComVlanIfStatus.setDescription('The status column for this VLAN interface. This OBJECT can be set to: active(1) createAndGo(4) createAndWait(5) destroy(6) The following values may be read: active(1) notInService(2) notReady(3). Setting this object to createAndGo(4) causes the agent to attempt to create and commit the row based on the contents of the objects in the row. If all necessary information is present in the row and the values are acceptible to the agent, the agent will change the status to active(1). If any of the necessary objects are not available, the agent will reject the creation request. Setting this object to createAndWait(5) causes a row in in this table to be created. The agent sets the status to notInService(2) if all of the information is present in the row and the values are acceptible to the agent; otherwise, the agent sets the status to notReady(3). Setting this object to active(1) is only valid when the current status is active(1) or notInService(2). When the state of the row transitions to active(1), the agent creates the corresponding row in the ifTable.. Setting this object to destroy(6) will remove the corresponding VLAN interface, remove the entry in this table, and the corresponding entries in the a3ComVlanGlobalMappingTable and the ifTable. In order for a set of this object to destroy(6) to succeed, all dependencies on this row must have been removed. These will include any stacking dependencies in the ifStackTable and any protocol specific tables dependencies.')
a3ComVlanIfModeType = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 1, 2, 1, 7), A3ComVlanModeType()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: a3ComVlanIfModeType.setStatus('mandatory')
if mibBuilder.loadTexts: a3ComVlanIfModeType.setDescription(' The VLAN mode type for this interface. This object can be set to: usedefault(1) open(2) closed(3) UseDefault Vlans: uses the bridge Vlan Mode value. The bridge Vlan Mode Value can be set to : Open, Closed or Mixed. Open VLANs: have no requirements about relationship between the bridge port that a frame was received upon and the bridge port(s) that it is transmitted on. All open VLANs within the bridge will share the same address table. Closed VLANs: require that the bridge port that a frame is received on is the same VLAN interface as the bridge port(s) that a frame is transmitted on. Each closed VLAN within the bridge will have its own address table.')
a3ComIpVlanTable = MibTable((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 2, 1), )
if mibBuilder.loadTexts: a3ComIpVlanTable.setStatus('mandatory')
if mibBuilder.loadTexts: a3ComIpVlanTable.setDescription('A list of IP VLAN interface information entries. Entries in this table are related to entries in the a3ComVlanIfTable by using the same index.')
a3ComIpVlanEntry = MibTableRow((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 2, 1, 1), ).setIndexNames((0, "GENERIC-3COM-VLAN-MIB-1-0-7", "a3ComVlanIfIndex"))
if mibBuilder.loadTexts: a3ComIpVlanEntry.setStatus('mandatory')
if mibBuilder.loadTexts: a3ComIpVlanEntry.setDescription('A a3ComIpVlanEntry contains layer 3 information about a particular IP VLAN interface. Note entries in this table cannot be deleted until the entries in the ifStackTable that produce overlap are removed.')
a3ComIpVlanIpNetAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 2, 1, 1, 1), IpAddress()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: a3ComIpVlanIpNetAddress.setStatus('mandatory')
if mibBuilder.loadTexts: a3ComIpVlanIpNetAddress.setDescription('The IP network number for the IP VLAN interface defined in the a3ComVlanIfTable identified with the same index. The IpNetAdress and the IpNetMask must be set and the the row creation process completed by a NMS before overlapping rows in the ifStackTable can be created. Sets to the ifStackTable that produce overlapping IP IP VLAN interfaces will fail if this object is not set.')
a3ComIpVlanIpNetMask = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 2, 1, 1, 2), IpAddress()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: a3ComIpVlanIpNetMask.setStatus('mandatory')
if mibBuilder.loadTexts: a3ComIpVlanIpNetMask.setDescription('The IP network mask corresponding to the IP Network address defined by a3ComIpVlanIpNetAddress. The IpNetAdress and the IpNetMask must be set and the row creation process completed by a NMS before overlapping rows in the ifStackTable can be created. Sets to the ifStackTable that produce overlapping IP VLAN interfaces will fail if this object is not set.')
a3ComIpVlanStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 2, 1, 1, 3), RowStatus()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: a3ComIpVlanStatus.setStatus('mandatory')
if mibBuilder.loadTexts: a3ComIpVlanStatus.setDescription('The status column for this IP VLAN entry. This object can be set to: active(1) createAndGo(4) createAndWait(5) destroy(6) The following values may be read: active(1) notInService(2) notReady(3). Setting this object to createAndGo(4) causes the agent to attempt to create and commit the row based on the contents of the objects in the row. If all necessary information is present in the row and the values are acceptible to the agent, the agent will change the status to active(1). If any of the necessary objects are not available, the agent will reject the row creation request. Setting this object to createAndWait(5) causes a row in in this table to be created. The agent sets the status to notInService(2) if all of the information is present in the row and the values are acceptible to the agent; otherwise, the agent sets the status to notReady(3). Setting this object to active(1) is only valid when the current status is active(1) or notInService(2). When the status changes to active(1), the agent applies the IP parmeters to the IP VLAN interface identified by the corresponding value of the a3ComIpVlanIndex object. Setting this object to destroy(6) will remove the IP parmeters from the IP VLAN interface and remove the entry from this table. Setting this object to destroy(6) will remove the layer 3 information from the IP VLAN interface and will remove the row from this table. Note that this action cannot be performed if there are ifStackTable entries that result in overlapping IP VLAN interfaces. Note that these dependencies must be removed first.')
a3ComVlanProtocolTable = MibTable((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 2, 2), )
if mibBuilder.loadTexts: a3ComVlanProtocolTable.setStatus('mandatory')
if mibBuilder.loadTexts: a3ComVlanProtocolTable.setDescription('This table lists the configured protocols per Vlan. A single entry exists in this list for each protocol configured on a VLAN interface. The a3ComVlanIfType object in a3ComVlanIfTable has to be set to vlanLayeredProtocols in order to use this table.')
a3ComVlanProtocolEntry = MibTableRow((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 2, 2, 1), ).setIndexNames((0, "GENERIC-3COM-VLAN-MIB-1-0-7", "a3ComVlanProtocolIfIndex"), (0, "GENERIC-3COM-VLAN-MIB-1-0-7", "a3ComVlanProtocolIndex"))
if mibBuilder.loadTexts: a3ComVlanProtocolEntry.setStatus('mandatory')
if mibBuilder.loadTexts: a3ComVlanProtocolEntry.setDescription('A a3ComVlanProtocolEntry contains a single VLAN to protocol entry.')
a3ComVlanProtocolIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 2, 2, 1, 1), Integer32())
if mibBuilder.loadTexts: a3ComVlanProtocolIfIndex.setStatus('mandatory')
if mibBuilder.loadTexts: a3ComVlanProtocolIfIndex.setDescription("The first indice of this row and the vlan's ifIndex in the ifTable. The value of this object is the same as the corresponding a3ComVlanIfIndex in the a3ComVlanTable.")
a3ComVlanProtocolIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 2, 2, 1, 2), A3ComVlanLayer3Type())
if mibBuilder.loadTexts: a3ComVlanProtocolIndex.setStatus('mandatory')
if mibBuilder.loadTexts: a3ComVlanProtocolIndex.setDescription('The second indice of this row, which identifies one of possible many protocols associated with the VLAN interface identified by this entries first indice. The values are based on the layer 3 protocols specified in A3ComVlanType')
a3ComVlanProtocolStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 2, 2, 1, 3), RowStatus()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: a3ComVlanProtocolStatus.setStatus('mandatory')
if mibBuilder.loadTexts: a3ComVlanProtocolStatus.setDescription('The status column for this VLAN interface. This OBJECT can be set to: active(1) createAndGo(4) createAndWait(5) destroy(6) The following values may be read: active(1) notInService(2) notReady(3). Setting this object to createAndGo(4) causes the agent to attempt to create and commit the row based on the contents of the objects in the row. If all necessary information is present in the row and the values are acceptible to the agent, the agent will change the status to active(1). If any of the necessary objects are not available, the agent will reject the creation request. Setting this object to createAndWait(5) causes a row in this table to be created. The agent sets the status to notInService(2) if all of the information is present in the row and the values are acceptable to the agent; otherwise, the agent sets the status to notReady(3). Setting this object to active(1) is only valid when the current status is active(1) or notInService(2). Row creation to this table is only possible when a corresponding VLAN entry has been created in the a3ComVlanTable with an a3ComVlanType set to vlanLayeredProtocols(16). Setting this object to destroy(6) will remove the corresponding VLAN interface to protocol mapping.')
class A3ComVlanEncapsType(Integer32):
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3))
namedValues = NamedValues(("vlanEncaps3ComProprietaryVLT", 1), ("vlanEncaps8021q", 2), ("vlanEncapsPre8021qONcore", 3))
a3ComVlanEncapsIfTable = MibTable((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 4, 1), )
if mibBuilder.loadTexts: a3ComVlanEncapsIfTable.setStatus('mandatory')
if mibBuilder.loadTexts: a3ComVlanEncapsIfTable.setDescription('This table lists VLAN encapsulation interfaces that exist within a device. A single entry exists in this list for each VLAN encapsulation interface in the system. A VLAN encapsulation interface may be created or destroyed.')
a3ComVlanEncapsIfEntry = MibTableRow((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 4, 1, 1), ).setIndexNames((0, "GENERIC-3COM-VLAN-MIB-1-0-7", "a3ComVlanEncapsIfIndex"))
if mibBuilder.loadTexts: a3ComVlanEncapsIfEntry.setStatus('mandatory')
if mibBuilder.loadTexts: a3ComVlanEncapsIfEntry.setDescription('An individual VLAN encapsulation interface entry. When an NMS wishes to create a new entry in this table, it must obtain a non-zero index from the a3ComNextAvailableVirtIfIndex object. Row creation in this table will fail if the chosen index value does not match the current value returned from the a3ComNextAvailableVirtIfIndex object.')
a3ComVlanEncapsIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 4, 1, 1, 1), Integer32())
if mibBuilder.loadTexts: a3ComVlanEncapsIfIndex.setStatus('mandatory')
if mibBuilder.loadTexts: a3ComVlanEncapsIfIndex.setDescription("The index value of this row and the encapsulation interface's ifIndex in the ifTable. The NMS obtains the index value used for creating a row in this table by reading the a3ComNextAvailableVirtIfIndex object.")
a3ComVlanEncapsIfType = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 4, 1, 1, 2), A3ComVlanEncapsType()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: a3ComVlanEncapsIfType.setStatus('mandatory')
if mibBuilder.loadTexts: a3ComVlanEncapsIfType.setDescription('The encapsulation algorithm used when encapsulating packets transmitted, or de-encapsulating packets received through this interface.')
a3ComVlanEncapsIfTag = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 4, 1, 1, 3), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: a3ComVlanEncapsIfTag.setStatus('mandatory')
if mibBuilder.loadTexts: a3ComVlanEncapsIfTag.setDescription('The tag used when encapsulating packets transmitted, or de-encapsulating packets received through this interface.')
a3ComVlanEncapsIfStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 4, 1, 1, 4), RowStatus()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: a3ComVlanEncapsIfStatus.setStatus('mandatory')
if mibBuilder.loadTexts: a3ComVlanEncapsIfStatus.setDescription('The row status for this VLAN encapsulation interface. This OBJECT can be set to: active(1) createAndGo(4) createAndWait(5) destroy(6) The following values may be read: active(1) notReady(3). In order for a row to become active, the NMS must set a3ComVlanEncapsIfTagType and a3ComVlanEncapsIfTag to some valid and consistent values. Setting this object to createAndGo(4) causes the agent to attempt to create and commit the row based on the contents of the objects in the row. If all necessary information is present in the row, the agent will create the row and change the status to active(1). If any of the necessary objects are not available, or specify an invalid configuration, the row will not be created and the agent will return an appropriate error. Setting this object to createAndWait(5) causes a row in in this table to be created. If all necessary objects in the row have been assigned values and specify a valid configuration, the status of the row will be set to notInService(2); otherwise, the status will be set to notReady(3). This object may only be set to createAndGo(4) or createAndWait(5) if it does not exist. Setting this object to active(1) when the status is notInService(2) causes the agent to commit the row. Setting this object to active(1) when its value is already active(1) is a no-op. Setting this object to destroy(6) will remove the corresponding VLAN encapsulation interface, remote the entry in this table, and remove the corresponding entry in the ifTable. In order for a set of this object to destroy(6) to succeed, all dependencies on this row must have been removed. These will include any references to this interface in the ifStackTable.')
a3ComNextAvailableVirtIfIndex = MibScalar((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 3, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: a3ComNextAvailableVirtIfIndex.setStatus('mandatory')
if mibBuilder.loadTexts: a3ComNextAvailableVirtIfIndex.setDescription("The value of the next available virtual ifIndex. This object is used by an NMS to select an index value for row-creation in tables indexed by ifIndex. The current value of this object is changed to a new value when the current value is written to an agent's table, that is indexed by ifIndex. Row creation using the current value of this object, allocates a virtual ifIndex. Note the following: 1. A newly created row does not have to be active(1) for the agent to allocate the virtual ifIndex. 2. Race conditions between multiple NMS's end when a row is created. Rows are deemed created when a setRequest is successfully committed (i.e. the errorStats is noError(0)). 3. An agent that exhausts its supply of virual ifIndex values returns zero as the value of this object. This can be used by an NMS as an indication to deleted unused rows and reboot the device.")
mibBuilder.exportSymbols("GENERIC-3COM-VLAN-MIB-1-0-7", a3ComVlanEncapsIfStatus=a3ComVlanEncapsIfStatus, a3ComEncapsulationGroup=a3ComEncapsulationGroup, A3ComVlanLayer3Type=A3ComVlanLayer3Type, a3ComVlanIfTable=a3ComVlanIfTable, generic=generic, a3ComIpVlanTable=a3ComIpVlanTable, a3ComVlanIfModeType=a3ComVlanIfModeType, a3ComVlanProtocolTable=a3ComVlanProtocolTable, a3ComVirtualGroup=a3ComVirtualGroup, A3ComVlanType=A3ComVlanType, a3ComIpVlanIpNetMask=a3ComIpVlanIpNetMask, a3ComVlanGlobalMappingTable=a3ComVlanGlobalMappingTable, a3ComVlanEncapsIfIndex=a3ComVlanEncapsIfIndex, a3ComIpVlanIpNetAddress=a3ComIpVlanIpNetAddress, a3ComVlanProtocolIndex=a3ComVlanProtocolIndex, a3ComVlanGlobalMappingEntry=a3ComVlanGlobalMappingEntry, a3ComVlanEncapsIfTag=a3ComVlanEncapsIfTag, a3ComVlanIfIndex=a3ComVlanIfIndex, a3ComNextAvailableVirtIfIndex=a3ComNextAvailableVirtIfIndex, a3ComVlanIfDescr=a3ComVlanIfDescr, a3ComVlanIfStatus=a3ComVlanIfStatus, a3ComVlanGlobalMappingIfIndex=a3ComVlanGlobalMappingIfIndex, a3ComVlanEncapsIfEntry=a3ComVlanEncapsIfEntry, a3ComVlanEncapsIfTable=a3ComVlanEncapsIfTable, a3ComVlanIfGlobalIdentifier=a3ComVlanIfGlobalIdentifier, a3ComVlanIfInfo=a3ComVlanIfInfo, a3ComVlanProtocolIfIndex=a3ComVlanProtocolIfIndex, genVirtual=genVirtual, RowStatus=RowStatus, a3ComIpVlanEntry=a3ComIpVlanEntry, a3ComVlanIfEntry=a3ComVlanIfEntry, a3ComVlanProtocolEntry=a3ComVlanProtocolEntry, A3ComVlanModeType=A3ComVlanModeType, a3ComIpVlanStatus=a3ComIpVlanStatus, a3Com=a3Com, a3ComVlanGroup=a3ComVlanGroup, a3ComVlanEncapsIfType=a3ComVlanEncapsIfType, a3ComVlanProtocolStatus=a3ComVlanProtocolStatus, a3ComVlanIfType=a3ComVlanIfType, a3ComVlanProtocolsGroup=a3ComVlanProtocolsGroup, A3ComVlanEncapsType=A3ComVlanEncapsType, a3ComVlanGlobalMappingIdentifier=a3ComVlanGlobalMappingIdentifier, genExperimental=genExperimental)
| (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, single_value_constraint, value_range_constraint, value_size_constraint, constraints_intersection) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsUnion', 'SingleValueConstraint', 'ValueRangeConstraint', 'ValueSizeConstraint', 'ConstraintsIntersection')
(module_compliance, notification_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'NotificationGroup')
(notification_type, counter32, integer32, object_identity, counter64, ip_address, mib_identifier, iso, module_identity, unsigned32, gauge32, time_ticks, mib_scalar, mib_table, mib_table_row, mib_table_column, bits, enterprises) = mibBuilder.importSymbols('SNMPv2-SMI', 'NotificationType', 'Counter32', 'Integer32', 'ObjectIdentity', 'Counter64', 'IpAddress', 'MibIdentifier', 'iso', 'ModuleIdentity', 'Unsigned32', 'Gauge32', 'TimeTicks', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'Bits', 'enterprises')
(textual_convention, display_string) = mibBuilder.importSymbols('SNMPv2-TC', 'TextualConvention', 'DisplayString')
class Rowstatus(Integer32):
subtype_spec = Integer32.subtypeSpec + constraints_union(single_value_constraint(1, 2, 3, 4, 5, 6))
named_values = named_values(('active', 1), ('notInService', 2), ('notReady', 3), ('createAndGo', 4), ('createAndWait', 5), ('destroy', 6))
a3_com = mib_identifier((1, 3, 6, 1, 4, 1, 43))
generic = mib_identifier((1, 3, 6, 1, 4, 1, 43, 10))
gen_experimental = mib_identifier((1, 3, 6, 1, 4, 1, 43, 10, 1))
gen_virtual = mib_identifier((1, 3, 6, 1, 4, 1, 43, 10, 1, 14))
a3_com_vlan_group = mib_identifier((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 1))
a3_com_vlan_protocols_group = mib_identifier((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 2))
a3_com_virtual_group = mib_identifier((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 3))
a3_com_encapsulation_group = mib_identifier((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 4))
class A3Comvlantype(Integer32):
subtype_spec = Integer32.subtypeSpec + constraints_union(single_value_constraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20))
named_values = named_values(('vlanLayer2', 1), ('vlanUnspecifiedProtocols', 2), ('vlanIPProtocol', 3), ('vlanIPXProtocol', 4), ('vlanAppleTalkProtocol', 5), ('vlanXNSProtocol', 6), ('vlanISOProtocol', 7), ('vlanDECNetProtocol', 8), ('vlanNetBIOSProtocol', 9), ('vlanSNAProtocol', 10), ('vlanVINESProtocol', 11), ('vlanX25Protocol', 12), ('vlanIGMPProtocol', 13), ('vlanSessionLayer', 14), ('vlanNetBeui', 15), ('vlanLayeredProtocols', 16), ('vlanIPXIIProtocol', 17), ('vlanIPX8022Protocol', 18), ('vlanIPX8023Protocol', 19), ('vlanIPX8022SNAPProtocol', 20))
class A3Comvlanlayer3Type(Integer32):
subtype_spec = Integer32.subtypeSpec + constraints_union(single_value_constraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13))
named_values = named_values(('vlanIPProtocol', 1), ('vlanIPXProtocol', 2), ('vlanAppleTalkProtocol', 3), ('vlanXNSProtocol', 4), ('vlanSNAProtocol', 5), ('vlanDECNetProtocol', 6), ('vlanNetBIOSProtocol', 7), ('vlanVINESProtocol', 8), ('vlanX25Protocol', 9), ('vlanIPXIIProtocol', 10), ('vlanIPX8022Protocol', 11), ('vlanIPX8023Protocol', 12), ('vlanIPX8022SNAPProtocol', 13))
class A3Comvlanmodetype(Integer32):
subtype_spec = Integer32.subtypeSpec + constraints_union(single_value_constraint(1, 2, 3))
named_values = named_values(('vlanUseDefault', 1), ('vlanOpen', 2), ('vlanClosed', 3))
a3_com_vlan_global_mapping_table = mib_table((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 1, 1))
if mibBuilder.loadTexts:
a3ComVlanGlobalMappingTable.setStatus('mandatory')
if mibBuilder.loadTexts:
a3ComVlanGlobalMappingTable.setDescription('This table lists VLAN interfaces that are globally identified. A single entry exists in this list for each VLAN interface in the system that is bound to a global identifier.')
a3_com_vlan_global_mapping_entry = mib_table_row((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 1, 1, 1)).setIndexNames((0, 'GENERIC-3COM-VLAN-MIB-1-0-7', 'a3ComVlanGlobalMappingIdentifier'))
if mibBuilder.loadTexts:
a3ComVlanGlobalMappingEntry.setStatus('mandatory')
if mibBuilder.loadTexts:
a3ComVlanGlobalMappingEntry.setDescription('An individual VLAN interface global mapping entry. Entries in this table are created by setting the a3ComVlanIfGlobalIdentifier object in the a3ComVlanIfTable to a non-zero value.')
a3_com_vlan_global_mapping_identifier = mib_table_column((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 1, 1, 1, 1), integer32().subtype(subtypeSpec=value_range_constraint(0, 65535)))
if mibBuilder.loadTexts:
a3ComVlanGlobalMappingIdentifier.setStatus('mandatory')
if mibBuilder.loadTexts:
a3ComVlanGlobalMappingIdentifier.setDescription('An index into the a3ComVlanGlobalMappingTable and an administratively assigned global VLAN identifier. The value of this object globally identifies the VLAN interface. For VLAN interfaces, on different network devices, which are part of the same globally identified VLAN, the value of this object will be the same.')
a3_com_vlan_global_mapping_if_index = mib_table_column((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 1, 1, 1, 2), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
a3ComVlanGlobalMappingIfIndex.setStatus('mandatory')
if mibBuilder.loadTexts:
a3ComVlanGlobalMappingIfIndex.setDescription('The value of a3ComVlanIfIndex for the VLAN interface in the a3ComVlanIfTable, which is bound to the global identifier specified by this entry.')
a3_com_vlan_if_table = mib_table((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 1, 2))
if mibBuilder.loadTexts:
a3ComVlanIfTable.setStatus('mandatory')
if mibBuilder.loadTexts:
a3ComVlanIfTable.setDescription('This table lists VLAN interfaces that exist within a device. A single entry exists in this list for each VLAN interface in the system. A VLAN interface may be created, destroyed and/or mapped to a globally identified vlan.')
a3_com_vlan_if_entry = mib_table_row((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 1, 2, 1)).setIndexNames((0, 'GENERIC-3COM-VLAN-MIB-1-0-7', 'a3ComVlanIfIndex'))
if mibBuilder.loadTexts:
a3ComVlanIfEntry.setStatus('mandatory')
if mibBuilder.loadTexts:
a3ComVlanIfEntry.setDescription('An individual VLAN interface entry. When an NMS wishes to create a new entry in this table, it must obtain a non-zero index from the a3ComNextAvailableVirtIfIndex object. Row creation in this table will fail if the chosen index value does not match the current value returned from the a3ComNextAvailableVirtIfIndex object.')
a3_com_vlan_if_index = mib_table_column((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 1, 2, 1, 1), integer32())
if mibBuilder.loadTexts:
a3ComVlanIfIndex.setStatus('mandatory')
if mibBuilder.loadTexts:
a3ComVlanIfIndex.setDescription("The index value of this row and the vlan's ifIndex in the ifTable. The NMS obtains the index value for this row by reading the a3ComNextAvailableVirtIfIndex object.")
a3_com_vlan_if_descr = mib_table_column((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 1, 2, 1, 2), display_string().subtype(subtypeSpec=value_size_constraint(0, 80))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
a3ComVlanIfDescr.setStatus('mandatory')
if mibBuilder.loadTexts:
a3ComVlanIfDescr.setDescription('This is a description of the VLAN interface.')
a3_com_vlan_if_type = mib_table_column((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 1, 2, 1, 3), a3_com_vlan_type()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
a3ComVlanIfType.setStatus('mandatory')
if mibBuilder.loadTexts:
a3ComVlanIfType.setDescription('The VLAN interface type.')
a3_com_vlan_if_global_identifier = mib_table_column((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 1, 2, 1, 4), integer32().subtype(subtypeSpec=value_range_constraint(0, 65535))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
a3ComVlanIfGlobalIdentifier.setStatus('mandatory')
if mibBuilder.loadTexts:
a3ComVlanIfGlobalIdentifier.setDescription('An administratively assigned global VLAN identifier. For VLAN interfaces, on different network devices, which are part of the same globally identified VLAN, the value of this object will be the same. The binding between a global identifier and a VLAN interface can be created or removed. To create a binding an NMS must write a non-zero value to this object. To delete a binding, the NMS must write a zero to this object.')
a3_com_vlan_if_info = mib_table_column((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 1, 2, 1, 5), octet_string()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
a3ComVlanIfInfo.setStatus('mandatory')
if mibBuilder.loadTexts:
a3ComVlanIfInfo.setDescription('A TLV encoded information string for the VLAN interface. The information contained within this string corresponds to VLAN information not contained within this table, but contained elsewhere within this MIB module. The purpose of this string is to provide an NMS with a quick read mechanism of all related VLAN interface information. The encoding rules are defined according to: tag = 2 bytes length = 2 bytes value = n bytes The following tags are defined: TAG OBJECT DESCRIPTION 1 a3ComIpVlanIpNetAddress IP Network Address of IP VLAN 2 a3ComIpVlanIpNetMask IP Network Mask of IP VLAN')
a3_com_vlan_if_status = mib_table_column((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 1, 2, 1, 6), row_status()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
a3ComVlanIfStatus.setStatus('mandatory')
if mibBuilder.loadTexts:
a3ComVlanIfStatus.setDescription('The status column for this VLAN interface. This OBJECT can be set to: active(1) createAndGo(4) createAndWait(5) destroy(6) The following values may be read: active(1) notInService(2) notReady(3). Setting this object to createAndGo(4) causes the agent to attempt to create and commit the row based on the contents of the objects in the row. If all necessary information is present in the row and the values are acceptible to the agent, the agent will change the status to active(1). If any of the necessary objects are not available, the agent will reject the creation request. Setting this object to createAndWait(5) causes a row in in this table to be created. The agent sets the status to notInService(2) if all of the information is present in the row and the values are acceptible to the agent; otherwise, the agent sets the status to notReady(3). Setting this object to active(1) is only valid when the current status is active(1) or notInService(2). When the state of the row transitions to active(1), the agent creates the corresponding row in the ifTable.. Setting this object to destroy(6) will remove the corresponding VLAN interface, remove the entry in this table, and the corresponding entries in the a3ComVlanGlobalMappingTable and the ifTable. In order for a set of this object to destroy(6) to succeed, all dependencies on this row must have been removed. These will include any stacking dependencies in the ifStackTable and any protocol specific tables dependencies.')
a3_com_vlan_if_mode_type = mib_table_column((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 1, 2, 1, 7), a3_com_vlan_mode_type()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
a3ComVlanIfModeType.setStatus('mandatory')
if mibBuilder.loadTexts:
a3ComVlanIfModeType.setDescription(' The VLAN mode type for this interface. This object can be set to: usedefault(1) open(2) closed(3) UseDefault Vlans: uses the bridge Vlan Mode value. The bridge Vlan Mode Value can be set to : Open, Closed or Mixed. Open VLANs: have no requirements about relationship between the bridge port that a frame was received upon and the bridge port(s) that it is transmitted on. All open VLANs within the bridge will share the same address table. Closed VLANs: require that the bridge port that a frame is received on is the same VLAN interface as the bridge port(s) that a frame is transmitted on. Each closed VLAN within the bridge will have its own address table.')
a3_com_ip_vlan_table = mib_table((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 2, 1))
if mibBuilder.loadTexts:
a3ComIpVlanTable.setStatus('mandatory')
if mibBuilder.loadTexts:
a3ComIpVlanTable.setDescription('A list of IP VLAN interface information entries. Entries in this table are related to entries in the a3ComVlanIfTable by using the same index.')
a3_com_ip_vlan_entry = mib_table_row((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 2, 1, 1)).setIndexNames((0, 'GENERIC-3COM-VLAN-MIB-1-0-7', 'a3ComVlanIfIndex'))
if mibBuilder.loadTexts:
a3ComIpVlanEntry.setStatus('mandatory')
if mibBuilder.loadTexts:
a3ComIpVlanEntry.setDescription('A a3ComIpVlanEntry contains layer 3 information about a particular IP VLAN interface. Note entries in this table cannot be deleted until the entries in the ifStackTable that produce overlap are removed.')
a3_com_ip_vlan_ip_net_address = mib_table_column((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 2, 1, 1, 1), ip_address()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
a3ComIpVlanIpNetAddress.setStatus('mandatory')
if mibBuilder.loadTexts:
a3ComIpVlanIpNetAddress.setDescription('The IP network number for the IP VLAN interface defined in the a3ComVlanIfTable identified with the same index. The IpNetAdress and the IpNetMask must be set and the the row creation process completed by a NMS before overlapping rows in the ifStackTable can be created. Sets to the ifStackTable that produce overlapping IP IP VLAN interfaces will fail if this object is not set.')
a3_com_ip_vlan_ip_net_mask = mib_table_column((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 2, 1, 1, 2), ip_address()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
a3ComIpVlanIpNetMask.setStatus('mandatory')
if mibBuilder.loadTexts:
a3ComIpVlanIpNetMask.setDescription('The IP network mask corresponding to the IP Network address defined by a3ComIpVlanIpNetAddress. The IpNetAdress and the IpNetMask must be set and the row creation process completed by a NMS before overlapping rows in the ifStackTable can be created. Sets to the ifStackTable that produce overlapping IP VLAN interfaces will fail if this object is not set.')
a3_com_ip_vlan_status = mib_table_column((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 2, 1, 1, 3), row_status()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
a3ComIpVlanStatus.setStatus('mandatory')
if mibBuilder.loadTexts:
a3ComIpVlanStatus.setDescription('The status column for this IP VLAN entry. This object can be set to: active(1) createAndGo(4) createAndWait(5) destroy(6) The following values may be read: active(1) notInService(2) notReady(3). Setting this object to createAndGo(4) causes the agent to attempt to create and commit the row based on the contents of the objects in the row. If all necessary information is present in the row and the values are acceptible to the agent, the agent will change the status to active(1). If any of the necessary objects are not available, the agent will reject the row creation request. Setting this object to createAndWait(5) causes a row in in this table to be created. The agent sets the status to notInService(2) if all of the information is present in the row and the values are acceptible to the agent; otherwise, the agent sets the status to notReady(3). Setting this object to active(1) is only valid when the current status is active(1) or notInService(2). When the status changes to active(1), the agent applies the IP parmeters to the IP VLAN interface identified by the corresponding value of the a3ComIpVlanIndex object. Setting this object to destroy(6) will remove the IP parmeters from the IP VLAN interface and remove the entry from this table. Setting this object to destroy(6) will remove the layer 3 information from the IP VLAN interface and will remove the row from this table. Note that this action cannot be performed if there are ifStackTable entries that result in overlapping IP VLAN interfaces. Note that these dependencies must be removed first.')
a3_com_vlan_protocol_table = mib_table((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 2, 2))
if mibBuilder.loadTexts:
a3ComVlanProtocolTable.setStatus('mandatory')
if mibBuilder.loadTexts:
a3ComVlanProtocolTable.setDescription('This table lists the configured protocols per Vlan. A single entry exists in this list for each protocol configured on a VLAN interface. The a3ComVlanIfType object in a3ComVlanIfTable has to be set to vlanLayeredProtocols in order to use this table.')
a3_com_vlan_protocol_entry = mib_table_row((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 2, 2, 1)).setIndexNames((0, 'GENERIC-3COM-VLAN-MIB-1-0-7', 'a3ComVlanProtocolIfIndex'), (0, 'GENERIC-3COM-VLAN-MIB-1-0-7', 'a3ComVlanProtocolIndex'))
if mibBuilder.loadTexts:
a3ComVlanProtocolEntry.setStatus('mandatory')
if mibBuilder.loadTexts:
a3ComVlanProtocolEntry.setDescription('A a3ComVlanProtocolEntry contains a single VLAN to protocol entry.')
a3_com_vlan_protocol_if_index = mib_table_column((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 2, 2, 1, 1), integer32())
if mibBuilder.loadTexts:
a3ComVlanProtocolIfIndex.setStatus('mandatory')
if mibBuilder.loadTexts:
a3ComVlanProtocolIfIndex.setDescription("The first indice of this row and the vlan's ifIndex in the ifTable. The value of this object is the same as the corresponding a3ComVlanIfIndex in the a3ComVlanTable.")
a3_com_vlan_protocol_index = mib_table_column((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 2, 2, 1, 2), a3_com_vlan_layer3_type())
if mibBuilder.loadTexts:
a3ComVlanProtocolIndex.setStatus('mandatory')
if mibBuilder.loadTexts:
a3ComVlanProtocolIndex.setDescription('The second indice of this row, which identifies one of possible many protocols associated with the VLAN interface identified by this entries first indice. The values are based on the layer 3 protocols specified in A3ComVlanType')
a3_com_vlan_protocol_status = mib_table_column((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 2, 2, 1, 3), row_status()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
a3ComVlanProtocolStatus.setStatus('mandatory')
if mibBuilder.loadTexts:
a3ComVlanProtocolStatus.setDescription('The status column for this VLAN interface. This OBJECT can be set to: active(1) createAndGo(4) createAndWait(5) destroy(6) The following values may be read: active(1) notInService(2) notReady(3). Setting this object to createAndGo(4) causes the agent to attempt to create and commit the row based on the contents of the objects in the row. If all necessary information is present in the row and the values are acceptible to the agent, the agent will change the status to active(1). If any of the necessary objects are not available, the agent will reject the creation request. Setting this object to createAndWait(5) causes a row in this table to be created. The agent sets the status to notInService(2) if all of the information is present in the row and the values are acceptable to the agent; otherwise, the agent sets the status to notReady(3). Setting this object to active(1) is only valid when the current status is active(1) or notInService(2). Row creation to this table is only possible when a corresponding VLAN entry has been created in the a3ComVlanTable with an a3ComVlanType set to vlanLayeredProtocols(16). Setting this object to destroy(6) will remove the corresponding VLAN interface to protocol mapping.')
class A3Comvlanencapstype(Integer32):
subtype_spec = Integer32.subtypeSpec + constraints_union(single_value_constraint(1, 2, 3))
named_values = named_values(('vlanEncaps3ComProprietaryVLT', 1), ('vlanEncaps8021q', 2), ('vlanEncapsPre8021qONcore', 3))
a3_com_vlan_encaps_if_table = mib_table((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 4, 1))
if mibBuilder.loadTexts:
a3ComVlanEncapsIfTable.setStatus('mandatory')
if mibBuilder.loadTexts:
a3ComVlanEncapsIfTable.setDescription('This table lists VLAN encapsulation interfaces that exist within a device. A single entry exists in this list for each VLAN encapsulation interface in the system. A VLAN encapsulation interface may be created or destroyed.')
a3_com_vlan_encaps_if_entry = mib_table_row((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 4, 1, 1)).setIndexNames((0, 'GENERIC-3COM-VLAN-MIB-1-0-7', 'a3ComVlanEncapsIfIndex'))
if mibBuilder.loadTexts:
a3ComVlanEncapsIfEntry.setStatus('mandatory')
if mibBuilder.loadTexts:
a3ComVlanEncapsIfEntry.setDescription('An individual VLAN encapsulation interface entry. When an NMS wishes to create a new entry in this table, it must obtain a non-zero index from the a3ComNextAvailableVirtIfIndex object. Row creation in this table will fail if the chosen index value does not match the current value returned from the a3ComNextAvailableVirtIfIndex object.')
a3_com_vlan_encaps_if_index = mib_table_column((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 4, 1, 1, 1), integer32())
if mibBuilder.loadTexts:
a3ComVlanEncapsIfIndex.setStatus('mandatory')
if mibBuilder.loadTexts:
a3ComVlanEncapsIfIndex.setDescription("The index value of this row and the encapsulation interface's ifIndex in the ifTable. The NMS obtains the index value used for creating a row in this table by reading the a3ComNextAvailableVirtIfIndex object.")
a3_com_vlan_encaps_if_type = mib_table_column((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 4, 1, 1, 2), a3_com_vlan_encaps_type()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
a3ComVlanEncapsIfType.setStatus('mandatory')
if mibBuilder.loadTexts:
a3ComVlanEncapsIfType.setDescription('The encapsulation algorithm used when encapsulating packets transmitted, or de-encapsulating packets received through this interface.')
a3_com_vlan_encaps_if_tag = mib_table_column((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 4, 1, 1, 3), integer32()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
a3ComVlanEncapsIfTag.setStatus('mandatory')
if mibBuilder.loadTexts:
a3ComVlanEncapsIfTag.setDescription('The tag used when encapsulating packets transmitted, or de-encapsulating packets received through this interface.')
a3_com_vlan_encaps_if_status = mib_table_column((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 4, 1, 1, 4), row_status()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
a3ComVlanEncapsIfStatus.setStatus('mandatory')
if mibBuilder.loadTexts:
a3ComVlanEncapsIfStatus.setDescription('The row status for this VLAN encapsulation interface. This OBJECT can be set to: active(1) createAndGo(4) createAndWait(5) destroy(6) The following values may be read: active(1) notReady(3). In order for a row to become active, the NMS must set a3ComVlanEncapsIfTagType and a3ComVlanEncapsIfTag to some valid and consistent values. Setting this object to createAndGo(4) causes the agent to attempt to create and commit the row based on the contents of the objects in the row. If all necessary information is present in the row, the agent will create the row and change the status to active(1). If any of the necessary objects are not available, or specify an invalid configuration, the row will not be created and the agent will return an appropriate error. Setting this object to createAndWait(5) causes a row in in this table to be created. If all necessary objects in the row have been assigned values and specify a valid configuration, the status of the row will be set to notInService(2); otherwise, the status will be set to notReady(3). This object may only be set to createAndGo(4) or createAndWait(5) if it does not exist. Setting this object to active(1) when the status is notInService(2) causes the agent to commit the row. Setting this object to active(1) when its value is already active(1) is a no-op. Setting this object to destroy(6) will remove the corresponding VLAN encapsulation interface, remote the entry in this table, and remove the corresponding entry in the ifTable. In order for a set of this object to destroy(6) to succeed, all dependencies on this row must have been removed. These will include any references to this interface in the ifStackTable.')
a3_com_next_available_virt_if_index = mib_scalar((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 3, 1), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
a3ComNextAvailableVirtIfIndex.setStatus('mandatory')
if mibBuilder.loadTexts:
a3ComNextAvailableVirtIfIndex.setDescription("The value of the next available virtual ifIndex. This object is used by an NMS to select an index value for row-creation in tables indexed by ifIndex. The current value of this object is changed to a new value when the current value is written to an agent's table, that is indexed by ifIndex. Row creation using the current value of this object, allocates a virtual ifIndex. Note the following: 1. A newly created row does not have to be active(1) for the agent to allocate the virtual ifIndex. 2. Race conditions between multiple NMS's end when a row is created. Rows are deemed created when a setRequest is successfully committed (i.e. the errorStats is noError(0)). 3. An agent that exhausts its supply of virual ifIndex values returns zero as the value of this object. This can be used by an NMS as an indication to deleted unused rows and reboot the device.")
mibBuilder.exportSymbols('GENERIC-3COM-VLAN-MIB-1-0-7', a3ComVlanEncapsIfStatus=a3ComVlanEncapsIfStatus, a3ComEncapsulationGroup=a3ComEncapsulationGroup, A3ComVlanLayer3Type=A3ComVlanLayer3Type, a3ComVlanIfTable=a3ComVlanIfTable, generic=generic, a3ComIpVlanTable=a3ComIpVlanTable, a3ComVlanIfModeType=a3ComVlanIfModeType, a3ComVlanProtocolTable=a3ComVlanProtocolTable, a3ComVirtualGroup=a3ComVirtualGroup, A3ComVlanType=A3ComVlanType, a3ComIpVlanIpNetMask=a3ComIpVlanIpNetMask, a3ComVlanGlobalMappingTable=a3ComVlanGlobalMappingTable, a3ComVlanEncapsIfIndex=a3ComVlanEncapsIfIndex, a3ComIpVlanIpNetAddress=a3ComIpVlanIpNetAddress, a3ComVlanProtocolIndex=a3ComVlanProtocolIndex, a3ComVlanGlobalMappingEntry=a3ComVlanGlobalMappingEntry, a3ComVlanEncapsIfTag=a3ComVlanEncapsIfTag, a3ComVlanIfIndex=a3ComVlanIfIndex, a3ComNextAvailableVirtIfIndex=a3ComNextAvailableVirtIfIndex, a3ComVlanIfDescr=a3ComVlanIfDescr, a3ComVlanIfStatus=a3ComVlanIfStatus, a3ComVlanGlobalMappingIfIndex=a3ComVlanGlobalMappingIfIndex, a3ComVlanEncapsIfEntry=a3ComVlanEncapsIfEntry, a3ComVlanEncapsIfTable=a3ComVlanEncapsIfTable, a3ComVlanIfGlobalIdentifier=a3ComVlanIfGlobalIdentifier, a3ComVlanIfInfo=a3ComVlanIfInfo, a3ComVlanProtocolIfIndex=a3ComVlanProtocolIfIndex, genVirtual=genVirtual, RowStatus=RowStatus, a3ComIpVlanEntry=a3ComIpVlanEntry, a3ComVlanIfEntry=a3ComVlanIfEntry, a3ComVlanProtocolEntry=a3ComVlanProtocolEntry, A3ComVlanModeType=A3ComVlanModeType, a3ComIpVlanStatus=a3ComIpVlanStatus, a3Com=a3Com, a3ComVlanGroup=a3ComVlanGroup, a3ComVlanEncapsIfType=a3ComVlanEncapsIfType, a3ComVlanProtocolStatus=a3ComVlanProtocolStatus, a3ComVlanIfType=a3ComVlanIfType, a3ComVlanProtocolsGroup=a3ComVlanProtocolsGroup, A3ComVlanEncapsType=A3ComVlanEncapsType, a3ComVlanGlobalMappingIdentifier=a3ComVlanGlobalMappingIdentifier, genExperimental=genExperimental) |
"""
User configuration file for the client.
"""
SERVER_ADDRESS = "127.0.0.1"
SERVER_PORT = 50000
| """
User configuration file for the client.
"""
server_address = '127.0.0.1'
server_port = 50000 |
# PROBLEM
#
# Assume s is a string of lower case characters.
#
# Write a program that prints the longest substring of s in which the letters
# occur in alphabetical order. For example, if s = 'azcbobobegghakl', then your
# program should print:
#
# 'Longest substring in alphabetical order is: beggh'
#
# In case of ties, print the first substring. For example, if s = 'abcbcd',
# then your program should print:
#
# 'Longest substring in alphabetical order is: abc'
# For test purposes
s = 'azcbobobegghakl'
# SOLUTION
if len(s) > 1:
substring = s[0]
length = 1
# Store initial solution
bestsubstring = substring
bestlength = length
for num in range(len(s)-1): # Last letter is checked by 2nd-last letter
if s[num] <= s[num+1]:
substring = substring + s[num+1]
length += 1
if length > bestlength:
bestsubstring = substring
bestlength = length
else: # Reset substring and length
substring = s[num+1]
length = 1
else:
bestsubstring = s
print ('Longest substring in alphabetical order is: ' + bestsubstring)
| s = 'azcbobobegghakl'
if len(s) > 1:
substring = s[0]
length = 1
bestsubstring = substring
bestlength = length
for num in range(len(s) - 1):
if s[num] <= s[num + 1]:
substring = substring + s[num + 1]
length += 1
if length > bestlength:
bestsubstring = substring
bestlength = length
else:
substring = s[num + 1]
length = 1
else:
bestsubstring = s
print('Longest substring in alphabetical order is: ' + bestsubstring) |
mandatory = \
{
'article' : ['ENTRYTYPE', 'ID', 'author', 'title', 'journal', 'year', 'volume'],
'book' : ['ENTRYTYPE', 'ID', 'title', 'publisher', 'year'],
'booklet' : ['ENTRYTYPE', 'ID', 'title', 'year'],
'conference' : ['ENTRYTYPE', 'ID', 'author', 'title', 'booktitle', 'publisher', 'year'],
'inbook' : ['ENTRYTYPE', 'ID', 'title', 'publisher', 'year'],
'incollection' : ['ENTRYTYPE', 'ID', 'author', 'title', 'booktitle', 'publisher', 'year'],
'inproceedings' : ['ENTRYTYPE', 'ID', 'author', 'title', 'booktitle', 'year'],
'manual' : ['ENTRYTYPE', 'ID', 'title', 'year'],
'mastersthesis' : ['ENTRYTYPE', 'ID', 'author', 'title', 'school', 'year'],
'misc' : ['ENTRYTYPE', 'ID', 'title', 'year'],
'phdthesis' : ['ENTRYTYPE', 'ID', 'author', 'title', 'school', 'year'],
'proceedings' : ['ENTRYTYPE', 'ID', 'title', 'year'],
'techreport' : ['ENTRYTYPE', 'ID', 'author', 'title', 'institution', 'year'],
'unpublished' : ['ENTRYTYPE', 'ID', 'author', 'title', 'note']
} | mandatory = {'article': ['ENTRYTYPE', 'ID', 'author', 'title', 'journal', 'year', 'volume'], 'book': ['ENTRYTYPE', 'ID', 'title', 'publisher', 'year'], 'booklet': ['ENTRYTYPE', 'ID', 'title', 'year'], 'conference': ['ENTRYTYPE', 'ID', 'author', 'title', 'booktitle', 'publisher', 'year'], 'inbook': ['ENTRYTYPE', 'ID', 'title', 'publisher', 'year'], 'incollection': ['ENTRYTYPE', 'ID', 'author', 'title', 'booktitle', 'publisher', 'year'], 'inproceedings': ['ENTRYTYPE', 'ID', 'author', 'title', 'booktitle', 'year'], 'manual': ['ENTRYTYPE', 'ID', 'title', 'year'], 'mastersthesis': ['ENTRYTYPE', 'ID', 'author', 'title', 'school', 'year'], 'misc': ['ENTRYTYPE', 'ID', 'title', 'year'], 'phdthesis': ['ENTRYTYPE', 'ID', 'author', 'title', 'school', 'year'], 'proceedings': ['ENTRYTYPE', 'ID', 'title', 'year'], 'techreport': ['ENTRYTYPE', 'ID', 'author', 'title', 'institution', 'year'], 'unpublished': ['ENTRYTYPE', 'ID', 'author', 'title', 'note']} |
class ParkingLot:
def __init__(self, username, latitude, longitude, totalSpace, costHour):
self.username = username
self.latitude = latitude
self.longitude = longitude
self.totalSpace = totalSpace
self.availableSpace = totalSpace
self.costHour = costHour
def getSpace(self):
return self.availableSpace
def setBook(self):
self.availableSpace -= 1
class signUp:
def __init__(self, username, password):
self.username = username
self.password = password
# def getDetails():
| class Parkinglot:
def __init__(self, username, latitude, longitude, totalSpace, costHour):
self.username = username
self.latitude = latitude
self.longitude = longitude
self.totalSpace = totalSpace
self.availableSpace = totalSpace
self.costHour = costHour
def get_space(self):
return self.availableSpace
def set_book(self):
self.availableSpace -= 1
class Signup:
def __init__(self, username, password):
self.username = username
self.password = password |
class AnalyticalModelStick(AnalyticalModel,IDisposable):
"""
An element that represents a stick in the structural analytical model.
Could be one of beam,brace or column type.
"""
def Dispose(self):
""" Dispose(self: Element,A_0: bool) """
pass
def GetAlignmentMethod(self,selector):
"""
GetAlignmentMethod(self: AnalyticalModelStick,selector: AnalyticalElementSelector) -> AnalyticalAlignmentMethod
Gets the alignment method for a given selector.
selector: End of the analytical model.
Returns: The alignment method at a given end.
"""
pass
def getBoundingBox(self,*args):
""" getBoundingBox(self: Element,view: View) -> BoundingBoxXYZ """
pass
def GetLocalCoordinateSystem(self,*__args):
"""
GetLocalCoordinateSystem(self: AnalyticalModelStick,point: XYZ) -> Transform
Gets the local coordinate system (LCS) reflects analytical model orientation at
the specified point.
point: The point on the analytical model stick element.
Returns: Transformation matrix.
x - longitudinal axis,y - transversal,section -
horizontal,strong axis,z - transversal,section - vertical,weak axis,origin
- base point of LCS.
GetLocalCoordinateSystem(self: AnalyticalModelStick,parameter: float) -> Transform
Gets the local coordinate system (LCS) reflects analytical model orientation at
the specified parameter value along a curve.
parameter: The parameter value along a curve that should be in the range [0,1],where 0
represents start and 1 represents end of the element.
Returns: Transformation matrix.
x - longitudinal axis,y - transversal,section -
horizontal,strong axis,z - transversal,section - vertical,weak axis,origin
- base point of LCS.
"""
pass
def GetMemberForces(self):
"""
GetMemberForces(self: AnalyticalModelStick) -> IList[MemberForces]
Gets the member forces associated with this element.
Returns: Returns a collection of Member Forces associated with this element. Empty
collection will be returned if element doesn't have any Member Forces.
To
find out with which end member forces are associated use
Autodesk::Revit::DB::Structure::MemberForces::Position
property to obtain a
position of Member Forces on element.
"""
pass
def GetProjectionPlaneY(self,selector):
"""
GetProjectionPlaneY(self: AnalyticalModelStick,selector: AnalyticalElementSelector) -> ElementId
Retrieves analytical model projection information for Y direction.
selector: End of the analytical model.
Returns: Plane on to which analytical model is projected,or invalidElementId if
not
projected to a Plane.
"""
pass
def GetProjectionPlaneZ(self,selector):
"""
GetProjectionPlaneZ(self: AnalyticalModelStick,selector: AnalyticalElementSelector) -> ElementId
Retrieves analytical model projection information for Z direction.
selector: End of the analytical model.
Returns: Plane on to which analytical model is projected,or invalidElementId if
not
projected to a Plane.
"""
pass
def GetProjectionY(self,selector):
"""
GetProjectionY(self: AnalyticalModelStick,selector: AnalyticalElementSelector) -> StickElementProjectionY
Retrieves analytical model projection information for Y direction.
selector: End of the analytical model.
Returns: Indicates if the projection is a preset value,or refers to a Plane.
"""
pass
def GetProjectionZ(self,selector):
"""
GetProjectionZ(self: AnalyticalModelStick,selector: AnalyticalElementSelector) -> StickElementProjectionZ
Retrieves analytical model projection information for Z direction.
selector: End of the analytical model.
Returns: Indicates if the projection is a preset value,or refers to a Plane.
"""
pass
def GetReleases(self,start,fx,fy,fz,mx,my,mz):
"""
GetReleases(self: AnalyticalModelStick,start: bool) -> (bool,bool,bool,bool,bool,bool)
Gets the releases of element.
start: The position on analytical model stick element. True for start,false for end.
"""
pass
def GetReleaseType(self,start):
"""
GetReleaseType(self: AnalyticalModelStick,start: bool) -> ReleaseType
Gets the release type.
start: The position on analytical model stick element. True for start,false for end.
Returns: The type of release.
"""
pass
def ReleaseUnmanagedResources(self,*args):
""" ReleaseUnmanagedResources(self: Element,disposing: bool) """
pass
def RemoveAllMemberForces(self):
"""
RemoveAllMemberForces(self: AnalyticalModelStick) -> bool
Removes all member forces associated with element.
Returns: True if any member forces were removed,false otherwise.
"""
pass
def RemoveMemberForces(self,start):
"""
RemoveMemberForces(self: AnalyticalModelStick,start: bool) -> bool
Removes member forces defined for given position.
start: Member Forces position on analytical model stick element. True for start,false
for end.
Returns: True if member forces for provided position were removed,false otherwise.
"""
pass
def SetAlignmentMethod(self,selector,method):
"""
SetAlignmentMethod(self: AnalyticalModelStick,selector: AnalyticalElementSelector,method: AnalyticalAlignmentMethod)
Sets the alignment method for a given selector.
selector: End of the analytical model.
method: The alignment method at a given end.
"""
pass
def setElementType(self,*args):
""" setElementType(self: Element,type: ElementType,incompatibleExceptionMessage: str) """
pass
def SetMemberForces(self,*__args):
"""
SetMemberForces(self: AnalyticalModelStick,start: bool,force: XYZ,moment: XYZ)
Adds Member Forces to element.
start: Member Forces position on analytical model stick element. True for start,false
for end.
force: The translational forces at specified position of the element.
The x value
of XYZ object represents force along x-axis of the analytical model coordinate
system,y along y-axis,z along z-axis respectively.
moment: The rotational forces at specified position of the element.
The x value of
XYZ object represents moment about x-axis of the analytical model coordinate
system,y about y-axis,z about z-axis respectively.
SetMemberForces(self: AnalyticalModelStick,memberForces: MemberForces)
Sets Member Forces to element.
memberForces: End to which member forces will be added is defined by setting
Autodesk::Revit::DB::Structure::MemberForces::Position
property in provided
Member Forces object.
"""
pass
def SetProjection(self,selector,*__args):
"""
SetProjection(self: AnalyticalModelStick,selector: AnalyticalElementSelector,planeIdY: ElementId,projectionZ: StickElementProjectionZ)
Sets the analytical model projection to a preset value.
selector: End of the analytical model.
planeIdY: Plane on to which analytical model may be projected in Y direction.
Plane
identifies a Level,a Grid,or a Ref Plane.
projectionZ: Preset value for Analytical Model Stick projection Z.
SetProjection(self: AnalyticalModelStick,selector: AnalyticalElementSelector,projectionY: StickElementProjectionY,projectionZ: StickElementProjectionZ)
Sets the analytical model projection to a preset value.
selector: End of the analytical model.
projectionY: Preset value for Analytical Model Stick projection Y.
projectionZ: Preset value for Analytical Model Stick projection Z.
SetProjection(self: AnalyticalModelStick,selector: AnalyticalElementSelector,planeIdY: ElementId,planeIdZ: ElementId)
Sets the analytical model projection to a preset value.
selector: End of the analytical model.
planeIdY: Plane on to which analytical model may be projected in Y direction.
Plane
identifies a Level,a Grid,or a Ref Plane.
planeIdZ: Plane on to which analytical model may be projected in Z direction.
Plane
identifies a Level,a Grid,or a Ref Plane.
SetProjection(self: AnalyticalModelStick,selector: AnalyticalElementSelector,projectionY: StickElementProjectionY,planeIdZ: ElementId)
Sets the analytical model projection to a preset value.
selector: End of the analytical model.
projectionY: Preset value for Analytical Model Stick projection Y.
planeIdZ: Plane on to which analytical model may be projected in Z direction.
Plane
identifies a Level,a Grid,or a Ref Plane.
"""
pass
def SetReleases(self,start,fx,fy,fz,mx,my,mz):
"""
SetReleases(self: AnalyticalModelStick,start: bool,fx: bool,fy: bool,fz: bool,mx: bool,my: bool,mz: bool)
Sets the releases of element.
start: The position on analytical model stick element. True for start,false for end.
"""
pass
def SetReleaseType(self,start,releaseType):
"""
SetReleaseType(self: AnalyticalModelStick,start: bool,releaseType: ReleaseType)
Sets the release type.
start: The position on analytical model stick element. True for start,false for end.
releaseType: The type of release.
"""
pass
def __enter__(self,*args):
""" __enter__(self: IDisposable) -> object """
pass
def __exit__(self,*args):
""" __exit__(self: IDisposable,exc_type: object,exc_value: object,exc_back: object) """
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
| class Analyticalmodelstick(AnalyticalModel, IDisposable):
"""
An element that represents a stick in the structural analytical model.
Could be one of beam,brace or column type.
"""
def dispose(self):
""" Dispose(self: Element,A_0: bool) """
pass
def get_alignment_method(self, selector):
"""
GetAlignmentMethod(self: AnalyticalModelStick,selector: AnalyticalElementSelector) -> AnalyticalAlignmentMethod
Gets the alignment method for a given selector.
selector: End of the analytical model.
Returns: The alignment method at a given end.
"""
pass
def get_bounding_box(self, *args):
""" getBoundingBox(self: Element,view: View) -> BoundingBoxXYZ """
pass
def get_local_coordinate_system(self, *__args):
"""
GetLocalCoordinateSystem(self: AnalyticalModelStick,point: XYZ) -> Transform
Gets the local coordinate system (LCS) reflects analytical model orientation at
the specified point.
point: The point on the analytical model stick element.
Returns: Transformation matrix.
x - longitudinal axis,y - transversal,section -
horizontal,strong axis,z - transversal,section - vertical,weak axis,origin
- base point of LCS.
GetLocalCoordinateSystem(self: AnalyticalModelStick,parameter: float) -> Transform
Gets the local coordinate system (LCS) reflects analytical model orientation at
the specified parameter value along a curve.
parameter: The parameter value along a curve that should be in the range [0,1],where 0
represents start and 1 represents end of the element.
Returns: Transformation matrix.
x - longitudinal axis,y - transversal,section -
horizontal,strong axis,z - transversal,section - vertical,weak axis,origin
- base point of LCS.
"""
pass
def get_member_forces(self):
"""
GetMemberForces(self: AnalyticalModelStick) -> IList[MemberForces]
Gets the member forces associated with this element.
Returns: Returns a collection of Member Forces associated with this element. Empty
collection will be returned if element doesn't have any Member Forces.
To
find out with which end member forces are associated use
Autodesk::Revit::DB::Structure::MemberForces::Position
property to obtain a
position of Member Forces on element.
"""
pass
def get_projection_plane_y(self, selector):
"""
GetProjectionPlaneY(self: AnalyticalModelStick,selector: AnalyticalElementSelector) -> ElementId
Retrieves analytical model projection information for Y direction.
selector: End of the analytical model.
Returns: Plane on to which analytical model is projected,or invalidElementId if
not
projected to a Plane.
"""
pass
def get_projection_plane_z(self, selector):
"""
GetProjectionPlaneZ(self: AnalyticalModelStick,selector: AnalyticalElementSelector) -> ElementId
Retrieves analytical model projection information for Z direction.
selector: End of the analytical model.
Returns: Plane on to which analytical model is projected,or invalidElementId if
not
projected to a Plane.
"""
pass
def get_projection_y(self, selector):
"""
GetProjectionY(self: AnalyticalModelStick,selector: AnalyticalElementSelector) -> StickElementProjectionY
Retrieves analytical model projection information for Y direction.
selector: End of the analytical model.
Returns: Indicates if the projection is a preset value,or refers to a Plane.
"""
pass
def get_projection_z(self, selector):
"""
GetProjectionZ(self: AnalyticalModelStick,selector: AnalyticalElementSelector) -> StickElementProjectionZ
Retrieves analytical model projection information for Z direction.
selector: End of the analytical model.
Returns: Indicates if the projection is a preset value,or refers to a Plane.
"""
pass
def get_releases(self, start, fx, fy, fz, mx, my, mz):
"""
GetReleases(self: AnalyticalModelStick,start: bool) -> (bool,bool,bool,bool,bool,bool)
Gets the releases of element.
start: The position on analytical model stick element. True for start,false for end.
"""
pass
def get_release_type(self, start):
"""
GetReleaseType(self: AnalyticalModelStick,start: bool) -> ReleaseType
Gets the release type.
start: The position on analytical model stick element. True for start,false for end.
Returns: The type of release.
"""
pass
def release_unmanaged_resources(self, *args):
""" ReleaseUnmanagedResources(self: Element,disposing: bool) """
pass
def remove_all_member_forces(self):
"""
RemoveAllMemberForces(self: AnalyticalModelStick) -> bool
Removes all member forces associated with element.
Returns: True if any member forces were removed,false otherwise.
"""
pass
def remove_member_forces(self, start):
"""
RemoveMemberForces(self: AnalyticalModelStick,start: bool) -> bool
Removes member forces defined for given position.
start: Member Forces position on analytical model stick element. True for start,false
for end.
Returns: True if member forces for provided position were removed,false otherwise.
"""
pass
def set_alignment_method(self, selector, method):
"""
SetAlignmentMethod(self: AnalyticalModelStick,selector: AnalyticalElementSelector,method: AnalyticalAlignmentMethod)
Sets the alignment method for a given selector.
selector: End of the analytical model.
method: The alignment method at a given end.
"""
pass
def set_element_type(self, *args):
""" setElementType(self: Element,type: ElementType,incompatibleExceptionMessage: str) """
pass
def set_member_forces(self, *__args):
"""
SetMemberForces(self: AnalyticalModelStick,start: bool,force: XYZ,moment: XYZ)
Adds Member Forces to element.
start: Member Forces position on analytical model stick element. True for start,false
for end.
force: The translational forces at specified position of the element.
The x value
of XYZ object represents force along x-axis of the analytical model coordinate
system,y along y-axis,z along z-axis respectively.
moment: The rotational forces at specified position of the element.
The x value of
XYZ object represents moment about x-axis of the analytical model coordinate
system,y about y-axis,z about z-axis respectively.
SetMemberForces(self: AnalyticalModelStick,memberForces: MemberForces)
Sets Member Forces to element.
memberForces: End to which member forces will be added is defined by setting
Autodesk::Revit::DB::Structure::MemberForces::Position
property in provided
Member Forces object.
"""
pass
def set_projection(self, selector, *__args):
"""
SetProjection(self: AnalyticalModelStick,selector: AnalyticalElementSelector,planeIdY: ElementId,projectionZ: StickElementProjectionZ)
Sets the analytical model projection to a preset value.
selector: End of the analytical model.
planeIdY: Plane on to which analytical model may be projected in Y direction.
Plane
identifies a Level,a Grid,or a Ref Plane.
projectionZ: Preset value for Analytical Model Stick projection Z.
SetProjection(self: AnalyticalModelStick,selector: AnalyticalElementSelector,projectionY: StickElementProjectionY,projectionZ: StickElementProjectionZ)
Sets the analytical model projection to a preset value.
selector: End of the analytical model.
projectionY: Preset value for Analytical Model Stick projection Y.
projectionZ: Preset value for Analytical Model Stick projection Z.
SetProjection(self: AnalyticalModelStick,selector: AnalyticalElementSelector,planeIdY: ElementId,planeIdZ: ElementId)
Sets the analytical model projection to a preset value.
selector: End of the analytical model.
planeIdY: Plane on to which analytical model may be projected in Y direction.
Plane
identifies a Level,a Grid,or a Ref Plane.
planeIdZ: Plane on to which analytical model may be projected in Z direction.
Plane
identifies a Level,a Grid,or a Ref Plane.
SetProjection(self: AnalyticalModelStick,selector: AnalyticalElementSelector,projectionY: StickElementProjectionY,planeIdZ: ElementId)
Sets the analytical model projection to a preset value.
selector: End of the analytical model.
projectionY: Preset value for Analytical Model Stick projection Y.
planeIdZ: Plane on to which analytical model may be projected in Z direction.
Plane
identifies a Level,a Grid,or a Ref Plane.
"""
pass
def set_releases(self, start, fx, fy, fz, mx, my, mz):
"""
SetReleases(self: AnalyticalModelStick,start: bool,fx: bool,fy: bool,fz: bool,mx: bool,my: bool,mz: bool)
Sets the releases of element.
start: The position on analytical model stick element. True for start,false for end.
"""
pass
def set_release_type(self, start, releaseType):
"""
SetReleaseType(self: AnalyticalModelStick,start: bool,releaseType: ReleaseType)
Sets the release type.
start: The position on analytical model stick element. True for start,false for end.
releaseType: The type of release.
"""
pass
def __enter__(self, *args):
""" __enter__(self: IDisposable) -> object """
pass
def __exit__(self, *args):
""" __exit__(self: IDisposable,exc_type: object,exc_value: object,exc_back: object) """
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 |
lst1=list()
lst1.append('K')
lst1.append('A')
lst2=['U', 'S', 'H', 'I', 'K']
print(lst1+lst2)
print(lst2[0] +lst2[1]+lst1[1])
for i in lst1+lst2:
print(i)
| lst1 = list()
lst1.append('K')
lst1.append('A')
lst2 = ['U', 'S', 'H', 'I', 'K']
print(lst1 + lst2)
print(lst2[0] + lst2[1] + lst1[1])
for i in lst1 + lst2:
print(i) |
class Photo(object):
def __init__(self, photo_id: int, orientation: str, number_of_tags: int, tags: set):
self.id = photo_id
self.orientation = orientation
self.number_of_tags = number_of_tags
self.tags = tags
self.is_vertical = orientation == 'V'
self.is_horizontal = orientation == 'H'
def __str__(self):
return str(self.id)
| class Photo(object):
def __init__(self, photo_id: int, orientation: str, number_of_tags: int, tags: set):
self.id = photo_id
self.orientation = orientation
self.number_of_tags = number_of_tags
self.tags = tags
self.is_vertical = orientation == 'V'
self.is_horizontal = orientation == 'H'
def __str__(self):
return str(self.id) |
# addition will takes place after multiplication and addition
num1 = 1 + 4 * 3 / 2;
# same as 5 * 3 /2
num2 = (1 + 4) * 3 / 2;
# same as 1+12/2
num3 = 1 + (4 * 3) / 2;
print("python follow precedence rules");
# this should produce 7.5
print(num1);
print(num2);
print(num3); | num1 = 1 + 4 * 3 / 2
num2 = (1 + 4) * 3 / 2
num3 = 1 + 4 * 3 / 2
print('python follow precedence rules')
print(num1)
print(num2)
print(num3) |
class Fruit:
def __init__(self,name,parents):
self.name = name
self.parents = parents
self.children = []
self.family = []
self.siblings = []
self.node = None ## Link to node object in graph
def find_children(self,basket): # basket is a list of Fruit objects
for fruit in basket:
if fruit.name is not self.name:
if self.name in [parent.name for parent in fruit.parents]:
self.children.append(fruit)
self.family = self.parents + self.children
def find_siblings(self,basket):
for fruit in basket:
if fruit.name is not self.name:
if set(fruit.parents).is_disjoint(set(self.parents)):
continue
else:
self.siblings.append(fruit)
| class Fruit:
def __init__(self, name, parents):
self.name = name
self.parents = parents
self.children = []
self.family = []
self.siblings = []
self.node = None
def find_children(self, basket):
for fruit in basket:
if fruit.name is not self.name:
if self.name in [parent.name for parent in fruit.parents]:
self.children.append(fruit)
self.family = self.parents + self.children
def find_siblings(self, basket):
for fruit in basket:
if fruit.name is not self.name:
if set(fruit.parents).is_disjoint(set(self.parents)):
continue
else:
self.siblings.append(fruit) |
file = open("text.txt", "r")
file2 = open("text2.txt", "w")
for data in file:
file2.write(data)
file.close()
file2.close()
| file = open('text.txt', 'r')
file2 = open('text2.txt', 'w')
for data in file:
file2.write(data)
file.close()
file2.close() |
animals = ['cat', 'dog', 'pig']
for animal in animals :
print (animal + 'would make a great pet.')
print ('All of those animals would makea great pet')
| animals = ['cat', 'dog', 'pig']
for animal in animals:
print(animal + 'would make a great pet.')
print('All of those animals would makea great pet') |
"""Exceptions of the library"""
class PyConnectError(Exception):
"""Base class for all exceptions in py_connect."""
class InvalidPowerCombination(PyConnectError):
"""Connection of different power pins."""
class MaxConnectionsError(PyConnectError):
"""Interface has exceeded it's max connections limit."""
class InvalidGpioError(PyConnectError):
"""Invalid connection of two gpio pins."""
class AlreadyConnectedError(PyConnectError):
"""One or more pins of the interface are already connected."""
class TwoMasterError(PyConnectError):
"""Error when connecting two master interfaces."""
class TwoSlaveError(PyConnectError):
"""Error when connecting two slave interfaces."""
class ChipEnabledFullError(PyConnectError):
"""All chip enable pins are in use."""
class NotImplementedDriverError(PyConnectError):
"""This peripheral doesn't have an implemented driver."""
class UnicludedDeviceError(PyConnectError):
"""Device hasn't been included in connections specification."""
class EmptyListError(PyConnectError):
"""Empty list given for an attribute."""
| """Exceptions of the library"""
class Pyconnecterror(Exception):
"""Base class for all exceptions in py_connect."""
class Invalidpowercombination(PyConnectError):
"""Connection of different power pins."""
class Maxconnectionserror(PyConnectError):
"""Interface has exceeded it's max connections limit."""
class Invalidgpioerror(PyConnectError):
"""Invalid connection of two gpio pins."""
class Alreadyconnectederror(PyConnectError):
"""One or more pins of the interface are already connected."""
class Twomastererror(PyConnectError):
"""Error when connecting two master interfaces."""
class Twoslaveerror(PyConnectError):
"""Error when connecting two slave interfaces."""
class Chipenabledfullerror(PyConnectError):
"""All chip enable pins are in use."""
class Notimplementeddrivererror(PyConnectError):
"""This peripheral doesn't have an implemented driver."""
class Unicludeddeviceerror(PyConnectError):
"""Device hasn't been included in connections specification."""
class Emptylisterror(PyConnectError):
"""Empty list given for an attribute.""" |
genres = ['blues', 'classical', 'country', 'disco', 'hiphop', 'jazz', 'metal', 'pop', 'reggae', 'rock']
num_files = 100
with open(f'INPUT_FULL', 'w') as f:
for genre in genres:
for i in range(num_files):
for j in range(6):
f.write(f'/datasets/duet/genres/{genre}.{i:05d}.{j}.wav /datasets/duet/genres/{genre}.{i:05d}.{j}.wav\n') | genres = ['blues', 'classical', 'country', 'disco', 'hiphop', 'jazz', 'metal', 'pop', 'reggae', 'rock']
num_files = 100
with open(f'INPUT_FULL', 'w') as f:
for genre in genres:
for i in range(num_files):
for j in range(6):
f.write(f'/datasets/duet/genres/{genre}.{i:05d}.{j}.wav\t/datasets/duet/genres/{genre}.{i:05d}.{j}.wav\n') |
# Copyright 2020 University of Adelaide
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
def check_inst(inst, mask, match):
return inst & mask == match
def cycles_push(inst):
if check_inst(inst, 0b1111111000000000, 0b1011010000000000):
return 1 + bin(inst & 0x00ff).count('1')
return -1
def cycles_pop(inst):
# Format 14: push/pop registers
if check_inst(inst, 0b1111111000000000, 0b1011110000000000):
return 1 + bin(inst & 0x00ff).count('1')
return -1
def cycles_pop_pc(inst):
# Format 14: push/pop registers
if check_inst(inst, 0b1111111100000000, 0b1011110100000000):
return 4 + bin(inst & 0x00ff).count('1')
return -1
def cycles_add(inst):
# Format 2: add/subtract
if check_inst(inst, 0b1111101000000000, 0b0001100000000000):
return 1
return -1
def cycles_add_pc(inst):
return -1
def cycles_rot(inst):
# Format 4
if check_inst(inst, 0b1111111111000000, 0b0100000111000000):
return 1
return -1
def cycles_ldr(inst):
# Format 7
# Format 9
if check_inst(inst, 0b1111101000000000, 0b0101100000000000) or \
check_inst(inst, 0b1110100000000000, 0b0110100000000000):
return 2
return -1
def cycles_str(inst):
# Format 7
# Format 9
if check_inst(inst, 0b1111101000000000, 0b0101000000000000) or \
check_inst(inst, 0b1110100000000000, 0b0110000000000000):
return 2
return -1
def cycles_mov(inst):
# Format 1: move shifted register
# Format 3: move/compare/add/subtract immediate
# Format 5: Hi register operations/branch exchange
if check_inst(inst, 0b1111111111000000, 0b0000000000000000) or \
check_inst(inst, 0b1111100000000000, 0b0010000000000000) or \
check_inst(inst, 0b1111111100000000, 0b0100011000000000):
return 1
return -1
def cycles_mov_pc(inst):
# Format 5: dest = pc
if check_inst(inst, 0b1111111101000111, 0b0100011001000111):
return 3
return -1
__cycle_counts = [
[ cycles_mov, cycles_mov_pc ],
[ cycles_add, cycles_add_pc ],
[ cycles_ldr ],
[ cycles_str ],
[ cycles_rot ],
[ cycles_pop, cycles_pop_pc ],
[ cycles_push ]
]
def get_cycle_counts():
return __cycle_counts | def check_inst(inst, mask, match):
return inst & mask == match
def cycles_push(inst):
if check_inst(inst, 65024, 46080):
return 1 + bin(inst & 255).count('1')
return -1
def cycles_pop(inst):
if check_inst(inst, 65024, 48128):
return 1 + bin(inst & 255).count('1')
return -1
def cycles_pop_pc(inst):
if check_inst(inst, 65280, 48384):
return 4 + bin(inst & 255).count('1')
return -1
def cycles_add(inst):
if check_inst(inst, 64000, 6144):
return 1
return -1
def cycles_add_pc(inst):
return -1
def cycles_rot(inst):
if check_inst(inst, 65472, 16832):
return 1
return -1
def cycles_ldr(inst):
if check_inst(inst, 64000, 22528) or check_inst(inst, 59392, 26624):
return 2
return -1
def cycles_str(inst):
if check_inst(inst, 64000, 20480) or check_inst(inst, 59392, 24576):
return 2
return -1
def cycles_mov(inst):
if check_inst(inst, 65472, 0) or check_inst(inst, 63488, 8192) or check_inst(inst, 65280, 17920):
return 1
return -1
def cycles_mov_pc(inst):
if check_inst(inst, 65351, 17991):
return 3
return -1
__cycle_counts = [[cycles_mov, cycles_mov_pc], [cycles_add, cycles_add_pc], [cycles_ldr], [cycles_str], [cycles_rot], [cycles_pop, cycles_pop_pc], [cycles_push]]
def get_cycle_counts():
return __cycle_counts |
d = {'key1': 1, 'key2': 2, 'key3': 3}
for k in d:
print(k)
# key1
# key2
# key3
for k in d.keys():
print(k)
# key1
# key2
# key3
keys = d.keys()
print(keys)
print(type(keys))
# dict_keys(['key1', 'key2', 'key3'])
# <class 'dict_keys'>
k_list = list(d.keys())
print(k_list)
print(type(k_list))
# ['key1', 'key2', 'key3']
# <class 'list'>
for v in d.values():
print(v)
# 1
# 2
# 3
values = d.values()
print(values)
print(type(values))
# dict_values([1, 2, 3])
# <class 'dict_values'>
v_list = list(d.values())
print(v_list)
print(type(v_list))
# [1, 2, 3]
# <class 'list'>
for k, v in d.items():
print(k, v)
# key1 1
# key2 2
# key3 3
for t in d.items():
print(t)
print(type(t))
print(t[0])
print(t[1])
print('---')
# ('key1', 1)
# <class 'tuple'>
# key1
# 1
# ---
# ('key2', 2)
# <class 'tuple'>
# key2
# 2
# ---
# ('key3', 3)
# <class 'tuple'>
# key3
# 3
# ---
items = d.items()
print(items)
print(type(items))
# dict_items([('key1', 1), ('key2', 2), ('key3', 3)])
# <class 'dict_items'>
i_list = list(d.items())
print(i_list)
print(type(i_list))
# [('key1', 1), ('key2', 2), ('key3', 3)]
# <class 'list'>
print(i_list[0])
print(type(i_list[0]))
# ('key1', 1)
# <class 'tuple'>
| d = {'key1': 1, 'key2': 2, 'key3': 3}
for k in d:
print(k)
for k in d.keys():
print(k)
keys = d.keys()
print(keys)
print(type(keys))
k_list = list(d.keys())
print(k_list)
print(type(k_list))
for v in d.values():
print(v)
values = d.values()
print(values)
print(type(values))
v_list = list(d.values())
print(v_list)
print(type(v_list))
for (k, v) in d.items():
print(k, v)
for t in d.items():
print(t)
print(type(t))
print(t[0])
print(t[1])
print('---')
items = d.items()
print(items)
print(type(items))
i_list = list(d.items())
print(i_list)
print(type(i_list))
print(i_list[0])
print(type(i_list[0])) |
# Testing out some stuff with async and await
async def hello(name):
print ("hello" + name)
return "hello" + name
# We can use the await statement in coroutines to call
# coroutines as normal functions; i.e. what it implies is that
# if we runt return await func(*args) in a courtoune
# is like running return func2(*args) in a normal def function
async def await_hello(func, *args):
return await func(*args)
def run(coro, *args):
try:
# We need to create the coroutine object before we start using it.
#
g = coro(*args)
# In order to run the coroutine from a normal function, we need to
# send it a value, in this case None.
g.send(None)
# However, the coroutine will run til it returns a StopIteration
# which we need to catch, and then catch the value of that
# exception, so as to find out what it has produced
except StopIteration as e:
return e.value
print(run(await_hello, hello, "wut")) | async def hello(name):
print('hello' + name)
return 'hello' + name
async def await_hello(func, *args):
return await func(*args)
def run(coro, *args):
try:
g = coro(*args)
g.send(None)
except StopIteration as e:
return e.value
print(run(await_hello, hello, 'wut')) |
number = int(input())
raiz = number/2
for i in range(1,20):
raiz = ((raiz ** 2) + number) / (2 * raiz)
print(raiz) | number = int(input())
raiz = number / 2
for i in range(1, 20):
raiz = (raiz ** 2 + number) / (2 * raiz)
print(raiz) |
class Item:
def __init__(self,weight,value) -> None:
self.weight=weight
self.value=value
self.ratio=value/weight
def knapsackMethod(items,capacity):
items.sort(key=lambda x: x.ratio,reverse=True)
usedCapacity=0
totalValue=0
for i in items:
if usedCapacity+i.weight<=capacity:
usedCapacity+=i.weight
totalValue+=i.value
else:
unusedWeight=capacity-usedCapacity
value=i.ratio*unusedWeight
usedCapacity+=unusedWeight
totalValue+=value
if usedCapacity==capacity:
break
print("Total value obtained: "+str(totalValue))
item1=Item(20,100)
item2=Item(30,120)
item3=Item(10,60)
cList=[item1,item2,item3]
knapsackMethod(cList,50) | class Item:
def __init__(self, weight, value) -> None:
self.weight = weight
self.value = value
self.ratio = value / weight
def knapsack_method(items, capacity):
items.sort(key=lambda x: x.ratio, reverse=True)
used_capacity = 0
total_value = 0
for i in items:
if usedCapacity + i.weight <= capacity:
used_capacity += i.weight
total_value += i.value
else:
unused_weight = capacity - usedCapacity
value = i.ratio * unusedWeight
used_capacity += unusedWeight
total_value += value
if usedCapacity == capacity:
break
print('Total value obtained: ' + str(totalValue))
item1 = item(20, 100)
item2 = item(30, 120)
item3 = item(10, 60)
c_list = [item1, item2, item3]
knapsack_method(cList, 50) |
class Node:
"""
A node class used in A* Pathfinding.
parent: it is parent of current node
position: it is current position of node in the maze.
g: cost from start to current Node
h: heuristic based estimated cost for current Node to end Node
f: total cost of present node i.e. : f = g + h
"""
def __init__(self , parent=None , poistion=None):
self.parent = parent
self.position = poistion
self.g = 0
self.f = 0
self.h = 0
def __eq__(self , other):
return self.position == other.position
class FindPath():
def __init__(self , maze , cost , start , end):
self.maze = maze
self.cost = cost
self.start = start
self.end = end
self.move = [ [-1, 0] , # go up
[ 0,-1] , # go left
[ 1, 0] , # go down
[ 0, 1] , # go right
[-1,-1] , # go left-up
[-1, 1] , # go left down
[ 1,-1] , # go right down
[ 1, 1] ] # go right up
def return_path(self,curr_node,cost_matrix):
path = []
no_rows , no_columns = np.shape(cost_matrix)
# here we create the initialized result maze with -1 in every position
res = [[-1 for i in range(no_columns)] for j in range(no_rows)]
#we will iterate over all parents of node and store in path
curr = curr_node
while curr is not None:
path.append(curr.position)
curr = curr.parent
path = path[::-1]
initial_value = 0
# we will insert the path in matrix
for i in range(len(path)):
res[path[i][0]][path[i][1]] = initial_value
initial_value += 1
return res
def search(self):
"""
Returns a list of tuples as a path from the given start to the given end in the given maze
"""
# we will create start node and end node
# we will initialize g, h and f value zero
start_node = Node(None, tuple(self.start))
start_node.g = 0
start_node.h = 0
start_node.f = 0
end_node = Node(None, tuple(self.end))
end_node.g = 0
end_node.h = 0
end_node.f = 0
# we need to initialize both queue and visited list
# we will find the lowest cost node to expand next
queue = []
# we will store all visited node
visited_list = []
# Add the start node
queue.append(start_node)
# calculate the maximiuim number of steps we can move in the matrix
counter = 0
max_steps = (len(self.maze) // 2) ** 10
# Get number of rows and columns
no_rows, no_columns = np.shape(self.maze)
# Loop until you find the end
while len(queue) > 0:
# Every time any node is visited increase the counter
counter += 1
# Get the current node
current_node = queue[0]
current_index = 0
for index, item in enumerate(queue):
if item.f < current_node.f:
current_node = item
current_index = index
# if we hit this point return the path such as it may be no solution or
# computation cost is too high
if counter > max_steps:
print ("Destination cannot be reached")
return self.return_path(current_node , self.maze)
# Pop current node out off
queue.pop(current_index)
# mark it visited
visited_list.append(current_node)
# check if goal is reached or not
if current_node == end_node:
return self.return_path(current_node , self.maze)
# Generate coordinate from all adjacent coordinates
coordinates = []
for move in self.move:
# Get node position
current_node_position = (current_node.position[0] + move[0] , current_node.position[1] + move[1])
# check if all the moves are in maze limit
if (current_node_position[0] > (no_rows - 1) or current_node_position[0] < 0 or current_node_position[1] > (no_columns -1) or current_node_position[1] < 0):
continue
# Make sure walkable terrain
if self.maze[current_node_position[0]][current_node_position[1]] != 0:
continue
# Create new node
new_node = Node(current_node , current_node_position)
# Append
coordinates.append(new_node)
# Loop through children
for child in coordinates:
# Child is on the visited list (search entire visited list)
if len([visited_child for visited_child in visited_list if visited_child == child]) > 0:
continue
# calculate f, g, and h values
child.g = current_node.g + self.cost
# calculated Heuristic costs, this is using eucledian distance
child.h = (((child.position[0] - end_node.position[0]) ** 2) + ((child.position[1] - end_node.position[1]) ** 2))
child.f = child.g + child.h
# Child if already in queue and g cost is already lower
if len([i for i in queue if child == i and child.g > i.g]) > 0:
continue
queue.append(child)
class Preprocess:
def __init__(self , maze , n , m):
self.maze = maze
self.n = n
self.m = m
def check(self , value):
data=''
for i in range(len(value)):
if(value[i] == '[' or value[i] == ']'):
continue
else:
data+=value[i]
return data
def process_text(self):
c=0
matrix = self.maze
matrix = matrix.split(',')
data = []
for i in range(self.n):
l = []
for j in range(self.m):
l.append(int(self.check(matrix[c])))
c += 1
data.append(l)
return data
if __name__ == '__main__':
no_rows = int(input("Enter number of rows: "))
no_cols = int(input("Enter number of columns: "))
matrix = Preprocess(str(input("Enter Matrix: ")) , no_rows , no_cols).process_text()
start_x = int(input("Enter x coordinate of starting node: "))
start_y = int(input("Enter y coordinate of starting node: "))
end_x = int(input("Enter x coordinate of ending node: "))
end_y = int(input("Enter y coordinate of ending node: "))
cost = int(input("Enter cost: "))
start = [start_x , start_y]
end = [end_x , end_y]
path = FindPath(matrix , cost , start , end).search()
if(path != None):
print("Path found: ")
for i in range(len(path)):
for j in range(len(path[i])):
if(path[i][j] == -1):
print(0 , end=" ")
else:
print(path[i][j] , end=" ")
print()
else:
print("No Path found")
#input:
# Enter number of rows: 5
# Enter number of columns: 6
# Enter Matrix: [[0, 1, 0, 0, 0, 0],
# [0, 1, 0, 0, 0, 0],
# [0, 1, 0, 1, 0, 0],
# [0, 1, 0, 0, 1, 0],
# [0, 0, 0, 0, 1, 0]]
# Enter x coordinate of starting node: 0
# Enter y coordinate of starting node: 0
# Enter x coordinate of ending node: 4
# Enter y coordinate of ending node: 5
# Enter cost: 1
#Path found:
# 0 0 0 0 0 0
# 1 0 0 0 0 0
# 2 0 0 0 7 0
# 3 0 0 6 0 8
# 0 4 5 0 0 9
| class Node:
"""
A node class used in A* Pathfinding.
parent: it is parent of current node
position: it is current position of node in the maze.
g: cost from start to current Node
h: heuristic based estimated cost for current Node to end Node
f: total cost of present node i.e. : f = g + h
"""
def __init__(self, parent=None, poistion=None):
self.parent = parent
self.position = poistion
self.g = 0
self.f = 0
self.h = 0
def __eq__(self, other):
return self.position == other.position
class Findpath:
def __init__(self, maze, cost, start, end):
self.maze = maze
self.cost = cost
self.start = start
self.end = end
self.move = [[-1, 0], [0, -1], [1, 0], [0, 1], [-1, -1], [-1, 1], [1, -1], [1, 1]]
def return_path(self, curr_node, cost_matrix):
path = []
(no_rows, no_columns) = np.shape(cost_matrix)
res = [[-1 for i in range(no_columns)] for j in range(no_rows)]
curr = curr_node
while curr is not None:
path.append(curr.position)
curr = curr.parent
path = path[::-1]
initial_value = 0
for i in range(len(path)):
res[path[i][0]][path[i][1]] = initial_value
initial_value += 1
return res
def search(self):
"""
Returns a list of tuples as a path from the given start to the given end in the given maze
"""
start_node = node(None, tuple(self.start))
start_node.g = 0
start_node.h = 0
start_node.f = 0
end_node = node(None, tuple(self.end))
end_node.g = 0
end_node.h = 0
end_node.f = 0
queue = []
visited_list = []
queue.append(start_node)
counter = 0
max_steps = (len(self.maze) // 2) ** 10
(no_rows, no_columns) = np.shape(self.maze)
while len(queue) > 0:
counter += 1
current_node = queue[0]
current_index = 0
for (index, item) in enumerate(queue):
if item.f < current_node.f:
current_node = item
current_index = index
if counter > max_steps:
print('Destination cannot be reached')
return self.return_path(current_node, self.maze)
queue.pop(current_index)
visited_list.append(current_node)
if current_node == end_node:
return self.return_path(current_node, self.maze)
coordinates = []
for move in self.move:
current_node_position = (current_node.position[0] + move[0], current_node.position[1] + move[1])
if current_node_position[0] > no_rows - 1 or current_node_position[0] < 0 or current_node_position[1] > no_columns - 1 or (current_node_position[1] < 0):
continue
if self.maze[current_node_position[0]][current_node_position[1]] != 0:
continue
new_node = node(current_node, current_node_position)
coordinates.append(new_node)
for child in coordinates:
if len([visited_child for visited_child in visited_list if visited_child == child]) > 0:
continue
child.g = current_node.g + self.cost
child.h = (child.position[0] - end_node.position[0]) ** 2 + (child.position[1] - end_node.position[1]) ** 2
child.f = child.g + child.h
if len([i for i in queue if child == i and child.g > i.g]) > 0:
continue
queue.append(child)
class Preprocess:
def __init__(self, maze, n, m):
self.maze = maze
self.n = n
self.m = m
def check(self, value):
data = ''
for i in range(len(value)):
if value[i] == '[' or value[i] == ']':
continue
else:
data += value[i]
return data
def process_text(self):
c = 0
matrix = self.maze
matrix = matrix.split(',')
data = []
for i in range(self.n):
l = []
for j in range(self.m):
l.append(int(self.check(matrix[c])))
c += 1
data.append(l)
return data
if __name__ == '__main__':
no_rows = int(input('Enter number of rows: '))
no_cols = int(input('Enter number of columns: '))
matrix = preprocess(str(input('Enter Matrix: ')), no_rows, no_cols).process_text()
start_x = int(input('Enter x coordinate of starting node: '))
start_y = int(input('Enter y coordinate of starting node: '))
end_x = int(input('Enter x coordinate of ending node: '))
end_y = int(input('Enter y coordinate of ending node: '))
cost = int(input('Enter cost: '))
start = [start_x, start_y]
end = [end_x, end_y]
path = find_path(matrix, cost, start, end).search()
if path != None:
print('Path found: ')
for i in range(len(path)):
for j in range(len(path[i])):
if path[i][j] == -1:
print(0, end=' ')
else:
print(path[i][j], end=' ')
print()
else:
print('No Path found') |
#LeetCode problem 54: Spiral Matrix
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
if(len(matrix)==0 or len(matrix[0])==0):
return []
res=[]
rb=0
re=len(matrix)
cb=0
ce=len(matrix[0])
while(re>rb and ce>cb):
for j in range(cb,ce):
res.append(matrix[rb][j])
for k in range(rb+1,re-1):
res.append(matrix[k][ce-1])
if(re!=rb+1):
for l in range(ce-1,cb-1,-1):
res.append(matrix[re-1][l])
if(cb!=ce-1):
for m in range(re-2,rb,-1):
res.append(matrix[m][cb])
rb+=1
ce-=1
cb+=1
re-=1
return(res) | class Solution:
def spiral_order(self, matrix: List[List[int]]) -> List[int]:
if len(matrix) == 0 or len(matrix[0]) == 0:
return []
res = []
rb = 0
re = len(matrix)
cb = 0
ce = len(matrix[0])
while re > rb and ce > cb:
for j in range(cb, ce):
res.append(matrix[rb][j])
for k in range(rb + 1, re - 1):
res.append(matrix[k][ce - 1])
if re != rb + 1:
for l in range(ce - 1, cb - 1, -1):
res.append(matrix[re - 1][l])
if cb != ce - 1:
for m in range(re - 2, rb, -1):
res.append(matrix[m][cb])
rb += 1
ce -= 1
cb += 1
re -= 1
return res |
"""
Non-orthogonal Reflection
by Ira Greenberg.
Based on the equation (R = 2N(N * L) - L) where R is the reflection vector, N
is the normal, and L is the incident vector.
"""
# Position of left hand side of floor.
base1 = None
# Position of right hand side of floor.
base2 = None
# A list of subpoints along the floor path.
coords = []
# Variables related to moving ball.
position = None
velocity = None
r = 6
speed = 3.5
def setup():
size(640, 360)
fill(128)
base1 = PVector(0, height - 150)
base2 = PVector(width, height)
createGround()
# Start ellipse at middle top of screen.
position = PVector(width / 2, 0)
# Calculate initial random velocity.
velocity = PVector.random2D()
velocity.mult(speed)
def draw():
# Draw background.
fill(0, 12)
noStroke()
rect(0, 0, width, height)
# Draw base.
fill(200)
quad(base1.x, base1.y, base2.x, base2.y, base2.x, height, 0, height)
# Calculate base top normal.
baseDelta = PVector.sub(base2, base1)
baseDelta.normalize()
normal = PVector(-baseDelta.y, baseDelta.x)
# Draw ellipse.
noStroke()
fill(255)
ellipse(position.x, position.y, r * 2, r * 2)
# Move elipse.
position.add(velocity)
# Normalized incidence vector.
incidence = PVector.mult(velocity, -1)
incidence.normalize()
# Detect and handle collision.
for coord in coords:
# Check distance between ellipse and base top coordinates.
if PVector.dist(position, coord) < r:
# Calculate dot product of incident vector and base top normal.
dot = incidence.dot(normal)
# Calculate reflection vector.
# Assign reflection vector to direction vector.
velocity.set(2 * normal.x * dot - incidence.x,
2 * normal.y * dot - incidence.y, 0)
velocity.mult(speed)
# Draw base top normal at collision point.
stroke(255, 128, 0)
line(position.x, position.y,
position.x - normal.x * 100, position.y - normal.y * 100)
# Detect boundary collision.
# Right.
if position.x > width - r:
position.x = width - r
velocity.x *= -1
# Left.
if position.x < r:
position.x = r
velocity.x *= -1
# Top.
if position.y < r:
position.y = r
velocity.y *= -1
# Randomize base top.
base1.y = random(height - 100, height)
base2.y = random(height - 100, height)
createGround()
# Calculate variables for the ground.
def createGround():
# Calculate length of base top.
baseLength = PVector.dist(base1, base2)
# Fill base top coordinate array.
coords = [PVector(base1.x + ((base2.x - base1.x) / baseLength) * i,
base1.y + ((base2.y - base1.y) / baseLength) * i)
for i in range(ceil(baseLength))]
| """
Non-orthogonal Reflection
by Ira Greenberg.
Based on the equation (R = 2N(N * L) - L) where R is the reflection vector, N
is the normal, and L is the incident vector.
"""
base1 = None
base2 = None
coords = []
position = None
velocity = None
r = 6
speed = 3.5
def setup():
size(640, 360)
fill(128)
base1 = p_vector(0, height - 150)
base2 = p_vector(width, height)
create_ground()
position = p_vector(width / 2, 0)
velocity = PVector.random2D()
velocity.mult(speed)
def draw():
fill(0, 12)
no_stroke()
rect(0, 0, width, height)
fill(200)
quad(base1.x, base1.y, base2.x, base2.y, base2.x, height, 0, height)
base_delta = PVector.sub(base2, base1)
baseDelta.normalize()
normal = p_vector(-baseDelta.y, baseDelta.x)
no_stroke()
fill(255)
ellipse(position.x, position.y, r * 2, r * 2)
position.add(velocity)
incidence = PVector.mult(velocity, -1)
incidence.normalize()
for coord in coords:
if PVector.dist(position, coord) < r:
dot = incidence.dot(normal)
velocity.set(2 * normal.x * dot - incidence.x, 2 * normal.y * dot - incidence.y, 0)
velocity.mult(speed)
stroke(255, 128, 0)
line(position.x, position.y, position.x - normal.x * 100, position.y - normal.y * 100)
if position.x > width - r:
position.x = width - r
velocity.x *= -1
if position.x < r:
position.x = r
velocity.x *= -1
if position.y < r:
position.y = r
velocity.y *= -1
base1.y = random(height - 100, height)
base2.y = random(height - 100, height)
create_ground()
def create_ground():
base_length = PVector.dist(base1, base2)
coords = [p_vector(base1.x + (base2.x - base1.x) / baseLength * i, base1.y + (base2.y - base1.y) / baseLength * i) for i in range(ceil(baseLength))] |
def isPower(n):
'''
Determine if the given number is a power of some non-negative integer.
'''
if n == 1:
return True
sqrt = math.sqrt(n)
for a in range(int(sqrt)+1):
for b in range(2, int(sqrt)+1):
if a ** b == n:
return True
return False | def is_power(n):
"""
Determine if the given number is a power of some non-negative integer.
"""
if n == 1:
return True
sqrt = math.sqrt(n)
for a in range(int(sqrt) + 1):
for b in range(2, int(sqrt) + 1):
if a ** b == n:
return True
return False |
# Add your own choices here!
fruit = ["apples", "oranges", "pears", "grapes", "blueberries"]
lunch = ["pho", "timmies", "thai", "burgers", "buffet!", "indian", "montanas"]
situations = {"fruit":fruit, "lunch":lunch}
| fruit = ['apples', 'oranges', 'pears', 'grapes', 'blueberries']
lunch = ['pho', 'timmies', 'thai', 'burgers', 'buffet!', 'indian', 'montanas']
situations = {'fruit': fruit, 'lunch': lunch} |
__author__ = 'Brian Nguyen'
def greeting(msg):
print("We would like to say: " + msg) | __author__ = 'Brian Nguyen'
def greeting(msg):
print('We would like to say: ' + msg) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.